diff --git a/C3d/Include/alg_base.h b/C3d/Include/alg_base.h index 51c2760..526d573 100644 --- a/C3d/Include/alg_base.h +++ b/C3d/Include/alg_base.h @@ -19,7 +19,6 @@ #include #include #include -#include #include #include diff --git a/C3d/Include/assembly.h b/C3d/Include/assembly.h index 4955473..818eea4 100644 --- a/C3d/Include/assembly.h +++ b/C3d/Include/assembly.h @@ -136,6 +136,9 @@ public: // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ bool GetItems( MbeSpaceType type, const MbMatrix3D & from, RPArray & items, SArray & matrs ) override; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + std::vector> & items, std::vector & matrs ) override; // \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 . \~ diff --git a/C3d/Include/attr_user_attribute.h b/C3d/Include/attr_user_attribute.h index 631bd44..0369264 100644 --- a/C3d/Include/attr_user_attribute.h +++ b/C3d/Include/attr_user_attribute.h @@ -197,33 +197,33 @@ public : /// \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbUserAttribType AttrTypeEx() const = 0; - virtual MbAttribute & Duplicate( MbRegDuplicate * = nullptr ) 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. + virtual MbAttribute & Duplicate( MbRegDuplicate * = nullptr ) const override = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const override = 0; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ) override = 0; // \ru Инициализировать данные по присланным. \en Initialize data. // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. - void OnChangeOwner( const MbAttributeContainer & owner ) override; - // \ru Выполнить действия при конвертации владельца. \en Perform actions when converting the owner. - void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; + virtual void OnChangeOwner( const MbAttributeContainer & owner ) override; + // \ru Выполнить действия при конвертации владельца. \en Perform actions when converting the owner. + virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = nullptr ) override; + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = nullptr ) override; // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = nullptr ) override; + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = nullptr ) override; // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override; + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override; // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = nullptr ) override; + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = nullptr ) override; // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. - void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. - void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) override; // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. - void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ) override; + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ) override; // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. - void OnDeleteOwner( const MbAttributeContainer & owner ) override; + virtual void OnDeleteOwner( const MbAttributeContainer & owner ) override; - void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. - size_t SetProperties( const MbProperties & ) override; // \ru Установить свойства объекта. \en Set properties of the object. + virtual void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ) override; // \ru Установить свойства объекта. \en Set properties of the object. MbePrompt GetPropertyName() override; // \ru Выдать заголовок свойства объекта. \en Get a name of object property. OBVIOUS_PRIVATE_COPY( MbExternalAttribute ) diff --git a/C3d/Include/attribute_item.h b/C3d/Include/attribute_item.h index 26d3d21..9a9c41e 100644 --- a/C3d/Include/attribute_item.h +++ b/C3d/Include/attribute_item.h @@ -11,7 +11,7 @@ #define __ATTRIBUTE_ITEM_H -#include +#include #include #include #include @@ -566,6 +566,8 @@ namespace c3d // namespace C3D constexpr TCHAR c3dStr_TextureUrl[] = _T("C3D_Texture_URL"); /// \ru Подсказка для атрибута хот-точки в уклоне. \en Prompt for attribute of hot point in draft operations. constexpr TCHAR c3d_DraftOperationHotPoint[] = _T("c3d_DraftOperationHotPoint"); + /// \ru Подсказка для типа замкнутости оболочки в исходных данных. \en Promt for shell closure type in source data. + constexpr TCHAR c3d_ShellOpenClosedOriginal[] = _T( "c3d_ShellOpenClosedOriginal" ); } // namespace C3D diff --git a/C3d/Include/collection.h b/C3d/Include/collection.h index bb982fb..75789b8 100644 --- a/C3d/Include/collection.h +++ b/C3d/Include/collection.h @@ -65,7 +65,6 @@ private: \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; - mutable DPtr topo; ///< \ru Дополнительная информация о топологии коллекции. \en Additional information about a topology of the collection. private: // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. MbCollection( const MbCollection & init ); @@ -320,12 +319,6 @@ public: void ConvertAllToTriangles(); /// \ru Удалить дублирующие с заданной точностью друг друга точки. \en Remove redundant points with a given tolerance (duplicates). bool RemoveRedundantPoints( bool deleteNormals, double epsilon = LENGTH_EPSILON ); - /// \ru Готова ли топология коллекции. \en Whether information about collection topology is ready. - bool IsGridTopologyReady() const { return topo != nullptr; } - /// \ru Создать новый временный объект информации о топологии. \en Create new temporary maintenance object information about collection topology. - const MbGridTopology * CreateGridTopology( bool keepExisting ) const; - /// \ru Удалить информацию о топологии. \en Delete a information about collection topology. - void ResetGridTopology() const; /** \} */ private: /// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/constraint.h b/C3d/Include/constraint.h index 2813827..7c795a8 100644 --- a/C3d/Include/constraint.h +++ b/C3d/Include/constraint.h @@ -93,7 +93,7 @@ public: /// \ru Оператор копирования. \en Copy operator. \~ MtGeomArgument & operator = ( const MtGeomArgument & ); -KNOWN_OBJECTS_RW_REF_OPERATORS( MtGeomArgument ) // Serializing into a file format +KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MtGeomArgument, MATH_FUNC_EX ) // Serializing into a file format }; // MtGeomArgument diff --git a/C3d/Include/constraint_item.h b/C3d/Include/constraint_item.h index 480d3f2..ac6c80f 100644 --- a/C3d/Include/constraint_item.h +++ b/C3d/Include/constraint_item.h @@ -28,6 +28,7 @@ #include #include #include +#include //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/conv_exchange_settings.h b/C3d/Include/conv_exchange_settings.h index f8e87c1..215d581 100644 --- a/C3d/Include/conv_exchange_settings.h +++ b/C3d/Include/conv_exchange_settings.h @@ -15,6 +15,7 @@ #include #include #include +#include class MbProductInfo; diff --git a/C3d/Include/conv_model_exchange.h b/C3d/Include/conv_model_exchange.h index 870386f..ac4750d 100644 --- a/C3d/Include/conv_model_exchange.h +++ b/C3d/Include/conv_model_exchange.h @@ -48,6 +48,7 @@ enum MbeModelExchangeFormat { 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_3MF, ///< \ru Интерпретировать содержимое как 3MF (.3mf). \en Read data from buffer as 3MF (.3mf). mxf_OBJ, ///< \ru Интерпретировать содержимое как OBJ (.obj). \en Read data from buffer as OBJ (.obj). 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). @@ -733,6 +734,27 @@ public: */ virtual MbeConvResType VRMLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата 3MF. + \en Write a file of 3MF format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \param[in] devSag - \ru Угловой шаг для расчёта триангуляционной сетки. + \en Deviate sag requiref for grid calculateion. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup VRML_Exchange + */ + virtual MbeConvResType ThreeMFWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + + /** \brief \ru Прочитать файл формата GRDECL. \en Read a file of GRDECL format. \~ \param[in] prop - \ru Реализация интерфейса свойств конвертера. @@ -1148,6 +1170,20 @@ CONV_FUNC( MbeConvResType ) GRDECLWrite( IConvertorProperty3D& prop, ItModelDocu */ CONV_FUNC( MbeConvResType ) VRMLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); +/** \brief \ru Записать файл формата 3MF. + \en Write a file of 3MF format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup VRML_Exchange +*/ +CONV_FUNC( MbeConvResType ) ThreeMFWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + /** \brief \ru Прочитать файл с облаком точек в формате ASCII. \en Read a file of ASCII Point Cloud format. \~ diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index 01844d6..aa00a80 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -457,7 +457,14 @@ public: bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const override; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if the curve is planar. bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const override; - // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after use). + /**\ru Дать поверхностную кривую, если пространственная кривая поверхностная. После использования вызывать + DeleteItem на аргументы. В некоторых случаях переданная поверхность surface может быть + использована для устранения неопределённости выбора кривой (например, при стыке двух + одинаковых по IsSame или IsSimilar поверхностей). + \en Get a surface curve if a spatial curve lies on a surface. Call 'DeleteItem' for arguments after use. + In some cases the input 'surface' argument may be can be used to eliminate uncertainty in the choice + of a curve (e.g. curves on a junction of surfaces which are same by IsSame or IsSimilar checks). + */ bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const override; double GetParamToUnit() const override; // \ru Дать приращение параметра, осреднённо соответствующее единичной длине в пространстве. \en Get parameter increment which averagingly corresponds to the unit length in space. diff --git a/C3d/Include/curve.h b/C3d/Include/curve.h index bafda3a..edc56eb 100644 --- a/C3d/Include/curve.h +++ b/C3d/Include/curve.h @@ -25,6 +25,7 @@ #include #include #include +#include class MATH_CLASS MbPlacement; diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index ea8f830..3a303dd 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include diff --git a/C3d/Include/func_curve_coordinate.h b/C3d/Include/func_curve_coordinate.h index c13484e..32ed0a5 100644 --- a/C3d/Include/func_curve_coordinate.h +++ b/C3d/Include/func_curve_coordinate.h @@ -25,25 +25,25 @@ */ // --- class MATH_CLASS MbCurveCoordinate : public MbFunction { -public : - SPtr curve; ///< \ru Кривая. \en The curve. - size_t coordinate; ///< \ru Координата кривой: X(0), Y(1), Z(2). \en The curve coordinate: X(0), Y(1), Z(2). +private : + c3d::SpaceCurveSPtr curve; ///< \ru Кривая. \en The curve. + size_t coordinate; ///< \ru Координата кривой: X(0), Y(1), Z(2). \en The curve coordinate: X(0), Y(1), Z(2). MbCartPoint3D origin; ///< \ru Точка отсчёта параметра функции. \en The origin point for parameter. - MbVector3D derive; ///< \ru Вектор перемещения по параметру. \en The vector of movement by parameter. - std::vector tBreaks; ///< \ru Параметры функции, в которых она терпит излом. \en The function parameters for which the function have a break. + MbVector3D derive; ///< \ru Вектор перемещения по параметру. \en The vector of movement by parameter. + c3d::DoubleVector tBreaks; ///< \ru Параметры функции, в которых она терпит излом. \en The function parameters for which the function have a break. -public : - ///< \ru Конструктор по значениям и параметрам. \en Constructor by values and parameters. - MbCurveCoordinate( const MbCurve3D & cur, size_t process, const MbPlacement3D & place, size_t coord ); private: + ///< \ru Конструктор по кривой и индексу координаты. \en Constructor by curve and index of coordinate. MbCurveCoordinate( MbCurve3D & cur, size_t coord ); MbCurveCoordinate( const MbCurveCoordinate & ); // \ru Не реализовано \en Not implemented MbCurveCoordinate( const MbCurveCoordinate &, MbRegDuplicate * iReg ); + public : virtual ~MbCurveCoordinate(); public: - void Init( const MbCurve3D & cur, size_t process, const MbPlacement3D & place, size_t coord ); ///< \ru Инициализация по значениям и параметрам. \en Initialization by values and parameters. + /// \ru Создание объекта. \en Object creation. + static MbFunction * Create( const MbCurve3D & cur, size_t coord, const MbPlacement3D * place, MbResultType & res ); // \ru Общие функции математического объекта \en Common functions of mathematical object MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element @@ -59,14 +59,14 @@ public: void SetClosed( bool cl ) override; // \ru Замкнутость функции \en A function closedness double Value ( double & t ) const override; // \ru Значение функции для t \en The value of function for a given t - double FirstDer ( double & t ) const override; // \ru Первая производная по t \en The first derivative with respect to t - double SecondDer ( double & t ) const override; // \ru Вторая производная по t \en The second derivative with respect to t - double ThirdDer ( double & t ) const override; // \ru Третья производная по t \en The third derivative with respect to t + double FirstDer ( double & t ) const override; // \ru Первая производная по t. Может вернуть значение MB_INFINITY. \en The first derivative with respect to t. May return MB_INFINITY. + double SecondDer ( double & t ) const override; // \ru Вторая производная по t. Может вернуть значение MB_QNAN. \en The second derivative with respect to t. May return MB_QNAN. + double ThirdDer ( double & t ) const override; // \ru Третья производная по t. Может вернуть значение MB_QNAN. \en The third derivative with respect to t. May return MB_QNAN. double _Value ( double t ) const override; // \ru Значение функции для t \en The value of function for a given t - double _FirstDer ( double t ) const override; // \ru Первая производная по t \en The first derivative with respect to t - double _SecondDer ( double t ) const override; // \ru Вторая производная по t \en The second derivative with respect to t - double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t + double _FirstDer ( double t ) const override; // \ru Первая производная по t. Может вернуть значение MB_INFINITY. \en The first derivative with respect to t. May return MB_INFINITY. + double _SecondDer ( double t ) const override; // \ru Вторая производная по t. Может вернуть значение MB_QNAN. \en The second derivative with respect to t. May return MB_QNAN. + double _ThirdDer ( double t ) const override; // \ru Третья производная по t. Может вернуть значение MB_QNAN. \en The third derivative with respect to t. May return MB_QNAN. // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const override; @@ -97,8 +97,11 @@ public: void BreakPoints( std::vector & vBreaks, double precision = ANGLE_REGION ) const override; // \ ru Определение точек излома функции. \en The determination of function smoothness break points. private: - void SetOriginAndDerive(); - double GetCurveParam( double & t, bool ext ) const; + static MbResultType CheckCurve( const MbCurve3D & curve, size_t coord ); + void SetOriginAndDerive(); + double GetCurveParam( double & t, bool ext ) const; + double GetFuncParam( double w ) const; + void ExploreFunctionDerivatives( double & t, bool ext, double * fir, double * sec, double * thr ) const; void operator = ( const MbCurveCoordinate & ); // \ru Не реализовано \en Not implemented DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveCoordinate ) diff --git a/C3d/Include/function.h b/C3d/Include/function.h index d1232c5..0c150ba 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -11,7 +11,8 @@ #define __FUNCTION_H -#include +#include +#include #include #include #include diff --git a/C3d/Include/gcm_api.h b/C3d/Include/gcm_api.h index c4e2c85..b127556 100644 --- a/C3d/Include/gcm_api.h +++ b/C3d/Include/gcm_api.h @@ -1,8 +1,7 @@ ////////////////////////////////////////////////////////////////////////////////////////// /** - \file - \brief \ru Программный интерфейс 3D решателя геометрических ограничений. - \en Program interface of three-dimensional geometric constraints solver. \~ + \file \brief \ru Программный интерфейс 3D решателя геометрических ограничений. + \en Program interface of three-dimensional geometric constraints solver. \~ */ ////////////////////////////////////////////////////////////////////////////////////////// @@ -10,11 +9,11 @@ #define __GCM_API_H #include -// -#include #include #include +#include + class reader; class writer; @@ -99,12 +98,12 @@ GCM_FUNC(bool) GCM_ReadSystem( GCM_system gSys, reader & in ); GCM_FUNC(bool) GCM_WriteSystem( GCM_system gSys, writer & out ); //---------------------------------------------------------------------------------------- -/// Query to interrupt calculations +/// Query to interrupt calculations. //--- typedef bool ( *GCM_abort )(); //---------------------------------------------------------------------------------------- -/** \brief \ru Назначить функцию прерывания вычислений +/** \brief \ru Назначить функцию прерывания вычислений. \en Set a callback to interrupt the calculations. \~ \param[in] gSys - \ru Система ограничений. \en System of constraints. \~ @@ -1172,6 +1171,7 @@ GCM_FUNC(bool) GCM_SetJournal( GCM_system gSys, const char * fName ); /** \} */ // GCM_3D_API struct GCT_diagnostic_pars; + //---------------------------------------------------------------------------------------- /* It's used for testing purposes only. diff --git a/C3d/Include/gcm_geom.h b/C3d/Include/gcm_geom.h index da5e84b..5697d5f 100644 --- a/C3d/Include/gcm_geom.h +++ b/C3d/Include/gcm_geom.h @@ -1,8 +1,12 @@ ////////////////////////////////////////////////////////////////////////////////////////// /** - \file - \brief \ru Геометрические типы данных - \en Geometrical types of data \~ + \file \brief \ru Геометрические типы данных C3D Solver. + \en Geometrical types of data C3D Solver. \~ + \details \ru Геометрические типы данных для объектно-ориентированной части + программного интерфейса C3D Solver. См. также базовую часть + интерфейса . + \en Geometry data types for the object-oriented part of C3D Solver API. + See also file that represents basic part of the C3D Solver API. \~ */ ////////////////////////////////////////////////////////////////////////////////////////// @@ -31,8 +35,6 @@ typedef GCM_geom MtPatternId; typedef GCM_g_type MtGeomType; typedef GCM_c_type MtMateType; -/** \} */ - //---------------------------------------------------------------------------------------- /** \brief \ru Геометрический объект. \en Geometrical object. \~ \details \ru Геометрический объект этого типа данных, характеризуется матрицей @@ -91,7 +93,7 @@ private: // It will be removed ... use GetPlacement instead. /* ItGeom as pointer type. */ -typedef ItGeom * ItGeomPtr; +typedef ItGeom * ItGeomPtr; //---------------------------------------------------------------------------------------- // \ru Трансформация из стандартного положения \en Transformation from the standard position @@ -115,12 +117,11 @@ inline void ItGeom::GetTransMatrix( MbMatrix3D & mat ) const } //---------------------------------------------------------------------------------------- -// Internal data types +// Internal data types forward declaration. //--- struct MtUnifiedGeom; class MtParGeom; - //---------------------------------------------------------------------------------------- /** \brief \ru Геометрический объект, аргумент геометрического ограничения. \en Geometric object, argument of geometric constraint. \~ @@ -141,9 +142,12 @@ public: public: /// \ru Тип геометрии, которому удовлетворяет объект. \en Type of geometry which is satisfied by the object. - MtGeomType GeomType() const; + GCM_g_type GeomType() const; + /// \ru Выдать данные геометрии в унифицированной форме записи. \en Get the uniform geometry data record. + GCM_g_record GeomRecord() const; /// \ru Выдать трансформацию объекта. \en Get transformation of the object. MbMatrix3D & GetTransMatrix( MbMatrix3D & ) const; + /// \ru Определить, является ли объект пустым. \en Define whether the object is empty. bool IsNull() const; @@ -152,7 +156,7 @@ public: /* Assigning methods MtGeomVariant & Assign( const MtGeomVariant & ); MtGeomVariant & Assign( MtParGeom & ); MtGeomVariant & Assign( const MtParGeom & ); - MtGeomVariant & Assign( MtGeomType, const MbCartPoint3D & org, const MbVector3D & zAxis + MtGeomVariant & Assign( GCM_g_type, const MbCartPoint3D & org, const MbVector3D & zAxis , const MbVector3D & xAxis, double r1 = 0.0, double r2 = 0.0 ); template MtGeomVariant & Assign( GeomDS * ); @@ -423,7 +427,7 @@ inline void MtMatingGeometry::_SetLCSMatrix( const MbMatrix3D & gSpan ) } //---------------------------------------------------------------------------------------- -// \ru Задать пустой объект \en Specify an empty object +// \ru Задать пустой объект. \en Specify an empty object. //--- inline void MtMatingGeometry::SetNull() { @@ -434,15 +438,21 @@ inline void MtMatingGeometry::SetNull() } //---------------------------------------------------------------------------------------- -// \ru Конвертировать структуру MtMatingGeometry в аргумент ограничения \en Convert the structure MtMatingGeometry to the argument of constraint +/** \brief \ru Конвертировать структуру MtMatingGeometry в аргумент ограничения. + \en Convert the structure MtMatingGeometry to the argument of constraint. \~ + \param[in] cVer - \ru Версия ограничений, для которого будет применяться аргумент. + \en The version of constraint using the resulting argument. \~ +*/ //--- -GCM_FUNC(MtGeomVariant) GeomArgument( const MtMatingGeometry &, VERSION constraintVersion ); +GCM_FUNC(MtGeomVariant) GeomArgument( const MtMatingGeometry &, VERSION cVer ); + +/** \} */ //---------------------------------------------------------------------------------------- // //--- -typedef ItGeom * IfGeomPtr; // deprecated -typedef const ItGeom * IfConstGeomPtr; // deprecated +typedef ItGeom * IfGeomPtr; // deprecated. +typedef const ItGeom * IfConstGeomPtr; // deprecated. #endif // __IT_GEOM_H diff --git a/C3d/Include/gcm_types.h b/C3d/Include/gcm_types.h index e4d26fe..66e1f80 100644 --- a/C3d/Include/gcm_types.h +++ b/C3d/Include/gcm_types.h @@ -16,7 +16,7 @@ class MbPlacement3D; // Local coordinate system that represents position an struct MtSystemHolder {}; // An internal data object that provides the constraint system. #define GCM_ID_TYPE 1 // 1 - MtObjectId is a pod struct, 0 - MtObjectId is simple integer. -#define GCM_SYSTEM_TYPE 1 // 1 - GCM_system is ptr , 0 - GCM_system is a ptr. +#define GCM_SYSTEM_TYPE 0 // 1 - GCM_system is ptr , 0 - GCM_system is a ptr. #if ( GCM_ID_TYPE == 1 ) diff --git a/C3d/Include/instance_item.h b/C3d/Include/instance_item.h index 272a247..c9b0db9 100644 --- a/C3d/Include/instance_item.h +++ b/C3d/Include/instance_item.h @@ -109,6 +109,9 @@ public : // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ bool GetItems( MbeSpaceType type, const MbMatrix3D & from, RPArray & items, SArray & matrs ) override; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + std::vector> & items, std::vector & matrs ) override; // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const override; // \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. diff --git a/C3d/Include/io_buffer.h b/C3d/Include/io_buffer.h index 76c6367..8417469 100644 --- a/C3d/Include/io_buffer.h +++ b/C3d/Include/io_buffer.h @@ -137,6 +137,8 @@ namespace io skippedUnknAttr = 0x08000000L, /// \ru Файл нулевой длины. \en Zero-length file. emptyFile = 0x10000000L, + /// \ru Лицензия не найдена. \en License not found. + licenseMissing = 0x20000000L, /// \ru Все ошибки. \en All errors. //AR all = 0xffffffe0L allMask = 0xffffffffL diff --git a/C3d/Include/io_tape.h b/C3d/Include/io_tape.h index ea668dc..a931227 100644 --- a/C3d/Include/io_tape.h +++ b/C3d/Include/io_tape.h @@ -1,8 +1,8 @@ //////////////////////////////////////////////////////////////////////////////// /** \file - \brief \ru Сериализация: чтение и запись потоковых классов. - \en Serialization: reading and writing of stream classes. \~ + \brief \ru Сериализация:. Утилиты чтения и записи потоковых классов. + \en Serialization: utilities for reading and writing of stream classes. \~ */ //////////////////////////////////////////////////////////////////////////////// @@ -15,399 +15,16 @@ /// \en Compile with the given preprocessor define for control of reading/writing char* and TCHAR* only via ReadTCHAR/WriteTCHAR(), not via illegally operator << and >>. //#define DISABLE_RWTCHAR - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Классы, для которых при записи и чтении точно известен тип, \en Classes for which the type is exactly known while reading and writing -// \ru могут записываться в поток и читаться из потока с помощью \en can be written to the stream and read from the stream using -// \ru операторов << и >>, \en << and >> operators. -// \ru Это, например, классы лежащие в массиве SArray \en They are, for instance, classes contained in array SArray -// -// \ru Для таких объектов необходимо в описании класса установить : \en For such objects one should set in the class definition: -// \ru KNOWN_OBJECTS_RW_REF_OPERATORS( Class ) - для работы со ссылками и объектами класса \en KNOWN_OBJECTS_RW_REF_OPERATORS( Class ) - for work with references and class objects -// \ru KNOWN_OBJECTS_RW_PTR_OPERATORS( Class ) - для работы с указателями на объекты класса \en KNOWN_OBJECTS_RW_PTR_OPERATORS( Class ) - for work with pointers to class objects -// -// \ru и определить тела самих операторов : \en and define the solids of operators: -// -// \ru -- для ссылок \en -- for references -// inline reader& operator >> ( reader& in, Class& ref ) { -// return in >> ref. >> ref.... ; -// } -// -// writer& operator << ( writer& out, const Class& ref ) { -// return out << ref. << ref. ... ; -// } -// -// \ru -- для указателей \en -- for pointers -// inline reader& operator >> ( reader& in, Class*& ptr ) { -// ptr = new Class(...); -// return in >> ptr-> >> ptr->.... ; -// } -// -// writer& operator << ( writer& out, const Class* ptr ) { -// return out << ptr-> << ptr-> ... ; -// } -// -// \ru Классы, для которых при записи и чтении тип не известен. \en Classes for which the type is unknown while writing and reading. -// \ru Для описания такого класса Class как поточного в общем случае требуется : \en There are the following requirements for description of such class Class as a stream class: -// \ru -- Наследовать класс от TapeBase напрямую или через своих предков \en -- Inherit the class from TapeBase directly or via ancestors -// \ru Примечание : \en Note: -// \ru Если класс наследует более чем от одного поточного класса, \en If the class is inherited from more than one stream class, -// \ru то его предки !!!обязательно!!! должны наследовать от TapeBase \en then its parents MUST be inherited from TapeBase -// \ru виртуально, т.е. \en virtually, i.e. -// class A : public virtual TapeBase { -// ... -// }; -// -// class B : public virtual TapeBase { -// ... -// }; -// -// class C : public A, public B { -// ... -// }; -// -// \ru При этом классы A,B равно как и C нельзя укладывать в SArray, \en At the same time classes A,B cannot be put to array SArray, as well as class C, -// \ru поскольку они неявно содержат указатель на виртуальную базу \en since they implicitly contain a pointer to the virtual base -// -// \ru -- В декларации класса установить : \en -- Set in declaration of the class: -// \ru DECLARE_PERSISTENT_CLASS( Class ) - если Class не имеет поточных предков \en DECLARE_PERSISTENT_CLASS( Class ) - if Class does not have stream ancestors -// -// \ru -- В любом *.cpp файле установить : \en -- Set in any *.cpp file: -// \ru IMP_PERSISTENT_CLASS( AppID, Class ); - требуется написание конструктора \en IMP_PERSISTENT_CLASS( AppID, Class ); - the constructor implementation is required -// -// \ru -- Описать тела функций : \en -- Describe the solids of functions: -// void Class::Read( reader& in, Class* obj ); -// void Class::Write( writer& out, const Class* obj ); -// -// \ru Если Class не содержит своих полей данных, которые необходимо \en If Class does not contain its own data fields which should -// \ru писать в поток и читать оттуда, то вместо \en be written to stream and be read from stream, then instead of -// \ru IMP_PERSISTENT_CLASS следует применять \en IMP_PERSISTENT_CLASS one should use -// IMP_PERSISTENT_CLASS_FROM_BASE( Class, Base ), -// \ru при этом не надо определять функции Class::Read и Class::Write \en at that the functions Class::Read and Class::Write don't have to be defined -// -// \ru Если Class абстрактный -- применять \en If Class is abstract - apply -// IMP_A_PERSISTENT_CLASS( Class ); -// -// \ru Если Class не наследует ни от кого кроме TapeBase и плюс к этому \en If Class does not inherit from any class except TapeBase and, in addition, -// \ru не имеет полей данных для записи, применять : \en does not have data fields for writing, apply: -// \ru в cpp-файле \en in cpp-file -// \ru для абстрактного -- IMP_AWD_PERSISTENT_CLASS( Class ); \en for the abstract one -- IMP_AWD_PERSISTENT_CLASS( Class ); -// \ru для обычного -- IMP_WD_PERSISTENT_CLASS( Class ); \en for the ordinary one -- MP_WD_PERSISTENT_CLASS( Class ); -// \ru примечание : WD - Without Data \en note: WD - Without Data -// -// \ru Если Class наследует более чем от одного TapeBase'а \en If Class inherit from more than one TaperBase class, -// \ru наследование от него должно быть virtual'ным, например : \en the inheritance from it should be virtual, for instance: -// class first : virtual public TapeBase { -// ... -// DECLARE_PERSISTENT_CLASS( AppID, first ); -// }; -// -// class second : virtual public TapeBase { -// ... -// DECLARE_PERSISTENT_CLASS( AppID, second ); -// }; -// -// class third : public first, public second { -// ... -// DECLARE_PERSISTENT_CLASS( AppID, third ); -// }; -// IMP_PERSISTENT_CLASS( AppID, first ) -// IMP_PERSISTENT_CLASS( AppID, second ) -// IMP_PERSISTENT_CLASS( AppID, third ) -// \ru + функции чтения - записи \en + functions of reading-writing -// \ru + соответствующие конструкторы чтения \en + the corresponding reading constructors -// -// \ru Если Class template'ный, то для описания класса поточным требуется : \en If Class is a template class, then the following is required for definition the class as a stream class: -// \ru -- Наследовать template от TapeBase \en -- Inherit template from TapeBase -// -// \ru -- В декларации template'а установить : \en -- Set in the declaration of template : -// DECLARE_T_PERSISTENT_CLASS( Templ, Arg ); -// \ru где Templ - имя самого template'а \en where Templ is the name of template -// \ru Arg - имя формального template'ного аргумента \en Arg - the name of formal argument of template -// -// \ru -- В этом же h-файле вне декларации template'а установить \en -- Set in the same h-file outside the template declaration -// IMP_T_PERSISTENT_OPS( Templ ); -// -// \ru -- В этом же h-файле вне декларации template'а описать тела функций : \en -- In the same h-file outside the template declaration describe solids of functions: -// template -// void Templ::Read( reader& in, Templ* obj ); -// template -// void Templ::Write( writer& out, const Templ* obj ); -// \ru где \en where -// \ru Arg - формальный аргумент \en Arg - formal argument -// -// \ru -- В любом(ых) cpp-файле(ах) установить для каждого применения template'а : \en -- In any cpp-files set for each use of template: -// IMP_T_PERSISTENT_CLASS( Templ, Class ); -// \ru где \en where -// \ru Class - имя класса с которым применяется template ( фактический аргумент ) \en Class - name of the class the template is used with (the actual argument) -// -// \ru Примечание : для классов List, DList, SArray, PArray, Array2 все действия \en Note: for classes List, DList, SArray, PArray, Array2 all the instructions -// \ru уже выполнены, кроме последнего пункта. \en already applied except the last one. -// -// -// \ru По поводу функции Class::Read( reader& in, Class* obj ) рекомендуется \en Regarding function Class::Read( reader& in, Class* obj ) it is recommended -// \ru обратить внимание на : \en to pay attention to: -// -// \ru 1.Поля данных базового класса самостоятельно читать не нужно, вместо этого \en 1.Data fields of the base class don't require any special code to be read, instead of it -// \ru нужно вызвать функцию ReadBase( out, (Base*)obj ). \en one should call function ReadBase( out, (Base*)obj ). -// \ru Вызывать ее желательно в голове функции Class::Read \en It is desirable to call it in the head of function Class::Read -// \ru Обратите внимание на преобразование типа (Base*)obj ! \en Pay attention to the conversion like (Base*)obj ! -// -// \ru 2.Функция Class::Read декларирована статической (static), поэтому она не имеет \en 2. Function Class::Read is declared as static so it has no -// \ru указателя this ==> не пытайтесь делать что-нибудь типа : \en 'this' pointer ==> don't try to do something like: -// in >> field -// \ru правильно : \en the correct variant is: -// in >> obj->field; -// -// \ru По поводу функции Class::Write( writer& out, const Class* obj ) рекомендуется \en As for function Class::Write( writer& out, const Class* obj ), it is recommended -// \ru обратить внимание на : \en to pay attention to: -// -// \ru 1.Поля данных базового класса самостоятельно писать не нужно, вместо этого \en 1.Data fields of the base class don't require any special code to be written, instead of it -// \ru нужно вызвать функцию WriteBase( out, (const Base*)obj ). \en one should call function WriteBase( out, (const Base*)obj ). -// \ru Вызывать ее желательно в голове функции Class::Write \en It is desirable to call it in the head of function Class::Write -// \ru Обратите внимание на преобразование типа (const Base*)obj ! \en Pay attention to the conversion like (const Base*)obj ! -// -// \ru 2.Функция Write декларирована статической (static), поэтому она не имеет \en 2.Function Class::Write is declared as static so it has no -// \ru указателя this ==> не пытайтесь делать что-нибудь типа : \en 'this' pointer ==> don't try to do something like: -// out << field -// \ru правильно : \en the correct variant is: -// out << obj->field; -// -// -// \ru По поводу поддержки версий : \en As for versions support: -// \ru 1. При записи - \en 1. While reading - -// \ru iobuf имеет статическое поле данных iobuf_defaultVersionCont - контейнер версии \en iobuf has static data field iobuf_defaultVersionCont - the version container -// \ru и статическую функцию void iobuf::SetDefaultVersion( VERSION ); \en and the static function void iobuf::SetDefaultVersion( VERSION); -// \ru которую можно вызывать в любом месте программы, например : \en which can be called in any place of the program, for instance: -// iobuf::SetDefaultVersion( 192 ); -// \ru все потоки, которые будут записываться после этого, будут записывать этот \en all the streams which will be written after this will write this -// \ru номер в качестве версии \en number as a version -// \ru 2. При чтении - \en 2. While reading - -// \ru номер версии, записанный в поток возвращается функцией \en the version number written to the stream is returned by function -// VERSION in.MathVersion(), -// \ru где in - экземпляр потока \en where in - is the stream instance -// -//////////////////////////////////////////////////////////////////////////////// - -#include +#include #include #include -#include -#include -#include #include -#include -#include #include #include #include -#include #include -#include -#include -#include -#include -#include #include -#include - -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif - #include -#include - -//---------------------------------------------------------------------------------------- -// \ru Предварительное объявление классов чтения/записи. -// \en The forward declaration of the read/write classes. \~ -// --- -class TapeManager; -class reader; -class writer; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Типы регистрации объектов. - \en Types of objects registration. \~ - \details \ru Типы регистрации потоковых объектов. \n - \en Types of stream objects registration. \n \~ - \ingroup Base_Tools_IO -*/ //--- -enum RegistrableRec { - noRegistrable, ///< \ru Нерегистрируемый объект. \en Unregistrable object. - registrable ///< \ru Регистрируемый объект. \en Registrable object. -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Типы инициализации объектов. - \en The objects initialization types. \~ - \details \ru Типы регистрации потоковых объектов. \n - \en Types of stream objects registration. \n \~ - \ingroup Base_Tools_IO -*/ //--- -enum TapeInit { - tapeInit ///< \ru По умолчанию. \en By default. -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Упакованное имя класса. - \en Packed class name. \~ - \details \ru Упакованное имя одного класса - для набора массива потоковых классов в TapeClass. \n - \en Packed name of one class - for array of stream classes in TapeClass. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS ClassDescriptor -{ -protected: - uint16 val; ///< \ru Хэш имени класса. \en The class name hash. - MbUuid appID_; ///< \ru Дополнительный идентификатор приложения. \en Additional application identifier. -private: - /// \ru Признак записи appID. \en AppID record flag. - static const uint16 rwIdFlag; - -public: - /// \ru Конструктор. \en Constructor. - ClassDescriptor(); - /// \ru Конструктор по хэшу. \en Constructor by hash. - ClassDescriptor( uint16 v ); - /// \ru Конструктор по имени. \en Constructor by name. - ClassDescriptor( const char * name ); - /// \ru Конструктор по хэшу. \en Constructor by hash. - ClassDescriptor( uint16 v, const MbUuid & appID ); - /// \ru Конструктор по имени. \en Constructor by name. - ClassDescriptor( const char * name, const MbUuid & appID ); - /// \ru Конструктор по хэшу. \en Constructor by hash. - ClassDescriptor( const ClassDescriptor & other ); - - /// \ru Оператор присваивания. \en An assignment operator. - ClassDescriptor & operator = ( const ClassDescriptor & other ); - - /// \ru Оператор равенства. \en The equality operator. - bool operator == ( const ClassDescriptor & other ) const; - /// \ru Оператор неравенства. \en The inequality operator. - bool operator != ( const ClassDescriptor & other ) const; - /// \ru Оператор сравнения. \en Comparison operator. - bool operator < (const ClassDescriptor & other ) const; - /// \ru Оператор сравнения. \en Comparison operator. - bool operator > ( const ClassDescriptor & other ) const; -#ifdef C3D_DEBUG - /// \ru Оператор доступа. \en An access operator. - operator uint16() const { return val; } -#endif - /// \ru Оператор записи. \en Write operator. - void Write( writer & out ); - /// \ru Оператор чтения. \en Read operator. - bool Read( reader & in ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый класс для потоковых классов. - \en Base class for stream classes. \~ - \details \ru Базовый класс для потоковых классов. \n - \en Base class for stream classes. \n \~ - \ingroup Base_Tools_IO -*/ // --- -#ifndef ENABLE_MEMORY_LEAKS_CHECK -class MATH_CLASS TapeBase { -#else -class MATH_CLASS TapeBase : virtual public c3d::MemoryLeaksVerifiable { -#endif -private: - mutable use_count_type m_countRegistrable; ///< \ru Счетчик ссылок регистрируемого объекта. \en Number of usages of the registrable object. - -public: - /// \ru Конструктор. \en Constructor. - TapeBase( RegistrableRec regs = noRegistrable ); - /// \ru Конструктор копирования \en Copy-constructor. - TapeBase( const TapeBase & ); - /// \ru Деструктор. \en Destructor. - virtual ~TapeBase(); - -public: - /// \ru Является ли потоковый класс регистрируемым. \en Whether the stream class is registrable. - RegistrableRec GetRegistrable() const; - /// \ru Установить состояние регистрации потокового класса. \en Set the state of registration of the stream class. - void SetRegistrable( RegistrableRec regs = registrable ) const; - /// \ru Получить дескриптор класса - //virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const { return ClassDescriptor( ::pureName(typeid(*this).name()) ); } - virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const = 0; - /// \ru Получить имя класса. \en Get the class name. - virtual const char * GetPureName( const VersionContainer & ) const; - /// \ru Принадлежит ли объект к регистрируемому семейству. \en Whether the object belongs to a registrable family. - virtual bool IsFamilyRegistrable() const; - -private: - /// \ru Функция-пустышка для обеспечения полиморфизма данного класса и его наследников. \en Dummy function for providing polymorphism of the given class and its descendants. - virtual void dummy(); // I need this to make class polymorphic - /// \ru Оператор присваивания \en Assignment operator - void operator = ( const TapeBase & other ); -}; - - -//---------------------------------------------------------------------------------------- -/// \ru Шаблон функции создания нового экземпляра. \en Template of function of a new instance creation. \~ \ingroup Base_Tools_IO -//--- -typedef TapeBase * (CALL_DECLARATION * BUILD_FUNC) ( void ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Шаблон функции преобразования. - \en Template of conversion function. \~ - \details \ru Шаблон функции преобразования из указателя на TapeBase к указателю на класс. \n - \en Template of function of conversion from a pointer to TapeBase to a pointer to the class. \n \~ - \ingroup Base_Tools_IO -*/ //--- -typedef void * (CALL_DECLARATION * CAST_FUNC) ( const TapeBase * ); - -//---------------------------------------------------------------------------------------- -/**\ru Шаблон функции чтения экземпляра. - \en Template of instance reading function. \~ - \ingroup Base_Tools_IO -*/ //--- -typedef void (CALL_DECLARATION * READ_FUNC) ( reader & in, void * /*obj*/ ); - -//---------------------------------------------------------------------------------------- -/// \ru Шаблон функции записи экземпляра. \en Template of instance writing function. \~ \ingroup Base_Tools_IO -//--- -typedef void (CALL_DECLARATION * WRITE_FUNC) ( writer & out, void * /*obj*/ ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru "Обертка" для одного потокового класса. - \en "Wrapper" for one stream class. \~ - \details \ru "Обертка" для одного потокового класса ( не экземпляра! ). - Xранит упакованное имя класса и адреса функций, необходимых при чтении/записи. \n - \en "Wrapper" for one stream class ( not instance! ). - Stores packed class name and addresses of functions necessary while reading/writing. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS TapeClass { -protected: - ClassDescriptor hashValue; ///< \ru Упакованное имя класса. \en Packed class name. - BUILD_FUNC _builder; ///< \ru Функция создания нового экземпляра. \en Functions of a new instance creation. - CAST_FUNC _caster; ///< \ru Функция преобразования от TapeBase к указателю на класс. \en Function of conversion from TapeBase to a pointer to a class. - READ_FUNC _reader; ///< \ru Функция чтения. \en Read function. - WRITE_FUNC _writer; ///< \ru Функция записи. \en Write function. - -public: - /// \ru Конструктор. \en Constructor. - /// \ru Конструктор. \en Constructor. - TapeClass( const char * name, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); - TapeClass( const char * name, MbUuid appID, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); - /// \ru Деструктор. \en Destructor. - virtual ~TapeClass(); - /// \ru Получить упакованное имя класса. \en Get the packed class name. - ClassDescriptor GetPackedClassName() const; - /// \ru Получить упакованное имя класса для записи с учетом версии. \en Get the packed class name for writing subject to the version. - virtual ClassDescriptor GetPackedClassNameForWrite( VERSION ) const; - - friend class TapeManager; - friend struct TapeClassContainer; - -OBVIOUS_PRIVATE_COPY( TapeClass ) -}; //---------------------------------------------------------------------------------------- @@ -523,236 +140,6 @@ OBVIOUS_PRIVATE_COPY( TapeRegistratorEx ) }; -//---------------------------------------------------------------------------------------- -/** \brief \ru Cпособы записи указателей. - \en Methods of writing pointers. \~ - \details \ru Cпособы записи указателей. \n - \en Methods of writing pointers. \n \~ - \ingroup Base_Tools_IO -*/ //--- -enum TapePointerType { - tpt_Null = 0x00, ///< \ru Нулевой указатель. \en Null pointer. - tpt_Indexed16 = 0x01, ///< \ru Индекс указателя в массиве регистрации (2 байта). \en Pointer index in the registration array (2 bytes). - tpt_Object = 0x02, ///< \ru Тело объекта. \en The object solid. - tpt_Indexed8 = 0x03, ///< \ru Индекс указателя в массиве регистрации (1 байт). \en Index of pointer in the registration array (1 byte). - tpt_Indexed32 = 0x04, ///< \ru Индекс указателя в массиве регистрации (4 байта). \en Pointer index in the registration array (4 bytes). - tpt_Indexed64 = 0x05, ///< \ru Индекс указателя в массиве регистрации (8 байт). \en Index of pointer in the registration array (8 byte). - tpt_DetachedObject = 0x06, ///< \ru Тело объекта в отдельном FileSpace. \en The object solid in separated FileSpace. - tpt_ObjectCatalog = 0x07, ///< \ru Каталог объектов в отдельном FileSpace. \en The object catalog in separated FileSpace. -}; - - -#pragma pack( push, 1 ) -//---------------------------------------------------------------------------------------- -/** \brief \ru Базовый класс потока для реализации чтения и записи. - \en The base class of the stream for implementation of reading and writing. \~ - \details \ru Базовый класс потока для реализации чтения и записи. \n - \en The base class of the stream for implementation of reading and writing. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS tape { -protected: - iobuf_Seq & buf; ///< \ru Буфер для данных. \en Buffer for data. - TapeManager & manager; ///< \ru Менеджер потоков. \en Stream manager. - uint8 level; ///< \ru Уровень вложенности при чтении/записи. \en Nesting level while reading/writing. - TapeRegistrator & registrator; ///< \ru Структура для регистрации записанных/прочитанных адресов. \en Structure for registration of written/read addresses. - mutable ProgressBarWrapper * progress; ///< \ru Индикатор прогресса. \en Progress indicator. -private: - uint8 ownBuf; ///< \ru Владеет ли буфером. \en Whether it owns the buffer. - bool ownReg; ///< \ru Признак владения регистратором. \en Whether it owns of the registrar. - -public: - /// \ru Тип объекта. \en An object type. - enum objectType { - otNull, - otIndexed, - otObject - }; - /// \ru Деструктор. \en Destructor. - virtual ~tape(); - - /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE iobuf & buffer() const; - /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE iobuf & operator()() const; - - /// \ru Получить доступ к буферу. \en Get access to the buffer. - const iobuf_Seq & GetIOBuffer() const; - /// \ru Получить доступ к буферу. \en Get access to the buffer. - iobuf_Seq & GetIOBuffer(); - - /// \ru Узнать режим работы буфера. \en Get the buffer mode. - uint8 mode() const; //AR getMode - /// \ru Установить режим работы буфера. \en Set the buffer mode. - void setMode( uint8 m ); - /// \ru Убрать состояние буфера. \en Remove the buffer state. - void clearState( io::state sub ); - /// \ru Добавить состояние буфера. \en Add the buffer state. - void setState ( io::state add ); - - /// \ru Установить текущую версию равной версии хранилища. \en Set the current version to be equal to the storage version. - void SetVersionsByStorage(); - /// \ru Вернуть главную версию (математического ядра). \en Return the main version (of the mathematical kernel). - VERSION MathVersion() const; - /// \ru Вернуть дополнительную версию (конечного приложения). \en Return the additional version (of the target application). - VERSION AppVersion( size_t ind = -1 ) const; - - /// \ru Получить доступ к контейнеру версий. \en Get access to the version container. - const VersionContainer & GetVersionsContainer() const; - /// \ru Установить версию открытого файла. \en Set the version of open file. - void SetVersionsContainer( const VersionContainer & vers ) const; - /// \ru Установить версию хранилища. \en Set the storage version. - VERSION SetStorageVersion( VERSION v ); - - /// \ru Свежий ли буфер? \en Is the buffer fresh? - int fresh() const; - /// \ru Корректно ли состояние буфера.. \en Whether the buffer state is correct. - bool good() const; - /// \ru Достигнут ли конец файла? \en Is the end of file reached? - virtual uint8 eof() const; - /// \ru Получить флаг состояния буфера. \en Get the flag of the buffer state. - virtual uint32 state() const; - /// \ru Получить текущую позицию в потоке. \en Get current position in stream - virtual io::pos tell(); - ///< \ru Зарегистрировать указатель. \en Register the pointer. - void registrate( const TapeBase * e ); - ///< \ru Отменить регистрацию указателя. \en Unregister the pointer. - void unregistrate( const TapeBase * e ); - ///< \ru Есть ли зарегистрированный объект? \en Does a registered object exist? - bool exist ( const TapeBase * e ) const; - ///< \ru Очистить массив регистрации. \en Flush the registration array. - void flushRegister (); - ///< \ru Получить количество зарегистрированных объектов. \en Get the number of registered objects. - size_t RegisteredCount() const; - ///< \ru Получить максимально возможное количество объектов для регистрации. \en Get the maximal possible number of objects for registration. - size_t GetMaxRegisteredCount() const; - ///< \ru Зарезервировать память под n объектов. \en Reserve memory for n objects. - void ReserveRegistered( size_t n ); - - /// \ru Владеем ли буфером? \en Do we own the buffer? - bool IsOwnBuffer() const; - /// \ru Установить флаг владения буфером. \en Set the flag of buffer ownership. - void SetOwnBuffer( bool own ); - - /// \ru Получить тип индекса. \en Get index type. - uint8 GetIndexType( size_t index ) const; - - /// \ru Работа с индикатором прогресса. \en Work with progress indicator. - - /// Инициализировать индикатор прогресса. \en Initialize progress indicator. - void InitProgress( IProgressIndicator * pr ); - void InitProgress( ProgressBarWrapper & pr ); - /// \ru Освободить текущий индикатор прогресса. Установить родительский индикатор прогресса, если он есть. - /// \en Release current progress indicator. Set parent progress indicator if it exists. - void ResetProgress(); - /// \ru Получить индикатор прогресса. \en Get progress indicator. - ProgressBarWrapper * GetProgress(); - /// \ru Завершить индикатор прогресса. \en End the progress indicator. - void FinishProgress(); - -protected: - /// \ru Конструктор. \en Constructor. - tape( membuf &, bool openSys, uint8 om, TapeRegistrator * , bool ownReg = false); - - /// \ru Конструктор. \en Constructor. - tape( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * , bool ownReg = false); //AR(DP) - -private: - /// \ru Открыть системный файл в соответствующем режиме (чтение или запись). \en Open the system file in the appropriate mode (reading or writing). - void init( uint8 om ); - -OBVIOUS_PRIVATE_COPY( tape ) -}; -#pragma pack( pop ) - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Поток для чтения. - \en Stream for reading. \~ - \details \ru Поток для чтения. \n - \en Stream for reading. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS reader : public virtual tape { -public: - typedef std::unique_ptr reader_ptr; -protected: - /// \ru Конструктор. \en Constructor. - reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator * reg ); - - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator & reg ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); - -public: - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader( iobuf_Seq & buf, uint16 om ); - - virtual ~reader() {} - -public: - /// \ru Создать читатель для последовательного буфера. \en Create reader for iobuf_Seq. - static reader_ptr CreateReader ( std::unique_ptr buf, uint16 om ); - /// \ru Создать читатель для буфера в памяти. \en Create reader for membuf. - static reader_ptr CreateMemReader ( membuf & sb, uint8 om ); - -public: - /// \ru Прочитать объект. \en Read the object. - TapeBase * readObject ( TapeBase * mem = 0 ); - /// \ru Прочитать указатель на объект. \en Read a pointer to the object. - TapeBase * readObjectPointer(); - - /// \ru Читать каталог объектов. \en Read the object catalog. - virtual void ReadObjectCatalog(); - /// \ru Читать объект по позиции в кластере. \en Read an object by position in cluster. - virtual TapeBase * ReadObjectByPosition ( const ClusterReference & ) { return nullptr; } - /// \ru Установить позицию чтения. \en Set reading position. - virtual bool SetReadPosition ( ClusterReference & ) { return false; } // not supported - - /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE size_t readSBytes ( void * bf, size_t len ); - - /// \ru Прочитать беззнаковое 64-разрядное целое \en Read unsigned 64-bit integer. - bool readUInt64( uint64 & ); - /// \ru Прочитать 64-разрядное целое \en Read 64-bit integer. - bool readInt64( int64 & ); - - /// \ru Прочитать байт из буфера. \en Read a byte from the buffer. - virtual int readByte(); - /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. - virtual bool readBytes( void * bf, size_t len ); - - /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree() const { return nullptr; } // not supported - - /// \ru Получить признак полного чтения текущего объекта. \en Get indicator of full reading of the current object. - /// \ru Установить признак полного чтения текущего объекта. \en Set indicator of full reading of the current object. - virtual bool IsFullRead() { return true; } // not supported - virtual void SetFullRead( bool ) {} // not supported - - /// \ru Получить ошибки чтения. \en Get reading errors. - virtual uint32 GetLastError(); - - // \ru Работа с индикатором прогресса. - // \en Work with progress indicator. - void InitProgress( IProgressIndicator * pr ); - void InitProgress( ProgressBarWrapper & pr ); - -protected: - /// \ru Читаем объект по заданной позиции. \en Read object on defined position. - virtual TapeBase * ReadDetachedObject (); - /// \ru Регистрируем объект. \en Register the object. - virtual void RegisterObject( TapeBase * obj, uint8 regId, ClusterReference ref = ClusterReference() ); - /// \ru Читаем индекс объекта. \en Read object index. - size_t ReadObjectIndex(); - -OBVIOUS_PRIVATE_COPY( reader ) -}; - - //---------------------------------------------------------------------------------------- /** \brief \ru Индикатор прогресса в области видимости для reader. \en Scoped progress indicator for reader. \~ @@ -780,240 +167,6 @@ private: void operator = ( const ScopedReadProgress & ); }; -//---------------------------------------------------------------------------------------- -/** \brief \ru Поток для чтения с возможностью чтения из нескольких FileSpaces по заданным позициям. - \en Stream for reading from several FileSpaces by given positions in clusters. \~ - \details \ru Поток для чтения с возможностью чтения из разных FileSpaces по заданным позициям. \n - \en Stream for reading from several FileSpace by given positions in clusters. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS reader_ex : public reader -{ - std::unique_ptr m_tree; - uint32 m_lastError; - bool m_fullRead; -protected: - /// \ru Конструктор. \en Constructor. - reader_ex( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om ); - -public: - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader_ex( membuf & sb, uint8 om ); - - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE reader_ex( iobuf_Seq & buf, uint16 om ); - - virtual ~reader_ex() {} - -public: - /// \ru Создать экземпляр reader_ex для последовательного буфера. \en Create reader_ex instance for sequential buffer. - static std::unique_ptr CreateReaderEx( std::unique_ptr buf, uint16 om ); - - /// \ru Создать читатель для буфера в памяти. \en Create reader for membuf. - static std::unique_ptr CreateMemReaderEx ( membuf & sb, uint8 om ); - - -public: - /// \ru Читаем каталог объектов. \en Read the object catalog. - virtual void ReadObjectCatalog(); - /// \ru Читать объект по позиции в кластере. \en Read an object by position in cluster. - virtual TapeBase * ReadObjectByPosition ( const ClusterReference& position ); - /// \ru Установить позицию чтения. \en Set reading position. - virtual bool SetReadPosition ( ClusterReference & ); - - /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree() const; - - /// \ru Признак полного чтения текущего объекта. - /// При чтении произвольного объекта может возникнуть необходимость чтения некоторых данных его родителя. - /// В этом случае объект родителя читается не полностью и имеет флаг FullRead = false. - /// \en Indicator of full reading of the current object. - /// While reading an arbitrary object there can be a need to read some data from its parent. - /// In this case the parent object is read partially and has the flag FullRead = false. - - /// \ru Получить признак полного чтения текущего объекта. \en Get indicator of full reading of the current object. - virtual bool IsFullRead(); - /// \ru Установить признак полного чтения текущего объекта. \en Set indicator of full reading of the current object. - virtual void SetFullRead( bool full ); - - /// \ru Получить ошибки чтения. \en Get reading errors. - virtual uint32 GetLastError(); - -protected: - /// \ru Читать объект по заданной позиции. \en Read object on defined position. - virtual TapeBase * ReadDetachedObject(); - /// \ru Зарегистрировать объект. \en Register the object. - virtual void RegisterObject( TapeBase * obj, uint8 regId, ClusterReference ref = ClusterReference() ); - -OBVIOUS_PRIVATE_COPY( reader_ex ) -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Поток для записи. - \en Stream for writing. \~ - \details \ru Поток для записи. \n - \en Stream for writing. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS writer : public virtual tape { -public: - typedef std::unique_ptr writer_ptr; -protected: - /// \ru Конструктор. \en Constructor. - writer ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator & reg ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer ( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); - -public: - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer ( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer ( iobuf_Seq & buf, uint16 om ); - - virtual ~writer() {} - -public: - /// \ru Создать писатель для последовательного буфера. \en Create writer for iobuf_Seq. - static writer_ptr CreateWriter( std::unique_ptr buf, uint16 om ); - /// \ru Создать писатель для буфера в памяти. \en Create writer for membuf. - static writer_ptr CreateMemWriter( membuf & sb, uint8 om ); - -public: - /// \ru Записать объект. \en Write the object. - void writeObject( const TapeBase * ); - /// \ru Записать указатель на объект. \en Write the pointer to the object. - void writeObjectPointer( const TapeBase * ); - - /// \ru Записать дерево модели. \en Write the model tree. - virtual void WriteModelCatalog(); - /// \ru Выдать следующую позицию записи. \en Get next writing position. - virtual ClusterReference GetNextWritePosition () { return ClusterReference(); } // not supported - - /// \ru Записать байт в буфер. \en Write the byte to the buffer. - virtual void writeByte ( uint8 ch ); - /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. - virtual void writeBytes ( const void * bf, size_t len ); - /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE size_t writeSBytes( const void * bf, size_t len ); - /// \ru Записать беззнаковое 64-разрядное целое. \en Write unsigned 64-bit integer. \~ \return \ru Возвращает количество записанных байт. \en Returns the number of written bytes. \~ - void writeUInt64( const uint64 & val ); - /// \ru Записать 64-разрядное целое. \en Write 64-bit integer. \~ \return \ru Возвращает количество записанных байт. \en Returns the number of written bytes. \~ - void writeInt64 ( const int64 & val ); - - // \ru Запись CHAR строки в поток (кодировка ANSI, русская локаль). \en Writing CHAR string to the stream. (ANSI coding, Russian locale). - writer & __writeChar ( const char * s ); - // \ru Запись WCHAR строки в поток (в потоке хранится как UTF-16). \en Writing WCHAR string to the stream (stored in the stream as UTF-16). - writer & __writeWchar( const TCHAR * s ); - // \ru Запись WCHAR строки в поток (в потоке хранится как UTF-16). \en Writing WCHAR string to the stream (stored in the stream as UTF-16). - writer & __writeWcharT( const wchar_t * s ); - // \ru Длина записи WCHAR строки в поток (в потоке хранится как UTF-16). \en Length of WCHAR string in the stream (stored in the stream as UTF-16). - size_t __lenWchar( const TCHAR * s ); - - /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree() const { return nullptr; } // not supported - -protected: - /// \ru Записать объект и тип. \en Write the object and type. - virtual void WriteObjectAndType ( const TapeBase * ); - /// \ru Зарегистрировать объект. \en Register the object. - virtual void RegisterObject ( const TapeBase * ); - /// \ru Завершить запись объекта. \en Finish writing the object. - virtual void EndWriteObject ( const TapeBase * ); - /// \ru Добавить ссылку на объект в каталог. \en Add reference to the object to the object catalog. - virtual void UpdateObjectCatalog ( const TapeBase * , const ClusterReference & ); - /// \ru Является ли объект регистрируемым. \en Whether the object is registrable. - virtual bool IsRegistrable( const TapeBase * mem ); - /// Записать индекс объекта - void WriteObjectIndex ( size_t index ); - -OBVIOUS_PRIVATE_COPY( writer ) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Поток для записи в разные FileSpaces. - \en Stream for writing to several FileSpaces. \~ - \details \ru Поток для записи в разные FileSpaces. \n - \en Stream for writing to several FileSpaces. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS writer_ex : public writer -{ - std::unique_ptr m_tree; - ClusterReference m_catalogRef; -protected: - /// \ru Конструктор. \en Constructor. - writer_ex ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om ); - -public: - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer_ex ( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE writer_ex ( iobuf_Seq & buf, uint16 om ); - - virtual ~writer_ex() {} - -public: - /// \ru Создать писатель для последовательного буфера. \en Create writer for iobuf_Seq. - static std::unique_ptr CreateWriterEx( std::unique_ptr buf, uint16 om ); - /// \ru Создать писатель для буфера в памяти. \en Create writer for membuf. - static std::unique_ptr CreateMemWriterEx( membuf & sb, uint8 om ); - -public: - /// \ru Записать дерево модели. \en Write the model tree. - virtual void WriteModelCatalog(); - /// \ru Выдать следующую позицию записи. \en Get next writing position. - virtual ClusterReference GetNextWritePosition (); - /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree () const; - -protected: - /// \ru Записать объект и тип. \en Write the object and type. - virtual void WriteObjectAndType ( const TapeBase * ); - /// \ru Зарегистрировать объект. \en Register the object. - virtual void RegisterObject ( const TapeBase * ); - /// \ru Завершить запись объекта. \en Finish writing the object. - virtual void EndWriteObject ( const TapeBase * ); - /// \ru Добавить ссылку на объект в каталог. \en Add reference to the object to the object catalog. - virtual void UpdateObjectCatalog ( const TapeBase *mem, const ClusterReference& ref ); - /// \ru Является ли объект регистрируемым. \en Whether the object is registrable. - virtual bool IsRegistrable( const TapeBase * mem ); - -OBVIOUS_PRIVATE_COPY( writer_ex ) -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Поток для чтения и записи. - \en Stream for reading and writing. \~ - \details \ru Поток для чтения и записи. \n - \en Stream for reading and writing. \n \~ - \ingroup Base_Tools_IO -*/ // --- -class MATH_CLASS rw : public writer, public reader { -public: - typedef std::unique_ptr rw_ptr; -public: - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. - DEPRECATE_DECLARE rw( membuf & sb, uint8 om ); - - /// \ru Создать читатель/писатель для буфера в памяти. \en Create reader/writer for membuf. - static rw_ptr CreateMemWriter( membuf & sb, uint8 om ); - - /// \ru Конструктор. \en Constructor. - rw( iobuf & buf, uint16 om ); - - virtual ~rw() {} - -private: - /// \ru Конструктор. \en Constructor. - rw( iobuf_Seq & sb, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); - -OBVIOUS_PRIVATE_COPY( rw ) -}; - //---------------------------------------------------------------------------------------- /** \brief \ru Менеджер потоков. @@ -1150,728 +303,6 @@ void WriteVBase( writer & out, const Base * base ) } -//---------------------------------------------------------------------------------------- -/** - \brief \ru Дружественные операторы чтения и записи указателей и ссылок. - \en Friend operators of reading and writing of pointers and references. \~ - \ingroup Base_Tools_IO -*/ -// --- -#define DECLARE_PERSISTENT_OPS( Class ) \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ) { \ - in.readObject( dynamic_cast(&ref) ); \ - return in; \ - } \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ) { \ - ptr = dynamic_cast( in.readObjectPointer() ); \ - return in; \ - } \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, const Class *& ptr ) \ - { \ - ptr = dynamic_cast( in.readObjectPointer() ); \ - return in; \ - } \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ) { \ - out.writeObject( dynamic_cast(&ref) ); \ - return out; \ - } \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ) { \ - out.writeObjectPointer( dynamic_cast(ptr) ); \ - return out; \ - } \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { \ - out.writeObject( dynamic_cast(&ref) ); \ - return out; \ - } \ - friend inline writer & CALL_DECLARATION operator << ( writer& out, Class * ptr ) { \ - out.writeObjectPointer( dynamic_cast(ptr) ); \ - return out; \ - } - -/** - \brief \ru Объявление операторов чтения и записи указателей и ссылок. - \en Declaration of operators of reading and writing of pointers and references. \~ - \ingroup Base_Tools_IO -*/ -// --- -#define DECLARE_PERSISTENT_OPS_B( Class ) \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, const Class *& ptr ); \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ); \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ); \ - friend inline writer & CALL_DECLARATION operator << ( writer & out, Class & ref ); \ - friend inline writer & CALL_DECLARATION operator << ( writer& out, Class * ptr ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Операторы чтения и записи указателей и ссылок. - \en Operators of reading and writing of pointers and references. \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMPL_PERSISTENT_OPS( Class ) - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Операторы чтения указателей и ссылок для класса без записи. - \en Operators of reading pointers and references for a class without writing. \~ - \ingroup Base_Tools_IO -*/ -// --- -#define DECLARE_PERSISTENT_RO_OPS( Class ) \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ) { \ - in.readObject( dynamic_cast(&ref) ); \ - return in; \ - } \ - friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ) { \ - ptr = dynamic_cast( in.readObjectPointer() ); \ - return in; \ - } - -//---------------------------------------------------------------------------------------- -/// \ru Функции чтения и записи. \en Functions of reading and writing. \~ \ingroup Base_Tools_IO -// --- -#define DECLARE_PERSISTENT_FUNCS( Class ) \ - public: \ - static void Read ( reader & in, Class * obj ); \ - static void Write( writer & out, const Class * obj ) - -//---------------------------------------------------------------------------------------- -/// \ru Функции чтения для класса без записи. \en Function of reading for class without writing. \~ \ingroup Base_Tools_IO -// --- -#define DECLARE_PERSISTENT_RO_FUNCS( Class ) \ - public: \ - static void Read( reader & in, Class * obj ) - -//------------------------------------------------------------------------------ -/// \ru Функции получения дескриптора класса. \~ \ingroup Base_Tools_IO -// --- -#define DECLARE_CLASS_DESC_FUNC( Class ) \ - public: \ - ClassDescriptor GetClassDescriptor( const VersionContainer & ) const override; - -//------------------------------------------------------------------------------ -/// \ru Функции получения дескриптора (хэш + APP UID) класса. \~ \ingroup Base_Tools_IO -// --- -#define IMP_CLASS_DESC_FUNC( AppID, Class ) \ - ClassDescriptor Class::GetClassDescriptor( const VersionContainer & v) const \ - { return ClassDescriptor( GetPureName(v), AppID ); } - -//---------------------------------------------------------------------------------------- -/// \ru Конструктор для потокового класса. \en Constructor for a stream class. \~ \ingroup Base_Tools_IO -// --- -#define DECLARE_PERSISTENT_CTOR( Class ) \ - public: \ - Class( TapeInit ) - -//---------------------------------------------------------------------------------------- -/// \ru Конструктор для потокового класса. \en Constructor for a stream class. \~ \ingroup Base_Tools_IO -// --- -#define IMP_PERSISTENT_CTOR( Class ) \ - Class::Class( TapeInit ) {} - -//---------------------------------------------------------------------------------------- -/// \ru Конструктор для класса с одной потоковой базой. \en Constructor for a class with one stream base. \~ \ingroup Base_Tools_IO -// --- -#define IMP_PERSISTENT_CTOR1( Class, Base ) \ - Class::Class( TapeInit ) : Base( tapeInit ) {} - -//---------------------------------------------------------------------------------------- -/// \ru Конструктор для класса с двумя потоковыми базами. \en Constructor for a class with two stream bases. \~ \ingroup Base_Tools_IO -// --- -#define IMP_PERSISTENT_CTOR2( Class, Base1, Base2 ) \ - Class::Class( TapeInit ) : Base1( tapeInit ), Base2( tapeInit ) {} - -//---------------------------------------------------------------------------------------- -/** \brief \ru Конструирование нового экземпляра класса. - \en Construction of a new instance of the class. \~ - \details \ru Конструирование нового экземпляра класса. \n - Определяются функция конструирования нового экземпляра класса, - функция преобразования от указателя на TapeBase к указателю на класс - и класс (не экземпляр!) добавляется в массив потоковых - путем создания переменной r ## Class типа TapeClass - (а в конструкторе TapeClass производится - добавление в массив потоковых классов). - Символ ## - это указание препроцессору о необходимости "склейки" - текущего идентификатора с последующим. - \en Construction of a new instance of the class. \n - Definition of functions of construction a new instance of the class, - function of conversion from a pointer to TapeBase to a pointer to the class - and addition of the class (not an instance) to the array of stream classes - by creating variable r ## Class of type TapeClass - (and in constructor of TapeClass - addition to array of stream classes is performed). - Symbol ## is a directive for preprocessor about the necessity of "gluing" - of the current identifier with the next one. \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_REGISTRATION( AppID, Class ) \ - TapeBase * CALL_DECLARATION make ## _ ## Class () { \ - return new Class(tapeInit); \ - } \ - void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ - return dynamic_cast(const_cast(obj) ); \ - } \ - \ - TapeClass r ## Class( \ - typeid(Class).name(), \ - AppID, \ - (BUILD_FUNC) make ## _ ## Class, \ - (CAST_FUNC ) cast ## _ ## Class, \ - (READ_FUNC ) Class::Read, \ - (WRITE_FUNC) Class::Write \ - ) - -//------------------------------------------------------------------------------ -// \ru Как записать переименованный класс в старую версию (с) Столяров А.Г. \en How to write the renamed class to the old version (c) Stolyarov A.G. -/* #define IMP_PERSISTENT_REGISTRATION_OLDCLASS( Class, OldClass ) \ - TapeBase * CALL_DECLARATION make ## _ ## Class () { \ - return dynamic_cast( new Class(tapeInit) ); \ - } \ - void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ - return dynamic_cast(const_cast(obj) ); \ - } \ - TapeClass r ## Class( \ - typeid(Class).name(), \ - typeid(OldClass).name(), \ - (BUILD_FUNC) make ## _ ## Class, \ - (CAST_FUNC ) cast ## _ ## Class, \ - (READ_FUNC ) Class::Read, \ - (WRITE_FUNC) Class::Write \ - ) - -#define IMP_PERSISTENT_OLDCLASS( Class, OldClass ) \ - IMP_PERSISTENT_REGISTRATION_OLDCLASS( Class, OldClass ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) - -IMP_PERSISTENT_OLDCLASS( Class, OldClass ); - -class TapeClassForNewObjects : public TapeClass { -protected : - ClassDescriptor hashValueOld; // \ru упакованное имя класса для старой версии файла \en packed class name for the old version of file -public : - TapeClassForNewObjects( const char * name, const char * oldName, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); - virtual ~TapeClassForNewObjects(); - virtual ClassDescriptor GetPackedClassNameForWrite( long version ) const; - OBVIOUS_PRIVATE_COPY(TapeClassForNewObjects); -}; - -TapeClassForNewObjects::TapeClassForNewObjects( const char * name, const char * oldName, - BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ) - : TapeClass( name, b, c, r, w ) - , hashValueOld( ::hash(::pureName( oldName ) ) ) -{ -} - -ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version ) const { - uint16 res = version > CHANGE_VERSION ? TapeClass::GetPackedClassName() : uint16(hashValueOld); - return res; -} -*/ - -//---------------------------------------------------------------------------------------- -/// \ru Конструирование нового экземпляра класса для класса без записи. \en Construction of a new instance of the class for a class without writing. \~ \ingroup Base_Tools_IO -// --- -#define IMP_PERSISTENT_RO_REGISTRATION( AppID, Class ) \ - TapeBase * CALL_DECLARATION make ## _ ## Class () { \ - return new Class(tapeInit); \ - } \ - void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ - return dynamic_cast(const_cast(obj) ); \ - } \ - TapeClass r ## Class( \ - typeid(Class).name(), \ - AppID, \ - (BUILD_FUNC) make ## _ ## Class, \ - (CAST_FUNC ) cast ## _ ## Class, \ - (READ_FUNC ) Class::Read, \ - (WRITE_FUNC) 0 \ - ) - -/** \brief \ru Переменная включает перегрузку операторов new/delete, - обеспечивающую последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en The variable enables overloading of new/delete operators - which provides sequential access to the allocation/deallocation functions - from different threads. \~ - \details \ru Переменная включает перегрузку операторов new/delete, - обеспечивающую последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en The variable enables overloading of new/delete operators - which provides sequential access to the allocation/deallocation functions - from different threads. \~ -\ingroup Base_Tools_IO -*/ -// --- -#define __OVERLOAD_MEMORY_ALLOCATE_FREE_ - -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ - //---------------------------------------------------------------------------------------- - /// \ru Объявление функций new, delete и операторов доступа. \en Declaration of functions new, delete and access operators. \~ \ingroup Base_Tools_IO - // \ru операторы * и -> автоматически не перегружаются, \en operators * and -> are not overloaded automatically, - // \ru для их использования нужно писать примерно так: \n \en one should write like this to use them: \n - // \ru вместо ptr->F(); ptr->operator ->()->F(); \n \en instead of ptr->F(); ptr->operator ->()->F(); \n - // \ru или ptr->operator *().F(); \n \en or ptr->operator *().F(); \n - // \ru или ptr->operator Class*()->F(); \n \en or ptr->operator Class*()->F(); \n - // \ru Для ссылок так же. \en Similarly for references. - // --- - #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 ); \ - void * operator new [] ( size_t ); \ - void operator delete [] ( void * ); - - //-------------------------------------------------------------------------------------- - /// \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 ) \ - void * Class::operator new( size_t size ) { \ - return ::Allocate( size, typeid(Class).name() ); } \ - void Class::operator delete ( void *ptr, size_t size ) { \ - ::Free( ptr, size, typeid(Class).name() ); } \ - \ - void * Class::operator new[] ( size_t size ) { \ - return ::AllocateArray( size, typeid(Class[]).name()); } \ - void Class::operator delete[] ( void *ptr ) { \ - ::FreeArray( ptr, typeid(Class[]).name() ); } - -#else // __DEBUG_MEMORY_ALLOCATE_FREE_ - //-------------------------------------------------------------------------------------- - /// \ru Объявление функций new, delete и операторов доступа. \en Declaration of functions new, delete and access operators. \~ \ingroup Base_Tools_IO - // --- - #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 ) - -#if defined(__OVERLOAD_MEMORY_ALLOCATE_FREE_) && !defined(C3D_DEBUG) - - //-------------------------------------------------------------------------------------- - /// \ru Объявление операторов new и delete, обеспечивающих последовательное обращение - /// к функциям выделения/освобождения памяти из разных потоков. - /// Перегружаются все стандартные операторы new и delete. - /// \en Declaration of new and delete operators which provide sequential access - /// to the allocation/deallocation functions from different threads. - /// All standard new and delete operators are overloaded. \~ - /// \ingroup Base_Tools_IO - // --- - #define DECLARE_NEW_DELETE_CLASS_EX( Class ) \ - public: \ - void * operator new ( size_t ); \ - void * operator new ( size_t, const std::nothrow_t & ) throw(); \ - void * operator new ( size_t, void * ); \ - void * operator new [] ( size_t ); \ - void * operator new [] ( size_t, const std::nothrow_t & ) throw(); \ - void * operator new [] ( size_t, void * ); \ - void operator delete ( void * ); \ - void operator delete ( void *, const std::nothrow_t & ) throw(); \ - void operator delete ( void *, void* ); \ - void operator delete [] ( void * ); \ - void operator delete [] ( void *, const std::nothrow_t & ) throw(); \ - void operator delete [] ( void *, void * ); - - //-------------------------------------------------------------------------------------- - /// \ru Реализация операторов new и delete, обеспечивающая последовательное обращение - /// к функциям выделения/освобождения памяти из разных потоков. - /// Перегружаются все стандартные операторы new и delete. - /// \en Implementation of new and delete operators which provides sequential access - /// to the allocation/deallocation functions from different threads. - /// All standard new and delete operators are overloaded. \~ - /// \ingroup Base_Tools_IO - // --- - #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) \ - void* Class::operator new( size_t size ) { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new( size ); } \ - void Class::operator delete( void *ptr ) { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete( ptr ); } \ - \ - void* Class::operator new( size_t size, void *ptr ) { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new( size, ptr ); } \ - void Class::operator delete( void *ptr, void *ptr2 ) { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete( ptr, ptr2 ); } \ - \ - void* Class::operator new[]( size_t size ) { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new[]( size ); } \ - void Class::operator delete[]( void *ptr ) { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete[]( ptr ); } \ - \ - void* Class::operator new []( size_t size, void *ptr ) { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new[]( size, ptr ); } \ - void Class::operator delete []( void *ptr, void *ptr2 ) { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete[]( ptr, ptr2 ); } \ - \ - void* Class::operator new( size_t size, const std::nothrow_t &nt ) throw() { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new( size, nt ); } \ - void Class::operator delete( void *ptr, const std::nothrow_t &nt ) throw() { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete( ptr, nt ); } \ - \ - void* Class::operator new []( size_t size, const std::nothrow_t &nt ) throw() { \ - SET_MEMORY_SCOPED_LOCK; \ - return ::operator new[]( size, nt ); } \ - void Class::operator delete []( void *ptr, const std::nothrow_t &nt ) throw() { \ - SET_MEMORY_SCOPED_LOCK; \ - ::operator delete[]( ptr, nt ); } - -#else // __OVERLOAD_MEMORY_ALLOCATE_FREE_ - - //-------------------------------------------------------------------------------------- - /// \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 provides sequential access - /// to the allocation/deallocation functions from different threads. \~ - /// \ingroup Base_Tools_IO - // --- - #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) - -#endif // __OVERLOAD_MEMORY_ALLOCATE_FREE_ - -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - -//------------------------------------------------------------------------------ -/** \brief \ru Объявление класса Class поточным. - \en Declaration of class Class as a stream one. \~ - \details \ru Объявление класс Class поточным. - Устанавливается в декларации класса в файле *.h. - Декларирует операторы <<, >>, а также функции Read и Write, - которые должны быть определены в любом файле *.cpp - Class должен наследовать от TapeBase. - Для этого класса должен быть определен конструктор чтения, - а его тело должно быть в .cpp файле. \n - \en Declaration of class Class as a stream one. - It is set in the declaration of class in file *.h. - Declares operators <<, >> and also functions Read and Write - which must be defined in any file *.cpp - Class must be inherited from TapeBase. - The read constructor must be defined for the class - and its solid should be in .cpp file. \n \~ - \ingroup Base_Tools_IO -*/ -// --- -#define DECLARE_PERSISTENT_CLASS( Class ) \ - DECLARE_PERSISTENT_FUNCS( Class ); \ - DECLARE_PERSISTENT_OPS( Class ); \ - DECLARE_PERSISTENT_CTOR( Class ); \ - DECLARE_NEW_DELETE_CLASS( Class ); \ - DECLARE_CLASS_DESC_FUNC(Class) - -/** \brief \ru Аналог макроса DECLARE_PERSISTENT_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en Analog of DECLARE_PERSISTENT_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads. \~ -\details \ru Аналог макроса DECLARE_PERSISTENT_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков - (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). - \en Analog of DECLARE_PERSISTENT_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads - (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ -\ingroup Base_Tools_IO -*/ -// --- -#define DECLARE_PERSISTENT_CLASS_NEW_DEL( Class ) \ - DECLARE_PERSISTENT_CLASS( Class ) \ - DECLARE_NEW_DELETE_CLASS_EX( Class ) - -//------------------------------------------------------------------------------ -/** \brief \ru Реализация объявления DECLARE_PERSISTENT_CLASS. - \en Implementation of DECLARE_PERSISTENT_CLASS declaration. \~ - \details \ru Реализация объявления DECLARE_PERSISTENT_CLASS. - Описывает необходимые действия для поточного класса. - Устанавливается в любой .cpp файл. - Class должен наследовать от TapeBase. - Должны быть реализованы функции чтения Read и записи Write. \n - \en Implementation of DECLARE_PERSISTENT_CLASS declaration. - Describes the necessary operations for a stream class. - It is set into any .cpp file. - Class must be inherited from TapeBase. - Function Read of reading and function Write of writing should be implemented. \n \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_CLASS( AppID, Class ) \ - IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ); \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - -/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en Analog of IMP_PERSISTENT_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads. \~ - \details \ru Аналог макроса IMP_PERSISTENT_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков - (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). - \en Analog of IMP_PERSISTENT_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads - (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_CLASS_NEW_DEL( AppID, Class ) \ - IMP_PERSISTENT_CLASS( AppID, Class ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ); - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые действия для поточного класса без записи \en Describes the necessary operations for a stream class without writing. -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется наличие функций \en 2. There must be the following functions -// - void Class:Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// --- -#define IMP_PERSISTENT_RO_CLASS( AppID, Class ) \ - IMP_PERSISTENT_RO_REGISTRATION( AppID, Class ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) - -//------------------------------------------------------------------------------ -/** \brief \ru Аналог макроса IMP_PERSISTENT_RO_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en Analog of IMP_PERSISTENT_RO_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads. \~ - \details \ru Аналог макроса IMP_PERSISTENT_RO_CLASS - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков - (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). - \en Analog of IMP_PERSISTENT_RO_CLASS macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads - (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_RO_CLASS_NEW_DEL( AppID, Class ) \ - IMP_PERSISTENT_RO_CLASS( AppID, Class ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции для абстрактного \en Describes the necessary operations for abstract -// \ru поточного класса \en stream class -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется наличие функций \en 2. There must be the following functions -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// --- -#define IMP_A_PERSISTENT_CLASS( AppID, Class ) \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции абстрактного поточного класса, \en Describes the necessary operations for the abstract stream class -// \ru наследующего от другого такого же, и у которого \en inherited from another class which is the same and which -// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// \ru эти функции генерируются автоматически \en these functions are generated automatically -// --- -#define IMP_A_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ - void Class::Read( reader & in, Class * obj ) { \ - Base::Read( in, obj ); \ - } \ - void Class::Write( writer & out, const Class * obj ) { \ - Base::Write( out, obj ); \ - } \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции поточного класса, \en Describes the necessary operations of the stream class -// \ru наследующего от другого такого же, и у которого \en inherited from another class which is the same and which -// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// \ru эти функции генерируются автоматически \en these functions are generated automatically -// --- -#define IMP_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ - IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ - IMP_A_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) - -//------------------------------------------------------------------------------ -/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS_FROM_BASE - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en Analog of IMP_PERSISTENT_CLASS_FROM_BASE macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads. \~ - \details \ru Аналог макроса IMP_PERSISTENT_CLASS_FROM_BASE - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков - (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). - \en Analog of IMP_PERSISTENT_CLASS_FROM_BASE macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads - (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_CLASS_FROM_BASE_NEW_DEL( AppID, Class, Base ) \ - IMP_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ - IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции для поточного класса, \en Describes the necessary operations for the stream class -// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which -// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// --- -#define IMP_PERSISTENT_CLASS_WD( AppID, Class ) \ - IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ - void Class::Read( reader &, Class * ) {} \ - void Class::Write( writer &, const Class * ) {} \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - -//---------------------------------------------------------------------------------------- -/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS_WD - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков. - \en Analog of IMP_PERSISTENT_CLASS_WD macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads. \~ - \details \ru Аналог макроса IMP_PERSISTENT_CLASS_WD - с возможностью перегрузки операторов new/delete, - обеспечивающий последовательное обращение к функциям - выделения/освобождения памяти из разных потоков - (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). - \en Analog of IMP_PERSISTENT_CLASS_WD macro - with support of new/delete operators overloading which provides - sequential access to the allocation/deallocation functions - from different threads - (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ - \ingroup Base_Tools_IO -*/ -// --- -#define IMP_PERSISTENT_CLASS_WD_NEW_DEL( AppID, Class ) \ - IMP_PERSISTENT_CLASS_WD( AppID, Class ); \ - IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции для абстрактного поточного класса, \en Describes the necessary operations for the abstract stream class -// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which -// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// --- -#define IMP_A_PERSISTENT_CLASS_WD( AppID, Class ) \ - void Class::Read( reader &, Class * ) {} \ - void Class::Write( writer &, const Class * ) {} \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - - -//---------------------------------------------------------------------------------------- -// \ru Описывает необходимые операции для абстрактного поточного класса с проверкой главной версии потока (версии математического ядра), -// \en Describes the necessary operations for the abstract stream class with check of the main stream version (the mathenatical kernel version), -// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which -// \ru нет своих полей данных для записи в поток. \en has no its own data fields for writing to stream. -// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file -// \ru Примечание : \en Note: -// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase -// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) -// - void Class::Read( reader& in, Class* obj ); -// - void Class::Write( writer& out, const Class* obj ); -// \ru где Class - имя класса \en where Class is a class name -// --- -#define IMP_A_PERSISTENT_MATH_CLASS_WD( AppID, Class ) \ - void Class::Read( reader &, Class * ) {} \ - void Class::Write( writer & out, const Class * ) \ - { if ( out.MathVersion() < wrv_FirstRelease ) out.setState( io::cantWriteObject ); } \ - IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ - IMP_CLASS_DESC_FUNC( AppID, Class ) - - //---------------------------------------------------------------------------------------- // \ru Удаление пробелов, записей перед пробелами, символов "<" и ">". // \en Deleting of spaces, records before spaces, symbols "<" and ">". \~ diff --git a/C3d/Include/io_tape_define.h b/C3d/Include/io_tape_define.h new file mode 100644 index 0000000..4091f10 --- /dev/null +++ b/C3d/Include/io_tape_define.h @@ -0,0 +1,1591 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Сериализация: чтение и запись потоковых классов. Основные определения. + \en Serialization: reading and writing of stream classes. Main definitions. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IO_TAPE_DEFINE_H +#define __IO_TAPE_DEFINE_H + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru Классы, для которых при записи и чтении точно известен тип, \en Classes for which the type is exactly known while reading and writing +// \ru могут записываться в поток и читаться из потока с помощью \en can be written to the stream and read from the stream using +// \ru операторов << и >>, \en << and >> operators. +// \ru Это, например, классы лежащие в массиве SArray \en They are, for instance, classes contained in array SArray +// +// \ru Для таких объектов необходимо в описании класса установить : \en For such objects one should set in the class definition: +// \ru KNOWN_OBJECTS_RW_REF_OPERATORS( Class ) - для работы со ссылками и объектами класса \en KNOWN_OBJECTS_RW_REF_OPERATORS( Class ) - for work with references and class objects +// \ru KNOWN_OBJECTS_RW_PTR_OPERATORS( Class ) - для работы с указателями на объекты класса \en KNOWN_OBJECTS_RW_PTR_OPERATORS( Class ) - for work with pointers to class objects +// +// \ru и определить тела самих операторов : \en and define the solids of operators: +// +// \ru -- для ссылок \en -- for references +// inline reader& operator >> ( reader& in, Class& ref ) { +// return in >> ref. >> ref.... ; +// } +// +// writer& operator << ( writer& out, const Class& ref ) { +// return out << ref. << ref. ... ; +// } +// +// \ru -- для указателей \en -- for pointers +// inline reader& operator >> ( reader& in, Class*& ptr ) { +// ptr = new Class(...); +// return in >> ptr-> >> ptr->.... ; +// } +// +// writer& operator << ( writer& out, const Class* ptr ) { +// return out << ptr-> << ptr-> ... ; +// } +// +// \ru Классы, для которых при записи и чтении тип не известен. \en Classes for which the type is unknown while writing and reading. +// \ru Для описания такого класса Class как поточного в общем случае требуется : \en There are the following requirements for description of such class Class as a stream class: +// \ru -- Наследовать класс от TapeBase напрямую или через своих предков \en -- Inherit the class from TapeBase directly or via ancestors +// \ru Примечание : \en Note: +// \ru Если класс наследует более чем от одного поточного класса, \en If the class is inherited from more than one stream class, +// \ru то его предки !!!обязательно!!! должны наследовать от TapeBase \en then its parents MUST be inherited from TapeBase +// \ru виртуально, т.е. \en virtually, i.e. +// class A : public virtual TapeBase { +// ... +// }; +// +// class B : public virtual TapeBase { +// ... +// }; +// +// class C : public A, public B { +// ... +// }; +// +// \ru При этом классы A,B равно как и C нельзя укладывать в SArray, \en At the same time classes A,B cannot be put to array SArray, as well as class C, +// \ru поскольку они неявно содержат указатель на виртуальную базу \en since they implicitly contain a pointer to the virtual base +// +// \ru -- В декларации класса установить : \en -- Set in declaration of the class: +// \ru DECLARE_PERSISTENT_CLASS( Class ) - если Class не имеет поточных предков \en DECLARE_PERSISTENT_CLASS( Class ) - if Class does not have stream ancestors +// +// \ru -- В любом *.cpp файле установить : \en -- Set in any *.cpp file: +// \ru IMP_PERSISTENT_CLASS( AppID, Class ); - требуется написание конструктора \en IMP_PERSISTENT_CLASS( AppID, Class ); - the constructor implementation is required +// +// \ru -- Описать тела функций : \en -- Describe the solids of functions: +// void Class::Read( reader& in, Class* obj ); +// void Class::Write( writer& out, const Class* obj ); +// +// \ru Если Class не содержит своих полей данных, которые необходимо \en If Class does not contain its own data fields which should +// \ru писать в поток и читать оттуда, то вместо \en be written to stream and be read from stream, then instead of +// \ru IMP_PERSISTENT_CLASS следует применять \en IMP_PERSISTENT_CLASS one should use +// IMP_PERSISTENT_CLASS_FROM_BASE( Class, Base ), +// \ru при этом не надо определять функции Class::Read и Class::Write \en at that the functions Class::Read and Class::Write don't have to be defined +// +// \ru Если Class абстрактный -- применять \en If Class is abstract - apply +// IMP_A_PERSISTENT_CLASS( Class ); +// +// \ru Если Class не наследует ни от кого кроме TapeBase и плюс к этому \en If Class does not inherit from any class except TapeBase and, in addition, +// \ru не имеет полей данных для записи, применять : \en does not have data fields for writing, apply: +// \ru в cpp-файле \en in cpp-file +// \ru для абстрактного -- IMP_AWD_PERSISTENT_CLASS( Class ); \en for the abstract one -- IMP_AWD_PERSISTENT_CLASS( Class ); +// \ru для обычного -- IMP_WD_PERSISTENT_CLASS( Class ); \en for the ordinary one -- MP_WD_PERSISTENT_CLASS( Class ); +// \ru примечание : WD - Without Data \en note: WD - Without Data +// +// \ru Если Class наследует более чем от одного TapeBase'а \en If Class inherit from more than one TaperBase class, +// \ru наследование от него должно быть virtual'ным, например : \en the inheritance from it should be virtual, for instance: +// class first : virtual public TapeBase { +// ... +// DECLARE_PERSISTENT_CLASS( AppID, first ); +// }; +// +// class second : virtual public TapeBase { +// ... +// DECLARE_PERSISTENT_CLASS( AppID, second ); +// }; +// +// class third : public first, public second { +// ... +// DECLARE_PERSISTENT_CLASS( AppID, third ); +// }; +// IMP_PERSISTENT_CLASS( AppID, first ) +// IMP_PERSISTENT_CLASS( AppID, second ) +// IMP_PERSISTENT_CLASS( AppID, third ) +// \ru + функции чтения - записи \en + functions of reading-writing +// \ru + соответствующие конструкторы чтения \en + the corresponding reading constructors +// +// \ru Если Class template'ный, то для описания класса поточным требуется : \en If Class is a template class, then the following is required for definition the class as a stream class: +// \ru -- Наследовать template от TapeBase \en -- Inherit template from TapeBase +// +// \ru -- В декларации template'а установить : \en -- Set in the declaration of template : +// DECLARE_T_PERSISTENT_CLASS( Templ, Arg ); +// \ru где Templ - имя самого template'а \en where Templ is the name of template +// \ru Arg - имя формального template'ного аргумента \en Arg - the name of formal argument of template +// +// \ru -- В этом же h-файле вне декларации template'а установить \en -- Set in the same h-file outside the template declaration +// IMP_T_PERSISTENT_OPS( Templ ); +// +// \ru -- В этом же h-файле вне декларации template'а описать тела функций : \en -- In the same h-file outside the template declaration describe solids of functions: +// template +// void Templ::Read( reader& in, Templ* obj ); +// template +// void Templ::Write( writer& out, const Templ* obj ); +// \ru где \en where +// \ru Arg - формальный аргумент \en Arg - formal argument +// +// \ru -- В любом(ых) cpp-файле(ах) установить для каждого применения template'а : \en -- In any cpp-files set for each use of template: +// IMP_T_PERSISTENT_CLASS( Templ, Class ); +// \ru где \en where +// \ru Class - имя класса с которым применяется template ( фактический аргумент ) \en Class - name of the class the template is used with (the actual argument) +// +// \ru Примечание : для классов List, DList, SArray, PArray, Array2 все действия \en Note: for classes List, DList, SArray, PArray, Array2 all the instructions +// \ru уже выполнены, кроме последнего пункта. \en already applied except the last one. +// +// +// \ru По поводу функции Class::Read( reader& in, Class* obj ) рекомендуется \en Regarding function Class::Read( reader& in, Class* obj ) it is recommended +// \ru обратить внимание на : \en to pay attention to: +// +// \ru 1.Поля данных базового класса самостоятельно читать не нужно, вместо этого \en 1.Data fields of the base class don't require any special code to be read, instead of it +// \ru нужно вызвать функцию ReadBase( out, (Base*)obj ). \en one should call function ReadBase( out, (Base*)obj ). +// \ru Вызывать ее желательно в голове функции Class::Read \en It is desirable to call it in the head of function Class::Read +// \ru Обратите внимание на преобразование типа (Base*)obj ! \en Pay attention to the conversion like (Base*)obj ! +// +// \ru 2.Функция Class::Read декларирована статической (static), поэтому она не имеет \en 2. Function Class::Read is declared as static so it has no +// \ru указателя this ==> не пытайтесь делать что-нибудь типа : \en 'this' pointer ==> don't try to do something like: +// in >> field +// \ru правильно : \en the correct variant is: +// in >> obj->field; +// +// \ru По поводу функции Class::Write( writer& out, const Class* obj ) рекомендуется \en As for function Class::Write( writer& out, const Class* obj ), it is recommended +// \ru обратить внимание на : \en to pay attention to: +// +// \ru 1.Поля данных базового класса самостоятельно писать не нужно, вместо этого \en 1.Data fields of the base class don't require any special code to be written, instead of it +// \ru нужно вызвать функцию WriteBase( out, (const Base*)obj ). \en one should call function WriteBase( out, (const Base*)obj ). +// \ru Вызывать ее желательно в голове функции Class::Write \en It is desirable to call it in the head of function Class::Write +// \ru Обратите внимание на преобразование типа (const Base*)obj ! \en Pay attention to the conversion like (const Base*)obj ! +// +// \ru 2.Функция Write декларирована статической (static), поэтому она не имеет \en 2.Function Class::Write is declared as static so it has no +// \ru указателя this ==> не пытайтесь делать что-нибудь типа : \en 'this' pointer ==> don't try to do something like: +// out << field +// \ru правильно : \en the correct variant is: +// out << obj->field; +// +// +// \ru По поводу поддержки версий : \en As for versions support: +// \ru 1. При записи - \en 1. While reading - +// \ru iobuf имеет статическое поле данных iobuf_defaultVersionCont - контейнер версии \en iobuf has static data field iobuf_defaultVersionCont - the version container +// \ru и статическую функцию void iobuf::SetDefaultVersion( VERSION ); \en and the static function void iobuf::SetDefaultVersion( VERSION); +// \ru которую можно вызывать в любом месте программы, например : \en which can be called in any place of the program, for instance: +// iobuf::SetDefaultVersion( 192 ); +// \ru все потоки, которые будут записываться после этого, будут записывать этот \en all the streams which will be written after this will write this +// \ru номер в качестве версии \en number as a version +// \ru 2. При чтении - \en 2. While reading - +// \ru номер версии, записанный в поток возвращается функцией \en the version number written to the stream is returned by function +// VERSION in.MathVersion(), +// \ru где in - экземпляр потока \en where in - is the stream instance +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ +#include +#endif + +#include + +//---------------------------------------------------------------------------------------- +// \ru Предварительное объявление классов. +// \en The forward declaration of classes. \~ +// --- +class MATH_CLASS TapeManager; +class MATH_CLASS reader; +class MATH_CLASS writer; +class MATH_CLASS TapeRegistrator; +class MATH_CLASS iobuf_Seq; +class MATH_CLASS IProgressIndicator; +class MATH_CLASS ProgressBarWrapper; +struct TapeClassContainer; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Типы регистрации объектов. + \en Types of objects registration. \~ + \details \ru Типы регистрации потоковых объектов. \n + \en Types of stream objects registration. \n \~ + \ingroup Base_Tools_IO +*/ //--- +enum RegistrableRec { + noRegistrable, ///< \ru Нерегистрируемый объект. \en Unregistrable object. + registrable ///< \ru Регистрируемый объект. \en Registrable object. +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Типы инициализации объектов. + \en The objects initialization types. \~ + \details \ru Типы регистрации потоковых объектов. \n + \en Types of stream objects registration. \n \~ + \ingroup Base_Tools_IO +*/ //--- +enum TapeInit { + tapeInit ///< \ru По умолчанию. \en By default. +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Упакованное имя класса. + \en Packed class name. \~ + \details \ru Упакованное имя одного класса - для набора массива потоковых классов в TapeClass. \n + \en Packed name of one class - for array of stream classes in TapeClass. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS ClassDescriptor +{ +protected: + uint16 val; ///< \ru Хэш имени класса. \en The class name hash. + MbUuid appID_; ///< \ru Дополнительный идентификатор приложения. \en Additional application identifier. +private: + /// \ru Признак записи appID. \en AppID record flag. + static const uint16 rwIdFlag; + +public: + /// \ru Конструктор. \en Constructor. + ClassDescriptor(); + /// \ru Конструктор по хэшу. \en Constructor by hash. + ClassDescriptor( uint16 v ); + /// \ru Конструктор по имени. \en Constructor by name. + ClassDescriptor( const char * name ); + /// \ru Конструктор по хэшу. \en Constructor by hash. + ClassDescriptor( uint16 v, const MbUuid & appID ); + /// \ru Конструктор по имени. \en Constructor by name. + ClassDescriptor( const char * name, const MbUuid & appID ); + /// \ru Конструктор по хэшу. \en Constructor by hash. + ClassDescriptor( const ClassDescriptor & other ); + + /// \ru Оператор присваивания. \en An assignment operator. + ClassDescriptor & operator = ( const ClassDescriptor & other ); + + /// \ru Оператор равенства. \en The equality operator. + bool operator == ( const ClassDescriptor & other ) const; + /// \ru Оператор неравенства. \en The inequality operator. + bool operator != ( const ClassDescriptor & other ) const; + /// \ru Оператор сравнения. \en Comparison operator. + bool operator < (const ClassDescriptor & other ) const; + /// \ru Оператор сравнения. \en Comparison operator. + bool operator > ( const ClassDescriptor & other ) const; +#ifdef C3D_DEBUG + /// \ru Оператор доступа. \en An access operator. + operator uint16() const { return val; } +#endif + /// \ru Оператор записи. \en Write operator. + void Write( writer & out ); + /// \ru Оператор чтения. \en Read operator. + bool Read( reader & in ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый класс для потоковых классов. + \en Base class for stream classes. \~ + \details \ru Базовый класс для потоковых классов. \n + \en Base class for stream classes. \n \~ + \ingroup Base_Tools_IO +*/ // --- +#ifndef ENABLE_MEMORY_LEAKS_CHECK +class MATH_CLASS TapeBase { +#else +class MATH_CLASS TapeBase : virtual public c3d::MemoryLeaksVerifiable { +#endif +private: + mutable use_count_type m_countRegistrable; ///< \ru Счетчик ссылок регистрируемого объекта. \en Number of usages of the registrable object. + +public: + /// \ru Конструктор. \en Constructor. + TapeBase( RegistrableRec regs = noRegistrable ); + /// \ru Конструктор копирования \en Copy-constructor. + TapeBase( const TapeBase & ); + /// \ru Деструктор. \en Destructor. + virtual ~TapeBase(); + +public: + /// \ru Является ли потоковый класс регистрируемым. \en Whether the stream class is registrable. + RegistrableRec GetRegistrable() const; + /// \ru Установить состояние регистрации потокового класса. \en Set the state of registration of the stream class. + void SetRegistrable( RegistrableRec regs = registrable ) const; + /// \ru Получить дескриптор класса + //virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const { return ClassDescriptor( ::pureName(typeid(*this).name()) ); } + virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const = 0; + /// \ru Получить имя класса. \en Get the class name. + virtual const char * GetPureName( const VersionContainer & ) const; + /// \ru Принадлежит ли объект к регистрируемому семейству. \en Whether the object belongs to a registrable family. + virtual bool IsFamilyRegistrable() const; + +private: + /// \ru Функция-пустышка для обеспечения полиморфизма данного класса и его наследников. \en Dummy function for providing polymorphism of the given class and its descendants. + virtual void dummy(); // I need this to make class polymorphic + /// \ru Оператор присваивания \en Assignment operator + void operator = ( const TapeBase & other ); +}; + + +//---------------------------------------------------------------------------------------- +/// \ru Шаблон функции создания нового экземпляра. \en Template of function of a new instance creation. \~ \ingroup Base_Tools_IO +//--- +typedef TapeBase * (CALL_DECLARATION * BUILD_FUNC) ( void ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Шаблон функции преобразования. + \en Template of conversion function. \~ + \details \ru Шаблон функции преобразования из указателя на TapeBase к указателю на класс. \n + \en Template of function of conversion from a pointer to TapeBase to a pointer to the class. \n \~ + \ingroup Base_Tools_IO +*/ //--- +typedef void * (CALL_DECLARATION * CAST_FUNC) ( const TapeBase * ); + +//---------------------------------------------------------------------------------------- +/**\ru Шаблон функции чтения экземпляра. + \en Template of instance reading function. \~ + \ingroup Base_Tools_IO +*/ //--- +typedef void (CALL_DECLARATION * READ_FUNC) ( reader & in, void * /*obj*/ ); + +//---------------------------------------------------------------------------------------- +/// \ru Шаблон функции записи экземпляра. \en Template of instance writing function. \~ \ingroup Base_Tools_IO +//--- +typedef void (CALL_DECLARATION * WRITE_FUNC) ( writer & out, void * /*obj*/ ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru "Обертка" для одного потокового класса. + \en "Wrapper" for one stream class. \~ + \details \ru "Обертка" для одного потокового класса ( не экземпляра! ). + Xранит упакованное имя класса и адреса функций, необходимых при чтении/записи. \n + \en "Wrapper" for one stream class ( not instance! ). + Stores packed class name and addresses of functions necessary while reading/writing. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS TapeClass { +protected: + ClassDescriptor hashValue; ///< \ru Упакованное имя класса. \en Packed class name. + BUILD_FUNC _builder; ///< \ru Функция создания нового экземпляра. \en Functions of a new instance creation. + CAST_FUNC _caster; ///< \ru Функция преобразования от TapeBase к указателю на класс. \en Function of conversion from TapeBase to a pointer to a class. + READ_FUNC _reader; ///< \ru Функция чтения. \en Read function. + WRITE_FUNC _writer; ///< \ru Функция записи. \en Write function. + +public: + /// \ru Конструктор. \en Constructor. + /// \ru Конструктор. \en Constructor. + TapeClass( const char * name, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); + TapeClass( const char * name, MbUuid appID, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); + /// \ru Деструктор. \en Destructor. + virtual ~TapeClass(); + /// \ru Получить упакованное имя класса. \en Get the packed class name. + ClassDescriptor GetPackedClassName() const; + /// \ru Получить упакованное имя класса для записи с учетом версии. \en Get the packed class name for writing subject to the version. + virtual ClassDescriptor GetPackedClassNameForWrite( VERSION ) const; + + friend class TapeManager; + friend struct TapeClassContainer; + +OBVIOUS_PRIVATE_COPY( TapeClass ) +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Cпособы записи указателей. + \en Methods of writing pointers. \~ + \details \ru Cпособы записи указателей. \n + \en Methods of writing pointers. \n \~ + \ingroup Base_Tools_IO +*/ //--- +enum TapePointerType { + tpt_Null = 0x00, ///< \ru Нулевой указатель. \en Null pointer. + tpt_Indexed16 = 0x01, ///< \ru Индекс указателя в массиве регистрации (2 байта). \en Pointer index in the registration array (2 bytes). + tpt_Object = 0x02, ///< \ru Тело объекта. \en The object solid. + tpt_Indexed8 = 0x03, ///< \ru Индекс указателя в массиве регистрации (1 байт). \en Index of pointer in the registration array (1 byte). + tpt_Indexed32 = 0x04, ///< \ru Индекс указателя в массиве регистрации (4 байта). \en Pointer index in the registration array (4 bytes). + tpt_Indexed64 = 0x05, ///< \ru Индекс указателя в массиве регистрации (8 байт). \en Index of pointer in the registration array (8 byte). + tpt_DetachedObject = 0x06, ///< \ru Тело объекта в отдельном FileSpace. \en The object solid in separated FileSpace. + tpt_ObjectCatalog = 0x07, ///< \ru Каталог объектов в отдельном FileSpace. \en The object catalog in separated FileSpace. +}; + + +#pragma pack( push, 1 ) +//---------------------------------------------------------------------------------------- +/** \brief \ru Базовый класс потока для реализации чтения и записи. + \en The base class of the stream for implementation of reading and writing. \~ + \details \ru Базовый класс потока для реализации чтения и записи. \n + \en The base class of the stream for implementation of reading and writing. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS tape { +protected: + iobuf_Seq & buf; ///< \ru Буфер для данных. \en Buffer for data. + TapeManager & manager; ///< \ru Менеджер потоков. \en Stream manager. + uint8 level; ///< \ru Уровень вложенности при чтении/записи. \en Nesting level while reading/writing. + TapeRegistrator & registrator; ///< \ru Структура для регистрации записанных/прочитанных адресов. \en Structure for registration of written/read addresses. + mutable ProgressBarWrapper * progress; ///< \ru Индикатор прогресса. \en Progress indicator. +private: + uint8 ownBuf; ///< \ru Владеет ли буфером. \en Whether it owns the buffer. + bool ownReg; ///< \ru Признак владения регистратором. \en Whether it owns of the registrar. + +public: + /// \ru Тип объекта. \en An object type. + enum objectType { + otNull, + otIndexed, + otObject + }; + /// \ru Деструктор. \en Destructor. + virtual ~tape(); + + /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE iobuf & buffer() const; + /// \ru Получить доступ к буферу. \en Get access to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE iobuf & operator()() const; + + /// \ru Получить доступ к буферу. \en Get access to the buffer. + const iobuf_Seq & GetIOBuffer() const; + /// \ru Получить доступ к буферу. \en Get access to the buffer. + iobuf_Seq & GetIOBuffer(); + + /// \ru Узнать режим работы буфера. \en Get the buffer mode. + uint8 mode() const; //AR getMode + /// \ru Установить режим работы буфера. \en Set the buffer mode. + void setMode( uint8 m ); + /// \ru Убрать состояние буфера. \en Remove the buffer state. + void clearState( io::state sub ); + /// \ru Добавить состояние буфера. \en Add the buffer state. + void setState ( io::state add ); + + /// \ru Установить текущую версию равной версии хранилища. \en Set the current version to be equal to the storage version. + void SetVersionsByStorage(); + /// \ru Вернуть главную версию (математического ядра). \en Return the main version (of the mathematical kernel). + VERSION MathVersion() const; + /// \ru Вернуть дополнительную версию (конечного приложения). \en Return the additional version (of the target application). + VERSION AppVersion( size_t ind = -1 ) const; + + /// \ru Получить доступ к контейнеру версий. \en Get access to the version container. + const VersionContainer & GetVersionsContainer() const; + /// \ru Установить версию открытого файла. \en Set the version of open file. + void SetVersionsContainer( const VersionContainer & vers ) const; + /// \ru Установить версию хранилища. \en Set the storage version. + VERSION SetStorageVersion( VERSION v ); + + /// \ru Свежий ли буфер? \en Is the buffer fresh? + int fresh() const; + /// \ru Корректно ли состояние буфера.. \en Whether the buffer state is correct. + bool good() const; + /// \ru Достигнут ли конец файла? \en Is the end of file reached? + virtual uint8 eof() const; + /// \ru Получить флаг состояния буфера. \en Get the flag of the buffer state. + virtual uint32 state() const; + /// \ru Получить текущую позицию в потоке. \en Get current position in stream + virtual io::pos tell(); + ///< \ru Зарегистрировать указатель. \en Register the pointer. + void registrate( const TapeBase * e ); + ///< \ru Отменить регистрацию указателя. \en Unregister the pointer. + void unregistrate( const TapeBase * e ); + ///< \ru Есть ли зарегистрированный объект? \en Does a registered object exist? + bool exist ( const TapeBase * e ) const; + ///< \ru Очистить массив регистрации. \en Flush the registration array. + void flushRegister (); + ///< \ru Получить количество зарегистрированных объектов. \en Get the number of registered objects. + size_t RegisteredCount() const; + ///< \ru Получить максимально возможное количество объектов для регистрации. \en Get the maximal possible number of objects for registration. + size_t GetMaxRegisteredCount() const; + ///< \ru Зарезервировать память под n объектов. \en Reserve memory for n objects. + void ReserveRegistered( size_t n ); + + /// \ru Владеем ли буфером? \en Do we own the buffer? + bool IsOwnBuffer() const; + /// \ru Установить флаг владения буфером. \en Set the flag of buffer ownership. + void SetOwnBuffer( bool own ); + + /// \ru Получить тип индекса. \en Get index type. + uint8 GetIndexType( size_t index ) const; + + /// \ru Работа с индикатором прогресса. \en Work with progress indicator. + + /// Инициализировать индикатор прогресса. \en Initialize progress indicator. + void InitProgress( IProgressIndicator * pr ); + void InitProgress( ProgressBarWrapper & pr ); + /// \ru Освободить текущий индикатор прогресса. Установить родительский индикатор прогресса, если он есть. + /// \en Release current progress indicator. Set parent progress indicator if it exists. + void ResetProgress(); + /// \ru Получить индикатор прогресса. \en Get progress indicator. + ProgressBarWrapper * GetProgress(); + /// \ru Завершить индикатор прогресса. \en End the progress indicator. + void FinishProgress(); + +protected: + /// \ru Конструктор. \en Constructor. + tape( membuf &, bool openSys, uint8 om, TapeRegistrator * , bool ownReg = false); + + /// \ru Конструктор. \en Constructor. + tape( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * , bool ownReg = false); //AR(DP) + +private: + /// \ru Открыть системный файл в соответствующем режиме (чтение или запись). \en Open the system file in the appropriate mode (reading or writing). + void init( uint8 om ); + +OBVIOUS_PRIVATE_COPY( tape ) +}; +#pragma pack( pop ) + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Поток для чтения. + \en Stream for reading. \~ + \details \ru Поток для чтения. \n + \en Stream for reading. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS reader : public virtual tape { +public: + typedef std::unique_ptr reader_ptr; +protected: + /// \ru Конструктор. \en Constructor. + reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator * reg ); + + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator & reg ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); + +public: + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader( membuf & sb, uint8 om ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader( iobuf_Seq & buf, uint16 om ); + + virtual ~reader() {} + +public: + /// \ru Создать читатель для последовательного буфера. \en Create reader for iobuf_Seq. + static reader_ptr CreateReader ( std::unique_ptr buf, uint16 om ); + /// \ru Создать читатель для буфера в памяти. \en Create reader for membuf. + static reader_ptr CreateMemReader ( membuf & sb, uint8 om ); + +public: + /// \ru Прочитать объект. \en Read the object. + TapeBase * readObject ( TapeBase * mem = 0 ); + /// \ru Прочитать указатель на объект. \en Read a pointer to the object. + TapeBase * readObjectPointer(); + + /// \ru Читать каталог объектов. \en Read the object catalog. + virtual void ReadObjectCatalog(); + /// \ru Читать объект по позиции в кластере. \en Read an object by position in cluster. + virtual TapeBase * ReadObjectByPosition ( const ClusterReference & ) { return nullptr; } + /// \ru Установить позицию чтения. \en Set reading position. + virtual bool SetReadPosition ( ClusterReference & ) { return false; } // not supported + + /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE size_t readSBytes ( void * bf, size_t len ); + + /// \ru Прочитать беззнаковое 64-разрядное целое \en Read unsigned 64-bit integer. + bool readUInt64( uint64 & ); + /// \ru Прочитать 64-разрядное целое \en Read 64-bit integer. + bool readInt64( int64 & ); + + /// \ru Прочитать байт из буфера. \en Read a byte from the buffer. + virtual int readByte(); + /// \ru Прочитать последовательность байт из буфера. \en Read a sequence of bytes from the buffer. + virtual bool readBytes( void * bf, size_t len ); + + /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. + virtual const c3d::IModelTree * GetModelTree() const { return nullptr; } // not supported + + /// \ru Получить признак полного чтения текущего объекта. \en Get indicator of full reading of the current object. + /// \ru Установить признак полного чтения текущего объекта. \en Set indicator of full reading of the current object. + virtual bool IsFullRead() { return true; } // not supported + virtual void SetFullRead( bool ) {} // not supported + + /// \ru Получить ошибки чтения. \en Get reading errors. + virtual uint32 GetLastError(); + + // \ru Работа с индикатором прогресса. + // \en Work with progress indicator. + void InitProgress( IProgressIndicator * pr ); + void InitProgress( ProgressBarWrapper & pr ); + +protected: + /// \ru Читаем объект по заданной позиции. \en Read object on defined position. + virtual TapeBase * ReadDetachedObject (); + /// \ru Регистрируем объект. \en Register the object. + virtual void RegisterObject( TapeBase * obj, uint8 regId, ClusterReference ref = ClusterReference() ); + /// \ru Читаем индекс объекта. \en Read object index. + size_t ReadObjectIndex(); + +OBVIOUS_PRIVATE_COPY( reader ) +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Поток для чтения с возможностью чтения из нескольких FileSpaces по заданным позициям. + \en Stream for reading from several FileSpaces by given positions in clusters. \~ + \details \ru Поток для чтения с возможностью чтения из разных FileSpaces по заданным позициям. \n + \en Stream for reading from several FileSpace by given positions in clusters. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS reader_ex : public reader +{ + std::unique_ptr m_tree; + uint32 m_lastError; + bool m_fullRead; +protected: + /// \ru Конструктор. \en Constructor. + reader_ex( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om ); + +public: + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader_ex( membuf & sb, uint8 om ); + + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE reader_ex( iobuf_Seq & buf, uint16 om ); + + virtual ~reader_ex() {} + +public: + /// \ru Создать экземпляр reader_ex для последовательного буфера. \en Create reader_ex instance for sequential buffer. + static std::unique_ptr CreateReaderEx( std::unique_ptr buf, uint16 om ); + + /// \ru Создать читатель для буфера в памяти. \en Create reader for membuf. + static std::unique_ptr CreateMemReaderEx ( membuf & sb, uint8 om ); + + +public: + /// \ru Читаем каталог объектов. \en Read the object catalog. + virtual void ReadObjectCatalog(); + /// \ru Читать объект по позиции в кластере. \en Read an object by position in cluster. + virtual TapeBase * ReadObjectByPosition ( const ClusterReference& position ); + /// \ru Установить позицию чтения. \en Set reading position. + virtual bool SetReadPosition ( ClusterReference & ); + + /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. + virtual const c3d::IModelTree * GetModelTree() const; + + /// \ru Признак полного чтения текущего объекта. + /// При чтении произвольного объекта может возникнуть необходимость чтения некоторых данных его родителя. + /// В этом случае объект родителя читается не полностью и имеет флаг FullRead = false. + /// \en Indicator of full reading of the current object. + /// While reading an arbitrary object there can be a need to read some data from its parent. + /// In this case the parent object is read partially and has the flag FullRead = false. + + /// \ru Получить признак полного чтения текущего объекта. \en Get indicator of full reading of the current object. + virtual bool IsFullRead(); + /// \ru Установить признак полного чтения текущего объекта. \en Set indicator of full reading of the current object. + virtual void SetFullRead( bool full ); + + /// \ru Получить ошибки чтения. \en Get reading errors. + virtual uint32 GetLastError(); + +protected: + /// \ru Читать объект по заданной позиции. \en Read object on defined position. + virtual TapeBase * ReadDetachedObject(); + /// \ru Зарегистрировать объект. \en Register the object. + virtual void RegisterObject( TapeBase * obj, uint8 regId, ClusterReference ref = ClusterReference() ); + +OBVIOUS_PRIVATE_COPY( reader_ex ) +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Поток для записи. + \en Stream for writing. \~ + \details \ru Поток для записи. \n + \en Stream for writing. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS writer : public virtual tape { +public: + typedef std::unique_ptr writer_ptr; +protected: + /// \ru Конструктор. \en Constructor. + writer ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om, TapeRegistrator & reg ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer ( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); + +public: + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer ( membuf & sb, uint8 om ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer ( iobuf_Seq & buf, uint16 om ); + + virtual ~writer() {} + +public: + /// \ru Создать писатель для последовательного буфера. \en Create writer for iobuf_Seq. + static writer_ptr CreateWriter( std::unique_ptr buf, uint16 om ); + /// \ru Создать писатель для буфера в памяти. \en Create writer for membuf. + static writer_ptr CreateMemWriter( membuf & sb, uint8 om ); + +public: + /// \ru Записать объект. \en Write the object. + void writeObject( const TapeBase * ); + /// \ru Записать указатель на объект. \en Write the pointer to the object. + void writeObjectPointer( const TapeBase * ); + + /// \ru Записать дерево модели. \en Write the model tree. + virtual void WriteModelCatalog(); + /// \ru Выдать следующую позицию записи. \en Get next writing position. + virtual ClusterReference GetNextWritePosition () { return ClusterReference(); } // not supported + + /// \ru Записать байт в буфер. \en Write the byte to the buffer. + virtual void writeByte ( uint8 ch ); + /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. + virtual void writeBytes ( const void * bf, size_t len ); + /// \ru Записать последовательность байт в буфер. \en Write the sequence of bytes to the buffer. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE size_t writeSBytes( const void * bf, size_t len ); + /// \ru Записать беззнаковое 64-разрядное целое. \en Write unsigned 64-bit integer. \~ \return \ru Возвращает количество записанных байт. \en Returns the number of written bytes. \~ + void writeUInt64( const uint64 & val ); + /// \ru Записать 64-разрядное целое. \en Write 64-bit integer. \~ \return \ru Возвращает количество записанных байт. \en Returns the number of written bytes. \~ + void writeInt64 ( const int64 & val ); + + // \ru Запись CHAR строки в поток (кодировка ANSI, русская локаль). \en Writing CHAR string to the stream. (ANSI coding, Russian locale). + writer & __writeChar ( const char * s ); + // \ru Запись WCHAR строки в поток (в потоке хранится как UTF-16). \en Writing WCHAR string to the stream (stored in the stream as UTF-16). + writer & __writeWchar( const TCHAR * s ); + // \ru Запись WCHAR строки в поток (в потоке хранится как UTF-16). \en Writing WCHAR string to the stream (stored in the stream as UTF-16). + writer & __writeWcharT( const wchar_t * s ); + // \ru Длина записи WCHAR строки в поток (в потоке хранится как UTF-16). \en Length of WCHAR string in the stream (stored in the stream as UTF-16). + size_t __lenWchar( const TCHAR * s ); + + /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. + virtual const c3d::IModelTree * GetModelTree() const { return nullptr; } // not supported + +protected: + /// \ru Записать объект и тип. \en Write the object and type. + virtual void WriteObjectAndType ( const TapeBase * ); + /// \ru Зарегистрировать объект. \en Register the object. + virtual void RegisterObject ( const TapeBase * ); + /// \ru Завершить запись объекта. \en Finish writing the object. + virtual void EndWriteObject ( const TapeBase * ); + /// \ru Добавить ссылку на объект в каталог. \en Add reference to the object to the object catalog. + virtual void UpdateObjectCatalog ( const TapeBase * , const ClusterReference & ); + /// \ru Является ли объект регистрируемым. \en Whether the object is registrable. + virtual bool IsRegistrable( const TapeBase * mem ); + /// Записать индекс объекта + void WriteObjectIndex ( size_t index ); + +OBVIOUS_PRIVATE_COPY( writer ) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Поток для записи в разные FileSpaces. + \en Stream for writing to several FileSpaces. \~ + \details \ru Поток для записи в разные FileSpaces. \n + \en Stream for writing to several FileSpaces. \n \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS writer_ex : public writer +{ + std::unique_ptr m_tree; + ClusterReference m_catalogRef; +protected: + /// \ru Конструктор. \en Constructor. + writer_ex ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om ); + +public: + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer_ex ( membuf & sb, uint8 om ); + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE writer_ex ( iobuf_Seq & buf, uint16 om ); + + virtual ~writer_ex() {} + +public: + /// \ru Создать писатель для последовательного буфера. \en Create writer for iobuf_Seq. + static std::unique_ptr CreateWriterEx( std::unique_ptr buf, uint16 om ); + /// \ru Создать писатель для буфера в памяти. \en Create writer for membuf. + static std::unique_ptr CreateMemWriterEx( membuf & sb, uint8 om ); + +public: + /// \ru Записать дерево модели. \en Write the model tree. + virtual void WriteModelCatalog(); + /// \ru Выдать следующую позицию записи. \en Get next writing position. + virtual ClusterReference GetNextWritePosition (); + /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. + virtual const c3d::IModelTree * GetModelTree () const; + +protected: + /// \ru Записать объект и тип. \en Write the object and type. + virtual void WriteObjectAndType ( const TapeBase * ); + /// \ru Зарегистрировать объект. \en Register the object. + virtual void RegisterObject ( const TapeBase * ); + /// \ru Завершить запись объекта. \en Finish writing the object. + virtual void EndWriteObject ( const TapeBase * ); + /// \ru Добавить ссылку на объект в каталог. \en Add reference to the object to the object catalog. + virtual void UpdateObjectCatalog ( const TapeBase *mem, const ClusterReference& ref ); + /// \ru Является ли объект регистрируемым. \en Whether the object is registrable. + virtual bool IsRegistrable( const TapeBase * mem ); + +OBVIOUS_PRIVATE_COPY( writer_ex ) +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Поток для чтения и записи. + \en Stream for reading and writing. \~ + \details \ru Поток для чтения и записи. \n + \en Stream for reading and writing. \n \~ + \deprecated \ru Класс устарел и будет удален в версии 2023. + \en The class is deprecated and will be removed in version 2023. \~ + \ingroup Base_Tools_IO +*/ // --- +class MATH_CLASS rw : public writer, public reader { +public: + typedef std::unique_ptr rw_ptr; +public: + /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. + DEPRECATE_DECLARE rw( membuf & sb, uint8 om ); + + /// \ru Создать читатель/писатель для буфера в памяти. \en Create reader/writer for membuf. + static rw_ptr CreateMemWriter( membuf & sb, uint8 om ); + + /// \ru Конструктор. \en Constructor. + rw( iobuf & buf, uint16 om ); + + virtual ~rw() {} + +private: + /// \ru Конструктор. \en Constructor. + rw( iobuf_Seq & sb, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); + +OBVIOUS_PRIVATE_COPY( rw ) +}; + + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Дружественные операторы чтения и записи указателей и ссылок. + \en Friend operators of reading and writing of pointers and references. \~ + \ingroup Base_Tools_IO +*/ +// --- +#define DECLARE_PERSISTENT_OPS( Class ) \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ) { \ + in.readObject( dynamic_cast(&ref) ); \ + return in; \ + } \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ) { \ + ptr = dynamic_cast( in.readObjectPointer() ); \ + return in; \ + } \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, const Class *& ptr ) \ + { \ + ptr = dynamic_cast( in.readObjectPointer() ); \ + return in; \ + } \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ) { \ + out.writeObject( dynamic_cast(&ref) ); \ + return out; \ + } \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ) { \ + out.writeObjectPointer( dynamic_cast(ptr) ); \ + return out; \ + } \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { \ + out.writeObject( dynamic_cast(&ref) ); \ + return out; \ + } \ + friend inline writer & CALL_DECLARATION operator << ( writer& out, Class * ptr ) { \ + out.writeObjectPointer( dynamic_cast(ptr) ); \ + return out; \ + } + +/** + \brief \ru Объявление операторов чтения и записи указателей и ссылок. + \en Declaration of operators of reading and writing of pointers and references. \~ + \ingroup Base_Tools_IO +*/ +// --- +#define DECLARE_PERSISTENT_OPS_B( Class ) \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ); \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ); \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, const Class *& ptr ); \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ); \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ); \ + friend inline writer & CALL_DECLARATION operator << ( writer & out, Class & ref ); \ + friend inline writer & CALL_DECLARATION operator << ( writer& out, Class * ptr ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Операторы чтения и записи указателей и ссылок. + \en Operators of reading and writing of pointers and references. \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMPL_PERSISTENT_OPS( Class ) + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Операторы чтения указателей и ссылок для класса без записи. + \en Operators of reading pointers and references for a class without writing. \~ + \ingroup Base_Tools_IO +*/ +// --- +#define DECLARE_PERSISTENT_RO_OPS( Class ) \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ) { \ + in.readObject( dynamic_cast(&ref) ); \ + return in; \ + } \ + friend inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ) { \ + ptr = dynamic_cast( in.readObjectPointer() ); \ + return in; \ + } + +//---------------------------------------------------------------------------------------- +/// \ru Функции чтения и записи. \en Functions of reading and writing. \~ \ingroup Base_Tools_IO +// --- +#define DECLARE_PERSISTENT_FUNCS( Class ) \ + public: \ + static void Read ( reader & in, Class * obj ); \ + static void Write( writer & out, const Class * obj ) + +//---------------------------------------------------------------------------------------- +/// \ru Функции чтения для класса без записи. \en Function of reading for class without writing. \~ \ingroup Base_Tools_IO +// --- +#define DECLARE_PERSISTENT_RO_FUNCS( Class ) \ + public: \ + static void Read( reader & in, Class * obj ) + +//------------------------------------------------------------------------------ +/// \ru Функции получения дескриптора класса. \~ \ingroup Base_Tools_IO +// --- +#define DECLARE_CLASS_DESC_FUNC( Class ) \ + public: \ + ClassDescriptor GetClassDescriptor( const VersionContainer & ) const override; + +//------------------------------------------------------------------------------ +/// \ru Функции получения дескриптора (хэш + APP UID) класса. \~ \ingroup Base_Tools_IO +// --- +#define IMP_CLASS_DESC_FUNC( AppID, Class ) \ + ClassDescriptor Class::GetClassDescriptor( const VersionContainer & v) const \ + { return ClassDescriptor( GetPureName(v), AppID ); } + +//---------------------------------------------------------------------------------------- +/// \ru Конструктор для потокового класса. \en Constructor for a stream class. \~ \ingroup Base_Tools_IO +// --- +#define DECLARE_PERSISTENT_CTOR( Class ) \ + public: \ + Class( TapeInit ) + +//---------------------------------------------------------------------------------------- +/// \ru Конструктор для потокового класса. \en Constructor for a stream class. \~ \ingroup Base_Tools_IO +// --- +#define IMP_PERSISTENT_CTOR( Class ) \ + Class::Class( TapeInit ) {} + +//---------------------------------------------------------------------------------------- +/// \ru Конструктор для класса с одной потоковой базой. \en Constructor for a class with one stream base. \~ \ingroup Base_Tools_IO +// --- +#define IMP_PERSISTENT_CTOR1( Class, Base ) \ + Class::Class( TapeInit ) : Base( tapeInit ) {} + +//---------------------------------------------------------------------------------------- +/// \ru Конструктор для класса с двумя потоковыми базами. \en Constructor for a class with two stream bases. \~ \ingroup Base_Tools_IO +// --- +#define IMP_PERSISTENT_CTOR2( Class, Base1, Base2 ) \ + Class::Class( TapeInit ) : Base1( tapeInit ), Base2( tapeInit ) {} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Конструирование нового экземпляра класса. + \en Construction of a new instance of the class. \~ + \details \ru Конструирование нового экземпляра класса. \n + Определяются функция конструирования нового экземпляра класса, + функция преобразования от указателя на TapeBase к указателю на класс + и класс (не экземпляр!) добавляется в массив потоковых + путем создания переменной r ## Class типа TapeClass + (а в конструкторе TapeClass производится + добавление в массив потоковых классов). + Символ ## - это указание препроцессору о необходимости "склейки" + текущего идентификатора с последующим. + \en Construction of a new instance of the class. \n + Definition of functions of construction a new instance of the class, + function of conversion from a pointer to TapeBase to a pointer to the class + and addition of the class (not an instance) to the array of stream classes + by creating variable r ## Class of type TapeClass + (and in constructor of TapeClass + addition to array of stream classes is performed). + Symbol ## is a directive for preprocessor about the necessity of "gluing" + of the current identifier with the next one. \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_REGISTRATION( AppID, Class ) \ + TapeBase * CALL_DECLARATION make ## _ ## Class () { \ + return new Class(tapeInit); \ + } \ + void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ + return dynamic_cast(const_cast(obj) ); \ + } \ + \ + TapeClass r ## Class( \ + typeid(Class).name(), \ + AppID, \ + (BUILD_FUNC) make ## _ ## Class, \ + (CAST_FUNC ) cast ## _ ## Class, \ + (READ_FUNC ) Class::Read, \ + (WRITE_FUNC) Class::Write \ + ) + +//------------------------------------------------------------------------------ +// \ru Как записать переименованный класс в старую версию (с) Столяров А.Г. \en How to write the renamed class to the old version (c) Stolyarov A.G. +/* #define IMP_PERSISTENT_REGISTRATION_OLDCLASS( Class, OldClass ) \ + TapeBase * CALL_DECLARATION make ## _ ## Class () { \ + return dynamic_cast( new Class(tapeInit) ); \ + } \ + void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ + return dynamic_cast(const_cast(obj) ); \ + } \ + TapeClass r ## Class( \ + typeid(Class).name(), \ + typeid(OldClass).name(), \ + (BUILD_FUNC) make ## _ ## Class, \ + (CAST_FUNC ) cast ## _ ## Class, \ + (READ_FUNC ) Class::Read, \ + (WRITE_FUNC) Class::Write \ + ) + +#define IMP_PERSISTENT_OLDCLASS( Class, OldClass ) \ + IMP_PERSISTENT_REGISTRATION_OLDCLASS( Class, OldClass ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) + +IMP_PERSISTENT_OLDCLASS( Class, OldClass ); + +class TapeClassForNewObjects : public TapeClass { +protected : + ClassDescriptor hashValueOld; // \ru упакованное имя класса для старой версии файла \en packed class name for the old version of file +public : + TapeClassForNewObjects( const char * name, const char * oldName, BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ); + virtual ~TapeClassForNewObjects(); + virtual ClassDescriptor GetPackedClassNameForWrite( long version ) const; + OBVIOUS_PRIVATE_COPY(TapeClassForNewObjects); +}; + +TapeClassForNewObjects::TapeClassForNewObjects( const char * name, const char * oldName, + BUILD_FUNC b, CAST_FUNC c, READ_FUNC r, WRITE_FUNC w ) + : TapeClass( name, b, c, r, w ) + , hashValueOld( ::hash(::pureName( oldName ) ) ) +{ +} + +ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version ) const { + uint16 res = version > CHANGE_VERSION ? TapeClass::GetPackedClassName() : uint16(hashValueOld); + return res; +} +*/ + +//---------------------------------------------------------------------------------------- +/// \ru Конструирование нового экземпляра класса для класса без записи. \en Construction of a new instance of the class for a class without writing. \~ \ingroup Base_Tools_IO +// --- +#define IMP_PERSISTENT_RO_REGISTRATION( AppID, Class ) \ + TapeBase * CALL_DECLARATION make ## _ ## Class () { \ + return new Class(tapeInit); \ + } \ + void * CALL_DECLARATION cast ## _ ## Class ( const TapeBase * obj ) { \ + return dynamic_cast(const_cast(obj) ); \ + } \ + TapeClass r ## Class( \ + typeid(Class).name(), \ + AppID, \ + (BUILD_FUNC) make ## _ ## Class, \ + (CAST_FUNC ) cast ## _ ## Class, \ + (READ_FUNC ) Class::Read, \ + (WRITE_FUNC) 0 \ + ) + +/** \brief \ru Переменная включает перегрузку операторов new/delete, + обеспечивающую последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en The variable enables overloading of new/delete operators + which provides sequential access to the allocation/deallocation functions + from different threads. \~ + \details \ru Переменная включает перегрузку операторов new/delete, + обеспечивающую последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en The variable enables overloading of new/delete operators + which provides sequential access to the allocation/deallocation functions + from different threads. \~ +\ingroup Base_Tools_IO +*/ +// --- +#define __OVERLOAD_MEMORY_ALLOCATE_FREE_ + +#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ + //---------------------------------------------------------------------------------------- + /// \ru Объявление функций new, delete и операторов доступа. \en Declaration of functions new, delete and access operators. \~ \ingroup Base_Tools_IO + // \ru операторы * и -> автоматически не перегружаются, \en operators * and -> are not overloaded automatically, + // \ru для их использования нужно писать примерно так: \n \en one should write like this to use them: \n + // \ru вместо ptr->F(); ptr->operator ->()->F(); \n \en instead of ptr->F(); ptr->operator ->()->F(); \n + // \ru или ptr->operator *().F(); \n \en or ptr->operator *().F(); \n + // \ru или ptr->operator Class*()->F(); \n \en or ptr->operator Class*()->F(); \n + // \ru Для ссылок так же. \en Similarly for references. + // --- + #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 ); \ + void * operator new [] ( size_t ); \ + void operator delete [] ( void * ); + + //-------------------------------------------------------------------------------------- + /// \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 ) \ + void * Class::operator new( size_t size ) { \ + return ::Allocate( size, typeid(Class).name() ); } \ + void Class::operator delete ( void *ptr, size_t size ) { \ + ::Free( ptr, size, typeid(Class).name() ); } \ + \ + void * Class::operator new[] ( size_t size ) { \ + return ::AllocateArray( size, typeid(Class[]).name()); } \ + void Class::operator delete[] ( void *ptr ) { \ + ::FreeArray( ptr, typeid(Class[]).name() ); } + +#else // __DEBUG_MEMORY_ALLOCATE_FREE_ + //-------------------------------------------------------------------------------------- + /// \ru Объявление функций new, delete и операторов доступа. \en Declaration of functions new, delete and access operators. \~ \ingroup Base_Tools_IO + // --- + #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 ) + +#if defined(__OVERLOAD_MEMORY_ALLOCATE_FREE_) && !defined(C3D_DEBUG) + + //-------------------------------------------------------------------------------------- + /// \ru Объявление операторов new и delete, обеспечивающих последовательное обращение + /// к функциям выделения/освобождения памяти из разных потоков. + /// Перегружаются все стандартные операторы new и delete. + /// \en Declaration of new and delete operators which provide sequential access + /// to the allocation/deallocation functions from different threads. + /// All standard new and delete operators are overloaded. \~ + /// \ingroup Base_Tools_IO + // --- + #define DECLARE_NEW_DELETE_CLASS_EX( Class ) \ + public: \ + void * operator new ( size_t ); \ + void * operator new ( size_t, const std::nothrow_t & ) throw(); \ + void * operator new ( size_t, void * ); \ + void * operator new [] ( size_t ); \ + void * operator new [] ( size_t, const std::nothrow_t & ) throw(); \ + void * operator new [] ( size_t, void * ); \ + void operator delete ( void * ); \ + void operator delete ( void *, const std::nothrow_t & ) throw(); \ + void operator delete ( void *, void* ); \ + void operator delete [] ( void * ); \ + void operator delete [] ( void *, const std::nothrow_t & ) throw(); \ + void operator delete [] ( void *, void * ); + + //-------------------------------------------------------------------------------------- + /// \ru Реализация операторов new и delete, обеспечивающая последовательное обращение + /// к функциям выделения/освобождения памяти из разных потоков. + /// Перегружаются все стандартные операторы new и delete. + /// \en Implementation of new and delete operators which provides sequential access + /// to the allocation/deallocation functions from different threads. + /// All standard new and delete operators are overloaded. \~ + /// \ingroup Base_Tools_IO + // --- + #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) \ + void* Class::operator new( size_t size ) { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new( size ); } \ + void Class::operator delete( void *ptr ) { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete( ptr ); } \ + \ + void* Class::operator new( size_t size, void *ptr ) { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new( size, ptr ); } \ + void Class::operator delete( void *ptr, void *ptr2 ) { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete( ptr, ptr2 ); } \ + \ + void* Class::operator new[]( size_t size ) { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new[]( size ); } \ + void Class::operator delete[]( void *ptr ) { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete[]( ptr ); } \ + \ + void* Class::operator new []( size_t size, void *ptr ) { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new[]( size, ptr ); } \ + void Class::operator delete []( void *ptr, void *ptr2 ) { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete[]( ptr, ptr2 ); } \ + \ + void* Class::operator new( size_t size, const std::nothrow_t &nt ) throw() { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new( size, nt ); } \ + void Class::operator delete( void *ptr, const std::nothrow_t &nt ) throw() { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete( ptr, nt ); } \ + \ + void* Class::operator new []( size_t size, const std::nothrow_t &nt ) throw() { \ + SET_MEMORY_SCOPED_LOCK; \ + return ::operator new[]( size, nt ); } \ + void Class::operator delete []( void *ptr, const std::nothrow_t &nt ) throw() { \ + SET_MEMORY_SCOPED_LOCK; \ + ::operator delete[]( ptr, nt ); } + +#else // __OVERLOAD_MEMORY_ALLOCATE_FREE_ + + //-------------------------------------------------------------------------------------- + /// \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 provides sequential access + /// to the allocation/deallocation functions from different threads. \~ + /// \ingroup Base_Tools_IO + // --- + #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) + +#endif // __OVERLOAD_MEMORY_ALLOCATE_FREE_ + +#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ + +//------------------------------------------------------------------------------ +/** \brief \ru Объявление класса Class поточным. + \en Declaration of class Class as a stream one. \~ + \details \ru Объявление класс Class поточным. + Устанавливается в декларации класса в файле *.h. + Декларирует операторы <<, >>, а также функции Read и Write, + которые должны быть определены в любом файле *.cpp + Class должен наследовать от TapeBase. + Для этого класса должен быть определен конструктор чтения, + а его тело должно быть в .cpp файле. \n + \en Declaration of class Class as a stream one. + It is set in the declaration of class in file *.h. + Declares operators <<, >> and also functions Read and Write + which must be defined in any file *.cpp + Class must be inherited from TapeBase. + The read constructor must be defined for the class + and its solid should be in .cpp file. \n \~ + \ingroup Base_Tools_IO +*/ +// --- +#define DECLARE_PERSISTENT_CLASS( Class ) \ + DECLARE_PERSISTENT_FUNCS( Class ); \ + DECLARE_PERSISTENT_OPS( Class ); \ + DECLARE_PERSISTENT_CTOR( Class ); \ + DECLARE_NEW_DELETE_CLASS( Class ); \ + DECLARE_CLASS_DESC_FUNC(Class) + +/** \brief \ru Аналог макроса DECLARE_PERSISTENT_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en Analog of DECLARE_PERSISTENT_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads. \~ +\details \ru Аналог макроса DECLARE_PERSISTENT_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков + (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). + \en Analog of DECLARE_PERSISTENT_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads + (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ +\ingroup Base_Tools_IO +*/ +// --- +#define DECLARE_PERSISTENT_CLASS_NEW_DEL( Class ) \ + DECLARE_PERSISTENT_CLASS( Class ) \ + DECLARE_NEW_DELETE_CLASS_EX( Class ) + +//------------------------------------------------------------------------------ +/** \brief \ru Реализация объявления DECLARE_PERSISTENT_CLASS. + \en Implementation of DECLARE_PERSISTENT_CLASS declaration. \~ + \details \ru Реализация объявления DECLARE_PERSISTENT_CLASS. + Описывает необходимые действия для поточного класса. + Устанавливается в любой .cpp файл. + Class должен наследовать от TapeBase. + Должны быть реализованы функции чтения Read и записи Write. \n + \en Implementation of DECLARE_PERSISTENT_CLASS declaration. + Describes the necessary operations for a stream class. + It is set into any .cpp file. + Class must be inherited from TapeBase. + Function Read of reading and function Write of writing should be implemented. \n \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_CLASS( AppID, Class ) \ + IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ); \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + +/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en Analog of IMP_PERSISTENT_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads. \~ + \details \ru Аналог макроса IMP_PERSISTENT_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков + (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). + \en Analog of IMP_PERSISTENT_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads + (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_CLASS_NEW_DEL( AppID, Class ) \ + IMP_PERSISTENT_CLASS( AppID, Class ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ); + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые действия для поточного класса без записи \en Describes the necessary operations for a stream class without writing. +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется наличие функций \en 2. There must be the following functions +// - void Class:Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// --- +#define IMP_PERSISTENT_RO_CLASS( AppID, Class ) \ + IMP_PERSISTENT_RO_REGISTRATION( AppID, Class ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) + +//------------------------------------------------------------------------------ +/** \brief \ru Аналог макроса IMP_PERSISTENT_RO_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en Analog of IMP_PERSISTENT_RO_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads. \~ + \details \ru Аналог макроса IMP_PERSISTENT_RO_CLASS + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков + (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). + \en Analog of IMP_PERSISTENT_RO_CLASS macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads + (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_RO_CLASS_NEW_DEL( AppID, Class ) \ + IMP_PERSISTENT_RO_CLASS( AppID, Class ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции для абстрактного \en Describes the necessary operations for abstract +// \ru поточного класса \en stream class +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется наличие функций \en 2. There must be the following functions +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// --- +#define IMP_A_PERSISTENT_CLASS( AppID, Class ) \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции абстрактного поточного класса, \en Describes the necessary operations for the abstract stream class +// \ru наследующего от другого такого же, и у которого \en inherited from another class which is the same and which +// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// \ru эти функции генерируются автоматически \en these functions are generated automatically +// --- +#define IMP_A_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ + void Class::Read( reader & in, Class * obj ) { \ + Base::Read( in, obj ); \ + } \ + void Class::Write( writer & out, const Class * obj ) { \ + Base::Write( out, obj ); \ + } \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции поточного класса, \en Describes the necessary operations of the stream class +// \ru наследующего от другого такого же, и у которого \en inherited from another class which is the same and which +// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// \ru эти функции генерируются автоматически \en these functions are generated automatically +// --- +#define IMP_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ + IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ + IMP_A_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) + +//------------------------------------------------------------------------------ +/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS_FROM_BASE + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en Analog of IMP_PERSISTENT_CLASS_FROM_BASE macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads. \~ + \details \ru Аналог макроса IMP_PERSISTENT_CLASS_FROM_BASE + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков + (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). + \en Analog of IMP_PERSISTENT_CLASS_FROM_BASE macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads + (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_CLASS_FROM_BASE_NEW_DEL( AppID, Class, Base ) \ + IMP_PERSISTENT_CLASS_FROM_BASE( AppID, Class, Base ) \ + IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции для поточного класса, \en Describes the necessary operations for the stream class +// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which +// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// --- +#define IMP_PERSISTENT_CLASS_WD( AppID, Class ) \ + IMP_PERSISTENT_REGISTRATION( AppID, Class ); \ + void Class::Read( reader &, Class * ) {} \ + void Class::Write( writer &, const Class * ) {} \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + +//---------------------------------------------------------------------------------------- +/** \brief \ru Аналог макроса IMP_PERSISTENT_CLASS_WD + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков. + \en Analog of IMP_PERSISTENT_CLASS_WD macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads. \~ + \details \ru Аналог макроса IMP_PERSISTENT_CLASS_WD + с возможностью перегрузки операторов new/delete, + обеспечивающий последовательное обращение к функциям + выделения/освобождения памяти из разных потоков + (включается переменной __OVERLOAD_MEMORY_ALLOCATE_FREE_). + \en Analog of IMP_PERSISTENT_CLASS_WD macro + with support of new/delete operators overloading which provides + sequential access to the allocation/deallocation functions + from different threads + (enabled by defining __OVERLOAD_MEMORY_ALLOCATE_FREE_). \~ + \ingroup Base_Tools_IO +*/ +// --- +#define IMP_PERSISTENT_CLASS_WD_NEW_DEL( AppID, Class ) \ + IMP_PERSISTENT_CLASS_WD( AppID, Class ); \ + IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции для абстрактного поточного класса, \en Describes the necessary operations for the abstract stream class +// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which +// \ru нет своих полей данных для записи в поток \en has no its own data fields for writing to stream +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// --- +#define IMP_A_PERSISTENT_CLASS_WD( AppID, Class ) \ + void Class::Read( reader &, Class * ) {} \ + void Class::Write( writer &, const Class * ) {} \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + + +//---------------------------------------------------------------------------------------- +// \ru Описывает необходимые операции для абстрактного поточного класса с проверкой главной версии потока (версии математического ядра), +// \en Describes the necessary operations for the abstract stream class with check of the main stream version (the mathenatical kernel version), +// \ru не наследующего ни от кого кроме TapeBase, и у которого \en which is not inherited from any class except TapeBase and which +// \ru нет своих полей данных для записи в поток. \en has no its own data fields for writing to stream. +// \ru Устанавливается в любой .cpp файл \en It is set to any .cpp file +// \ru Примечание : \en Note: +// \ru 1. Class должен наследовать от TapeBase \en 1. Class must be inherited from TapeBase +// \ru 2. Требуется (!!!) отсутствие (!!!) функций \en 2. The following functions must be (!!!) absent (!!!) +// - void Class::Read( reader& in, Class* obj ); +// - void Class::Write( writer& out, const Class* obj ); +// \ru где Class - имя класса \en where Class is a class name +// --- +#define IMP_A_PERSISTENT_MATH_CLASS_WD( AppID, Class ) \ + void Class::Read( reader &, Class * ) {} \ + void Class::Write( writer & out, const Class * ) \ + { if ( out.MathVersion() < wrv_FirstRelease ) out.setState( io::cantWriteObject ); } \ + IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + IMP_CLASS_DESC_FUNC( AppID, Class ) + + +#endif // __IO_TAPE_DEFINE_H + diff --git a/C3d/Include/m2b_mesh_curvature.h b/C3d/Include/m2b_mesh_curvature.h index cf269b9..c722d1f 100644 --- a/C3d/Include/m2b_mesh_curvature.h +++ b/C3d/Include/m2b_mesh_curvature.h @@ -32,8 +32,60 @@ struct MATH_CLASS MbCurvature 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 ) {} + /// \ru Конструктор копирования. \en Copy constructor. + MbCurvature( const MbCurvature & that ) + : k_h ( that.k_h ) + , k_g ( that.k_g ) + , k1 ( that.k1 ) + , k2 ( that.k2 ) + , normal ( that.normal ) + , meanNormal( that.meanNormal ) + , cdir1 ( that.cdir1 ) + , cdir2 ( that.cdir2 ) + {} + + /// \ru Оператор присваивания. \en An assignment operator. + MbCurvature & operator = ( const MbCurvature & that ) + { + k_h = that.k_h; + k_g = that.k_g; + k1 = that.k1; + k2 = that.k2; + normal = that.normal; + meanNormal = that.meanNormal; + cdir1 = that.cdir1; + cdir2 = that.cdir2; + return ( *this ); + } + /// \ru Функция копирования данных. \en Copy function of data. + void Init( const MbCurvature & that ) + { + k_h = that.k_h; + k_g = that.k_g; + k1 = that.k1; + k2 = that.k2; + normal = that.normal; + meanNormal = that.meanNormal; + cdir1 = that.cdir1; + cdir2 = that.cdir2; + } + /// \ru Очистка данных. \en Clear data. + void Clear() + { + k_h = 0.; + k_g = 0.; + k1 = 0.; + k2 = 0.; + normal = MbVector3D::zero; + meanNormal = MbVector3D::zero; + cdir1 = MbVector3D::zero; + cdir2 = MbVector3D::zero; + } + /// \ru Определена ли кривизна. \en Is curvature defined. + bool IsDefined() const { return meanNormal.Length2() > PARAM_EPSILON; } }; diff --git a/C3d/Include/math_x.h b/C3d/Include/math_x.h index 3086abf..cfe6981 100644 --- a/C3d/Include/math_x.h +++ b/C3d/Include/math_x.h @@ -132,6 +132,21 @@ namespace c3d { x = -1.0; return ::acos( x ); } + + + //------------------------------------------------------------------------------ + /** \brief \ru Функция проверки является ли заданное число конечным. + \en Function to check whether the given number is finite. \~ + \details \ru Функция проверки является ли заданное число конечным. \n + Если число имеет значение MB_INFINITY или MB_QNAN, то оно не является конечным. \n + \en Function to check whether the given number is finite. \n + If given number is MB_INFINITY or MB_QNAN then it is not finite. \n \~ + \ingroup Base_Tools + */ + inline bool IsFinite( double val ) + { + return isfinite( val ); + } } //----------------------------------------------------------------------------- diff --git a/C3d/Include/mb_cart_point.h b/C3d/Include/mb_cart_point.h index 63226f6..5bba8db 100644 --- a/C3d/Include/mb_cart_point.h +++ b/C3d/Include/mb_cart_point.h @@ -532,7 +532,7 @@ public : /// \ru Является ли точка неопределенной? \en Is the point undefined? bool IsUndefined() const { return (x == UNDEFINED_DBL || y == UNDEFINED_DBL); } - KNOWN_OBJECTS_RW_REF_OPERATORS( MbCartPoint ) + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbCartPoint, MATH_FUNC_EX ) DECLARE_NEW_DELETE_CLASS( MbCartPoint ) DECLARE_NEW_DELETE_CLASS_EX( MbCartPoint ) }; // MbCartPoint @@ -1131,35 +1131,6 @@ inline void MbDirection::operator = ( const MbCartPoint & pnt ) } -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Глобальные функции \en Global functions -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -/// \ru Чтение точки из потока. \en Reading of point from the stream. -// --- -inline reader & CALL_DECLARATION operator >> ( reader & in, MbCartPoint & obj ) { - in >> obj.x; - in >> obj.y; - - return in; -} - - -//------------------------------------------------------------------------------ -/// \ru Запись точки в поток. \en Writing of point to the stream. -// --- -inline writer & CALL_DECLARATION operator << ( writer & out, const MbCartPoint & obj ) { - out << obj.x; - out << obj.y; - - return out; -} - - //////////////////////////////////////////////////////////////////////////////// // // \ru Глобальные функции \en Global functions diff --git a/C3d/Include/mb_cross_point.h b/C3d/Include/mb_cross_point.h index 285555f..beef5e5 100644 --- a/C3d/Include/mb_cross_point.h +++ b/C3d/Include/mb_cross_point.h @@ -11,7 +11,6 @@ #define __MB_CROSS_POINT_H -#include #include diff --git a/C3d/Include/mb_data.h b/C3d/Include/mb_data.h index 27900ea..bf2708c 100644 --- a/C3d/Include/mb_data.h +++ b/C3d/Include/mb_data.h @@ -581,6 +581,8 @@ public: bool switchFixFirstPointAtNoisy; ///< \ru Флаг фиксации сплайна в начальной точке. \en Flag of fixing a spline at the first point. bool switchFixLastPointAtNoisy; ///< \ru Флаг фиксации сплайна в конечной точке. \en Flag of fixing a spline at the last point. + const MbNurbs3D * referenceCurve; ///< \ru Кривая для сравнения с результатом аппроксимации. \en Curve for result comparing. + /// \ru Выходные параметры. \en Output parameters. MbeFairWarning warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ MbResultType error; ///< \ru Ошибка о работе. \en The operation error. \~ @@ -608,8 +610,9 @@ public: realAccuracyBSpl( METRIC_ACCURACY*0.1 ), switchEndTangents( false ), switchEndCurvature( false ), firstCurvature( 0.0 ), lastCurvature( 0.0 ), smoothTorsion( false ), - clearanceNoisy( 0.002 ), clearanceNoisyIteration( 200 ), scaleParam( 1.0 ), + clearanceNoisy( 0.002 ), clearanceNoisyIteration( 10 ), scaleParam( 1.0 ), switchFixFirstPointAtNoisy( false ), switchFixLastPointAtNoisy( false ), + referenceCurve( nullptr ), warning( fwarn_Success ), error( rt_Success ), errInfo() {} ~MbFairCurveData(); @@ -623,6 +626,12 @@ public: //< \ru Получить данные для фиксации точек и касательных. \en Get данные для фиксации точек и касательных. const IndexVectorArray & GetFixConstraints() const { return fixData; } + ///< \ru Получить кривую для сравнения. \en Get curve for result comparing. + const MbNurbs3D * GetReferenceCurve() const { return referenceCurve; } + + ///< \ru Установить кривую для сравнения. \en Set curve for result comparing. + void SetReferenceCurve( const MbNurbs3D * pCurve ) { referenceCurve = pCurve; } + /// \ru Оператор присваивания. \en Assignment operator. MbFairCurveData & operator = ( const MbFairCurveData & other ); diff --git a/C3d/Include/mb_matrix.h b/C3d/Include/mb_matrix.h index c9744d6..df314c1 100644 --- a/C3d/Include/mb_matrix.h +++ b/C3d/Include/mb_matrix.h @@ -586,7 +586,7 @@ private: void CheckRotation() const { ::CheckRotation( *this, flag, true ); } public: - KNOWN_OBJECTS_RW_REF_OPERATORS( MbMatrix ) // \ru Для работы со ссылками и объектами класса \en For working with references and objects of the class. + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbMatrix, MATH_FUNC_EX ) // \ru Для работы со ссылками и объектами класса \en For working with references and objects of the class. DECLARE_NEW_DELETE_CLASS( MbMatrix ) DECLARE_NEW_DELETE_CLASS_EX( MbMatrix ) }; @@ -745,24 +745,6 @@ inline bool MbMatrix::IsSame( const MbMatrix & m2, double accuracy ) const } -//------------------------------------------------------------------------------ -// \ru чтение матрицы из потока \en Reading of matrix from stream -// --- -inline reader & CALL_DECLARATION operator >> ( reader & in, MbMatrix & obj ) { - in.readBytes( obj.el, sizeof(obj.el) ); - obj.flag = MB_UNSET; - return in; -} - -//------------------------------------------------------------------------------ -// \ru Запись матрицы в поток \en Writing of matrix to the stream -// --- -inline writer & CALL_DECLARATION operator << ( writer & out, const MbMatrix & obj ) { - out.writeBytes( (double *)obj.el, sizeof(obj.el) ); - return out; -} - - //------------------------------------------------------------------------------ /** \brief \ru Перемножить матрицы. diff --git a/C3d/Include/mb_matrix3d.h b/C3d/Include/mb_matrix3d.h index 28acc03..7678c77 100644 --- a/C3d/Include/mb_matrix3d.h +++ b/C3d/Include/mb_matrix3d.h @@ -11,7 +11,7 @@ #define __MB_MATRIX3D_H -#include +#include #include #include diff --git a/C3d/Include/mb_operation_result.h b/C3d/Include/mb_operation_result.h index a917644..2030d26 100644 --- a/C3d/Include/mb_operation_result.h +++ b/C3d/Include/mb_operation_result.h @@ -278,6 +278,8 @@ enum MbResultType { rt_CurveClosedBothSides, ///< \ru Кривая замкнулась с двух сторон. \en The curve has been closed at both sides. rt_BeyondLimitsExtension, ///< \ru Продленная поверхностная кривая вышла за границы поверхности. \en Extended surface curve abandons surface boundary. + rt_NonBijectiveFunc, ///< \ru Отображение множества значений параметра функции во множество значений параметра кривой не является взаимно однозначным. \en A map from function parameter range to curve parameter range is not bijective. + // \ru !!! СТРОКИ ВСТАВЛЯТЬ СТРОГО ПЕРЕД ЭТОЙ СТРОКОЙ !!!! \en !!! INSERT LINES STRICTLY BEFORE THIS LINE !!!! rt_ErrorTotal // \ru НИЖЕ НЕ ДОБАВЛЯТЬ! \en DON'T ADD BELOW! }; diff --git a/C3d/Include/mb_point_mating.h b/C3d/Include/mb_point_mating.h index 271f450..d9e6d3a 100644 --- a/C3d/Include/mb_point_mating.h +++ b/C3d/Include/mb_point_mating.h @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include diff --git a/C3d/Include/mb_smooth_nurbs_fit_curve.h b/C3d/Include/mb_smooth_nurbs_fit_curve.h index c606f5c..e7f7d77 100644 --- a/C3d/Include/mb_smooth_nurbs_fit_curve.h +++ b/C3d/Include/mb_smooth_nurbs_fit_curve.h @@ -17,6 +17,7 @@ #include #include +#include #include diff --git a/C3d/Include/mb_variables.h b/C3d/Include/mb_variables.h index 5e087cb..b60de8a 100644 --- a/C3d/Include/mb_variables.h +++ b/C3d/Include/mb_variables.h @@ -19,6 +19,10 @@ /** \ru \name Общие константы \en \name Common constants \{ */ + +constexpr double MB_INFINITY = std::numeric_limits::infinity(); ///< \ru Значение, обозначающее бесконечность для double. \en Value representing infinity for double. +constexpr double MB_QNAN = std::numeric_limits::quiet_NaN(); ///< \ru "Тихое" нечисло. \en Quiet Not-A-Number. + constexpr double MB_MAXDOUBLE = 1.0E+300; ///< \ru Максимальное значение double 1.7976931348623158E+308. \en Maximum value of double 1.7976931348623158E+308. constexpr double MB_MINDOUBLE = 1.0E-300; ///< \ru Минимальное значение double 2.2250738585072014E-308. \en Minimum value of double 2.2250738585072014E-308. diff --git a/C3d/Include/mb_vector.h b/C3d/Include/mb_vector.h index 8196d67..4d08092 100644 --- a/C3d/Include/mb_vector.h +++ b/C3d/Include/mb_vector.h @@ -15,7 +15,7 @@ #define __MB_VECTOR_H -#include +#include #include @@ -213,7 +213,7 @@ public : /// \ru Являются ли объекты равными? \en Are the objects equal? bool IsSame( const MbVector & other, double accuracy ) const; - KNOWN_OBJECTS_RW_REF_OPERATORS( MbVector ) + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbVector, MATH_FUNC_EX ) DECLARE_NEW_DELETE_CLASS( MbVector ) DECLARE_NEW_DELETE_CLASS_EX( MbVector ) }; // MbVector @@ -711,7 +711,7 @@ public : /// \ru Являются ли объекты равными? \en Are the objects equal? bool IsSame( const MbDirection & other, double accuracy ) const; - KNOWN_OBJECTS_RW_REF_OPERATORS( MbDirection ) + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbDirection, MATH_FUNC_EX ) DECLARE_NEW_DELETE_CLASS( MbDirection ) DECLARE_NEW_DELETE_CLASS_EX( MbDirection ) }; // MbDirection @@ -1054,53 +1054,6 @@ inline bool MbDirection::IsSame( const MbDirection & other, double accuracy ) co //////////////////////////////////////////////////////////////////////////////// -//------------------------------------------------------------------------------ -/// \ru Чтение вектора из потока. \en Reading vector from stream. -// --- -inline reader & CALL_DECLARATION operator >> ( reader & in, MbVector & obj ) { - in >> obj.x; - in >> obj.y; - return in; -} - - -//------------------------------------------------------------------------------ -/// \ru Запись вектора в поток. \en Writing vector to stream. -// --- -inline writer & CALL_DECLARATION operator << ( writer & out, const MbVector & obj ) { - out << obj.x; - out << obj.y; - return out; -} - - -//------------------------------------------------------------------------------ -/// \ru Чтение нормализованного вектора из потока. \en Reading normalized vector from stream. -// --- -inline reader & CALL_DECLARATION operator >> ( reader & in, MbDirection & obj ) { - in >> obj.ax; - in >> obj.ay; - return in; -} - - -//------------------------------------------------------------------------------ -/// \ru Запись нормализованного вектора в поток. \en Writing normalized vector to stream. -// --- -inline writer & CALL_DECLARATION operator << ( writer & out, const MbDirection & obj ) { - out << obj.ax; - out << obj.ay; - return out; -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Глобальные функции \en Global functions -// -//////////////////////////////////////////////////////////////////////////////// - - //------------------------------------------------------------------------------ /** \brief \ru Вычисление минимального угла между двумя векторами \en Calculate minimal angle between two vectors \~ diff --git a/C3d/Include/mb_vector3d.h b/C3d/Include/mb_vector3d.h index 9b9bc69..8bb5f94 100644 --- a/C3d/Include/mb_vector3d.h +++ b/C3d/Include/mb_vector3d.h @@ -11,7 +11,7 @@ #define __MB_VECTOR3D_H -#include +#include #include @@ -585,7 +585,8 @@ inline void MbVector3D::Add( const MbVector3D & v1, double t1, const MbVector3D //------------------------------------------------------------------------------ // \ru Добавить к вектору значения. \en Add values to vector. // --- -inline void MbVector3D::Add( const MbVector3D & v1, double t1, const MbVector3D & v2, double t2, +inline void MbVector3D::Add( const MbVector3D & v1, double t1, + const MbVector3D & v2, double t2, const MbVector3D & v3, double t3 ) { x += v1.x * t1 + v2.x * t2 + v3.x * t3; @@ -641,9 +642,9 @@ inline MbVector3D operator * ( double factor, const MbVector3D & vector ) // --- inline void MbVector3D::SetVecM( const MbVector3D & vF, const MbVector3D & vS ) { - x = vF.y * vS.z - vF.z * vS.y; - y = vF.z * vS.x - vF.x * vS.z; - z = vF.x * vS.y - vF.y * vS.x; + Init( vF.y * vS.z - vF.z * vS.y, + vF.z * vS.x - vF.x * vS.z, + vF.x * vS.y - vF.y * vS.x ); } @@ -652,9 +653,9 @@ inline void MbVector3D::SetVecM( const MbVector3D & vF, const MbVector3D & vS ) // --- inline void MbVector3D::SetVecM( const MbVector3D & vF, const MbVector3D & vS, double mulKoef ) { - x = ( vF.y * vS.z - vF.z * vS.y ) * mulKoef; - y = ( vF.z * vS.x - vF.x * vS.z ) * mulKoef; - z = ( vF.x * vS.y - vF.y * vS.x ) * mulKoef; + Init( ( vF.y * vS.z - vF.z * vS.y ) * mulKoef, + ( vF.z * vS.x - vF.x * vS.z ) * mulKoef, + ( vF.x * vS.y - vF.y * vS.x ) * mulKoef ); } @@ -663,9 +664,9 @@ inline void MbVector3D::SetVecM( const MbVector3D & vF, const MbVector3D & vS, d // --- inline void MbVector3D::AddVecM( const MbVector3D & vF, const MbVector3D & vS ) { - x += vF.y * vS.z - vF.z * vS.y; - y += vF.z * vS.x - vF.x * vS.z; - z += vF.x * vS.y - vF.y * vS.x; + Init ( x + vF.y * vS.z - vF.z * vS.y, + y + vF.z * vS.x - vF.x * vS.z, + z + vF.x * vS.y - vF.y * vS.x); } @@ -674,9 +675,9 @@ inline void MbVector3D::AddVecM( const MbVector3D & vF, const MbVector3D & vS ) // --- inline void MbVector3D::AddVecM( const MbVector3D & vF, const MbVector3D & vS, double mulKoef ) { - x += (vF.y * vS.z - vF.z * vS.y) * mulKoef; - y += (vF.z * vS.x - vF.x * vS.z) * mulKoef; - z += (vF.x * vS.y - vF.y * vS.x) * mulKoef; + Init ( x + (vF.y * vS.z - vF.z * vS.y) * mulKoef, + y + (vF.z * vS.x - vF.x * vS.z) * mulKoef, + z + (vF.x * vS.y - vF.y * vS.x) * mulKoef ); } @@ -725,9 +726,9 @@ inline bool MbVector3D::IsSame( const MbVector3D & other, double accuracy ) cons inline void SetVecM( MbVector3D & vVec, const MbVector3D & vF, const MbVector3D & vS ) { - vVec.x = ( vF.y * vS.z - vF.z * vS.y ); - vVec.y = ( vF.z * vS.x - vF.x * vS.z ); - vVec.z = ( vF.x * vS.y - vF.y * vS.x ); + vVec.Init( vF.y * vS.z - vF.z * vS.y, + vF.z * vS.x - vF.x * vS.z, + vF.x * vS.y - vF.y * vS.x ); } //------------------------------------------------------------------------------ @@ -736,9 +737,9 @@ void SetVecM( MbVector3D & vVec, const MbVector3D & vF, const MbVector3D & vS ) inline void SetVecM( MbVector3D & vVec, const MbVector3D & vF, const MbVector3D & vS, double mulKoef ) { - vVec.x = ( vF.y * vS.z - vF.z * vS.y ) * mulKoef; - vVec.y = ( vF.z * vS.x - vF.x * vS.z ) * mulKoef; - vVec.z = ( vF.x * vS.y - vF.y * vS.x ) * mulKoef; + vVec.Init( ( vF.y * vS.z - vF.z * vS.y ) * mulKoef, + ( vF.z * vS.x - vF.x * vS.z ) * mulKoef, + ( vF.x * vS.y - vF.y * vS.x ) * mulKoef ); } diff --git a/C3d/Include/mesh_float_point3d.h b/C3d/Include/mesh_float_point3d.h index 6fdcd7e..8ff01af 100644 --- a/C3d/Include/mesh_float_point3d.h +++ b/C3d/Include/mesh_float_point3d.h @@ -9,7 +9,7 @@ #ifndef __MESH_FLOAT_POINT3D_H #define __MESH_FLOAT_POINT3D_H -#include +#include #include diff --git a/C3d/Include/mesh_plane_grid.h b/C3d/Include/mesh_plane_grid.h index 6797ba7..e968492 100644 --- a/C3d/Include/mesh_plane_grid.h +++ b/C3d/Include/mesh_plane_grid.h @@ -23,6 +23,7 @@ #ifndef __MESH_PLANE_GRID_H #define __MESH_PLANE_GRID_H +#include #include #include #include diff --git a/C3d/Include/mesh_polygon.h b/C3d/Include/mesh_polygon.h index 61fa11d..05b817d 100644 --- a/C3d/Include/mesh_polygon.h +++ b/C3d/Include/mesh_polygon.h @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// /** \file \brief \ru Полигоны. @@ -12,7 +12,7 @@ #include -#include +#include #include #include #include diff --git a/C3d/Include/mesh_primitive.h b/C3d/Include/mesh_primitive.h index a65b592..2d7f366 100644 --- a/C3d/Include/mesh_primitive.h +++ b/C3d/Include/mesh_primitive.h @@ -31,7 +31,6 @@ class MATH_CLASS MbPolygon; class MATH_CLASS MbFloatAxis3D; class MATH_CLASS MbFloatPoint3D; class MATH_CLASS MbGrid; -class MbGridTopology; struct MbGridSearchTree; @@ -64,8 +63,6 @@ typedef std::vector ConstGridsVector; typedef std::vector GridsSPtrVector; typedef std::vector ConstGridsSPtrVector; - -typedef DPtr GridTopologyPtr; } @@ -697,7 +694,6 @@ protected: */ mutable MbCube cube; mutable MbGridSearchTree * searchTree; ///< \ru Дерево поиска элементов. \en Elements search tree. - mutable c3d::GridTopologyPtr topo; ///< \ru Дополнительная информация о топологии триангуляции. \en Additional information about a topology of the triangulation. protected: // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. @@ -791,7 +787,6 @@ public: AddPoint( pnts[k] ); } DeleteSearchTree(); - ResetGridTopology(); cube.SetEmpty(); } /// \ru Добавить в триангуляцию нормали. \en Add normals to triangulation. @@ -823,7 +818,6 @@ public: for ( size_t k = 0; k < addCnt; ++k ) triangles.push_back( trngs[k] ); DeleteSearchTree(); - ResetGridTopology(); } /// \ru Добавить в триангуляцию объекты. \en Add objects to triangulation. template @@ -834,7 +828,6 @@ public: for ( size_t k = 0; k < addCnt; ++k ) quadrangles.push_back( qrngs[k] ); DeleteSearchTree(); - ResetGridTopology(); } /// \ru Добавить в коллекцию данных. \en Add scores to collection. @@ -905,13 +898,13 @@ public: virtual void NormalsInvert() = 0; /// \ru Добавить треугольник. \en Add a triangle. - void AddTriangle( const MbTriangle & triangle ) { triangles.push_back( triangle ); DeleteSearchTree(); ResetGridTopology(); } + void AddTriangle( const MbTriangle & triangle ) { triangles.push_back( triangle ); DeleteSearchTree(); } /// \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 ); DeleteSearchTree(); ResetGridTopology(); } + void AddTriangle( uint j0, uint j1, uint j2, bool o ) { MbTriangle t( j0, j1, j2, o ); triangles.push_back( t ); DeleteSearchTree(); } /// \ru Добавить четырёхугольник. \en Add a quadrangle. - void AddQuadrangle( const MbQuadrangle & quadrangle ) { quadrangles.push_back( quadrangle ); DeleteSearchTree(); ResetGridTopology(); } + void AddQuadrangle( const MbQuadrangle & quadrangle ) { quadrangles.push_back( quadrangle ); DeleteSearchTree(); } /// \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 ); DeleteSearchTree(); ResetGridTopology(); } + void AddQuadrangle( uint j0, uint j1, uint j2, uint j3, bool o ) { MbQuadrangle t( j0, j1, j2, j3, o ); quadrangles.push_back( t ); DeleteSearchTree(); } /// \ru Добавить полигон. \en Add a polygon. void AddGridLoop( MbGridLoop & poly ) { loops.push_back( &poly ); } @@ -1236,15 +1229,6 @@ public: \en Returns true if something was found. \~ */ bool FindIntersectingElements( const MbAxis3D & ray, c3d::IndicesVector & triIndices, c3d::IndicesVector & quadIndices, double eps = METRIC_EPSILON ) const; -public: - /// \ru Готова ли топология триангуляции. \en Whether information about triangulation topology is ready. - bool IsGridTopologyReady() const { return topo != nullptr; } - /// \ru Создать новый временный объект информации о топологии. \en Create new temporary maintenance object information about triangulation topology. - const MbGridTopology * CreateGridTopology( bool keepExisting ) const; - /// \ru Получить временный объект информации о топологии. \en Get a temporary maintenance object information about triangulation topology. - const MbGridTopology * GetGridTopology() const { return topo.get(); } - /// \ru Удалить информацию о топологии. \en Delete a information about triangulation topology. - void ResetGridTopology() const; protected: /// \ru Переместить дерево поиска элементов. \en Move elements search tree. void MoveSearchTree( const MbVector3D & ) const; diff --git a/C3d/Include/model_tree_data.h b/C3d/Include/model_tree_data.h index 77e654a..a810e50 100644 --- a/C3d/Include/model_tree_data.h +++ b/C3d/Include/model_tree_data.h @@ -9,7 +9,7 @@ #define __MODEL_TREE_DATA_H -#include +#include #include #include #include diff --git a/C3d/Include/name_flags.h b/C3d/Include/name_flags.h index c196596..4ebce59 100644 --- a/C3d/Include/name_flags.h +++ b/C3d/Include/name_flags.h @@ -11,7 +11,7 @@ #define __NAME_FLAGS_H -#include +#include #include @@ -38,7 +38,7 @@ public: /// \ru Получить все битовые флаги. \en Get all bit-flags. uint8 GetFlags() const { return flags; } - KNOWN_OBJECTS_RW_REF_OPERATORS( MbFlags ) + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbFlags, MATH_FUNC_EX ) }; diff --git a/C3d/Include/name_item.h b/C3d/Include/name_item.h index fe27d7f..ec95705 100644 --- a/C3d/Include/name_item.h +++ b/C3d/Include/name_item.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/C3d/Include/op_binding_data.h b/C3d/Include/op_binding_data.h index c653378..d9fd3b6 100644 --- a/C3d/Include/op_binding_data.h +++ b/C3d/Include/op_binding_data.h @@ -13,6 +13,7 @@ #include #include #include +#include class MATH_CLASS MbMatrix3D; diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h index c20dccb..2d43423 100644 --- a/C3d/Include/op_curve_parameter.h +++ b/C3d/Include/op_curve_parameter.h @@ -217,9 +217,9 @@ public: /// \ru Получить конец кривой на первой поверхности. \en Get the curve end on the first surface. const MbCartPoint & GetSurf1End() const { return _uv1end; } /// \ru Получить начало кривой на второй поверхности. \en Get the curve beginning on the second surface. - const MbCartPoint & GetSurf2Beg() const { return _uv1beg; } + const MbCartPoint & GetSurf2Beg() const { return _uv2beg; } /// \ru Получить конец кривой на второй поверхности. \en Get the curve end on the second surface. - const MbCartPoint & GetSurf2End() const { return _uv1end; } + const MbCartPoint & GetSurf2End() const { return _uv2end; } /// \ru Строить ли кривую на расширении первой поверхности. \en Whether to build the curve on the first surface extension. bool IfSurf1Ext () const { return _ext1; } @@ -255,9 +255,9 @@ enum MbeIntCurveBuildType { //------------------------------------------------------------------------------ /** \brief \ru Параметры кривой пересечения поверхностей. - \en Parameters of an surface intersection curve. \~ - \details \ru Параметры эквидистантной кривой в пространстве по трехмерной кривой и вектору направления. \n - \en Parameters of an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \en Parameters of a surface intersection curve. \~ + \details \ru Параметры кривой пересечения поверхностей. Варианты работы см. в #MbeIntCurveBuildType. \n + \en Parameters of a surface intersection curve. Work cases are in #MbeIntCurveBuildType. \n \~ \ingroup Curve3D_Building_Parameters */ // --- class MATH_CLASS MbIntCurveParams { @@ -736,10 +736,6 @@ public: \en Parameters of extension from the end point. \~ \param[in] allowClosure - \ru Допустимо ли замыкание удлиненной кривой. \en Whether closure of the extended curve is allowed. \~ - \param[in] alongSurface - \ru Если true, то будет удлинена параметрическая (2D) кривая. - Если false, будет удлинена пространственная (3D) кривая. - \en If that is true then the parametric (2D) curve will be extended. - If that is false then the spatial (3D) curve will be extended.\~ \param[in] operName - \ru Именователь операции. \en An object defining names generation in the operation. \~ */ @@ -809,7 +805,7 @@ public: VERSION GetVersion() const { return _operName->GetMathVersion(); } /// \ru Минимальная величина зазора (в параметрическом пространстве) для случая, когда запрещено создания замкнутых кривых. \en Minimal gap value (in parametric space) for case when closed result curves are forbidden. \~ - double GetMinUnclosedGap() const { return GetPrecision(); } + double GetMinUnclosedGap() const { return Math::metricPrecision; } /// \ru Оператор присваивания. \en Assignment operator. \~ MbCurveExtensionParameters & operator=( const MbCurveExtensionParameters & other ); @@ -1543,6 +1539,8 @@ public: bool _fixFirstPointNoisy; ///< \ru Флаг фиксации сплайна в начальной точке. \en Flag of fixing a spline at the first point. bool _fixLastPointNoisy; ///< \ru Флаг фиксации сплайна в конечной точке. \en Flag of fixing a spline at the last point. + const MbNurbs3D * _referenceCurve; ///< \ru Кривая для сравнения с результатом аппроксимации. \en Curve for result comparing. + // \ru Диагностика. \en The diagnostics. MbeFairWarning _warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ MbResultType _error; ///< \ru Ошибка о работе. \en The operation error. \~ @@ -1558,8 +1556,9 @@ public: _accountCurvature( fairCur_No ), _accountVectorInflect( fairVector_Tangent ), _fixPointTangent( fixPntTng_NotFix ), _degree( 8 ), _approx( fairApprox_IsoSpline ), _tangentCorrect( true ), _smoothTorsion( false ), _iterationsNumber( 1000 ), - _noisyDeviation( 0.002 ), _noisyIterations( 200 ), + _noisyDeviation( 0.002 ), _noisyIterations( 10 ), _fixFirstPointNoisy( false ), _fixLastPointNoisy( false ), + _referenceCurve( nullptr ), #ifdef C3D_DEBUG_FAIR_CURVES prt( nullptr ), #endif @@ -1573,6 +1572,12 @@ public: //< \ru Получить данные для фиксации точек и касательных. \en Get данные для фиксации точек и касательных. const IndexVectorArray & GetFixConstraints() const { return _fixData; } + ///< \ru Получить кривую для сравнения. \en Get curve for result comparing. + const MbNurbs3D * GetReferenceCurve() const { return _referenceCurve; } + + ///< \ru Установить кривую для сравнения. \en Set curve for result comparing. + void SetReferenceCurve( const MbNurbs3D * pCurve ) { _referenceCurve = pCurve; } + /// \ru Оператор присваивания. \en Assignment operator. MbFairCreateData & operator = ( const MbFairCreateData & other ); diff --git a/C3d/Include/pars_equation_tree.h b/C3d/Include/pars_equation_tree.h index 29b8ad2..e5c8001 100644 --- a/C3d/Include/pars_equation_tree.h +++ b/C3d/Include/pars_equation_tree.h @@ -12,7 +12,7 @@ #include // \ru СМВ для компиляции ICC \en СМВ for compilation by ICC -#include +#include #include #include #include diff --git a/C3d/Include/pars_tree_variable.h b/C3d/Include/pars_tree_variable.h index b2a1f13..dd831ec 100644 --- a/C3d/Include/pars_tree_variable.h +++ b/C3d/Include/pars_tree_variable.h @@ -9,7 +9,8 @@ #ifndef __ITTREEVARS_H #define __ITTREEVARS_H -#include +#include +#include class DefRange; class BTreeNode; diff --git a/C3d/Include/pars_user_function.h b/C3d/Include/pars_user_function.h index 30dd010..8a94a7b 100644 --- a/C3d/Include/pars_user_function.h +++ b/C3d/Include/pars_user_function.h @@ -11,7 +11,7 @@ #define __PARS_USER_FUNCTION_H -#include +#include #include #include #include diff --git a/C3d/Include/pars_yacc.h b/C3d/Include/pars_yacc.h index 6da6e3e..5b49d2e 100644 --- a/C3d/Include/pars_yacc.h +++ b/C3d/Include/pars_yacc.h @@ -25,7 +25,7 @@ struct ItIntervalTreeVariable; /// \ru Максимальная длина переменной. \en Maximum length of variable. constexpr size_t MAX_VARIABLE_NAME_LENGTH = 512; /// \ru Максимальная длина выражения. \en Maximum length of expression. -constexpr size_t MAX_EQU_LENGTH = 2048; +constexpr size_t MAX_EQU_LENGTH = 8192; // C3D-5977. //------------------------------------------------------------------------------- diff --git a/C3d/Include/plane_item.h b/C3d/Include/plane_item.h index ffcf465..2bd9d94 100644 --- a/C3d/Include/plane_item.h +++ b/C3d/Include/plane_item.h @@ -11,7 +11,7 @@ #define __PLANE_ITEM_H -#include +#include #include #include #include diff --git a/C3d/Include/point_frame.h b/C3d/Include/point_frame.h index a70b1ce..ed4e319 100644 --- a/C3d/Include/point_frame.h +++ b/C3d/Include/point_frame.h @@ -11,10 +11,10 @@ #define __POINT_FRAME_H +#include #include #include #include -#include #include #include #include diff --git a/C3d/Include/reference_item.h b/C3d/Include/reference_item.h index 338e0fb..be38bc3 100644 --- a/C3d/Include/reference_item.h +++ b/C3d/Include/reference_item.h @@ -19,6 +19,7 @@ #include #include #include +#include #include diff --git a/C3d/Include/space_instance.h b/C3d/Include/space_instance.h index 6fd7b62..9e97f39 100644 --- a/C3d/Include/space_instance.h +++ b/C3d/Include/space_instance.h @@ -98,6 +98,9 @@ public : // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ bool GetItems( MbeSpaceType type, const MbMatrix3D & from, RPArray & items, SArray & matrs ) override; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + std::vector> & items, std::vector & matrs ) override; // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const override; diff --git a/C3d/Include/space_item.h b/C3d/Include/space_item.h index badc63a..87689ed 100644 --- a/C3d/Include/space_item.h +++ b/C3d/Include/space_item.h @@ -11,9 +11,9 @@ #define __SPACE_ITEM_H -#include -#include +#include #include +#include #include #include #include diff --git a/C3d/Include/surf_evolution_surface.h b/C3d/Include/surf_evolution_surface.h index cef029f..7ca11c5 100644 --- a/C3d/Include/surf_evolution_surface.h +++ b/C3d/Include/surf_evolution_surface.h @@ -224,6 +224,7 @@ public: void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const override; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const override; // \ru NURBS копия поверхности. \en NURBS copy of a surface. + MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const override; // \ru NURBS копия поверхности. \en NURBS copy of a surface. MbSurface * Offset( double d, bool same ) const override; // \ru Создание эквидистантной поверхности. \en Create an offset surface. // \ru Подобные ли поверхности для объединения (слива) \en Whether the surfaces to union (joining) are similar diff --git a/C3d/Include/surf_revolution_surface.h b/C3d/Include/surf_revolution_surface.h index 8c063bd..df05d0e 100644 --- a/C3d/Include/surf_revolution_surface.h +++ b/C3d/Include/surf_revolution_surface.h @@ -15,6 +15,7 @@ #include #include #include +#include class MATH_CLASS MbSurfaceContiguousData; diff --git a/C3d/Include/system_dependency.h b/C3d/Include/system_dependency.h index 0191f8a..36e3992 100644 --- a/C3d/Include/system_dependency.h +++ b/C3d/Include/system_dependency.h @@ -100,7 +100,6 @@ inline uint8 GetBValue(COLORREF rgb_color) #include -#include // #error is not supported when compiling with /clr or /clr:pure. // #include @@ -123,6 +122,7 @@ inline uint8 GetBValue(COLORREF rgb_color) #endif +class MbTimerImp; //------------------------------------------------------------------------------ /** \brief \ru Высокоточный таймер. \en High resolution timer. \~ @@ -131,17 +131,17 @@ inline uint8 GetBValue(COLORREF rgb_color) \ingroup Base_Tools */ // --- -class MbAccurateTimer { -typedef std::chrono::high_resolution_clock::time_point TimePoint; +class MATH_CLASS MbAccurateTimer { protected: - double lastTime; ///< \ru Время в секундах. \en Time in seconds. + double lastTime; ///< \ru Время в секундах. \en Time in seconds. private: - TimePoint begTime; ///< \ru Засечка времени. \en Time stamp. + MbTimerImp * imp; ///< \ru Реализация таймера. \en Timer implementation. public: /// \ru Конструктор. \en Constructor. - MbAccurateTimer() : lastTime( 0.0 ) {} - virtual ~MbAccurateTimer() {} + MbAccurateTimer(); + /// \ru Деструктор. \en Destructor. + virtual ~MbAccurateTimer(); /// \ru Сброшен ли таймер. \en Is empty timer? virtual bool IsEmpty () const { return !(lastTime > 0.0); } @@ -160,25 +160,6 @@ public: }; -//------------------------------------------------------------------------------ -// \ru Начать отсчет. \en Start time measurement. -//--- -inline void MbAccurateTimer::Begin() -{ - begTime = std::chrono::high_resolution_clock::now(); -} - -//------------------------------------------------------------------------------ -// \ru Закончить отсчет. \en Finish time measurement. -// --- -inline void MbAccurateTimer::End() -{ - TimePoint endTime = std::chrono::high_resolution_clock::now(); - double t = std::chrono::duration_cast< std::chrono::duration >(endTime - begTime).count(); - SetTime( t ); -} - - //------------------------------------------------------------------------------ /** \brief \ru Таймер со статистикой. \en Average timer. \~ @@ -187,22 +168,30 @@ inline void MbAccurateTimer::End() \ingroup Base_Tools */ // --- -class MbAverageTimer : public MbAccurateTimer +class MATH_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. + uint runCount; ///< \ru Количество запусков. \en Number of launches. public: /// \ru Конструктор. \en Constructor. MbAverageTimer() : avgTime( 0.0 ), minTime( 0.0 ), maxTime ( 0.0 ), runCount( 0 ) {} + /// \ru Деструктор. \en Destructor. + virtual ~MbAverageTimer() {} + ///< \ru Пустой таймер? \en Empty timer? virtual bool IsEmpty() const { return (runCount == 0); } + ///< \ru Сбросить таймер. \en Reset timer. virtual void SetEmpty(); + ///< \ru Добавить значение. \en Add value. virtual bool SetTime( double ); + ///< \ru Получить cреднее время в секундах. \en Get average time in seconds. double GetAvg() const { return avgTime; } + ///< \ru Получить минимальное время в секундах. \en Get minimal time in seconds. double GetMin() const { return minTime; } + ///< \ru Получить максимальное время в секундах. \en Get maximal time in seconds. double GetMax() const { return maxTime; } }; diff --git a/C3d/Include/system_types.h b/C3d/Include/system_types.h index f4f5662..8ab53d9 100644 --- a/C3d/Include/system_types.h +++ b/C3d/Include/system_types.h @@ -73,7 +73,7 @@ typedef uint32 VERSION; ///< \ru Версия. \en Version. \~ /** \} */ //addtogroup Base_Tools #include - +#include //------------------------------------------------------------------------------ // \ru Системные лимиты \en System limits //--- diff --git a/C3d/Include/tool_mutex.h b/C3d/Include/tool_mutex.h index 9f1dab0..cd90d34 100644 --- a/C3d/Include/tool_mutex.h +++ b/C3d/Include/tool_mutex.h @@ -550,6 +550,9 @@ public: */ CommonMutex * GetLock() const; +protected: + MbPersistentSyncItem( const MbPersistentSyncItem & ); + MbPersistentSyncItem & operator = ( const MbPersistentSyncItem & ); }; //------------------------------------------------------------------------------ @@ -582,6 +585,7 @@ public: \en Get a pointer to the mutex object. */ CommonRecursiveMutex * GetLock() const; + protected: MbPersistentNestSyncItem( const MbPersistentNestSyncItem & ); MbPersistentNestSyncItem & operator = ( const MbPersistentNestSyncItem & ); diff --git a/C3d/Include/topology_item.h b/C3d/Include/topology_item.h index 047910b..f05c8f6 100644 --- a/C3d/Include/topology_item.h +++ b/C3d/Include/topology_item.h @@ -11,7 +11,7 @@ #define __TOPOLOGY_ITEM_H -#include +#include #include #include #include diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index 7eb61ff..16f807f 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 3877236..0437b8e 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 fd8b9ee..1e10696 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 7abdee0..e77b6db 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ