From 985def3416a9eb620aaa60d386a7108ee7c523f2 Mon Sep 17 00:00:00 2001 From: wmayer Date: Fri, 10 Nov 2023 18:27:44 +0100 Subject: [PATCH] Base: apply clang format --- src/Base/Axis.cpp | 15 +- src/Base/Axis.h | 41 +- src/Base/AxisPy.xml | 26 +- src/Base/AxisPyImp.cpp | 47 +- src/Base/BaseClass.cpp | 18 +- src/Base/BaseClass.h | 225 ++-- src/Base/BaseClassPyImp.cpp | 27 +- src/Base/BindingManager.cpp | 10 +- src/Base/BindingManager.h | 11 +- src/Base/Bitmask.h | 2 + src/Base/BoundBox.h | 896 ++++++------- src/Base/BoundBoxPy.xml | 154 +-- src/Base/BoundBoxPyImp.cpp | 327 ++--- src/Base/Builder3D.cpp | 447 +++---- src/Base/Builder3D.h | 199 ++- src/Base/Console.cpp | 634 +++++---- src/Base/Console.h | 700 +++++----- src/Base/ConsoleObserver.cpp | 173 +-- src/Base/ConsoleObserver.h | 93 +- src/Base/Converter.h | 68 +- src/Base/CoordinateSystem.cpp | 62 +- src/Base/CoordinateSystem.h | 36 +- src/Base/CoordinateSystemPyImp.cpp | 43 +- src/Base/Debugger.cpp | 12 +- src/Base/Debugger.h | 17 +- src/Base/DualNumber.h | 50 +- src/Base/DualQuaternion.cpp | 95 +- src/Base/DualQuaternion.h | 103 +- src/Base/Exception.cpp | 679 +++++----- src/Base/Exception.h | 841 ++++++------ src/Base/ExceptionFactory.cpp | 19 +- src/Base/ExceptionFactory.h | 30 +- src/Base/Factory.cpp | 76 +- src/Base/Factory.h | 45 +- src/Base/FileInfo.cpp | 273 ++-- src/Base/FileInfo.h | 70 +- src/Base/FileTemplate.cpp | 5 +- src/Base/FileTemplate.h | 32 +- src/Base/FutureWatcherProgress.cpp | 10 +- src/Base/FutureWatcherProgress.h | 10 +- src/Base/GeometryPyCXX.cpp | 84 +- src/Base/GeometryPyCXX.h | 154 ++- src/Base/Handle.cpp | 16 +- src/Base/Handle.h | 82 +- src/Base/InputSource.cpp | 66 +- src/Base/InputSource.h | 96 +- src/Base/Interpreter.cpp | 428 ++++--- src/Base/Interpreter.h | 172 ++- src/Base/Matrix.cpp | 883 +++++++------ src/Base/Matrix.h | 268 ++-- src/Base/MatrixPyImp.cpp | 462 ++++--- src/Base/MemDebug.cpp | 210 +-- src/Base/MemDebug.h | 5 +- src/Base/Mutex.cpp | 11 +- src/Base/Mutex.h | 6 +- src/Base/Observer.cpp | 5 +- src/Base/Observer.h | 297 ++--- src/Base/Parameter.cpp | 1270 +++++++++++-------- src/Base/Parameter.h | 211 +-- src/Base/ParameterPy.cpp | 456 ++++--- src/Base/Parser.bat | 2 +- src/Base/Persistence.cpp | 58 +- src/Base/Persistence.h | 46 +- src/Base/PersistencePy.xml | 30 +- src/Base/PersistencePyImp.cpp | 51 +- src/Base/Placement.cpp | 35 +- src/Base/Placement.h | 58 +- src/Base/PlacementPy.xml | 100 +- src/Base/PlacementPyImp.cpp | 258 ++-- src/Base/PreCompiled.h | 11 +- src/Base/Precision.h | 117 +- src/Base/PrecisionPyImp.cpp | 32 +- src/Base/ProgressIndicatorPy.cpp | 23 +- src/Base/ProgressIndicatorPy.h | 10 +- src/Base/PyExport.h | 137 +- src/Base/PyObjectBase.cpp | 18 +- src/Base/PyObjectBase.h | 4 +- src/Base/PyTools.c | 119 +- src/Base/PyTools.h | 68 +- src/Base/PyWrapParseTupleAndKeywords.h | 76 +- src/Base/PythonTypeExt.cpp | 10 +- src/Base/PythonTypeExt.h | 12 +- src/Base/QtTools.cpp | 12 +- src/Base/QtTools.h | 24 +- src/Base/Quantity.cpp | 425 ++++--- src/Base/Quantity.h | 183 +-- src/Base/QuantityLexer.c | 84 +- src/Base/QuantityParser.c | 2 + src/Base/QuantityParser.h | 2 + src/Base/QuantityPyImp.cpp | 404 +++--- src/Base/Reader.cpp | 187 +-- src/Base/Reader.h | 107 +- src/Base/Rotation.cpp | 761 +++++------ src/Base/Rotation.h | 70 +- src/Base/RotationPyImp.cpp | 387 +++--- src/Base/Sequencer.cpp | 116 +- src/Base/Sequencer.h | 54 +- src/Base/SmartPtrPy.cpp | 183 +-- src/Base/SmartPtrPy.h | 31 +- src/Base/StackWalker.cpp | 62 +- src/Base/StackWalker.h | 76 +- src/Base/Stream.cpp | 379 +++--- src/Base/Stream.h | 207 +-- src/Base/Swap.cpp | 104 +- src/Base/Swap.h | 42 +- src/Base/TimeInfo.cpp | 32 +- src/Base/TimeInfo.h | 102 +- src/Base/Tools.cpp | 143 ++- src/Base/Tools.h | 144 ++- src/Base/Tools2D.cpp | 663 +++++----- src/Base/Tools2D.h | 493 ++++--- src/Base/Tools3D.cpp | 105 +- src/Base/Tools3D.h | 37 +- src/Base/Translate.cpp | 98 +- src/Base/Translate.h | 9 +- src/Base/Type.cpp | 216 ++-- src/Base/Type.h | 127 +- src/Base/TypePyImp.cpp | 97 +- src/Base/Unit.cpp | 16 +- src/Base/Unit.h | 69 +- src/Base/UnitPyImp.cpp | 135 +- src/Base/UnitsApi.cpp | 127 +- src/Base/UnitsApi.h | 57 +- src/Base/UnitsApiPy.cpp | 103 +- src/Base/UnitsSchema.cpp | 5 +- src/Base/UnitsSchema.h | 57 +- src/Base/UnitsSchemaCentimeters.cpp | 8 +- src/Base/UnitsSchemaCentimeters.h | 15 +- src/Base/UnitsSchemaFemMilliMeterNewton.cpp | 6 +- src/Base/UnitsSchemaFemMilliMeterNewton.h | 10 +- src/Base/UnitsSchemaImperial1.cpp | 163 +-- src/Base/UnitsSchemaImperial1.h | 70 +- src/Base/UnitsSchemaInternal.cpp | 38 +- src/Base/UnitsSchemaInternal.h | 10 +- src/Base/UnitsSchemaMKS.cpp | 41 +- src/Base/UnitsSchemaMKS.h | 10 +- src/Base/UnitsSchemaMmMin.cpp | 7 +- src/Base/UnitsSchemaMmMin.h | 10 +- src/Base/Uuid.cpp | 7 +- src/Base/Uuid.h | 17 +- src/Base/Vector3D.cpp | 299 ++--- src/Base/Vector3D.h | 228 ++-- src/Base/VectorPy.xml | 82 +- src/Base/VectorPyImp.cpp | 382 +++--- src/Base/ViewProj.cpp | 39 +- src/Base/ViewProj.h | 54 +- src/Base/Writer.cpp | 81 +- src/Base/Writer.h | 88 +- src/Base/XMLTools.cpp | 42 +- src/Base/XMLTools.h | 30 +- src/Base/ZipHeader.cpp | 73 +- src/Base/ZipHeader.h | 26 +- src/Base/swigpyrun.cpp | 32 +- src/Base/swigpyrun.inl | 63 +- 154 files changed, 11874 insertions(+), 9872 deletions(-) diff --git a/src/Base/Axis.cpp b/src/Base/Axis.cpp index 6b615cece2..45959d991b 100644 --- a/src/Base/Axis.cpp +++ b/src/Base/Axis.cpp @@ -27,10 +27,9 @@ using namespace Base; Axis::Axis(const Vector3d& Orig, const Vector3d& Dir) - : _base{Orig} - , _dir{Dir} -{ -} + : _base {Orig} + , _dir {Dir} +{} void Axis::reverse() { @@ -49,24 +48,24 @@ void Axis::move(const Vector3d& MovVec) _base += MovVec; } -bool Axis::operator ==(const Axis& that) const +bool Axis::operator==(const Axis& that) const { return (this->_base == that._base) && (this->_dir == that._dir); } -bool Axis::operator !=(const Axis& that) const +bool Axis::operator!=(const Axis& that) const { return !(*this == that); } -Axis& Axis::operator *=(const Placement &p) +Axis& Axis::operator*=(const Placement& p) { p.multVec(this->_base, this->_base); p.getRotation().multVec(this->_dir, this->_dir); return *this; } -Axis Axis::operator *(const Placement &p) const +Axis Axis::operator*(const Placement& p) const { Axis a(*this); a *= p; diff --git a/src/Base/Axis.h b/src/Base/Axis.h index 3a2b963c38..b0ef8b04b3 100644 --- a/src/Base/Axis.h +++ b/src/Base/Axis.h @@ -27,7 +27,8 @@ #include "Placement.h" #include "Vector3D.h" -namespace Base { +namespace Base +{ /** * The Axis class. @@ -41,12 +42,24 @@ public: Axis(Axis&&) = default; Axis(const Vector3d& Orig, const Vector3d& Dir); /// Destruction - ~Axis () = default; + ~Axis() = default; - const Vector3d& getBase() const {return _base;} - const Vector3d& getDirection() const {return _dir;} - void setBase(const Vector3d& Orig) {_base=Orig;} - void setDirection(const Vector3d& Dir) {_dir=Dir;} + const Vector3d& getBase() const + { + return _base; + } + const Vector3d& getDirection() const + { + return _dir; + } + void setBase(const Vector3d& Orig) + { + _base = Orig; + } + void setDirection(const Vector3d& Dir) + { + _dir = Dir; + } void reverse(); Axis reversed() const; @@ -54,12 +67,12 @@ public: /** Operators. */ //@{ - Axis& operator *=(const Placement &p); - Axis operator *(const Placement &p) const; - bool operator ==(const Axis&) const; - bool operator !=(const Axis&) const; - Axis& operator =(const Axis&) = default; - Axis& operator =(Axis&&) = default; + Axis& operator*=(const Placement& p); + Axis operator*(const Placement& p) const; + bool operator==(const Axis&) const; + bool operator!=(const Axis&) const; + Axis& operator=(const Axis&) = default; + Axis& operator=(Axis&&) = default; //@} private: @@ -67,6 +80,6 @@ private: Vector3d _dir; }; -} // namespace Base +} // namespace Base -#endif // BASE_AXIS_H +#endif // BASE_AXIS_H diff --git a/src/Base/AxisPy.xml b/src/Base/AxisPy.xml index 65efaf8413..4f4798b001 100644 --- a/src/Base/AxisPy.xml +++ b/src/Base/AxisPy.xml @@ -13,18 +13,18 @@ FatherNamespace="Base"> - Base.Axis class. + Base.Axis class. -An Axis defines a direction and a position (base) in 3D space. +An Axis defines a direction and a position (base) in 3D space. -The following constructors are supported: +The following constructors are supported: Axis() -Empty constructor. +Empty constructor. Axis(axis) Copy constructor. -axis : Base.Axis +axis : Base.Axis Axis(base, direction) Define from a position and a direction. @@ -34,34 +34,34 @@ direction : Base.Vector > - copy() -> Base.Axis + copy() -> Base.Axis Returns a copy of this Axis. - move(vector) -> None + move(vector) -> None -Move the axis base along the given vector. +Move the axis base along the given vector. -vector : Base.Vector +vector : Base.Vector Vector by which to move the axis. - multiply(placement) -> Base.Axis + multiply(placement) -> Base.Axis -Multiply this axis by a placement. +Multiply this axis by a placement. -placement : Base.Placement +placement : Base.Placement Placement by which to multiply the axis. - reversed() -> Base.Axis + reversed() -> Base.Axis Compute the reversed axis. This returns a new Base.Axis with the original direction reversed. diff --git a/src/Base/AxisPyImp.cpp b/src/Base/AxisPyImp.cpp index d4e0e199ae..57de505bf5 100644 --- a/src/Base/AxisPyImp.cpp +++ b/src/Base/AxisPyImp.cpp @@ -39,14 +39,15 @@ std::string AxisPy::representation() const AxisPy::PointerType ptr = getAxisPtr(); std::stringstream str; str << "Axis [Base=("; - str << ptr->getBase().x << ","<< ptr->getBase().y << "," << ptr->getBase().z; + str << ptr->getBase().x << "," << ptr->getBase().y << "," << ptr->getBase().z; str << "), Direction=("; - str << ptr->getDirection().x << ","<< ptr->getDirection().y << "," << ptr->getDirection().z << ")]"; + str << ptr->getDirection().x << "," << ptr->getDirection().y << "," << ptr->getDirection().z + << ")]"; return str.str(); } -PyObject *AxisPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* AxisPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of AxisPy and the Twin object return new AxisPy(new Axis); @@ -55,22 +56,21 @@ PyObject *AxisPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pytho // constructor method int AxisPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - PyObject* o{}; + PyObject* o {}; if (PyArg_ParseTuple(args, "")) { return 0; } PyErr_Clear(); if (PyArg_ParseTuple(args, "O!", &(Base::AxisPy::Type), &o)) { - Base::Axis *a = static_cast(o)->getAxisPtr(); + Base::Axis* a = static_cast(o)->getAxisPtr(); *(getAxisPtr()) = *a; return 0; } PyErr_Clear(); - PyObject* d{}; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, - &(Base::VectorPy::Type), &d)) { + PyObject* d {}; + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &d)) { // NOTE: The first parameter defines the base (origin) and the second the direction. *getAxisPtr() = Base::Axis(static_cast(o)->value(), static_cast(d)->value()); @@ -81,42 +81,46 @@ int AxisPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -PyObject* AxisPy::move(PyObject * args) +PyObject* AxisPy::move(PyObject* args) { - PyObject *vec{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) + PyObject* vec {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) { return nullptr; + } getAxisPtr()->move(static_cast(vec)->value()); Py_Return; } -PyObject* AxisPy::multiply(PyObject * args) +PyObject* AxisPy::multiply(PyObject* args) { - PyObject *plm{}; - if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) + PyObject* plm {}; + if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) { return nullptr; + } Axis mult = (*getAxisPtr()) * (*static_cast(plm)->getPlacementPtr()); return new AxisPy(new Axis(mult)); } -PyObject* AxisPy::copy(PyObject * args) +PyObject* AxisPy::copy(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return new AxisPy(new Axis(*getAxisPtr())); } -PyObject* AxisPy::reversed(PyObject * args) +PyObject* AxisPy::reversed(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Axis a = getAxisPtr()->reversed(); return new AxisPy(new Axis(a)); } Py::Object AxisPy::getBase() const { - return Py::Vector(getAxisPtr()->getBase()); // NOLINT + return Py::Vector(getAxisPtr()->getBase()); // NOLINT } void AxisPy::setBase(Py::Object arg) @@ -126,7 +130,7 @@ void AxisPy::setBase(Py::Object arg) Py::Object AxisPy::getDirection() const { - return Py::Vector(getAxisPtr()->getDirection()); // NOLINT + return Py::Vector(getAxisPtr()->getDirection()); // NOLINT } void AxisPy::setDirection(Py::Object arg) @@ -134,7 +138,7 @@ void AxisPy::setDirection(Py::Object arg) getAxisPtr()->setDirection(Py::Vector(arg).toVector()); } -PyObject *AxisPy::getCustomAttributes(const char* /*attr*/) const +PyObject* AxisPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -143,4 +147,3 @@ int AxisPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - diff --git a/src/Base/BaseClass.cpp b/src/Base/BaseClass.cpp index a734dfee9e..2d6f024aca 100644 --- a/src/Base/BaseClass.cpp +++ b/src/Base/BaseClass.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "BaseClass.h" @@ -32,7 +32,7 @@ using namespace Base; -Type BaseClass::classTypeId = Base::Type::badType(); +Type BaseClass::classTypeId = Base::Type::badType(); // NOLINT //************************************************************************** @@ -64,9 +64,7 @@ void BaseClass::init() /* Set up entry in the type system. */ BaseClass::classTypeId = - Type::createType(Type::badType(), - "Base::BaseClass", - BaseClass::create); + Type::createType(Type::badType(), "Base::BaseClass", BaseClass::create); } Type BaseClass::getClassTypeId() @@ -80,7 +78,9 @@ Type BaseClass::getTypeId() const } -void BaseClass::initSubclass(Base::Type &toInit,const char* ClassName, const char *ParentName, +void BaseClass::initSubclass(Base::Type& toInit, + const char* ClassName, + const char* ParentName, Type::instantiationMethod method) { // don't init twice! @@ -88,7 +88,7 @@ void BaseClass::initSubclass(Base::Type &toInit,const char* ClassName, const cha // get the parent class Base::Type parentType(Base::Type::fromName(ParentName)); // forgot init parent! - assert(parentType != Base::Type::badType() ); + assert(parentType != Base::Type::badType()); // create the new type toInit = Base::Type::createType(parentType, ClassName, method); @@ -104,13 +104,13 @@ void BaseClass::initSubclass(Base::Type &toInit,const char* ClassName, const cha * * The default implementation returns 'None'. */ -PyObject *BaseClass::getPyObject() +PyObject* BaseClass::getPyObject() { assert(0); Py_Return; } -void BaseClass::setPyObject(PyObject *) +void BaseClass::setPyObject(PyObject*) { assert(0); } diff --git a/src/Base/BaseClass.h b/src/Base/BaseClass.h index 6d5abd285e..af78ec9aaa 100644 --- a/src/Base/BaseClass.h +++ b/src/Base/BaseClass.h @@ -31,72 +31,104 @@ using PyObject = struct _object; /// define for subclassing Base::BaseClass -#define TYPESYSTEM_HEADER() \ -public: \ - static Base::Type getClassTypeId(void); \ - virtual Base::Type getTypeId(void) const; \ - static void init(void);\ - static void *create(void);\ -private: \ - static Base::Type classTypeId +#define TYPESYSTEM_HEADER() \ +public: \ + static Base::Type getClassTypeId(void); \ + virtual Base::Type getTypeId(void) const; \ + static void init(void); \ + static void* create(void); \ + \ +private: \ + static Base::Type classTypeId /// Like TYPESYSTEM_HEADER, but declare getTypeId as 'override' -#define TYPESYSTEM_HEADER_WITH_OVERRIDE() \ -public: \ - static Base::Type getClassTypeId(void); \ - virtual Base::Type getTypeId(void) const override; \ - static void init(void);\ - static void *create(void);\ -private: \ - static Base::Type classTypeId +#define TYPESYSTEM_HEADER_WITH_OVERRIDE() \ +public: \ + static Base::Type getClassTypeId(void); \ + virtual Base::Type getTypeId(void) const override; \ + static void init(void); \ + static void* create(void); \ + \ +private: \ + static Base::Type classTypeId /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_P(_class_) \ -Base::Type _class_::getClassTypeId(void) { return _class_::classTypeId; } \ -Base::Type _class_::getTypeId(void) const { return _class_::classTypeId; } \ -Base::Type _class_::classTypeId = Base::Type::badType(); \ -void * _class_::create(void){\ - return new _class_ ();\ -} +#define TYPESYSTEM_SOURCE_P(_class_) \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::classTypeId = Base::Type::badType(); \ + void* _class_::create(void) \ + { \ + return new _class_(); \ + } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ -template<> Base::Type _class_::getClassTypeId(void) { return _class_::classTypeId; } \ -template<> Base::Type _class_::getTypeId(void) const { return _class_::classTypeId; } \ -template<> void * _class_::create(void){\ - return new _class_ ();\ -} +#define TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ + template<> \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + template<> \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + template<> \ + void* _class_::create(void) \ + { \ + return new _class_(); \ + } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ -Base::Type _class_::getClassTypeId(void) { return _class_::classTypeId; } \ -Base::Type _class_::getTypeId(void) const { return _class_::classTypeId; } \ -Base::Type _class_::classTypeId = Base::Type::badType(); \ -void * _class_::create(void){return 0;} +#define TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::classTypeId = Base::Type::badType(); \ + void* _class_::create(void) \ + { \ + return 0; \ + } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE(_class_, _parentclass_) \ -TYPESYSTEM_SOURCE_P(_class_)\ -void _class_::init(void){\ - initSubclass(_class_::classTypeId, #_class_ , #_parentclass_, &(_class_::create) ); \ -} +#define TYPESYSTEM_SOURCE(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_P(_class_) \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ + } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_TEMPLATE_T(_class_, _parentclass_) \ -TYPESYSTEM_SOURCE_TEMPLATE_P(_class_)\ -template<> void _class_::init(void){\ - initSubclass(_class_::classTypeId, #_class_ , #_parentclass_, &(_class_::create) ); \ -} +#define TYPESYSTEM_SOURCE_TEMPLATE_T(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ + template<> \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ + } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_ABSTRACT(_class_, _parentclass_) \ -TYPESYSTEM_SOURCE_ABSTRACT_P(_class_)\ -void _class_::init(void){\ - initSubclass(_class_::classTypeId, #_class_ , #_parentclass_, &(_class_::create) ); \ -} +#define TYPESYSTEM_SOURCE_ABSTRACT(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ + } namespace Base { @@ -104,54 +136,69 @@ namespace Base class BaseExport BaseClass { public: - static Type getClassTypeId(); - virtual Type getTypeId() const; - bool isDerivedFrom(const Type type) const {return getTypeId().isDerivedFrom(type);} + static Type getClassTypeId(); + virtual Type getTypeId() const; + bool isDerivedFrom(const Type type) const + { + return getTypeId().isDerivedFrom(type); + } - static void init(); + static void init(); - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + virtual PyObject* getPyObject(); + virtual void setPyObject(PyObject*); - static void *create(){return nullptr;} + static void* create() + { + return nullptr; + } - template - bool is() const - { - return getTypeId() == T::getClassTypeId(); - } + template + bool is() const + { + return getTypeId() == T::getClassTypeId(); + } + + template + bool isDerivedFrom() const + { + return getTypeId().isDerivedFrom(T::getClassTypeId()); + } - template - bool isDerivedFrom() const - { - return getTypeId().isDerivedFrom(T::getClassTypeId()); - } private: - static Type classTypeId; + static Type classTypeId; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) + protected: - static void initSubclass(Base::Type &toInit,const char* ClassName, const char *ParentName, Type::instantiationMethod method=nullptr); + static void initSubclass(Base::Type& toInit, + const char* ClassName, + const char* ParentName, + Type::instantiationMethod method = nullptr); public: - /// Construction - BaseClass(); - BaseClass(const BaseClass&) = default; - BaseClass& operator=(const BaseClass&) = default; - /// Destruction - virtual ~BaseClass(); - + /// Construction + BaseClass(); + BaseClass(const BaseClass&) = default; + BaseClass& operator=(const BaseClass&) = default; + BaseClass(BaseClass&&) = default; + BaseClass& operator=(BaseClass&&) = default; + /// Destruction + virtual ~BaseClass(); }; /** - * Template that works just like dynamic_cast, but expects the argument to - * inherit from Base::BaseClass. - * - */ -template T * freecad_dynamic_cast(Base::BaseClass * t) + * Template that works just like dynamic_cast, but expects the argument to + * inherit from Base::BaseClass. + * + */ +template +T* freecad_dynamic_cast(Base::BaseClass* t) { - if (t && t->isDerivedFrom(T::getClassTypeId())) + if (t && t->isDerivedFrom(T::getClassTypeId())) { return static_cast(t); - else + } + else { return nullptr; + } } /** @@ -159,16 +206,18 @@ template T * freecad_dynamic_cast(Base::BaseClass * t) * inherit from a const Base::BaseClass. * */ -template const T * freecad_dynamic_cast(const Base::BaseClass * t) +template +const T* freecad_dynamic_cast(const Base::BaseClass* t) { - if (t && t->isDerivedFrom(T::getClassTypeId())) + if (t && t->isDerivedFrom(T::getClassTypeId())) { return static_cast(t); - else + } + else { return nullptr; + } } -} //namespace Base - -#endif // BASE_BASECLASS_H +} // namespace Base +#endif // BASE_BASECLASS_H diff --git a/src/Base/BaseClassPyImp.cpp b/src/Base/BaseClassPyImp.cpp index 8aca46f3a7..e444c0c84a 100644 --- a/src/Base/BaseClassPyImp.cpp +++ b/src/Base/BaseClassPyImp.cpp @@ -36,27 +36,32 @@ std::string BaseClassPy::representation() const } -PyObject* BaseClassPy::isDerivedFrom(PyObject *args) +PyObject* BaseClassPy::isDerivedFrom(PyObject* args) { - char *name{}; - if (!PyArg_ParseTuple(args, "s", &name)) + char* name {}; + if (!PyArg_ParseTuple(args, "s", &name)) { return nullptr; + } + // clang-format off Base::Type type = Base::Type::fromName(name); bool valid = (type != Base::Type::badType() && getBaseClassPtr()->getTypeId().isDerivedFrom(type)); return PyBool_FromLong(valid ? 1 : 0); + // clang-format on } -PyObject* BaseClassPy::getAllDerivedFrom(PyObject *args) +PyObject* BaseClassPy::getAllDerivedFrom(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::vector ary; Base::Type::getAllDerivedFrom(getBaseClassPtr()->getTypeId(), ary); Py::List res; - for (const auto & it : ary) + for (const auto& it : ary) { res.append(Py::String(it.getName())); + } return Py::new_reference_to(res); } @@ -70,15 +75,17 @@ Py::String BaseClassPy::getModule() const std::string module(getBaseClassPtr()->getTypeId().getName()); std::string::size_type pos = module.find_first_of("::"); - if (pos != std::string::npos) + if (pos != std::string::npos) { module = std::string(module, 0, pos); - else + } + else { module.clear(); + } return {module}; } -PyObject *BaseClassPy::getCustomAttributes(const char* /*attr*/) const +PyObject* BaseClassPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -87,5 +94,3 @@ int BaseClassPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Base/BindingManager.cpp b/src/Base/BindingManager.cpp index 1b3c34363d..5bac684214 100644 --- a/src/Base/BindingManager.cpp +++ b/src/Base/BindingManager.cpp @@ -30,10 +30,11 @@ using namespace Base; -struct BindingManager::BindingManagerPrivate { +struct BindingManager::BindingManagerPrivate +{ std::unordered_map wrapperMapper; - bool hasWrapper(const void *cptr) + bool hasWrapper(const void* cptr) { auto it = wrapperMapper.find(cptr); return it != wrapperMapper.end(); @@ -71,12 +72,11 @@ BindingManager& BindingManager::instance() BindingManager::BindingManager() : p(new BindingManagerPrivate) -{ -} +{} BindingManager::~BindingManager() = default; -bool BindingManager::hasWrapper(const void *cptr) +bool BindingManager::hasWrapper(const void* cptr) { return p->hasWrapper(cptr); } diff --git a/src/Base/BindingManager.h b/src/Base/BindingManager.h index 641c1656c2..74aac9e287 100644 --- a/src/Base/BindingManager.h +++ b/src/Base/BindingManager.h @@ -37,13 +37,18 @@ class BaseExport BindingManager public: static BindingManager& instance(); - bool hasWrapper(const void *cptr); + bool hasWrapper(const void* cptr); void registerWrapper(const void* cptr, PyObject* pyObj); void releaseWrapper(const void* cptr, PyObject* pyObj); PyObject* retrieveWrapper(const void* cptr); + BindingManager(const BindingManager&) = delete; + BindingManager(BindingManager&&) = delete; + BindingManager& operator=(const BindingManager&) = delete; + BindingManager& operator=(BindingManager&&) = delete; + private: BindingManager(); ~BindingManager(); @@ -52,6 +57,6 @@ private: std::unique_ptr p; }; -} +} // namespace Base -#endif // BASE_BINDINGMANAGER_H +#endif // BASE_BINDINGMANAGER_H diff --git a/src/Base/Bitmask.h b/src/Base/Bitmask.h index 13b2f40352..1c6c0792b9 100644 --- a/src/Base/Bitmask.h +++ b/src/Base/Bitmask.h @@ -44,6 +44,7 @@ @endcode */ +// clang-format off // Based on https://stackoverflow.com/questions/1448396/how-to-use-enums-as-flags-in-c template struct enum_traits {}; @@ -128,5 +129,6 @@ public: } }; } +// clang-format on #endif diff --git a/src/Base/BoundBox.h b/src/Base/BoundBox.h index 2155d49e67..1ed4dd748c 100644 --- a/src/Base/BoundBox.h +++ b/src/Base/BoundBox.h @@ -31,12 +31,13 @@ #include "ViewProj.h" -namespace Base { +namespace Base +{ class ViewProjMethod; /** The 3D bounding box class. */ -template +template class BoundBox3 { // helper function @@ -58,47 +59,47 @@ public: //@} /** Builds box from pairs of x,y,z values. */ - inline explicit BoundBox3 (Precision fMinX = std::numeric_limits::max(), - Precision fMinY = std::numeric_limits::max(), - Precision fMinZ = std::numeric_limits::max(), - Precision fMaxX = -std::numeric_limits::max(), - Precision fMaxY = -std::numeric_limits::max(), - Precision fMaxZ = -std::numeric_limits::max()); - BoundBox3 (const BoundBox3 &rcBB) = default; - BoundBox3 (BoundBox3 &&rcBB) noexcept = default; + inline explicit BoundBox3(Precision fMinX = std::numeric_limits::max(), + Precision fMinY = std::numeric_limits::max(), + Precision fMinZ = std::numeric_limits::max(), + Precision fMaxX = -std::numeric_limits::max(), + Precision fMaxY = -std::numeric_limits::max(), + Precision fMaxZ = -std::numeric_limits::max()); + BoundBox3(const BoundBox3& rcBB) = default; + BoundBox3(BoundBox3&& rcBB) noexcept = default; /** Builds box from an array of points. */ - inline BoundBox3 (const Vector3 *pclVect, std::size_t ulCt); + inline BoundBox3(const Vector3* pclVect, std::size_t ulCt); /** Defines a bounding box around the center \a rcCnt with the * distances \a fDistance in each coordinate. */ - BoundBox3 (const Vector3& point, Precision distance); - ~BoundBox3 (); + BoundBox3(const Vector3& point, Precision distance); + ~BoundBox3(); /// Assignment operator - inline BoundBox3& operator = (const BoundBox3 &rcBound) = default; - inline BoundBox3& operator = (BoundBox3 &&rcBound) noexcept = default; + inline BoundBox3& operator=(const BoundBox3& rcBound) = default; + inline BoundBox3& operator=(BoundBox3&& rcBound) noexcept = default; /** Methods for intersection, cuttíng and union of bounding boxes */ //@{ /** Checks for intersection. */ - inline bool Intersect (const BoundBox3 &rcBB) const; + inline bool Intersect(const BoundBox3& rcBB) const; /** Checks for intersection. */ - inline bool operator && (const BoundBox3 &rcBB) const; + inline bool operator&&(const BoundBox3& rcBB) const; /** Checks for intersection. */ - inline bool Intersect (const BoundBox2d &rcBB) const; + inline bool Intersect(const BoundBox2d& rcBB) const; /** Checks for intersection. */ - inline bool operator && (const BoundBox2d &rcBB) const; + inline bool operator&&(const BoundBox2d& rcBB) const; /** Computes the intersection between two bounding boxes. - * The result is also a bounding box. - */ - BoundBox3 Intersected (const BoundBox3 &rcBB) const; + * The result is also a bounding box. + */ + BoundBox3 Intersected(const BoundBox3& rcBB) const; /** The union of two bounding boxes. */ - BoundBox3 United (const BoundBox3 &rcBB) const; + BoundBox3 United(const BoundBox3& rcBB) const; /** Appends the point to the box. The box can grow but not shrink. */ - inline void Add (const Vector3 &rclVect); + inline void Add(const Vector3& rclVect); /** Appends the bounding box to this box. The box can grow but not shrink. */ - inline void Add (const BoundBox3 &rcBB); + inline void Add(const BoundBox3& rcBB); //@} /** Test methods */ @@ -106,36 +107,56 @@ public: /** Checks if this point lies inside the box. * @note It's up to the client programmer to make sure that this bounding box is valid. */ - inline bool IsInBox (const Vector3 &rcVct) const; + inline bool IsInBox(const Vector3& rcVct) const; /** Checks if this 3D box lies inside the box. * @note It's up to the client programmer to make sure that both bounding boxes are valid. */ - inline bool IsInBox (const BoundBox3 &rcBB) const; + inline bool IsInBox(const BoundBox3& rcBB) const; /** Checks if this 2D box lies inside the box. * @note It's up to the client programmer to make sure that both bounding boxes are valid. */ - inline bool IsInBox (const BoundBox2d &rcbb) const; + inline bool IsInBox(const BoundBox2d& rcbb) const; /** Checks whether the bounding box is valid. */ - bool IsValid () const; + bool IsValid() const; //@} - enum OCTANT {OCT_LDB = 0, OCT_RDB, OCT_LUB, OCT_RUB, - OCT_LDF, OCT_RDF, OCT_LUF, OCT_RUF}; - bool GetOctantFromVector (const Vector3 &rclVct, OCTANT &rclOctant) const; - BoundBox3 CalcOctant (typename BoundBox3::OCTANT Octant) const; - - enum SIDE { LEFT =0, RIGHT=1, TOP=2, BOTTOM=3, FRONT=4, BACK=5, INVALID=255 }; - enum CORNER { - TLB = 0, // top-left-back - TLF = 1, // top-left-front - TRF = 2, // top-right-front - TRB = 3, // top-right-back - BLB = 4, // bottom-left-back - BLF = 5, // bottom-left-front - BRF = 6, // bottom-right-front - BRB = 7, // bottom-right-back + enum OCTANT + { + OCT_LDB = 0, + OCT_RDB, + OCT_LUB, + OCT_RUB, + OCT_LDF, + OCT_RDF, + OCT_LUF, + OCT_RUF }; - enum EDGE { + bool GetOctantFromVector(const Vector3& rclVct, OCTANT& rclOctant) const; + BoundBox3 CalcOctant(typename BoundBox3::OCTANT Octant) const; + + enum SIDE + { + LEFT = 0, + RIGHT = 1, + TOP = 2, + BOTTOM = 3, + FRONT = 4, + BACK = 5, + INVALID = 255 + }; + enum CORNER + { + TLB = 0, // top-left-back + TLF = 1, // top-left-front + TRF = 2, // top-right-front + TRB = 3, // top-right-back + BLB = 4, // bottom-left-back + BLF = 5, // bottom-left-front + BRF = 6, // bottom-right-front + BRB = 7, // bottom-right-back + }; + enum EDGE + { TLB_TLF = 0, TLF_TRF = 1, TRF_TRB = 2, @@ -153,52 +174,52 @@ public: /** * Returns the corner point \a usPoint. */ - inline Vector3 CalcPoint (unsigned short usPoint) const; + inline Vector3 CalcPoint(unsigned short usPoint) const; /** Returns the plane of the given side. */ - void CalcPlane (unsigned short usPlane, Vector3& rBase, - Vector3& rNormal) const; + void + CalcPlane(unsigned short usPlane, Vector3& rBase, Vector3& rNormal) const; /** Calculates the two points of an edge. */ - bool CalcEdge (unsigned short usEdge, Vector3& rcP0, Vector3& rcP1) const; + bool CalcEdge(unsigned short usEdge, Vector3& rcP0, Vector3& rcP1) const; /** Intersection point of an inner search ray with the bounding box, built of * the base \a rcVct and the direction \a rcVctDir. \a rcVct must lie inside the * bounding box. */ - bool IntersectionPoint (const Vector3 &rcVct, - const Vector3 &rcVctDir, - Vector3& cVctRes, - Precision epsilon) const; + bool IntersectionPoint(const Vector3& rcVct, + const Vector3& rcVctDir, + Vector3& cVctRes, + Precision epsilon) const; /** Checks for intersection with line incl. search tolerance. */ - bool IsCutLine (const Vector3& rcBase, - const Vector3& rcDir, - Precision fTolerance = 0.0F) const; + bool IsCutLine(const Vector3& rcBase, + const Vector3& rcDir, + Precision fTolerance = 0.0F) const; /** Checks if this plane specified by (point,normal) cuts this box. * @note It's up to the client programmer to make sure that this bounding box is valid. */ - inline bool IsCutPlane (const Vector3 &rclBase, - const Vector3 &rclNormal) const; + inline bool IsCutPlane(const Vector3& rclBase, + const Vector3& rclNormal) const; /** Computes the intersection points of line and bounding box. */ - bool IntersectWithLine (const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0, - Vector3& rcP1) const; + bool IntersectWithLine(const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0, + Vector3& rcP1) const; /** Computes the intersection point of line and a plane of the bounding box. */ - bool IntersectPlaneWithLine (unsigned short usSide, - const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0) const; + bool IntersectPlaneWithLine(unsigned short usSide, + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0) const; /** Returns the side of the bounding box the ray exits. */ - typename BoundBox3::SIDE GetSideFromRay (const Vector3 &rclPt, - const Vector3 &rclDir) const; + typename BoundBox3::SIDE GetSideFromRay(const Vector3& rclPt, + const Vector3& rclDir) const; /** Returns the side of the bounding box the ray exits. */ - typename BoundBox3::SIDE GetSideFromRay (const Vector3 &rclPt, - const Vector3 &rclDir, - Vector3& rcInt) const; + typename BoundBox3::SIDE GetSideFromRay(const Vector3& rclPt, + const Vector3& rclDir, + Vector3& rcInt) const; /** * Searches for the closest point of the bounding box. */ - Vector3 ClosestPoint (const Vector3 &rclPt) const; + Vector3 ClosestPoint(const Vector3& rclPt) const; /** Projects the box onto a plane and returns a 2D box. */ BoundBox2d ProjectBox(const ViewProjMethod* proj) const; /** Transform the corners of this box with the given matrix and create a new bounding box. @@ -207,56 +228,56 @@ public: BoundBox3 Transformed(const Matrix4D& mat) const; /** Returns the center of the box. */ - inline Vector3 GetCenter () const; + inline Vector3 GetCenter() const; /** Returns the minimum point of the box. */ - inline Vector3 GetMinimum () const; + inline Vector3 GetMinimum() const; /** Returns the maximum point of the box. */ - inline Vector3 GetMaximum () const; + inline Vector3 GetMaximum() const; /** Compute the diagonal length of this bounding box. * @note It's up to the client programmer to make sure that this bounding box is valid. */ - inline Precision CalcDiagonalLength () const; - void SetVoid (); + inline Precision CalcDiagonalLength() const; + void SetVoid(); /** Enlarges the box with \a fLen. */ - inline void Enlarge (Precision fLen); + inline void Enlarge(Precision fLen); /** Shrinks the box with \a fLen. */ - inline void Shrink (Precision fLen); + inline void Shrink(Precision fLen); /** Calculates expansion in x-direction. */ - inline Precision LengthX () const; + inline Precision LengthX() const; /** Calculates expansion in y-direction. */ - inline Precision LengthY () const; + inline Precision LengthY() const; /** Calculates expansion in z-direction. */ - inline Precision LengthZ () const; + inline Precision LengthZ() const; /** Calculates the volume. If the box is invalid a negative value is returned */ - inline Precision Volume () const; + inline Precision Volume() const; /** Moves in x-direction. */ - inline void MoveX (Precision value); + inline void MoveX(Precision value); /** Moves in y-direction. */ - inline void MoveY (Precision value); + inline void MoveY(Precision value); /** Moves in z-direction. */ - inline void MoveZ (Precision value); + inline void MoveZ(Precision value); /** Scales in x-direction. */ - inline void ScaleX (Precision value); + inline void ScaleX(Precision value); /** Scales in y-direction. */ - inline void ScaleY (Precision value); + inline void ScaleY(Precision value); /** Scales in z-direction. */ - inline void ScaleZ (Precision value); + inline void ScaleZ(Precision value); /** Prints the values to stream. */ - void Print (std::ostream&) const; + void Print(std::ostream&) const; }; -template +template bool BoundBox3::isOnRayW(Precision min, Precision max, Precision val) { // Checks if point val lies on the ray [min,max] return ((min <= val) && (val <= max)); } -template +template bool BoundBox3::isOnRayS(Precision min, Precision max, Precision val) { // Checks if point val lies on the ray [min,max[ @@ -264,26 +285,33 @@ bool BoundBox3::isOnRayS(Precision min, Precision max, Precision val) } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -template -inline BoundBox3::BoundBox3 (Precision fMinX, Precision fMinY, Precision fMinZ, - Precision fMaxX, Precision fMaxY, Precision fMaxZ) - : MinX(fMinX), MinY(fMinY), MinZ(fMinZ), - MaxX(fMaxX), MaxY(fMaxY), MaxZ(fMaxZ) -{ -} +template +inline BoundBox3::BoundBox3(Precision fMinX, + Precision fMinY, + Precision fMinZ, + Precision fMaxX, + Precision fMaxY, + Precision fMaxZ) + : MinX(fMinX) + , MinY(fMinY) + , MinZ(fMinZ) + , MaxX(fMaxX) + , MaxY(fMaxY) + , MaxZ(fMaxZ) +{} // NOLINTEND(bugprone-easily-swappable-parameters) -template -inline BoundBox3::BoundBox3 (const Vector3 *pclVect, std::size_t ulCt) - : MinX( std::numeric_limits::max()) - , MinY( std::numeric_limits::max()) - , MinZ( std::numeric_limits::max()) - , MaxX(-std::numeric_limits::max()) - , MaxY(-std::numeric_limits::max()) - , MaxZ(-std::numeric_limits::max()) +template +inline BoundBox3::BoundBox3(const Vector3* pclVect, std::size_t ulCt) + : MinX(std::numeric_limits::max()) + , MinY(std::numeric_limits::max()) + , MinZ(std::numeric_limits::max()) + , MaxX(-std::numeric_limits::max()) + , MaxY(-std::numeric_limits::max()) + , MaxZ(-std::numeric_limits::max()) { - const Vector3 *pI = nullptr; - const Vector3 *pEnd = pclVect + ulCt; + const Vector3* pI = nullptr; + const Vector3* pEnd = pclVect + ulCt; for (pI = pclVect; pI < pEnd; ++pI) { MinX = std::min(MinX, pI->x); MinY = std::min(MinY, pI->y); @@ -294,22 +322,21 @@ inline BoundBox3::BoundBox3 (const Vector3 *pclVect, std:: } } -template -inline BoundBox3::BoundBox3 (const Vector3& point, Precision distance) +template +inline BoundBox3::BoundBox3(const Vector3& point, Precision distance) : MinX(point.x - distance) , MinY(point.y - distance) , MinZ(point.z - distance) , MaxX(point.x + distance) , MaxY(point.y + distance) , MaxZ(point.z + distance) -{ -} +{} -template -inline BoundBox3::~BoundBox3 () = default; +template +inline BoundBox3::~BoundBox3() = default; -template -inline bool BoundBox3::Intersect (const BoundBox3 &rcBB) const +template +inline bool BoundBox3::Intersect(const BoundBox3& rcBB) const { if (rcBB.MaxX < this->MinX || rcBB.MinX > this->MaxX) { return false; @@ -323,14 +350,14 @@ inline bool BoundBox3::Intersect (const BoundBox3 &rcBB) c return true; } -template -bool BoundBox3::operator && (const BoundBox3 &rcBB) const +template +bool BoundBox3::operator&&(const BoundBox3& rcBB) const { return Intersect(rcBB); } -template -inline bool BoundBox3::Intersect (const BoundBox2d &rcBB) const +template +inline bool BoundBox3::Intersect(const BoundBox2d& rcBB) const { if (rcBB.MaxX < this->MinX || rcBB.MinX > this->MaxX) { return false; @@ -341,45 +368,45 @@ inline bool BoundBox3::Intersect (const BoundBox2d &rcBB) const return true; } -template -inline bool BoundBox3::operator && (const BoundBox2d &rcBB) const +template +inline bool BoundBox3::operator&&(const BoundBox2d& rcBB) const { return Intersect(rcBB); } -template +template inline BoundBox3 -BoundBox3::Intersected(const BoundBox3 &rcBB) const +BoundBox3::Intersected(const BoundBox3& rcBB) const { BoundBox3 cBBRes; - cBBRes.MinX = std::max (MinX, rcBB.MinX); - cBBRes.MaxX = std::min (MaxX, rcBB.MaxX); - cBBRes.MinY = std::max (MinY, rcBB.MinY); - cBBRes.MaxY = std::min (MaxY, rcBB.MaxY); - cBBRes.MinZ = std::max (MinZ, rcBB.MinZ); - cBBRes.MaxZ = std::min (MaxZ, rcBB.MaxZ); + cBBRes.MinX = std::max(MinX, rcBB.MinX); + cBBRes.MaxX = std::min(MaxX, rcBB.MaxX); + cBBRes.MinY = std::max(MinY, rcBB.MinY); + cBBRes.MaxY = std::min(MaxY, rcBB.MaxY); + cBBRes.MinZ = std::max(MinZ, rcBB.MinZ); + cBBRes.MaxZ = std::min(MaxZ, rcBB.MaxZ); return cBBRes; } -template -inline BoundBox3 BoundBox3::United(const BoundBox3 &rcBB) const +template +inline BoundBox3 BoundBox3::United(const BoundBox3& rcBB) const { BoundBox3 cBBRes; - cBBRes.MinX = std::min (MinX, rcBB.MinX); - cBBRes.MaxX = std::max (MaxX, rcBB.MaxX); - cBBRes.MinY = std::min (MinY, rcBB.MinY); - cBBRes.MaxY = std::max (MaxY, rcBB.MaxY); - cBBRes.MinZ = std::min (MinZ, rcBB.MinZ); - cBBRes.MaxZ = std::max (MaxZ, rcBB.MaxZ); + cBBRes.MinX = std::min(MinX, rcBB.MinX); + cBBRes.MaxX = std::max(MaxX, rcBB.MaxX); + cBBRes.MinY = std::min(MinY, rcBB.MinY); + cBBRes.MaxY = std::max(MaxY, rcBB.MaxY); + cBBRes.MinZ = std::min(MinZ, rcBB.MinZ); + cBBRes.MaxZ = std::max(MaxZ, rcBB.MaxZ); return cBBRes; } -template -inline void BoundBox3::Add (const Vector3 &rclVect) +template +inline void BoundBox3::Add(const Vector3& rclVect) { this->MinX = std::min(this->MinX, rclVect.x); this->MinY = std::min(this->MinY, rclVect.y); @@ -389,19 +416,19 @@ inline void BoundBox3::Add (const Vector3 &rclVect) this->MaxZ = std::max(this->MaxZ, rclVect.z); } -template -inline void BoundBox3::Add (const BoundBox3 &rcBB) +template +inline void BoundBox3::Add(const BoundBox3& rcBB) { - this->MinX = std::min (this->MinX, rcBB.MinX); - this->MaxX = std::max (this->MaxX, rcBB.MaxX); - this->MinY = std::min (this->MinY, rcBB.MinY); - this->MaxY = std::max (this->MaxY, rcBB.MaxY); - this->MinZ = std::min (this->MinZ, rcBB.MinZ); - this->MaxZ = std::max (this->MaxZ, rcBB.MaxZ); + this->MinX = std::min(this->MinX, rcBB.MinX); + this->MaxX = std::max(this->MaxX, rcBB.MaxX); + this->MinY = std::min(this->MinY, rcBB.MinY); + this->MaxY = std::max(this->MaxY, rcBB.MaxY); + this->MinZ = std::min(this->MinZ, rcBB.MinZ); + this->MaxZ = std::max(this->MaxZ, rcBB.MaxZ); } -template -inline bool BoundBox3::IsInBox (const Vector3 &rcVct) const +template +inline bool BoundBox3::IsInBox(const Vector3& rcVct) const { if (rcVct.x < this->MinX || rcVct.x > this->MaxX) { return false; @@ -415,8 +442,8 @@ inline bool BoundBox3::IsInBox (const Vector3 &rcVct) cons return true; } -template -inline bool BoundBox3::IsInBox (const BoundBox3 &rcBB) const +template +inline bool BoundBox3::IsInBox(const BoundBox3& rcBB) const { if (rcBB.MinX < this->MinX || rcBB.MaxX > this->MaxX) { return false; @@ -430,8 +457,8 @@ inline bool BoundBox3::IsInBox (const BoundBox3 &rcBB) con return true; } -template -inline bool BoundBox3::IsInBox (const BoundBox2d &rcBB) const +template +inline bool BoundBox3::IsInBox(const BoundBox2d& rcBB) const { if (rcBB.MinX < this->MinX || rcBB.MaxX > this->MaxX) { return false; @@ -442,226 +469,235 @@ inline bool BoundBox3::IsInBox (const BoundBox2d &rcBB) const return true; } -template -inline bool BoundBox3::IsValid () const +template +inline bool BoundBox3::IsValid() const { return ((MinX <= MaxX) && (MinY <= MaxY) && (MinZ <= MaxZ)); } -template -inline bool BoundBox3::GetOctantFromVector (const Vector3 &rclVct, - OCTANT &rclOctant) const +template +inline bool BoundBox3::GetOctantFromVector(const Vector3& rclVct, + OCTANT& rclOctant) const { - if (!IsInBox (rclVct)) { + if (!IsInBox(rclVct)) { return false; } unsigned short usNdx = 0; - if (isOnRayS ((MinX + MaxX)/2, MaxX, rclVct.x)) { // left/RIGHT + if (isOnRayS((MinX + MaxX) / 2, MaxX, rclVct.x)) { // left/RIGHT usNdx |= 1; } - if (isOnRayS ((MinY + MaxY)/2, MaxY, rclVct.y)) { // down/UP + if (isOnRayS((MinY + MaxY) / 2, MaxY, rclVct.y)) { // down/UP usNdx |= 2; } - if (isOnRayS ((MinZ + MaxZ)/2, MaxZ, rclVct.z)) { // back/FRONT + if (isOnRayS((MinZ + MaxZ) / 2, MaxZ, rclVct.z)) { // back/FRONT usNdx |= 4; } rclOctant = static_cast(usNdx); return true; } -template +template inline BoundBox3 -BoundBox3::CalcOctant (typename BoundBox3< Precision >::OCTANT Octant) const +BoundBox3::CalcOctant(typename BoundBox3::OCTANT Octant) const { - BoundBox3 cOct (*this); + BoundBox3 cOct(*this); switch (Octant) { - case OCT_LDB: - cOct.MaxX = (cOct.MinX + cOct.MaxX)/2; - cOct.MaxY = (cOct.MinY + cOct.MaxY)/2; - cOct.MaxZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_LDB: + cOct.MaxX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MaxY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MaxZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_RDB: - cOct.MinX = (cOct.MinX + cOct.MaxX)/2; - cOct.MaxY = (cOct.MinY + cOct.MaxY)/2; - cOct.MaxZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_RDB: + cOct.MinX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MaxY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MaxZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_LUB: - cOct.MaxX = (cOct.MinX + cOct.MaxX)/2; - cOct.MinY = (cOct.MinY + cOct.MaxY)/2; - cOct.MaxZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_LUB: + cOct.MaxX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MinY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MaxZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_RUB: - cOct.MinX = (cOct.MinX + cOct.MaxX)/2; - cOct.MinY = (cOct.MinY + cOct.MaxY)/2; - cOct.MaxZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_RUB: + cOct.MinX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MinY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MaxZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_LDF: - cOct.MaxX = (cOct.MinX + cOct.MaxX)/2; - cOct.MaxY = (cOct.MinY + cOct.MaxY)/2; - cOct.MinZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_LDF: + cOct.MaxX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MaxY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MinZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_RDF: - cOct.MinX = (cOct.MinX + cOct.MaxX)/2; - cOct.MaxY = (cOct.MinY + cOct.MaxY)/2; - cOct.MinZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_RDF: + cOct.MinX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MaxY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MinZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_LUF: - cOct.MaxX = (cOct.MinX + cOct.MaxX)/2; - cOct.MinY = (cOct.MinY + cOct.MaxY)/2; - cOct.MinZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_LUF: + cOct.MaxX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MinY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MinZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; - case OCT_RUF: - cOct.MinX = (cOct.MinX + cOct.MaxX)/2; - cOct.MinY = (cOct.MinY + cOct.MaxY)/2; - cOct.MinZ = (cOct.MinZ + cOct.MaxZ)/2; - break; + case OCT_RUF: + cOct.MinX = (cOct.MinX + cOct.MaxX) / 2; + cOct.MinY = (cOct.MinY + cOct.MaxY) / 2; + cOct.MinZ = (cOct.MinZ + cOct.MaxZ) / 2; + break; } return cOct; } -template -inline Vector3 BoundBox3::CalcPoint (unsigned short usPoint) const +template +inline Vector3 BoundBox3::CalcPoint(unsigned short usPoint) const { switch (usPoint) { - case TLB: return Vector3(MinX, MinY, MaxZ); - case TLF: return Vector3(MaxX, MinY, MaxZ); - case TRF: return Vector3(MaxX, MaxY, MaxZ); - case TRB: return Vector3(MinX, MaxY, MaxZ); - case BLB: return Vector3(MinX, MinY, MinZ); - case BLF: return Vector3(MaxX, MinY, MinZ); - case BRF: return Vector3(MaxX, MaxY, MinZ); - case BRB: return Vector3(MinX, MaxY, MinZ); + case TLB: + return Vector3(MinX, MinY, MaxZ); + case TLF: + return Vector3(MaxX, MinY, MaxZ); + case TRF: + return Vector3(MaxX, MaxY, MaxZ); + case TRB: + return Vector3(MinX, MaxY, MaxZ); + case BLB: + return Vector3(MinX, MinY, MinZ); + case BLF: + return Vector3(MaxX, MinY, MinZ); + case BRF: + return Vector3(MaxX, MaxY, MinZ); + case BRB: + return Vector3(MinX, MaxY, MinZ); } return Vector3(); } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -template -inline void BoundBox3::CalcPlane (unsigned short usPlane, - Vector3& rBase, - Vector3& rNormal) const +template +inline void BoundBox3::CalcPlane(unsigned short usPlane, + Vector3& rBase, + Vector3& rNormal) const // NOLINTEND(bugprone-easily-swappable-parameters) { switch (usPlane) { - case LEFT: - rBase.Set(MinX, MinY, MaxZ); - rNormal.Set(1.0F, 0.0F, 0.0F); - break; + case LEFT: + rBase.Set(MinX, MinY, MaxZ); + rNormal.Set(1.0F, 0.0F, 0.0F); + break; - case RIGHT: - rBase.Set(MaxX, MinY, MaxZ); - rNormal.Set(1.0F, 0.0F, 0.0F); - break; + case RIGHT: + rBase.Set(MaxX, MinY, MaxZ); + rNormal.Set(1.0F, 0.0F, 0.0F); + break; - case TOP: - rBase.Set(MinX, MaxY, MaxZ); - rNormal.Set(0.0F, 1.0F, 0.0F); - break; + case TOP: + rBase.Set(MinX, MaxY, MaxZ); + rNormal.Set(0.0F, 1.0F, 0.0F); + break; - case BOTTOM: - rBase.Set(MinX, MinY, MaxZ); - rNormal.Set(0.0F, 1.0F, 0.0F); - break; + case BOTTOM: + rBase.Set(MinX, MinY, MaxZ); + rNormal.Set(0.0F, 1.0F, 0.0F); + break; - case FRONT: - rBase.Set(MinX, MinY, MaxZ); - rNormal.Set(0.0F, 0.0F, 1.0F); - break; + case FRONT: + rBase.Set(MinX, MinY, MaxZ); + rNormal.Set(0.0F, 0.0F, 1.0F); + break; - case BACK: - rBase.Set(MinX, MinY, MinZ); - rNormal.Set(0.0F, 0.0F, 1.0F); - break; - default: - break; + case BACK: + rBase.Set(MinX, MinY, MinZ); + rNormal.Set(0.0F, 0.0F, 1.0F); + break; + default: + break; } } -template -inline bool BoundBox3::CalcEdge (unsigned short usEdge, Vector3& rcP0, - Vector3& rcP1) const +template +inline bool BoundBox3::CalcEdge(unsigned short usEdge, + Vector3& rcP0, + Vector3& rcP1) const { switch (usEdge) { - case TLB_TLF: - rcP0 = CalcPoint(TLB); - rcP1 = CalcPoint(TLF); - break; - case TLF_TRF: - rcP0 = CalcPoint(TLF); - rcP1 = CalcPoint(TRF); - break; - case TRF_TRB: - rcP0 = CalcPoint(TRF); - rcP1 = CalcPoint(TRB); - break; - case TRB_TLB: - rcP0 = CalcPoint(TRB); - rcP1 = CalcPoint(TLB); - break; - case BLB_BLF: - rcP0 = CalcPoint(BLB); - rcP1 = CalcPoint(BLF); - break; - case BLF_BRF: - rcP0 = CalcPoint(BLF); - rcP1 = CalcPoint(BRF); - break; - case BRF_BRB: - rcP0 = CalcPoint(BRF); - rcP1 = CalcPoint(BRB); - break; - case BRB_BLB: - rcP0 = CalcPoint(BRB); - rcP1 = CalcPoint(BLB); - break; - case TLB_BLB: - rcP0 = CalcPoint(TLB); - rcP1 = CalcPoint(BLB); - break; - case TLF_BLF: - rcP0 = CalcPoint(TLF); - rcP1 = CalcPoint(BLF); - break; - case TRF_BRF: - rcP0 = CalcPoint(TRF); - rcP1 = CalcPoint(BRF); - break; - case TRB_BRB: - rcP0 = CalcPoint(TRB); - rcP1 = CalcPoint(BRB); - break; - default: - return false; // undefined + case TLB_TLF: + rcP0 = CalcPoint(TLB); + rcP1 = CalcPoint(TLF); + break; + case TLF_TRF: + rcP0 = CalcPoint(TLF); + rcP1 = CalcPoint(TRF); + break; + case TRF_TRB: + rcP0 = CalcPoint(TRF); + rcP1 = CalcPoint(TRB); + break; + case TRB_TLB: + rcP0 = CalcPoint(TRB); + rcP1 = CalcPoint(TLB); + break; + case BLB_BLF: + rcP0 = CalcPoint(BLB); + rcP1 = CalcPoint(BLF); + break; + case BLF_BRF: + rcP0 = CalcPoint(BLF); + rcP1 = CalcPoint(BRF); + break; + case BRF_BRB: + rcP0 = CalcPoint(BRF); + rcP1 = CalcPoint(BRB); + break; + case BRB_BLB: + rcP0 = CalcPoint(BRB); + rcP1 = CalcPoint(BLB); + break; + case TLB_BLB: + rcP0 = CalcPoint(TLB); + rcP1 = CalcPoint(BLB); + break; + case TLF_BLF: + rcP0 = CalcPoint(TLF); + rcP1 = CalcPoint(BLF); + break; + case TRF_BRF: + rcP0 = CalcPoint(TRF); + rcP1 = CalcPoint(BRF); + break; + case TRB_BRB: + rcP0 = CalcPoint(TRB); + rcP1 = CalcPoint(BRB); + break; + default: + return false; // undefined } return true; } -template -inline bool BoundBox3::IntersectionPoint (const Vector3 &rcVct, - const Vector3 &rcVctDir, - Vector3& cVctRes, - Precision epsilon) const +template +inline bool BoundBox3::IntersectionPoint(const Vector3& rcVct, + const Vector3& rcVctDir, + Vector3& cVctRes, + Precision epsilon) const { const unsigned short num = 6; - bool rc=false; + bool rc = false; BoundBox3 cCmpBound(*this); // enlarge bounding box by epsilon cCmpBound.Enlarge(epsilon); // Is point inside? - if (cCmpBound.IsInBox (rcVct)) { + if (cCmpBound.IsInBox(rcVct)) { // test sides for (unsigned short i = 0; (i < num) && (!rc); i++) { rc = IntersectPlaneWithLine(i, rcVct, rcVctDir, cVctRes); @@ -682,10 +718,10 @@ inline bool BoundBox3::IntersectionPoint (const Vector3 &r return rc; } -template -inline bool BoundBox3::IsCutLine (const Vector3& rcBase, - const Vector3& rcDir, - Precision fTolerance) const +template +inline bool BoundBox3::IsCutLine(const Vector3& rcBase, + const Vector3& rcDir, + Precision fTolerance) const { const unsigned short num = 6; Precision fDist; @@ -703,31 +739,31 @@ inline bool BoundBox3::IsCutLine (const Vector3& rcBase, } // more detailed test here - Vector3 clVectRes; + Vector3 clVectRes; // intersect each face with the line for (unsigned short i = 0; i < num; i++) { if (IntersectPlaneWithLine(i, rcBase, rcDir, clVectRes)) { // Check whether the intersection point is within BB limits + Tolerance switch (i) { - case LEFT : // left and right plane - case RIGHT : - if ((isOnRayW (MinY - fTolerance, MaxY + fTolerance, clVectRes.y) && - isOnRayW (MinZ - fTolerance, MaxZ + fTolerance, clVectRes.z))) { + case LEFT: // left and right plane + case RIGHT: + if ((isOnRayW(MinY - fTolerance, MaxY + fTolerance, clVectRes.y) + && isOnRayW(MinZ - fTolerance, MaxZ + fTolerance, clVectRes.z))) { return true; } break; - case TOP : // top and bottom plane - case BOTTOM : - if ((isOnRayW (MinX - fTolerance, MaxX + fTolerance, clVectRes.x) && - isOnRayW (MinZ - fTolerance, MaxZ + fTolerance, clVectRes.z))) { + case TOP: // top and bottom plane + case BOTTOM: + if ((isOnRayW(MinX - fTolerance, MaxX + fTolerance, clVectRes.x) + && isOnRayW(MinZ - fTolerance, MaxZ + fTolerance, clVectRes.z))) { return true; } break; - case FRONT : // front and back plane - case BACK : - if ((isOnRayW (MinX - fTolerance, MaxX + fTolerance, clVectRes.x) && - isOnRayW (MinY - fTolerance, MaxY + fTolerance, clVectRes.y))) { + case FRONT: // front and back plane + case BACK: + if ((isOnRayW(MinX - fTolerance, MaxX + fTolerance, clVectRes.x) + && isOnRayW(MinY - fTolerance, MaxY + fTolerance, clVectRes.y))) { return true; } break; @@ -738,9 +774,9 @@ inline bool BoundBox3::IsCutLine (const Vector3& rcBase, return false; } -template -inline bool BoundBox3::IsCutPlane (const Vector3 &rclBase, - const Vector3 &rclNormal) const +template +inline bool BoundBox3::IsCutPlane(const Vector3& rclBase, + const Vector3& rclNormal) const { const unsigned short num = 8; if (fabs(GetCenter().DistanceToPlane(rclBase, rclNormal)) < CalcDiagonalLength()) { @@ -755,11 +791,11 @@ inline bool BoundBox3::IsCutPlane (const Vector3 &rclBase, } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -template -inline bool BoundBox3::IntersectWithLine (const Vector3 & rcBase, - const Vector3& rcDir, - Vector3& rcP0, - Vector3& rcP1) const +template +inline bool BoundBox3::IntersectWithLine(const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0, + Vector3& rcP1) const // NOLINTEND(bugprone-easily-swappable-parameters) { const unsigned short num = 6; @@ -767,8 +803,7 @@ inline bool BoundBox3::IntersectWithLine (const Vector3 & std::array, num> clVect; unsigned short numIntersect = 0; - auto checkIntersect = [&](Base::Vector3 p1, - Base::Vector3 p2) { + auto checkIntersect = [&](Base::Vector3 p1, Base::Vector3 p2) { if (isOnRayS(p1.x, p1.y, p1.z) && isOnRayS(p2.x, p2.y, p2.z)) { clVect[numIntersect] = clVectRes; numIntersect++; @@ -780,21 +815,21 @@ inline bool BoundBox3::IntersectWithLine (const Vector3 & if (IntersectPlaneWithLine(i, rcBase, rcDir, clVectRes)) { // check if intersection point is inside switch (i) { - case LEFT : // left and right plane - case RIGHT : - checkIntersect(Vector3{MinY, MaxY, clVectRes.y}, - Vector3{MinZ, MaxZ, clVectRes.z}); - break; - case TOP : // top and bottom plane - case BOTTOM : - checkIntersect(Vector3{MinX, MaxX, clVectRes.x}, - Vector3{MinZ, MaxZ, clVectRes.z}); - break; - case FRONT : // front and back plane - case BACK : - checkIntersect(Vector3{MinX, MaxX, clVectRes.x}, - Vector3{MinY, MaxY, clVectRes.y}); - break; + case LEFT: // left and right plane + case RIGHT: + checkIntersect(Vector3 {MinY, MaxY, clVectRes.y}, + Vector3 {MinZ, MaxZ, clVectRes.z}); + break; + case TOP: // top and bottom plane + case BOTTOM: + checkIntersect(Vector3 {MinX, MaxX, clVectRes.x}, + Vector3 {MinZ, MaxZ, clVectRes.z}); + break; + case FRONT: // front and back plane + case BACK: + checkIntersect(Vector3 {MinX, MaxX, clVectRes.x}, + Vector3 {MinY, MaxY, clVectRes.y}); + break; } } } @@ -805,7 +840,7 @@ inline bool BoundBox3::IntersectWithLine (const Vector3 & return true; } - if (numIntersect > 2) { // search two different intersection points + if (numIntersect > 2) { // search two different intersection points for (unsigned short i = 1; i < numIntersect; i++) { if (clVect[i] != clVect[0]) { rcP0 = clVect[0]; @@ -819,17 +854,17 @@ inline bool BoundBox3::IntersectWithLine (const Vector3 & } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -template -inline bool BoundBox3::IntersectPlaneWithLine (unsigned short usSide, - const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0) const +template +inline bool BoundBox3::IntersectPlaneWithLine(unsigned short usSide, + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0) const // NOLINTEND(bugprone-easily-swappable-parameters) { Precision value; Vector3 cBase; Vector3 cNormal; - Vector3 cDir(rcDir); + Vector3 cDir(rcDir); CalcPlane(usSide, cBase, cNormal); if ((cNormal * cDir) == 0.0F) { @@ -842,20 +877,20 @@ inline bool BoundBox3::IntersectPlaneWithLine (unsigned short usSide, return true; } -template +template inline typename BoundBox3::SIDE -BoundBox3::GetSideFromRay (const Vector3 &rclPt, - const Vector3 &rclDir) const +BoundBox3::GetSideFromRay(const Vector3& rclPt, + const Vector3& rclDir) const { Vector3 cIntersection; - return GetSideFromRay( rclPt, rclDir, cIntersection); + return GetSideFromRay(rclPt, rclDir, cIntersection); } -template +template inline typename BoundBox3::SIDE -BoundBox3::GetSideFromRay (const Vector3 &rclPt, - const Vector3 &rclDir, - Vector3& rcInt) const +BoundBox3::GetSideFromRay(const Vector3& rclPt, + const Vector3& rclDir, + Vector3& rcInt) const { Vector3 cP0; Vector3 cP1; @@ -863,9 +898,9 @@ BoundBox3::GetSideFromRay (const Vector3 &rclPt, return INVALID; } - Vector3 cOut; + Vector3 cOut; // same orientation - if ((cP1-cP0)*rclDir > 0) { + if ((cP1 - cP0) * rclDir > 0) { cOut = cP1; } else { @@ -874,35 +909,35 @@ BoundBox3::GetSideFromRay (const Vector3 &rclPt, rcInt = cOut; - Precision fMax = 1.0e-3F; //NOLINT - SIDE tSide = INVALID; + Precision fMax = 1.0e-3F; // NOLINT + SIDE tSide = INVALID; - if (fabs(cOut.x - MinX) < fMax) { // left plane + if (fabs(cOut.x - MinX) < fMax) { // left plane fMax = Precision(fabs(cOut.x - MinX)); tSide = LEFT; } - if (fabs(cOut.x - MaxX) < fMax) { // right plane + if (fabs(cOut.x - MaxX) < fMax) { // right plane fMax = Precision(fabs(cOut.x - MaxX)); tSide = RIGHT; } - if (fabs(cOut.y - MinY) < fMax) { // bottom plane + if (fabs(cOut.y - MinY) < fMax) { // bottom plane fMax = Precision(fabs(cOut.y - MinY)); tSide = BOTTOM; } - if (fabs(cOut.y - MaxY) < fMax) { // top plane + if (fabs(cOut.y - MaxY) < fMax) { // top plane fMax = Precision(fabs(cOut.y - MaxY)); tSide = TOP; } - if (fabs(cOut.z - MinZ) < fMax) { // front plane + if (fabs(cOut.z - MinZ) < fMax) { // front plane fMax = Precision(fabs(cOut.z - MinZ)); tSide = FRONT; } - if (fabs(cOut.z - MaxZ) < fMax) { // back plane + if (fabs(cOut.z - MaxZ) < fMax) { // back plane fMax = Precision(fabs(cOut.z - MaxZ)); tSide = BACK; } @@ -910,8 +945,8 @@ BoundBox3::GetSideFromRay (const Vector3 &rclPt, return tSide; } -template -inline Vector3 BoundBox3::ClosestPoint (const Vector3 &rclPt) const +template +inline Vector3 BoundBox3::ClosestPoint(const Vector3& rclPt) const { Vector3 closest = rclPt; @@ -920,9 +955,9 @@ inline Vector3 BoundBox3::ClosestPoint (const Vector3 fabs(devy)) && (fabs(devx) > fabs(devz))) { @@ -943,11 +978,11 @@ inline Vector3 BoundBox3::ClosestPoint (const Vector3 +template inline BoundBox2d BoundBox3::ProjectBox(const ViewProjMethod* proj) const { const int num = 8; - BoundBox2d clBB2D; + BoundBox2d clBB2D; clBB2D.SetVoid(); for (int i = 0; i < num; i++) { @@ -958,7 +993,7 @@ inline BoundBox2d BoundBox3::ProjectBox(const ViewProjMethod* proj) c return clBB2D; } -template +template inline BoundBox3 BoundBox3::Transformed(const Matrix4D& mat) const { const int num = 8; @@ -969,75 +1004,81 @@ inline BoundBox3 BoundBox3::Transformed(const Matrix4D& ma return bbox; } -template -inline Vector3 BoundBox3::GetCenter () const +template +inline Vector3 BoundBox3::GetCenter() const { - return Vector3((MaxX + MinX) / 2, - (MaxY + MinY) / 2, - (MaxZ + MinZ) / 2); + return Vector3((MaxX + MinX) / 2, (MaxY + MinY) / 2, (MaxZ + MinZ) / 2); } -template -inline Vector3 BoundBox3::GetMinimum () const +template +inline Vector3 BoundBox3::GetMinimum() const { return Vector3(MinX, MinY, MinZ); } -template -inline Vector3 BoundBox3::GetMaximum () const +template +inline Vector3 BoundBox3::GetMaximum() const { return Vector3(MaxX, MaxY, MaxZ); } -template -inline Precision BoundBox3::CalcDiagonalLength () const +template +inline Precision BoundBox3::CalcDiagonalLength() const { - return static_cast(sqrt (((MaxX - MinX) * (MaxX - MinX)) + - ((MaxY - MinY) * (MaxY - MinY)) + - ((MaxZ - MinZ) * (MaxZ - MinZ)))); + return static_cast(sqrt(((MaxX - MinX) * (MaxX - MinX)) + + ((MaxY - MinY) * (MaxY - MinY)) + + ((MaxZ - MinZ) * (MaxZ - MinZ)))); } -template -inline void BoundBox3::SetVoid () +template +inline void BoundBox3::SetVoid() { - MinX = MinY = MinZ = std::numeric_limits::max(); + MinX = MinY = MinZ = std::numeric_limits::max(); MaxX = MaxY = MaxZ = -std::numeric_limits::max(); } -template -inline void BoundBox3::Enlarge (Precision fLen) +template +inline void BoundBox3::Enlarge(Precision fLen) { - MinX -= fLen; MinY -= fLen; MinZ -= fLen; - MaxX += fLen; MaxY += fLen; MaxZ += fLen; + MinX -= fLen; + MinY -= fLen; + MinZ -= fLen; + MaxX += fLen; + MaxY += fLen; + MaxZ += fLen; } -template -inline void BoundBox3::Shrink (Precision fLen) +template +inline void BoundBox3::Shrink(Precision fLen) { - MinX += fLen; MinY += fLen; MinZ += fLen; - MaxX -= fLen; MaxY -= fLen; MaxZ -= fLen; + MinX += fLen; + MinY += fLen; + MinZ += fLen; + MaxX -= fLen; + MaxY -= fLen; + MaxZ -= fLen; } -template -inline Precision BoundBox3::LengthX () const +template +inline Precision BoundBox3::LengthX() const { return MaxX - MinX; } -template -inline Precision BoundBox3::LengthY () const +template +inline Precision BoundBox3::LengthY() const { return MaxY - MinY; } -template -inline Precision BoundBox3::LengthZ () const +template +inline Precision BoundBox3::LengthZ() const { return MaxZ - MinZ; } -template -inline Precision BoundBox3::Volume () const +template +inline Precision BoundBox3::Volume() const { if (!IsValid()) { return -1.0; @@ -1045,43 +1086,43 @@ inline Precision BoundBox3::Volume () const return LengthX() * LengthY() * LengthZ(); } -template -inline void BoundBox3::MoveX (Precision value) +template +inline void BoundBox3::MoveX(Precision value) { MinX += value; MaxX += value; } -template -inline void BoundBox3::MoveY (Precision value) +template +inline void BoundBox3::MoveY(Precision value) { MinY += value; MaxY += value; } -template -inline void BoundBox3::MoveZ (Precision value) +template +inline void BoundBox3::MoveZ(Precision value) { MinZ += value; MaxZ += value; } -template -inline void BoundBox3::ScaleX (Precision value) +template +inline void BoundBox3::ScaleX(Precision value) { MinX *= value; MaxX *= value; } -template -inline void BoundBox3::ScaleY (Precision value) +template +inline void BoundBox3::ScaleY(Precision value) { MinY *= value; MaxY *= value; } -template -inline void BoundBox3::ScaleZ (Precision value) +template +inline void BoundBox3::ScaleZ(Precision value) { MinZ *= value; MaxZ *= value; @@ -1090,7 +1131,6 @@ inline void BoundBox3::ScaleZ (Precision value) using BoundBox3f = BoundBox3; using BoundBox3d = BoundBox3; -} // namespace Base +} // namespace Base #endif // BASE_BOUNDBOX_H - diff --git a/src/Base/BoundBoxPy.xml b/src/Base/BoundBoxPy.xml index 876b4462c4..0af425be10 100644 --- a/src/Base/BoundBoxPy.xml +++ b/src/Base/BoundBoxPy.xml @@ -1,20 +1,20 @@ - This is the BoundBox export class - Base.BoundBox class. + Base.BoundBox class. This class represents a bounding box. A bounding box is a rectangular cuboid which is a way to describe outer @@ -23,50 +23,50 @@ It is often used to check if a 3D entity lies in the range of another object. Checking for bounding interference first can save a lot of computing time! An invalid BoundBox is represented by inconsistent values at each direction: The maximum float value of the system at the minimum coordinates, and the -opposite value at the maximum coordinates. +opposite value at the maximum coordinates. -The following constructors are supported: +The following constructors are supported: BoundBox() -Empty constructor. Returns an invalid BoundBox. +Empty constructor. Returns an invalid BoundBox. BoundBox(boundBox) Copy constructor. -boundBox : Base.BoundBox +boundBox : Base.BoundBox BoundBox(xMin, yMin=0, zMin=0, xMax=0, yMax=0, zMax=0) Define from the minimum and maximum values at each direction. -xMin : float +xMin : float Minimum value at x-coordinate. -yMin : float +yMin : float Minimum value at y-coordinate. -zMin : float +zMin : float Minimum value at z-coordinate. -xMax : float +xMax : float Maximum value at x-coordinate. -yMax : float +yMax : float Maximum value at y-coordinate. -zMax : float - Maximum value at z-coordinate. +zMax : float + Maximum value at z-coordinate. App.BoundBox(min, max) Define from two containers representing the minimum and maximum values of the coordinates in each direction. -min : Base.Vector, tuple +min : Base.Vector, tuple Minimum values of the coordinates. -max : Base.Vector, tuple +max : Base.Vector, tuple Maximum values of the coordinates. - setVoid() -> None + setVoid() -> None Invalidate the bounding box. - isValid() -> bool + isValid() -> bool Checks if the bounding box is valid. @@ -74,38 +74,38 @@ Checks if the bounding box is valid. add(minMax) -> None -add(x, y, z) -> None +add(x, y, z) -> None Increase the maximum values or decrease the minimum values of this BoundBox by replacing the current values with the given values, so the bounding box can grow -but not shrink. +but not shrink. -minMax : Base.Vector, tuple +minMax : Base.Vector, tuple Values to enlarge at each direction. -x : float +x : float Value to enlarge at x-direction. -y : float +y : float Value to enlarge at y-direction. -z : float +z : float Value to enlarge at z-direction. - getPoint(index) ->Base.Vector + getPoint(index) ->Base.Vector Get the point of the given index. -The index must be in the range of [0, 7]. +The index must be in the range of [0, 7]. index : int - getEdge(index) -> tuple of Base.Vector + getEdge(index) -> tuple of Base.Vector Get the edge points of the given index. -The index must be in the range of [0, 11]. +The index must be in the range of [0, 11]. index : int @@ -113,27 +113,27 @@ index : int closestPoint(point) -> Base.Vector -closestPoint(x, y, z) -> Base.Vector +closestPoint(x, y, z) -> Base.Vector -Get the closest point of the bounding box to the given point. +Get the closest point of the bounding box to the given point. -point : Base.Vector, tuple +point : Base.Vector, tuple Coordinates of the given point. -x : float +x : float X-coordinate of the given point. -y : float +y : float Y-coordinate of the given point. -z : float +z : float Z-coordinate of the given point. intersect(boundBox2) -> bool -intersect(base, dir) -> bool +intersect(base, dir) -> bool Checks if the given object intersects with this bounding box. That can be -another bounding box or a line specified by base and direction. +another bounding box or a line specified by base and direction. boundBox2 : Base.BoundBox base : Base.Vector, tuple @@ -142,28 +142,28 @@ dir : Base.Vector, tuple - intersected(boundBox2) -> Base.BoundBox + intersected(boundBox2) -> Base.BoundBox -Returns the intersection of this and the given bounding box. +Returns the intersection of this and the given bounding box. boundBox2 : Base.BoundBox - united(boundBox2) -> Base.BoundBox + united(boundBox2) -> Base.BoundBox -Returns the union of this and the given bounding box. +Returns the union of this and the given bounding box. boundBox2 : Base.BoundBox - enlarge(variation) -> None + enlarge(variation) -> None Decrease the minimum values and increase the maximum values by the given value. -A negative value shrinks the bounding box. +A negative value shrinks the bounding box. variation : float @@ -171,70 +171,70 @@ variation : float - getIntersectionPoint(base, dir, epsilon=0.0001) -> Base.Vector + getIntersectionPoint(base, dir, epsilon=0.0001) -> Base.Vector Calculate the intersection point of a line with the bounding box. -The base point must lie inside the bounding box, if not an exception is thrown. +The base point must lie inside the bounding box, if not an exception is thrown. -base : Base.Vector +base : Base.Vector Base point of the line. -dir : Base.Vector +dir : Base.Vector Direction of the line. -epsilon : float +epsilon : float Bounding box size tolerance. move(displacement) -> None -move(x, y, z) -> None +move(x, y, z) -> None -Move the bounding box by the given values. +Move the bounding box by the given values. -displacement : Base.Vector, tuple +displacement : Base.Vector, tuple Displacement at each direction. -x : float +x : float Displacement at x-direction. -y : float +y : float Displacement at y-direction. -z : float +z : float Displacement at z-direction. scale(factor) -> None -scale(x, y, z) -> None +scale(x, y, z) -> None -Scale the bounding box by the given values. +Scale the bounding box by the given values. -factor : Base.Vector, tuple +factor : Base.Vector, tuple Factor scale at each direction. -x : float +x : float Scale at x-direction. -y : float +y : float Scale at y-direction. -z : float +z : float Scale at z-direction. - transformed(matrix) -> Base.BoundBox + transformed(matrix) -> Base.BoundBox Returns a new BoundBox containing the transformed rectangular cuboid -represented by this BoundBox. +represented by this BoundBox. -matrix : Base.Matrix +matrix : Base.Matrix Transformation matrix. - isCutPlane(base, normal) -> bool + isCutPlane(base, normal) -> bool Check if the plane specified by base and normal intersects (cuts) this bounding -box. +box. base : Base.Vector normal : Base.Vector @@ -243,17 +243,17 @@ normal : Base.Vector isInside(object) -> bool -isInside(x, y, z) -> bool +isInside(x, y, z) -> bool -Check if a point or a bounding box is inside this bounding box. +Check if a point or a bounding box is inside this bounding box. -object : Base.Vector, Base.BoundBox +object : Base.Vector, Base.BoundBox Object to check if it is inside this bounding box. -x : float +x : float X-coordinate of the point to check. -y : float +y : float Y-coordinate of the point to check. -z : float +z : float Z-coordinate of the point to check. diff --git a/src/Base/BoundBoxPyImp.cpp b/src/Base/BoundBoxPyImp.cpp index df8ba28202..1f5e1c7282 100644 --- a/src/Base/BoundBoxPyImp.cpp +++ b/src/Base/BoundBoxPyImp.cpp @@ -37,18 +37,15 @@ std::string BoundBoxPy::representation() const { std::stringstream str; str << "BoundBox ("; - str << getBoundBoxPtr()->MinX << ", " - << getBoundBoxPtr()->MinY << ", " - << getBoundBoxPtr()->MinZ << ", " - << getBoundBoxPtr()->MaxX << ", " - << getBoundBoxPtr()->MaxY << ", " - << getBoundBoxPtr()->MaxZ ; + str << getBoundBoxPtr()->MinX << ", " << getBoundBoxPtr()->MinY << ", " + << getBoundBoxPtr()->MinZ << ", " << getBoundBoxPtr()->MaxX << ", " + << getBoundBoxPtr()->MaxY << ", " << getBoundBoxPtr()->MaxZ; str << ")"; return str.str(); } -PyObject *BoundBoxPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BoundBoxPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BoundBoxPy and the Twin object return new BoundBoxPy(new BoundBox3d); @@ -60,10 +57,10 @@ int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) if (PyArg_ParseTuple(args, "")) { return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() + PyErr_Clear(); // set by PyArg_ParseTuple() - double xMin=0.0,yMin=0.0,zMin=0.0,xMax=0.0,yMax=0.0,zMax=0.0; - PyObject *object1{}, *object2{}; + double xMin = 0.0, yMin = 0.0, zMin = 0.0, xMax = 0.0, yMax = 0.0, zMax = 0.0; + PyObject *object1 {}, *object2 {}; BoundBoxPy::PointerType ptr = getBoundBoxPtr(); if (PyArg_ParseTuple(args, "d|ddddd", &xMin, &yMin, &zMin, &xMax, &yMax, &zMax)) { ptr->MaxX = xMax; @@ -74,9 +71,8 @@ int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) ptr->MinZ = zMin; return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!O!",&PyTuple_Type, &object1, - &PyTuple_Type, &object2)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!O!", &PyTuple_Type, &object1, &PyTuple_Type, &object2)) { try { Vector3d v1 = getVectorFromTuple(object1); Vector3d v2 = getVectorFromTuple(object2); @@ -88,80 +84,92 @@ int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!O!",&(Base::VectorPy::Type), &object1, - &(Base::VectorPy::Type), &object2)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, + "O!O!", + &(Base::VectorPy::Type), + &object1, + &(Base::VectorPy::Type), + &object2)) { ptr->Add(*(static_cast(object1)->getVectorPtr())); ptr->Add(*(static_cast(object2)->getVectorPtr())); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object1)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object1)) { *ptr = *(static_cast(object1)->getBoundBoxPtr()); return 0; } - PyErr_SetString(PyExc_TypeError, "Either six floats, two instances of " - "Vector/Tuple or instance of BoundBox expected"); + PyErr_SetString(PyExc_TypeError, + "Either six floats, two instances of " + "Vector/Tuple or instance of BoundBox expected"); return -1; } -PyObject* BoundBoxPy::setVoid(PyObject *args) +PyObject* BoundBoxPy::setVoid(PyObject* args) { - if (!PyArg_ParseTuple(args,"")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getBoundBoxPtr()->SetVoid(); Py_Return; } -PyObject* BoundBoxPy::isValid(PyObject *args) +PyObject* BoundBoxPy::isValid(PyObject* args) { - if (!PyArg_ParseTuple(args,"")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return PyBool_FromLong(getBoundBoxPtr()->IsValid() ? 1 : 0); } -PyObject* BoundBoxPy::add(PyObject *args) +PyObject* BoundBoxPy::add(PyObject* args) { - double x{},y{},z{}; - PyObject *object{}; - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { - getBoundBoxPtr()->Add(Vector3d(x,y,z)); + double x {}, y {}, z {}; + PyObject* object {}; + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { + getBoundBoxPtr()->Add(Vector3d(x, y, z)); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &object)) { getBoundBoxPtr()->Add(getVectorFromTuple(object)); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { getBoundBoxPtr()->Add(*(static_cast(object)->getVectorPtr())); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!;Need a Vector, BoundBox or three floats as argument",&(Base::BoundBoxPy::Type), &object)) { + if (PyArg_ParseTuple(args, + "O!;Need a Vector, BoundBox or three floats as argument", + &(Base::BoundBoxPy::Type), + &object)) { getBoundBoxPtr()->Add(*(static_cast(object)->getBoundBoxPtr())); Py_Return; } - PyErr_SetString(PyExc_TypeError, "Either three floats, instance of Vector or instance of BoundBox expected"); + PyErr_SetString(PyExc_TypeError, + "Either three floats, instance of Vector or instance of BoundBox expected"); return nullptr; } -PyObject* BoundBoxPy::getPoint(PyObject *args) +PyObject* BoundBoxPy::getPoint(PyObject* args) { - unsigned short index{}; - if (!PyArg_ParseTuple(args,"H",&index)) + unsigned short index {}; + if (!PyArg_ParseTuple(args, "H", &index)) { return nullptr; + } if (index > 7) { - PyErr_SetString (PyExc_IndexError, "Invalid point index"); + PyErr_SetString(PyExc_IndexError, "Invalid point index"); return nullptr; } @@ -169,14 +177,15 @@ PyObject* BoundBoxPy::getPoint(PyObject *args) return new Base::VectorPy(new Base::Vector3d(pnt)); } -PyObject* BoundBoxPy::getEdge(PyObject *args) +PyObject* BoundBoxPy::getEdge(PyObject* args) { - unsigned short index{}; - if (!PyArg_ParseTuple(args,"H",&index)) + unsigned short index {}; + if (!PyArg_ParseTuple(args, "H", &index)) { return nullptr; + } if (index > 11) { - PyErr_SetString (PyExc_IndexError, "Invalid edge index"); + PyErr_SetString(PyExc_IndexError, "Invalid edge index"); return nullptr; } @@ -188,27 +197,27 @@ PyObject* BoundBoxPy::getEdge(PyObject *args) return Py::new_reference_to(tuple); } -PyObject* BoundBoxPy::closestPoint(PyObject *args) +PyObject* BoundBoxPy::closestPoint(PyObject* args) { - double x{},y{},z{}; - PyObject *object{}; + double x {}, y {}, z {}; + PyObject* object {}; Base::Vector3d vec; do { - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { - vec = Vector3d(x,y,z); + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { + vec = Vector3d(x, y, z); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &object)) { vec = getVectorFromTuple(object); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { vec = *(static_cast(object)->getVectorPtr()); break; } @@ -216,110 +225,125 @@ PyObject* BoundBoxPy::closestPoint(PyObject *args) PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return nullptr; } - } - while(false); + } while (false); Base::Vector3d point = getBoundBoxPtr()->ClosestPoint(vec); return new Base::VectorPy(new Base::Vector3d(point)); } -PyObject* BoundBoxPy::intersect(PyObject *args) +PyObject* BoundBoxPy::intersect(PyObject* args) { - PyObject *object{},*object2{}; + PyObject *object {}, *object2 {}; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box"); return nullptr; } do { - if (PyArg_ParseTuple(args,"O!O!",&(Base::VectorPy::Type), &object, - &(Base::VectorPy::Type), &object2)) { + if (PyArg_ParseTuple(args, + "O!O!", + &(Base::VectorPy::Type), + &object, + &(Base::VectorPy::Type), + &object2)) { retVal = getBoundBoxPtr()->IsCutLine( - *(static_cast(object )->getVectorPtr()), + *(static_cast(object)->getVectorPtr()), *(static_cast(object2)->getVectorPtr())); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object)) { if (!static_cast(object)->getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - retVal = getBoundBoxPtr()->Intersect(*(static_cast(object)->getBoundBoxPtr())); + retVal = getBoundBoxPtr()->Intersect( + *(static_cast(object)->getBoundBoxPtr())); break; } PyErr_SetString(PyExc_TypeError, "Either BoundBox or two Vectors expected"); return nullptr; - } - while(false); + } while (false); return Py::new_reference_to(retVal); } -PyObject* BoundBoxPy::intersected(PyObject *args) +PyObject* BoundBoxPy::intersected(PyObject* args) { if (!getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box"); return nullptr; } - PyObject *object{}; - if (!PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) + PyObject* object {}; + if (!PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object)) { return nullptr; + } if (!static_cast(object)->getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - Base::BoundBox3d bbox = getBoundBoxPtr()->Intersected(*static_cast(object)->getBoundBoxPtr()); + Base::BoundBox3d bbox = + getBoundBoxPtr()->Intersected(*static_cast(object)->getBoundBoxPtr()); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } -PyObject* BoundBoxPy::united(PyObject *args) +PyObject* BoundBoxPy::united(PyObject* args) { if (!getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box"); return nullptr; } - PyObject *object{}; - if (!PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) + PyObject* object {}; + if (!PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object)) { return nullptr; + } if (!static_cast(object)->getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - Base::BoundBox3d bbox = getBoundBoxPtr()->United(*static_cast(object)->getBoundBoxPtr()); + Base::BoundBox3d bbox = + getBoundBoxPtr()->United(*static_cast(object)->getBoundBoxPtr()); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } -PyObject* BoundBoxPy::enlarge(PyObject *args) +PyObject* BoundBoxPy::enlarge(PyObject* args) { - double s{}; - if (!PyArg_ParseTuple(args, "d;Need float parameter to enlarge", &s)) + double s {}; + if (!PyArg_ParseTuple(args, "d;Need float parameter to enlarge", &s)) { return nullptr; + } getBoundBoxPtr()->Enlarge(s); Py_Return; } -PyObject* BoundBoxPy::getIntersectionPoint(PyObject *args) +PyObject* BoundBoxPy::getIntersectionPoint(PyObject* args) { - PyObject *object{},*object2{}; - double epsilon=0.0001; - if (!PyArg_ParseTuple(args,"O!O!|d;Need base and direction vector", - &(Base::VectorPy::Type), &object,&(Base::VectorPy::Type), &object2, &epsilon)) + PyObject *object {}, *object2 {}; + double epsilon = 0.0001; + if (!PyArg_ParseTuple(args, + "O!O!|d;Need base and direction vector", + &(Base::VectorPy::Type), + &object, + &(Base::VectorPy::Type), + &object2, + &epsilon)) { return nullptr; + } Base::Vector3d point; bool ok = getBoundBoxPtr()->IntersectionPoint( *(static_cast(object)->getVectorPtr()), *(static_cast(object2)->getVectorPtr()), - point, epsilon); + point, + epsilon); if (ok) { return new VectorPy(point); } @@ -329,27 +353,27 @@ PyObject* BoundBoxPy::getIntersectionPoint(PyObject *args) } } -PyObject* BoundBoxPy::move(PyObject *args) +PyObject* BoundBoxPy::move(PyObject* args) { - double x{},y{},z{}; - PyObject *object{}; + double x {}, y {}, z {}; + PyObject* object {}; Base::Vector3d vec; do { - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { - vec = Vector3d(x,y,z); + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { + vec = Vector3d(x, y, z); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &object)) { vec = getVectorFromTuple(object); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { vec = *(static_cast(object)->getVectorPtr()); break; } @@ -357,8 +381,7 @@ PyObject* BoundBoxPy::move(PyObject *args) PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return nullptr; } - } - while(false); + } while (false); getBoundBoxPtr()->MoveX(vec.x); getBoundBoxPtr()->MoveY(vec.y); @@ -367,27 +390,27 @@ PyObject* BoundBoxPy::move(PyObject *args) Py_Return; } -PyObject* BoundBoxPy::scale(PyObject *args) +PyObject* BoundBoxPy::scale(PyObject* args) { - double x{},y{},z{}; - PyObject *object{}; + double x {}, y {}, z {}; + PyObject* object {}; Base::Vector3d vec; do { - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { - vec = Vector3d(x,y,z); + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { + vec = Vector3d(x, y, z); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &object)) { vec = getVectorFromTuple(object); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { vec = *(static_cast(object)->getVectorPtr()); break; } @@ -395,8 +418,7 @@ PyObject* BoundBoxPy::scale(PyObject *args) PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return nullptr; } - } - while(false); + } while (false); getBoundBoxPtr()->ScaleX(vec.x); getBoundBoxPtr()->ScaleY(vec.y); @@ -405,90 +427,98 @@ PyObject* BoundBoxPy::scale(PyObject *args) Py_Return; } -PyObject* BoundBoxPy::transformed(PyObject *args) +PyObject* BoundBoxPy::transformed(PyObject* args) { - PyObject *mat{}; + PyObject* mat {}; - if (!PyArg_ParseTuple(args,"O!", &(Base::MatrixPy::Type), &mat)) - return nullptr; - - if (!getBoundBoxPtr()->IsValid()) - throw Py::FloatingPointError("Cannot transform invalid bounding box"); - Base::BoundBox3d bbox = getBoundBoxPtr()->Transformed(*static_cast(mat)->getMatrixPtr()); - return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); -} - -PyObject* BoundBoxPy::isCutPlane(PyObject *args) -{ - PyObject *object{},*object2{}; - Py::Boolean retVal; - - if (!getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); + if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type), &mat)) { return nullptr; } - if (!PyArg_ParseTuple(args,"O!O!;Need base and normal vector of a plane", - &(Base::VectorPy::Type), &object,&(Base::VectorPy::Type), &object2)) - return nullptr; + if (!getBoundBoxPtr()->IsValid()) { + throw Py::FloatingPointError("Cannot transform invalid bounding box"); + } + Base::BoundBox3d bbox = + getBoundBoxPtr()->Transformed(*static_cast(mat)->getMatrixPtr()); + return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); +} - retVal = getBoundBoxPtr()->IsCutPlane( - *(static_cast(object)->getVectorPtr()), - *(static_cast(object2)->getVectorPtr())); +PyObject* BoundBoxPy::isCutPlane(PyObject* args) +{ + PyObject *object {}, *object2 {}; + Py::Boolean retVal; + + if (!getBoundBoxPtr()->IsValid()) { + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box"); + return nullptr; + } + + if (!PyArg_ParseTuple(args, + "O!O!;Need base and normal vector of a plane", + &(Base::VectorPy::Type), + &object, + &(Base::VectorPy::Type), + &object2)) { + return nullptr; + } + + retVal = getBoundBoxPtr()->IsCutPlane(*(static_cast(object)->getVectorPtr()), + *(static_cast(object2)->getVectorPtr())); return Py::new_reference_to(retVal); } -PyObject* BoundBoxPy::isInside(PyObject *args) +PyObject* BoundBoxPy::isInside(PyObject* args) { - double x{},y{},z{}; - PyObject *object{}; + double x {}, y {}, z {}; + PyObject* object {}; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box"); return nullptr; } do { - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { - retVal = getBoundBoxPtr()->IsInBox(Vector3d(x,y,z)); + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { + retVal = getBoundBoxPtr()->IsInBox(Vector3d(x, y, z)); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &object)) { retVal = getBoundBoxPtr()->IsInBox(getVectorFromTuple(object)); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { - retVal = getBoundBoxPtr()->IsInBox(*(static_cast(object)->getVectorPtr())); + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { + retVal = + getBoundBoxPtr()->IsInBox(*(static_cast(object)->getVectorPtr())); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object)) { if (!static_cast(object)->getBoundBoxPtr()->IsValid()) { - PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); + PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - retVal = getBoundBoxPtr()->IsInBox(*(static_cast(object)->getBoundBoxPtr())); + retVal = getBoundBoxPtr()->IsInBox( + *(static_cast(object)->getBoundBoxPtr())); break; } PyErr_SetString(PyExc_TypeError, "Either three floats, Vector(s) or BoundBox expected"); return nullptr; - } - while(false); + } while (false); return Py::new_reference_to(retVal); } Py::Object BoundBoxPy::getCenter() const { - return Py::Vector(getBoundBoxPtr()->GetCenter()); // NOLINT + return Py::Vector(getBoundBoxPtr()->GetCenter()); // NOLINT } Py::Float BoundBoxPy::getXMax() const @@ -496,7 +526,7 @@ Py::Float BoundBoxPy::getXMax() const return Py::Float(getBoundBoxPtr()->MaxX); } -void BoundBoxPy::setXMax(Py::Float arg) +void BoundBoxPy::setXMax(Py::Float arg) { getBoundBoxPtr()->MaxX = arg; } @@ -506,7 +536,7 @@ Py::Float BoundBoxPy::getYMax() const return Py::Float(getBoundBoxPtr()->MaxY); } -void BoundBoxPy::setYMax(Py::Float arg) +void BoundBoxPy::setYMax(Py::Float arg) { getBoundBoxPtr()->MaxY = arg; } @@ -516,7 +546,7 @@ Py::Float BoundBoxPy::getZMax() const return Py::Float(getBoundBoxPtr()->MaxZ); } -void BoundBoxPy::setZMax(Py::Float arg) +void BoundBoxPy::setZMax(Py::Float arg) { getBoundBoxPtr()->MaxZ = arg; } @@ -526,7 +556,7 @@ Py::Float BoundBoxPy::getXMin() const return Py::Float(getBoundBoxPtr()->MinX); } -void BoundBoxPy::setXMin(Py::Float arg) +void BoundBoxPy::setXMin(Py::Float arg) { getBoundBoxPtr()->MinX = arg; } @@ -536,7 +566,7 @@ Py::Float BoundBoxPy::getYMin() const return Py::Float(getBoundBoxPtr()->MinY); } -void BoundBoxPy::setYMin(Py::Float arg) +void BoundBoxPy::setYMin(Py::Float arg) { getBoundBoxPtr()->MinY = arg; } @@ -546,7 +576,7 @@ Py::Float BoundBoxPy::getZMin() const return Py::Float(getBoundBoxPtr()->MinZ); } -void BoundBoxPy::setZMin(Py::Float arg) +void BoundBoxPy::setZMin(Py::Float arg) { getBoundBoxPtr()->MinZ = arg; } @@ -568,12 +598,13 @@ Py::Float BoundBoxPy::getZLength() const Py::Float BoundBoxPy::getDiagonalLength() const { - if (!getBoundBoxPtr()->IsValid()) + if (!getBoundBoxPtr()->IsValid()) { throw Py::FloatingPointError("Cannot determine diagonal length of invalid bounding box"); + } return Py::Float(getBoundBoxPtr()->CalcDiagonalLength()); } -PyObject *BoundBoxPy::getCustomAttributes(const char* /*attr*/) const +PyObject* BoundBoxPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -582,5 +613,3 @@ int BoundBoxPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Base/Builder3D.cpp b/src/Base/Builder3D.cpp index 4c7c816367..73876446f5 100644 --- a/src/Base/Builder3D.cpp +++ b/src/Base/Builder3D.cpp @@ -24,16 +24,16 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include "Builder3D.h" @@ -51,16 +51,13 @@ using namespace Base; constexpr float valueMinLegal {-1.0F}; constexpr float valueMaxLegal {1.0F}; -ColorRGB::ColorRGB() : Rgb{1.0F, 1.0F, 1.0F} -{ -} +ColorRGB::ColorRGB() + : Rgb {1.0F, 1.0F, 1.0F} +{} ColorRGB::ColorRGB(float red, float green, float blue) - : Rgb{valueInRange(red), - valueInRange(green), - valueInRange(blue)} -{ -} + : Rgb {valueInRange(red), valueInRange(green), valueInRange(blue)} +{} float ColorRGB::valueInRange(float value) { @@ -70,14 +67,14 @@ float ColorRGB::valueInRange(float value) const char* DrawStyle::styleAsString() const { switch (style) { - case Style::Filled: - return "FILLED"; - case Style::Lines: - return "LINES"; - case Style::Points: - return "POINTS"; - case Style::Invisible: - return "INVISIBLE"; + case Style::Filled: + return "FILLED"; + case Style::Lines: + return "LINES"; + case Style::Points: + return "POINTS"; + case Style::Invisible: + return "INVISIBLE"; } return "FILLED"; } @@ -92,12 +89,12 @@ std::string DrawStyle::patternAsString() const const char* VertexOrdering::toString() const { switch (ordering) { - case Ordering::UnknownOrdering: - return "UNKNOWN_ORDERING"; - case Ordering::Clockwise: - return "CLOCKWISE"; - case Ordering::CounterClockwise: - return "COUNTERCLOCKWISE"; + case Ordering::UnknownOrdering: + return "UNKNOWN_ORDERING"; + case Ordering::Clockwise: + return "CLOCKWISE"; + case Ordering::CounterClockwise: + return "COUNTERCLOCKWISE"; } return "UNKNOWN_ORDERING"; } @@ -105,10 +102,10 @@ const char* VertexOrdering::toString() const const char* ShapeType::toString() const { switch (type) { - case Type::UnknownShapeType: - return "UNKNOWN_SHAPE_TYPE"; - case Type::Convex: - return "SOLID"; + case Type::UnknownShapeType: + return "UNKNOWN_SHAPE_TYPE"; + case Type::Convex: + return "SOLID"; } return "UNKNOWN_SHAPE_TYPE"; } @@ -116,32 +113,32 @@ const char* ShapeType::toString() const const char* BindingElement::bindingAsString() const { switch (value) { - case Binding::PerPart: - return "PER_PART"; - case Binding::PerPartIndexed: - return "PER_PART_INDEXED"; - case Binding::PerFace: - return "PER_FACE"; - case Binding::PerFaceIndexed: - return "PER_FACE_INDEXED"; - case Binding::PerVertex: - return "PER_VERTEX"; - case Binding::PerVertexIndexed: - return "PER_VERTEX_INDEXED"; - default: - return "OVERALL"; + case Binding::PerPart: + return "PER_PART"; + case Binding::PerPartIndexed: + return "PER_PART_INDEXED"; + case Binding::PerFace: + return "PER_FACE"; + case Binding::PerFaceIndexed: + return "PER_FACE_INDEXED"; + case Binding::PerVertex: + return "PER_VERTEX"; + case Binding::PerVertexIndexed: + return "PER_VERTEX_INDEXED"; + default: + return "OVERALL"; } } const char* PolygonOffset::styleAsString() const { switch (style) { - case Style::Filled: - return "FILLED"; - case Style::Lines: - return "LINES"; - case Style::Points: - return "POINTS"; + case Style::Filled: + return "FILLED"; + case Style::Lines: + return "LINES"; + case Style::Points: + return "POINTS"; } return "FILLED"; } @@ -149,10 +146,9 @@ const char* PolygonOffset::styleAsString() const // ----------------------------------------------------------------------------- InventorOutput::InventorOutput(std::ostream& result, Indentation& indent) - : result(result) - , indent(indent) -{ -} + : result(result) + , indent(indent) +{} std::ostream& InventorOutput::stream() { @@ -207,32 +203,41 @@ void InventorOutput::decreaseIndent() // ----------------------------------------------------------------------------- -namespace Base { -template -struct field_traits { }; +namespace Base +{ +template +struct field_traits +{ +}; -template <> -struct field_traits { +template<> +struct field_traits +{ using field_type = float; - static std::ostream& write(std::ostream& out, const field_type& item) { + static std::ostream& write(std::ostream& out, const field_type& item) + { out << item; return out; } }; -template <> -struct field_traits { +template<> +struct field_traits +{ using field_type = Vector3f; - static std::ostream& write(std::ostream& out, const field_type& item) { + static std::ostream& write(std::ostream& out, const field_type& item) + { out << item.x << " " << item.y << " " << item.z; return out; } }; -template <> -struct field_traits { +template<> +struct field_traits +{ using field_type = ColorRGB; - static std::ostream& write(std::ostream& out, const field_type& item) { + static std::ostream& write(std::ostream& out, const field_type& item) + { out << item.red() << " " << item.green() << " " << item.blue(); return out; } @@ -242,17 +247,21 @@ struct field_traits { * Writes a field type to a stream. * @author Werner Mayer */ -class InventorFieldWriter { +class InventorFieldWriter +{ public: template void write(const char* fieldName, const std::vector& fieldData, InventorOutput& out) const; }; template -void InventorFieldWriter::write(const char* fieldName, const std::vector& fieldData, InventorOutput& out) const +void InventorFieldWriter::write(const char* fieldName, + const std::vector& fieldData, + InventorOutput& out) const { - if (fieldData.empty()) + if (fieldData.empty()) { return; + } if (fieldData.size() == 1) { out.write() << fieldName << " "; @@ -271,36 +280,42 @@ void InventorFieldWriter::write(const char* fieldName, const std::vector& fie } template<> -void InventorFieldWriter::write(const char* fieldName, const std::vector& fieldData, InventorOutput& out) const +void InventorFieldWriter::write(const char* fieldName, + const std::vector& fieldData, + InventorOutput& out) const { - if (fieldData.empty()) + if (fieldData.empty()) { return; + } out.write() << fieldName << " [\n"; out.increaseIndent(); - std::size_t last_index{fieldData.size()}; - std::size_t index{}; + std::size_t last_index {fieldData.size()}; + std::size_t index {}; for (auto it : fieldData) { - if (index % 8 == 0) + if (index % 8 == 0) { out.write(); - if (index < last_index) + } + if (index < last_index) { out.stream() << it << ", "; - else + } + else { out.stream() << it << " ] \n"; - if (++index % 8 == 0) + } + if (++index % 8 == 0) { out.stream() << '\n'; + } } out.decreaseIndent(); out.write() << "]\n"; } -} +} // namespace Base // ----------------------------------------------------------------------------- -LabelItem::LabelItem(const std::string& text) : text(text) -{ - -} +LabelItem::LabelItem(const std::string& text) + : text(text) +{} void LabelItem::write(InventorOutput& out) const { @@ -311,10 +326,9 @@ void LabelItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -InfoItem::InfoItem(const std::string& text) : text(text) -{ - -} +InfoItem::InfoItem(const std::string& text) + : text(text) +{} void InfoItem::write(InventorOutput& out) const { @@ -325,10 +339,9 @@ void InfoItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -BaseColorItem::BaseColorItem(const ColorRGB& rgb) : rgb(rgb) -{ - -} +BaseColorItem::BaseColorItem(const ColorRGB& rgb) + : rgb(rgb) +{} void BaseColorItem::write(InventorOutput& out) const { @@ -343,15 +356,14 @@ PointItem::PointItem(const Base::Vector3f& point, DrawStyle drawStyle, const Col : point(point) , drawStyle(drawStyle) , rgb(rgb) -{ - -} +{} void PointItem::write(InventorOutput& out) const { out.write() << "Separator { \n"; out.write() << " Material { \n"; - out.write() << " diffuseColor " << rgb.red() << " "<< rgb.green() << " "<< rgb.blue() << '\n'; + out.write() << " diffuseColor " << rgb.red() << " " << rgb.green() << " " << rgb.blue() + << '\n'; out.write() << " }\n"; out.write() << " MaterialBinding { value PER_PART }\n"; out.write() << " DrawStyle { pointSize " << drawStyle.pointSize << "}\n"; @@ -359,7 +371,7 @@ void PointItem::write(InventorOutput& out) const out.write() << " point [ " << point.x << " " << point.y << " " << point.z << "]\n"; out.write() << " }\n"; out.write() << " PointSet { }\n"; - out.write() <<"}\n"; + out.write() << "}\n"; } // ----------------------------------------------------------------------------- @@ -368,21 +380,21 @@ LineItem::LineItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorRGB : line(line) , drawStyle(drawStyle) , rgb(rgb) -{ - -} +{} void LineItem::write(InventorOutput& out) const { std::string pattern = drawStyle.patternAsString(); out.write(" Separator { \n"); - out.write() << " Material { diffuseColor " << rgb.red() << " "<< rgb.green() << " "<< rgb.blue() << "} \n"; - out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern << " } \n"; + out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " " + << rgb.blue() << "} \n"; + out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern + << " } \n"; out.write() << " Coordinate3 { \n"; out.write() << " point [ "; - out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ","; - out.write() << line.p2.x << " " << line.p2.y << " " << line.p2.z; + out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ","; + out.write() << line.p2.x << " " << line.p2.y << " " << line.p2.z; out.write() << " ] \n"; out.write() << " } \n"; out.write() << " LineSet { } \n"; @@ -391,21 +403,23 @@ void LineItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -MultiLineItem::MultiLineItem(const std::vector& points, DrawStyle drawStyle, const ColorRGB& rgb) - : points{points} - , drawStyle{drawStyle} - , rgb{rgb} -{ - -} +MultiLineItem::MultiLineItem(const std::vector& points, + DrawStyle drawStyle, + const ColorRGB& rgb) + : points {points} + , drawStyle {drawStyle} + , rgb {rgb} +{} void MultiLineItem::write(InventorOutput& out) const { std::string pattern = drawStyle.patternAsString(); out.write() << "Separator {\n"; - out.write() << " Material { diffuseColor " << rgb.red() << " "<< rgb.green() << " "<< rgb.blue() << "}\n"; - out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern << " }\n"; + out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " " + << rgb.blue() << "}\n"; + out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " linePattern " << pattern + << " }\n"; out.write() << " Coordinate3 {\n"; InventorFieldWriter writer; @@ -424,9 +438,7 @@ ArrowItem::ArrowItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorR : line(line) , drawStyle(drawStyle) , rgb(rgb) -{ - -} +{} void ArrowItem::write(InventorOutput& out) const { @@ -434,7 +446,7 @@ void ArrowItem::write(InventorOutput& out) const float coneLength = length / 10.0F; float coneRadius = coneLength / 2.0F; float sf1 = length - coneLength; - float sf2 = length - coneLength/2.0F; + float sf2 = length - coneLength / 2.0F; Vector3f dir = line.GetDirection(); dir.Normalize(); @@ -449,20 +461,19 @@ void ArrowItem::write(InventorOutput& out) const float angle = Vector3f(0.0f, 1.0f, 0.0f).GetAngle(dir); out.write() << "Separator {\n"; - out.write() << " Material { diffuseColor " << rgb.red() << " "<< rgb.green() << " "<< rgb.blue() << "}\n"; + out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " " + << rgb.blue() << "}\n"; out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << " }\n"; out.write() << " Coordinate3 {\n"; out.write() << " point [ "; - out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ", "; - out.write() << pt2s.x << " " << pt2s.y << " " << pt2s.z; + out.write() << line.p1.x << " " << line.p1.y << " " << line.p1.z << ", "; + out.write() << pt2s.x << " " << pt2s.y << " " << pt2s.z; out.write() << " ]\n"; out.write() << " }\n"; out.write() << " LineSet { }\n"; out.write() << " Transform { \n"; - out.write() << " translation " - << cpt.x << " " << cpt.y << " " << cpt.z << '\n'; - out.write() << " rotation " - << rot.x << " " << rot.y << " " << rot.z << " " << angle << '\n'; + out.write() << " translation " << cpt.x << " " << cpt.y << " " << cpt.z << '\n'; + out.write() << " rotation " << rot.x << " " << rot.y << " " << rot.z << " " << angle << '\n'; out.write() << " }\n"; out.write() << " Cone { bottomRadius " << coneRadius << " height " << coneLength << "} \n"; out.write() << "}\n"; @@ -470,14 +481,15 @@ void ArrowItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -BoundingBoxItem::BoundingBoxItem(const Vector3f& pt1, const Vector3f& pt2, DrawStyle drawStyle, const ColorRGB& rgb) - : pt1{pt1} - , pt2{pt2} - , drawStyle{drawStyle} - , rgb{rgb} -{ - -} +BoundingBoxItem::BoundingBoxItem(const Vector3f& pt1, + const Vector3f& pt2, + DrawStyle drawStyle, + const ColorRGB& rgb) + : pt1 {pt1} + , pt2 {pt2} + , drawStyle {drawStyle} + , rgb {rgb} +{} void BoundingBoxItem::write(InventorOutput& out) const { @@ -491,24 +503,20 @@ void BoundingBoxItem::write(InventorOutput& out) const points[6].Set(pt2.x, pt2.y, pt1.z); points[7].Set(pt2.x, pt2.y, pt2.z); - std::vector lineset = { - 0, 2, 6, 4, 0, -1, - 1, 5, 7, 3, 1, -1, - 7, 6, 2, 3, 7, -1, - 3, 2, 0, 1, 3, -1, - 5, 1, 0, 4, 5, -1 - }; + std::vector lineset = {0, 2, 6, 4, 0, -1, 1, 5, 7, 3, 1, -1, 7, 6, 2, + 3, 7, -1, 3, 2, 0, 1, 3, -1, 5, 1, 0, 4, 5, -1}; out.write() << "Separator {\n"; - out.write() << " Material { diffuseColor " << rgb.red() << " "<< rgb.green() << " "<< rgb.blue() << "}\n"; + out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " " + << rgb.blue() << "}\n"; out.write() << " DrawStyle { lineWidth " << drawStyle.lineWidth << "}\n"; - Coordinate3Item coords{points}; + Coordinate3Item coords {points}; out.increaseIndent(); coords.write(out); out.decreaseIndent(); - IndexedLineSetItem indexed{lineset}; + IndexedLineSetItem indexed {lineset}; out.increaseIndent(); indexed.write(out); out.decreaseIndent(); @@ -622,16 +630,14 @@ void MaterialBindingItem::setValue(BindingElement::Binding bind) void MaterialBindingItem::write(InventorOutput& out) const { - out.write() << "MaterialBinding { value " - << value.bindingAsString() << " } \n"; + out.write() << "MaterialBinding { value " << value.bindingAsString() << " } \n"; } // ----------------------------------------------------------------------------- DrawStyleItem::DrawStyleItem(DrawStyle value) - : style{value} -{ -} + : style {value} +{} void DrawStyleItem::setValue(DrawStyle value) { @@ -650,10 +656,9 @@ void DrawStyleItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -ShapeHintsItem::ShapeHintsItem(float creaseAngle) : creaseAngle(creaseAngle) -{ - -} +ShapeHintsItem::ShapeHintsItem(float creaseAngle) + : creaseAngle(creaseAngle) +{} void ShapeHintsItem::setVertexOrdering(VertexOrdering::Ordering value) { @@ -696,8 +701,7 @@ void PolygonOffsetItem::write(InventorOutput& out) const Coordinate3Item::Coordinate3Item(const std::vector& points) : points(points) -{ -} +{} void Coordinate3Item::write(InventorOutput& out) const { @@ -737,11 +741,9 @@ void LineSetItem::write(InventorOutput& out) const FaceSetItem::FaceSetItem(const std::vector& indices) : indices(indices) -{ +{} -} - -void FaceSetItem::write(InventorOutput &out) const +void FaceSetItem::write(InventorOutput& out) const { out.write() << "FaceSet {\n"; out.increaseIndent(); @@ -755,11 +757,9 @@ void FaceSetItem::write(InventorOutput &out) const IndexedLineSetItem::IndexedLineSetItem(const std::vector& indices) : indices(indices) -{ +{} -} - -void IndexedLineSetItem::write(InventorOutput &out) const +void IndexedLineSetItem::write(InventorOutput& out) const { out.write() << "IndexedLineSet {\n"; out.increaseIndent(); @@ -773,11 +773,9 @@ void IndexedLineSetItem::write(InventorOutput &out) const IndexedFaceSetItem::IndexedFaceSetItem(const std::vector& indices) : indices(indices) -{ +{} -} - -void IndexedFaceSetItem::write(InventorOutput &out) const +void IndexedFaceSetItem::write(InventorOutput& out) const { out.write() << "IndexedFaceSet {\n"; out.increaseIndent(); @@ -791,8 +789,7 @@ void IndexedFaceSetItem::write(InventorOutput &out) const NormalItem::NormalItem(const std::vector& vec) : vector(vec) -{ -} +{} void NormalItem::write(InventorOutput& out) const { @@ -823,8 +820,7 @@ void NormalBindingItem::setValue(BindingElement::Binding bind) void NormalBindingItem::write(InventorOutput& out) const { - out.write() << "NormalBinding { value " - << value.bindingAsString() << " }\n"; + out.write() << "NormalBinding { value " << value.bindingAsString() << " }\n"; } // ----------------------------------------------------------------------------- @@ -909,22 +905,19 @@ void NurbsSurfaceItem::write(InventorOutput& out) const Text2Item::Text2Item(const std::string& string) : string(string) -{ - -} +{} void Text2Item::write(InventorOutput& out) const { - out.write() << "Text2 { string \"" << string << "\" " << "}\n"; + out.write() << "Text2 { string \"" << string << "\" " + << "}\n"; } // ----------------------------------------------------------------------------- TransformItem::TransformItem(const Base::Placement& placement) : placement(placement) -{ - -} +{} TransformItem::TransformItem(const Matrix4D& transform) { @@ -935,27 +928,26 @@ void TransformItem::write(InventorOutput& out) const { Base::Vector3d translation = placement.getPosition(); Base::Vector3d rotationaxis; - double angle{}; + double angle {}; placement.getRotation().getValue(rotationaxis, angle); out.write() << "Transform {\n"; - out.write() << " translation " - << translation.x << " " << translation.y << " " << translation.z << '\n'; - out.write() << " rotation " - << rotationaxis.x << " " << rotationaxis.y << " " << rotationaxis.z - << " " << angle << '\n'; - out.write() << "}" << '\n'; + out.write() << " translation " << translation.x << " " << translation.y << " " << translation.z + << '\n'; + out.write() << " rotation " << rotationaxis.x << " " << rotationaxis.y << " " << rotationaxis.z + << " " << angle << '\n'; + out.write() << "}" << '\n'; } // ----------------------------------------------------------------------------- InventorBuilder::InventorBuilder(std::ostream& output) - : result(output) + : result(output) { addHeader(); } -InventorBuilder:: ~InventorBuilder() = default; +InventorBuilder::~InventorBuilder() = default; void InventorBuilder::addHeader() { @@ -997,10 +989,9 @@ void InventorBuilder::endSeparator() * A more elaborate description of the constructor. */ Builder3D::Builder3D() - : result{} - , builder{result} -{ -} + : result {} + , builder {result} +{} /** * A destructor. @@ -1008,7 +999,7 @@ Builder3D::Builder3D() */ Builder3D::~Builder3D() = default; -void Builder3D::clear () +void Builder3D::clear() { // under gcc stringstream::str() returns a copy not a reference #if defined(_MSC_VER) @@ -1027,8 +1018,12 @@ void Builder3D::clear () void Builder3D::saveToLog() { ILogger* obs = Base::Console().Get("StatusBar"); - if (obs){ - obs->SendLog("Builder3D",result.str().c_str(), Base::LogStyle::Log, Base::IntendedRecipient::Developer, Base::ContentType::Untranslatable); + if (obs) { + obs->SendLog("Builder3D", + result.str().c_str(), + Base::LogStyle::Log, + Base::IntendedRecipient::Developer, + Base::ContentType::Untranslatable); } } @@ -1043,7 +1038,7 @@ void Builder3D::saveToLog() void Builder3D::saveToFile(const char* FileName) { Base::FileInfo fi(FileName); - Base::ofstream file(fi); + Base::ofstream file(fi); if (!file) { throw FileException("Cannot open file"); } @@ -1086,14 +1081,15 @@ std::vector InventorLoader::readData(const char* fieldName) const } } - if (!found) + if (!found) { return {}; + } do { boost::char_separator sep(" ,"); - boost::tokenizer > tokens(str, sep); + boost::tokenizer> tokens(str, sep); std::vector token_results; - token_results.assign(tokens.begin(),tokens.end()); + token_results.assign(tokens.begin(), tokens.end()); for (const auto& it : token_results) { try { @@ -1105,18 +1101,19 @@ std::vector InventorLoader::readData(const char* fieldName) const } // search for ']' to finish the reading - if (str.find("]") != std::string::npos) + if (str.find("]") != std::string::npos) { break; - } - while (std::getline(inp, str)); + } + } while (std::getline(inp, str)); return fieldValues; } std::vector InventorLoader::convert(const std::vector& data) const { - if (data.size() % 3 != 0) + if (data.size() % 3 != 0) { throw std::string("Reading failed"); + } std::size_t len = data.size() / 3; std::vector points; @@ -1139,11 +1136,11 @@ std::vector InventorLoader::convert(const std::vector> InventorLoader::split(const std::vector InventorLoader::convert(const std::vector>& coordIndex) const +std::vector +InventorLoader::convert(const std::vector>& coordIndex) const { std::vector faces; faces.reserve(coordIndex.size()); @@ -1207,15 +1205,17 @@ void InventorLoader::readFaceSet() bool InventorLoader::read() { - if (!inp || inp.bad()) + if (!inp || inp.bad()) { return false; + } std::string line; // Verify it's an Inventor 2.1 file std::getline(inp, line); - if (line.find("#Inventor V2.1 ascii") == std::string::npos) + if (line.find("#Inventor V2.1 ascii") == std::string::npos) { return false; + } while (std::getline(inp, line)) { // read the normals if they are defined @@ -1239,30 +1239,36 @@ bool InventorLoader::read() bool InventorLoader::isValid() const { - int32_t value{static_cast(points.size())}; + int32_t value {static_cast(points.size())}; auto inRange = [value](const Face& f) { - if (f.p1 < 0 || f.p1 >= value) + if (f.p1 < 0 || f.p1 >= value) { return false; - if (f.p2 < 0 || f.p2 >= value) + } + if (f.p2 < 0 || f.p2 >= value) { return false; - if (f.p3 < 0 || f.p3 >= value) + } + if (f.p3 < 0 || f.p3 >= value) { return false; + } return true; }; for (auto it : faces) { - if (!inRange(it)) + if (!inRange(it)) { return false; + } } return true; } -namespace Base { +namespace Base +{ BaseExport Vector3f to_vector(std::string str) { std::string_view view = str; - if (!boost::starts_with(view, "(") || !boost::ends_with(str, ")")) + if (!boost::starts_with(view, "(") || !boost::ends_with(str, ")")) { throw std::runtime_error("string is not a tuple"); + } view.remove_prefix(1); view.remove_suffix(1); @@ -1270,12 +1276,13 @@ BaseExport Vector3f to_vector(std::string str) str = view; boost::char_separator sep(" ,"); - boost::tokenizer > tokens(str, sep); + boost::tokenizer> tokens(str, sep); std::vector token_results; token_results.assign(tokens.begin(), tokens.end()); - if (token_results.size() != 3) + if (token_results.size() != 3) { throw std::runtime_error("not a tuple of three floats"); + } Base::Vector3f vec; vec.x = boost::lexical_cast(token_results.at(0)); @@ -1285,4 +1292,4 @@ BaseExport Vector3f to_vector(std::string str) return vec; } -} +} // namespace Base diff --git a/src/Base/Builder3D.h b/src/Base/Builder3D.h index 1968f0b403..4563e2f1f9 100644 --- a/src/Base/Builder3D.h +++ b/src/Base/Builder3D.h @@ -27,7 +27,7 @@ // Std. configurations #ifdef __GNUC__ -# include +#include #endif #include @@ -45,25 +45,33 @@ class BaseExport ColorRGB { public: ColorRGB(); + ColorRGB(const ColorRGB&) = default; + ColorRGB(ColorRGB&&) = default; explicit ColorRGB(float red, float green, float blue); ~ColorRGB() = default; + ColorRGB& operator=(const ColorRGB&) = default; + ColorRGB& operator=(ColorRGB&&) = default; - float red() const { + float red() const + { return Rgb.red; } - float green() const { + float green() const + { return Rgb.green; } - float blue() const { + float blue() const + { return Rgb.blue; } -protected: +private: /*! Returns the clamped value in range [-1, +1] */ static float valueInRange(float value); - struct { + struct + { float red; float green; float blue; @@ -73,7 +81,8 @@ protected: class BaseExport DrawStyle { public: - enum class Style { + enum class Style + { Filled, Lines, Points, @@ -91,7 +100,8 @@ public: class BaseExport VertexOrdering { public: - enum class Ordering { + enum class Ordering + { UnknownOrdering, Clockwise, CounterClockwise @@ -105,7 +115,8 @@ public: class BaseExport ShapeType { public: - enum class Type { + enum class Type + { UnknownShapeType, Convex }; @@ -118,7 +129,8 @@ public: class BaseExport BindingElement { public: - enum class Binding { + enum class Binding + { Overall = 2, PerPart = 3, PerPartIndexed = 4, @@ -137,7 +149,8 @@ public: class BaseExport PolygonOffset { public: - enum class Style { + enum class Style + { Filled, Lines, Points @@ -156,19 +169,23 @@ public: explicit Triangle(const Base::Vector3f& pt1, const Base::Vector3f& pt2, const Base::Vector3f& pt3) - : pt1(pt1), pt2(pt2), pt3(pt3) - { - } + : pt1(pt1) + , pt2(pt2) + , pt3(pt3) + {} - const Base::Vector3f& getPoint1() const { + const Base::Vector3f& getPoint1() const + { return pt1; } - const Base::Vector3f& getPoint2() const { + const Base::Vector3f& getPoint2() const + { return pt2; } - const Base::Vector3f& getPoint3() const { + const Base::Vector3f& getPoint3() const + { return pt3; } @@ -178,22 +195,28 @@ private: Base::Vector3f pt3; }; -class Indentation { +class Indentation +{ int spaces = 0; + public: - void increaseIndent() { + void increaseIndent() + { spaces += 2; } - void decreaseIndent() { + void decreaseIndent() + { spaces -= 2; } - int count() { + int count() + { return spaces; } - friend std::ostream& operator<<( std::ostream& os, Indentation m) + friend std::ostream& operator<<(std::ostream& os, Indentation m) { - for (int i = 0; i < m.count(); i++) + for (int i = 0; i < m.count(); i++) { os << " "; + } return os; } }; @@ -222,12 +245,19 @@ class BaseExport NodeItem public: virtual ~NodeItem() = default; virtual void write(InventorOutput& out) const = 0; + +protected: + NodeItem() = default; + NodeItem(const NodeItem&) = default; + NodeItem(NodeItem&&) = default; + NodeItem& operator=(const NodeItem&) = default; + NodeItem& operator=(NodeItem&&) = default; }; /*! * \brief The LabelItem class supports the SoLabel node. */ -class BaseExport LabelItem : public NodeItem +class BaseExport LabelItem: public NodeItem { public: explicit LabelItem(const std::string& text); @@ -240,7 +270,7 @@ private: /*! * \brief The InfoItem class supports the SoInfo node. */ -class BaseExport InfoItem : public NodeItem +class BaseExport InfoItem: public NodeItem { public: explicit InfoItem(const std::string& text); @@ -253,7 +283,7 @@ private: /*! * \brief The BaseColorItem class supports the SoBaseColor node. */ -class BaseExport BaseColorItem : public NodeItem +class BaseExport BaseColorItem: public NodeItem { public: explicit BaseColorItem(const ColorRGB& rgb); @@ -263,10 +293,12 @@ private: ColorRGB rgb; }; -class BaseExport PointItem : public NodeItem +class BaseExport PointItem: public NodeItem { public: - explicit PointItem(const Base::Vector3f& point, DrawStyle drawStyle, const ColorRGB& rgb = ColorRGB{1.0F, 1.0F, 1.0F}); + explicit PointItem(const Base::Vector3f& point, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); void write(InventorOutput& out) const override; private: @@ -275,10 +307,12 @@ private: ColorRGB rgb; }; -class BaseExport LineItem : public NodeItem +class BaseExport LineItem: public NodeItem { public: - explicit LineItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorRGB& rgb = ColorRGB{1.0F, 1.0F, 1.0F}); + explicit LineItem(const Base::Line3f& line, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); void write(InventorOutput& out) const override; private: @@ -287,11 +321,14 @@ private: ColorRGB rgb; }; -class BaseExport MultiLineItem : public NodeItem +class BaseExport MultiLineItem: public NodeItem { public: - /// add a line defined by a list of points whereat always a pair (i.e. a point and the following point) builds a line. - explicit MultiLineItem(const std::vector& points, DrawStyle drawStyle, const ColorRGB& rgb = ColorRGB{1.0F, 1.0F, 1.0F}); + /// add a line defined by a list of points whereat always a pair (i.e. a point and the following + /// point) builds a line. + explicit MultiLineItem(const std::vector& points, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); void write(InventorOutput& out) const override; private: @@ -300,10 +337,12 @@ private: ColorRGB rgb; }; -class BaseExport ArrowItem : public NodeItem +class BaseExport ArrowItem: public NodeItem { public: - explicit ArrowItem(const Base::Line3f& line, DrawStyle drawStyle, const ColorRGB& rgb = ColorRGB{1.0F, 1.0F, 1.0F}); + explicit ArrowItem(const Base::Line3f& line, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); void write(InventorOutput& out) const override; private: @@ -312,10 +351,13 @@ private: ColorRGB rgb; }; -class BaseExport BoundingBoxItem : public NodeItem +class BaseExport BoundingBoxItem: public NodeItem { public: - explicit BoundingBoxItem(const Vector3f& pt1, const Vector3f& pt2, DrawStyle drawStyle, const ColorRGB& rgb = ColorRGB{1.0F, 1.0F, 1.0F}); + explicit BoundingBoxItem(const Vector3f& pt1, + const Vector3f& pt2, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); void write(InventorOutput& out) const override; private: @@ -328,7 +370,7 @@ private: /*! * \brief The MaterialItem class supports the SoMaterial node. */ -class BaseExport MaterialItem : public NodeItem +class BaseExport MaterialItem: public NodeItem { public: void setAmbientColor(const std::vector& rgb); @@ -361,7 +403,7 @@ private: /*! * \brief The MaterialBindingItem class supports the SoMaterialBinding node. */ -class BaseExport MaterialBindingItem : public NodeItem +class BaseExport MaterialBindingItem: public NodeItem { public: MaterialBindingItem() = default; @@ -376,7 +418,7 @@ private: /*! * \brief The DrawStyleItem class supports the SoDrawStyle node. */ -class BaseExport DrawStyleItem : public NodeItem +class BaseExport DrawStyleItem: public NodeItem { public: DrawStyleItem() = default; @@ -391,7 +433,7 @@ private: /*! * \brief The ShapeHintsItem class supports the SoShapeHints node. */ -class BaseExport ShapeHintsItem : public NodeItem +class BaseExport ShapeHintsItem: public NodeItem { public: explicit ShapeHintsItem(float creaseAngle = 0.0F); @@ -408,7 +450,7 @@ private: /*! * \brief The PolygonOffsetItem class supports the SoPolygonOffset node. */ -class BaseExport PolygonOffsetItem : public NodeItem +class BaseExport PolygonOffsetItem: public NodeItem { public: void setValue(PolygonOffset value); @@ -421,7 +463,7 @@ private: /*! * \brief The Coordinate3Item class supports the SoCoordinate3 node. */ -class BaseExport Coordinate3Item : public NodeItem +class BaseExport Coordinate3Item: public NodeItem { public: Coordinate3Item(const std::vector& points); @@ -436,7 +478,7 @@ private: /*! * \brief The PointSetItem class supports the SoPointSet node. */ -class BaseExport PointSetItem : public NodeItem +class BaseExport PointSetItem: public NodeItem { public: void write(InventorOutput& out) const override; @@ -445,7 +487,7 @@ public: /*! * \brief The LineSetItem class supports the SoLineSet node. */ -class BaseExport LineSetItem : public NodeItem +class BaseExport LineSetItem: public NodeItem { public: void write(InventorOutput& out) const override; @@ -454,7 +496,7 @@ public: /*! * \brief The FaceSetItem class supports the SoFaceSet node. */ -class BaseExport FaceSetItem : public NodeItem +class BaseExport FaceSetItem: public NodeItem { public: FaceSetItem(const std::vector&); @@ -467,7 +509,7 @@ private: /*! * \brief The IndexedLineSetItem class supports the SoIndexedLineSet node. */ -class BaseExport IndexedLineSetItem : public NodeItem +class BaseExport IndexedLineSetItem: public NodeItem { public: IndexedLineSetItem(const std::vector&); @@ -480,7 +522,7 @@ private: /*! * \brief The IndexedFaceSetItem class supports the SoIndexedFaceSet node. */ -class BaseExport IndexedFaceSetItem : public NodeItem +class BaseExport IndexedFaceSetItem: public NodeItem { public: IndexedFaceSetItem(const std::vector&); @@ -493,7 +535,7 @@ private: /*! * \brief The NormalItem class supports the SoNormal node. */ -class BaseExport NormalItem : public NodeItem +class BaseExport NormalItem: public NodeItem { public: explicit NormalItem(const std::vector& vec); @@ -508,7 +550,7 @@ private: /*! * \brief The MaterialBindingItem class supports the SoMaterialBinding node. */ -class BaseExport NormalBindingItem : public NodeItem +class BaseExport NormalBindingItem: public NodeItem { public: NormalBindingItem() = default; @@ -522,7 +564,7 @@ private: /*! * \brief The CylinderItem class supports the SoCylinder node. */ -class BaseExport CylinderItem : public NodeItem +class BaseExport CylinderItem: public NodeItem { public: void setRadius(float); @@ -537,7 +579,7 @@ private: /*! * \brief The ConeItem class supports the SoCone node. */ -class BaseExport ConeItem : public NodeItem +class BaseExport ConeItem: public NodeItem { public: void setBottomRadius(float); @@ -552,7 +594,7 @@ private: /*! * \brief The SphereItem class supports the SoSphere node. */ -class BaseExport SphereItem : public NodeItem +class BaseExport SphereItem: public NodeItem { public: void setRadius(float); @@ -565,7 +607,7 @@ private: /*! * \brief The NurbsSurfaceItem class supports the SoNurbsSurface node. */ -class BaseExport NurbsSurfaceItem : public NodeItem +class BaseExport NurbsSurfaceItem: public NodeItem { public: void setControlPoints(int numU, int numV); @@ -582,7 +624,7 @@ private: /*! * \brief The Text2Item class supports the SoText2 node. */ -class BaseExport Text2Item : public NodeItem +class BaseExport Text2Item: public NodeItem { public: Text2Item(const std::string&); @@ -595,7 +637,7 @@ private: /*! * \brief The TransformItem class supports the SoTransform node. */ -class BaseExport TransformItem : public NodeItem +class BaseExport TransformItem: public NodeItem { public: explicit TransformItem(const Base::Placement&); @@ -649,8 +691,10 @@ private: void decreaseIndent(); public: - InventorBuilder (const InventorBuilder&) = delete; - void operator = (const InventorBuilder&) = delete; + InventorBuilder(const InventorBuilder&) = delete; + InventorBuilder(InventorBuilder&&) = delete; + void operator=(const InventorBuilder&) = delete; + void operator=(InventorBuilder&&) = delete; private: std::ostream& result; @@ -713,6 +757,11 @@ public: */ void endSeparator(); + Builder3D(const Builder3D&) = delete; + Builder3D(Builder3D&&) = delete; + Builder3D& operator=(const Builder3D&) = delete; + Builder3D& operator=(Builder3D&&) = delete; + private: /// the result string std::stringstream result; @@ -723,16 +772,22 @@ private: * Loads an OpenInventor file. * @author Werner Mayer */ -class BaseExport InventorLoader { +class BaseExport InventorLoader +{ public: - struct Face { + struct Face + { Face(int32_t p1, int32_t p2, int32_t p3) - : p1(p1), p2(p2), p3(p3) {} + : p1(p1) + , p2(p2) + , p3(p3) + {} int32_t p1, p2, p3; }; - explicit InventorLoader(std::istream &inp) : inp(inp) { - } + explicit InventorLoader(std::istream& inp) + : inp(inp) + {} /// Start the read process. Returns true if successful and false otherwise. /// The obtained data can be accessed with the appropriate getter functions. @@ -743,22 +798,26 @@ public: /// Returns true if the data come from a non-indexed node as SoFaceSet. /// This means that the read points contain duplicates. - bool isNonIndexed() const { + bool isNonIndexed() const + { return isnonindexed; } /// Return the vectors of an SoNormal node - const std::vector& getVector() const { + const std::vector& getVector() const + { return vector; } /// Return the points of an SoCoordinate3 node - const std::vector& getPoints() const { + const std::vector& getPoints() const + { return points; } /// Return the faces of an SoIndexedFaceSet node - const std::vector& getFaces() const { + const std::vector& getFaces() const + { return faces; } @@ -779,7 +838,7 @@ private: std::vector vector; std::vector points; std::vector faces; - std::istream &inp; + std::istream& inp; }; /*! @@ -789,6 +848,6 @@ private: */ BaseExport Base::Vector3f to_vector(std::string); -} //namespace Base +} // namespace Base -#endif // BASE_BUILDER3D_H +#endif // BASE_BUILDER3D_H diff --git a/src/Base/Console.cpp b/src/Base/Console.cpp index 94f841eaf8..c161c25244 100644 --- a/src/Base/Console.cpp +++ b/src/Base/Console.cpp @@ -24,13 +24,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# if defined(FC_OS_WIN32) -# include -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) -# include -# endif -# include -# include +#if defined(FC_OS_WIN32) +#include +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) +#include +#endif +#include +#include #endif #include "Console.h" @@ -44,9 +44,11 @@ using namespace Base; //========================================================================= -namespace Base { +namespace Base +{ -class ConsoleEvent : public QEvent { +class ConsoleEvent: public QEvent +{ public: ConsoleSingleton::FreeCAD_ConsoleMsgType msgtype; IntendedRecipient recipient; @@ -54,48 +56,83 @@ public: std::string notifier; std::string msg; - ConsoleEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, IntendedRecipient recipient, - ContentType content, const std::string& notifier, const std::string& msg) - : QEvent(QEvent::User), msgtype(type), recipient(recipient), content(content), notifier(notifier), msg(msg) - { - } + ConsoleEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, + IntendedRecipient recipient, + ContentType content, + const std::string& notifier, + const std::string& msg) + : QEvent(QEvent::User) + , msgtype(type) + , recipient(recipient) + , content(content) + , notifier(notifier) + , msg(msg) + {} ~ConsoleEvent() override = default; }; -class ConsoleOutput : public QObject // clazy:exclude=missing-qobject-macro +class ConsoleOutput: public QObject // clazy:exclude=missing-qobject-macro { public: - static ConsoleOutput* getInstance() { - if (!instance) + static ConsoleOutput* getInstance() + { + if (!instance) { instance = new ConsoleOutput; + } return instance; } - static void destruct() { + static void destruct() + { delete instance; instance = nullptr; } - void customEvent(QEvent* ev) override { + void customEvent(QEvent* ev) override + { if (ev->type() == QEvent::User) { ConsoleEvent* ce = static_cast(ev); switch (ce->msgtype) { case ConsoleSingleton::MsgType_Txt: - Console().notifyPrivate(LogStyle::Message, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Message, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; case ConsoleSingleton::MsgType_Log: - Console().notifyPrivate(LogStyle::Log, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Log, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; case ConsoleSingleton::MsgType_Wrn: - Console().notifyPrivate(LogStyle::Warning, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Warning, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; case ConsoleSingleton::MsgType_Err: - Console().notifyPrivate(LogStyle::Error, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Error, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; case ConsoleSingleton::MsgType_Critical: - Console().notifyPrivate(LogStyle::Critical, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Critical, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; case ConsoleSingleton::MsgType_Notification: - Console().notifyPrivate(LogStyle::Notification, ce->recipient, ce->content, ce->notifier, ce->msg); + Console().notifyPrivate(LogStyle::Notification, + ce->recipient, + ce->content, + ce->notifier, + ce->msg); break; } } @@ -110,7 +147,7 @@ private: ConsoleOutput* ConsoleOutput::instance = nullptr; -} +} // namespace Base //************************************************************************** // Construction destruction @@ -118,18 +155,18 @@ ConsoleOutput* ConsoleOutput::instance = nullptr; ConsoleSingleton::ConsoleSingleton() #ifdef FC_DEBUG - : _defaultLogLevel(FC_LOGLEVEL_LOG) + : _defaultLogLevel(FC_LOGLEVEL_LOG) #else - : _defaultLogLevel(FC_LOGLEVEL_MSG) + : _defaultLogLevel(FC_LOGLEVEL_MSG) #endif -{ -} +{} ConsoleSingleton::~ConsoleSingleton() { ConsoleOutput::destruct(); - for (ILogger* Iter : _aclObservers) + for (ILogger* Iter : _aclObservers) { delete Iter; + } } @@ -141,8 +178,9 @@ ConsoleSingleton::~ConsoleSingleton() */ void ConsoleSingleton::SetConsoleMode(ConsoleMode m) { - if (m & Verbose) + if (m & Verbose) { _bVerbose = true; + } } /** @@ -150,18 +188,21 @@ void ConsoleSingleton::SetConsoleMode(ConsoleMode m) */ void ConsoleSingleton::UnsetConsoleMode(ConsoleMode m) { - if (m & Verbose) + if (m & Verbose) { _bVerbose = false; + } } /** * \a type can be OR'ed with any of the FreeCAD_ConsoleMsgType flags to enable -- if \a b is true -- * or to disable -- if \a b is false -- a console observer with name \a sObs. - * The return value is an OR'ed value of all message types that have changed their state. For example + * The return value is an OR'ed value of all message types that have changed their state. For + * example * @code * // switch off warnings and error messages * ConsoleMsgFlags ret = Base::Console().SetEnabledMsgType("myObs", - * Base:ConsoleSingleton::MsgType_Wrn|Base::ConsoleSingleton::MsgType_Err, false); + * Base:ConsoleSingleton::MsgType_Wrn|Base::ConsoleSingleton::MsgType_Err, + * false); * // do something without notifying observer myObs * ... * // restore the former configuration again @@ -173,37 +214,43 @@ void ConsoleSingleton::UnsetConsoleMode(ConsoleMode m) ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool b) { ILogger* pObs = Get(sObs); - if ( pObs ){ - ConsoleMsgFlags flags=0; + if (pObs) { + ConsoleMsgFlags flags = 0; - if ( type&MsgType_Err ){ - if ( pObs->bErr != b ) + if (type & MsgType_Err) { + if (pObs->bErr != b) { flags |= MsgType_Err; + } pObs->bErr = b; } - if ( type&MsgType_Wrn ){ - if ( pObs->bWrn != b ) + if (type & MsgType_Wrn) { + if (pObs->bWrn != b) { flags |= MsgType_Wrn; + } pObs->bWrn = b; } - if ( type&MsgType_Txt ){ - if ( pObs->bMsg != b ) + if (type & MsgType_Txt) { + if (pObs->bMsg != b) { flags |= MsgType_Txt; + } pObs->bMsg = b; } - if ( type&MsgType_Log ){ - if ( pObs->bLog != b ) + if (type & MsgType_Log) { + if (pObs->bLog != b) { flags |= MsgType_Log; + } pObs->bLog = b; } - if ( type&MsgType_Critical ){ - if ( pObs->bCritical != b ) + if (type & MsgType_Critical) { + if (pObs->bCritical != b) { flags |= MsgType_Critical; + } pObs->bCritical = b; } - if ( type&MsgType_Notification ){ - if ( pObs->bNotification != b ) + if (type & MsgType_Notification) { + if (pObs->bNotification != b) { flags |= MsgType_Notification; + } pObs->bNotification = b; } @@ -219,20 +266,20 @@ bool ConsoleSingleton::IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType ILogger* pObs = Get(sObs); if (pObs) { switch (type) { - case MsgType_Txt: - return pObs->bMsg; - case MsgType_Log: - return pObs->bLog; - case MsgType_Wrn: - return pObs->bWrn; - case MsgType_Err: - return pObs->bErr; - case MsgType_Critical: - return pObs->bCritical; - case MsgType_Notification: - return pObs->bNotification; - default: - return false; + case MsgType_Txt: + return pObs->bMsg; + case MsgType_Log: + return pObs->bLog; + case MsgType_Wrn: + return pObs->bWrn; + case MsgType_Err: + return pObs->bErr; + case MsgType_Critical: + return pObs->bCritical; + case MsgType_Notification: + return pObs->bNotification; + default: + return false; } } @@ -258,10 +305,10 @@ void ConsoleSingleton::SetConnectionMode(ConnectionMode mode) * be forwarded to it. * @see ILogger */ -void ConsoleSingleton::AttachObserver(ILogger *pcObserver) +void ConsoleSingleton::AttachObserver(ILogger* pcObserver) { // double insert !! - assert(_aclObservers.find(pcObserver) == _aclObservers.end() ); + assert(_aclObservers.find(pcObserver) == _aclObservers.end()); _aclObservers.insert(pcObserver); } @@ -271,76 +318,95 @@ void ConsoleSingleton::AttachObserver(ILogger *pcObserver) * After detaching you can destruct the Observer or reinsert it later. * @see ILogger */ -void ConsoleSingleton::DetachObserver(ILogger *pcObserver) +void ConsoleSingleton::DetachObserver(ILogger* pcObserver) { _aclObservers.erase(pcObserver); } -void Base::ConsoleSingleton::notifyPrivate(LogStyle category, IntendedRecipient recipient, - ContentType content, const std::string& notifiername, const std::string& msg) +void Base::ConsoleSingleton::notifyPrivate(LogStyle category, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg) { for (ILogger* Iter : _aclObservers) { if (Iter->isActive(category)) { - Iter->SendLog(notifiername, msg, category, recipient, content); // send string to the listener + Iter->SendLog(notifiername, + msg, + category, + recipient, + content); // send string to the listener } } } -void ConsoleSingleton::postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, IntendedRecipient recipient, - ContentType content, const std::string& notifiername, const std::string& msg) +void ConsoleSingleton::postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg) { - QCoreApplication::postEvent(ConsoleOutput::getInstance(), new ConsoleEvent(type, recipient, content, notifiername, msg)); + QCoreApplication::postEvent(ConsoleOutput::getInstance(), + new ConsoleEvent(type, recipient, content, notifiername, msg)); } -ILogger *ConsoleSingleton::Get(const char *Name) const +ILogger* ConsoleSingleton::Get(const char* Name) const { - const char* OName{}; + const char* OName {}; for (ILogger* Iter : _aclObservers) { - OName = Iter->Name(); // get the name - if (OName && strcmp(OName,Name) == 0) + OName = Iter->Name(); // get the name + if (OName && strcmp(OName, Name) == 0) { return Iter; + } } return nullptr; } -int *ConsoleSingleton::GetLogLevel(const char *tag, bool create) { - if (!tag) tag = ""; - if (_logLevels.find(tag) != _logLevels.end()) +int* ConsoleSingleton::GetLogLevel(const char* tag, bool create) +{ + if (!tag) { + tag = ""; + } + if (_logLevels.find(tag) != _logLevels.end()) { return &_logLevels[tag]; - if (!create) + } + if (!create) { return nullptr; - int &ret = _logLevels[tag]; + } + int& ret = _logLevels[tag]; ret = -1; return &ret; } -void ConsoleSingleton::Refresh() { - if (_bCanRefresh) +void ConsoleSingleton::Refresh() +{ + if (_bCanRefresh) { qApp->processEvents(QEventLoop::ExcludeUserInputEvents); + } } -void ConsoleSingleton::EnableRefresh(bool enable) { +void ConsoleSingleton::EnableRefresh(bool enable) +{ _bCanRefresh = enable; } //************************************************************************** // Singleton stuff -ConsoleSingleton * ConsoleSingleton::_pcSingleton = nullptr; +ConsoleSingleton* ConsoleSingleton::_pcSingleton = nullptr; void ConsoleSingleton::Destruct() { // not initialized or double destructed! assert(_pcSingleton); delete _pcSingleton; - _pcSingleton=nullptr; + _pcSingleton = nullptr; } -ConsoleSingleton & ConsoleSingleton::Instance() +ConsoleSingleton& ConsoleSingleton::Instance() { // not initialized? - if (!_pcSingleton) - { + if (!_pcSingleton) { _pcSingleton = new ConsoleSingleton(); } return *_pcSingleton; @@ -351,85 +417,118 @@ ConsoleSingleton & ConsoleSingleton::Instance() // ConsoleSingleton Methods structure PyMethodDef ConsoleSingleton::Methods[] = { - {"PrintMessage", ConsoleSingleton::sPyMessage, METH_VARARGS, + {"PrintMessage", + ConsoleSingleton::sPyMessage, + METH_VARARGS, "PrintMessage(obj) -> None\n\n" "Print a message to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintLog", ConsoleSingleton::sPyLog, METH_VARARGS, + {"PrintLog", + ConsoleSingleton::sPyLog, + METH_VARARGS, "PrintLog(obj) -> None\n\n" "Print a log message to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintError", ConsoleSingleton::sPyError, METH_VARARGS, + {"PrintError", + ConsoleSingleton::sPyError, + METH_VARARGS, "PrintError(obj) -> None\n\n" "Print an error message to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintDeveloperError", ConsoleSingleton::sPyDeveloperError, METH_VARARGS, + {"PrintDeveloperError", + ConsoleSingleton::sPyDeveloperError, + METH_VARARGS, "PrintDeveloperError(obj) -> None\n\n" "Print an error message intended only for Developers to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintUserError", ConsoleSingleton::sPyUserError, METH_VARARGS, + {"PrintUserError", + ConsoleSingleton::sPyUserError, + METH_VARARGS, "PrintUserError(obj) -> None\n\n" "Print an error message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintTranslatedUserError", ConsoleSingleton::sPyTranslatedUserError, METH_VARARGS, + {"PrintTranslatedUserError", + ConsoleSingleton::sPyTranslatedUserError, + METH_VARARGS, "PrintTranslatedUserError(obj) -> None\n\n" "Print an already translated error message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintWarning", ConsoleSingleton::sPyWarning, METH_VARARGS, + {"PrintWarning", + ConsoleSingleton::sPyWarning, + METH_VARARGS, "PrintWarning(obj) -> None\n\n" "Print a warning message to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintDeveloperWarning", ConsoleSingleton::sPyDeveloperWarning, METH_VARARGS, + {"PrintDeveloperWarning", + ConsoleSingleton::sPyDeveloperWarning, + METH_VARARGS, "PrintDeveloperWarning(obj) -> None\n\n" "Print an warning message intended only for Developers to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintUserWarning", ConsoleSingleton::sPyUserWarning, METH_VARARGS, + {"PrintUserWarning", + ConsoleSingleton::sPyUserWarning, + METH_VARARGS, "PrintUserWarning(obj) -> None\n\n" "Print a warning message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintTranslatedUserWarning", ConsoleSingleton::sPyTranslatedUserWarning, METH_VARARGS, + {"PrintTranslatedUserWarning", + ConsoleSingleton::sPyTranslatedUserWarning, + METH_VARARGS, "PrintTranslatedUserWarning(obj) -> None\n\n" "Print an already translated warning message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintCritical",ConsoleSingleton::sPyCritical, METH_VARARGS, + {"PrintCritical", + ConsoleSingleton::sPyCritical, + METH_VARARGS, "PrintCritical(obj) -> None\n\n" "Print a critical message to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintNotification", ConsoleSingleton::sPyNotification, METH_VARARGS, + {"PrintNotification", + ConsoleSingleton::sPyNotification, + METH_VARARGS, "PrintNotification(obj) -> None\n\n" "Print a user notification to the output.\n\n" "obj : object\n The string representation is printed."}, - {"PrintTranslatedNotification", ConsoleSingleton::sPyTranslatedNotification, METH_VARARGS, + {"PrintTranslatedNotification", + ConsoleSingleton::sPyTranslatedNotification, + METH_VARARGS, "PrintTranslatedNotification(obj) -> None\n\n" "Print an already translated notification to the output.\n\n" "obj : object\n The string representation is printed."}, - {"SetStatus", ConsoleSingleton::sPySetStatus, METH_VARARGS, + {"SetStatus", + ConsoleSingleton::sPySetStatus, + METH_VARARGS, "SetStatus(observer, type, status) -> None\n\n" "Set the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n\n" "observer : str\n Logging interface name.\n" "type : str\n Message type.\n" "status : bool"}, - {"GetStatus", ConsoleSingleton::sPyGetStatus, METH_VARARGS, + {"GetStatus", + ConsoleSingleton::sPyGetStatus, + METH_VARARGS, "GetStatus(observer, type) -> bool or None\n\n" "Get the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n" "Returns None if the specified observer doesn't exist.\n\n" "observer : str\n Logging interface name.\n" "type : str\n Message type."}, - {"GetObservers", ConsoleSingleton::sPyGetObservers, METH_VARARGS, + {"GetObservers", + ConsoleSingleton::sPyGetObservers, + METH_VARARGS, "GetObservers() -> list of str\n\n" "Get the names of the current logging interfaces."}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; -namespace { -PyObject* FC_PYCONSOLE_MSG(std::function func, PyObject* args) +namespace { - PyObject *output{}; - PyObject *notifier{}; +PyObject* FC_PYCONSOLE_MSG(std::function func, PyObject* args) +{ + PyObject* output {}; + PyObject* notifier {}; const char* notifierStr = ""; - auto retrieveString = [] (PyObject* pystr) { + auto retrieveString = [](PyObject* pystr) { PyObject* unicode = nullptr; const char* outstr = nullptr; @@ -439,8 +538,9 @@ PyObject* FC_PYCONSOLE_MSG(std::function func, } else { unicode = PyObject_Str(pystr); - if (unicode) + if (unicode) { outstr = PyUnicode_AsUTF8(unicode); + } } Py_XDECREF(unicode); @@ -454,221 +554,285 @@ PyObject* FC_PYCONSOLE_MSG(std::function func, if (!PyArg_ParseTuple(args, "O", &output)) { return nullptr; } - } - else { // retrieve notifier - PY_TRY { + else { // retrieve notifier + PY_TRY + { notifierStr = retrieveString(notifier); } PY_CATCH } - PY_TRY { + PY_TRY + { const char* string = retrieveString(output); - if (string) - func(notifierStr, string); /*process message*/ - + if (string) { + func(notifierStr, string); /*process message*/ + } } PY_CATCH Py_Return; } +} // namespace + +PyObject* ConsoleSingleton::sPyMessage(PyObject* /*self*/, PyObject* args) +{ + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyMessage(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyWarning(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance().Warning(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyWarning(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyDeveloperWarning(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Warning(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyDeveloperWarning(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyUserWarning(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyUserWarning(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyTranslatedUserWarning(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyTranslatedUserWarning(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyError(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyError(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyDeveloperError(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyDeveloperError(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyUserError(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyUserError(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyTranslatedUserError(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyTranslatedUserError(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyLog(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyLog(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyCritical(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyCritical(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyNotification(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyNotification(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyTranslatedNotification(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); + return FC_PYCONSOLE_MSG( + [](const std::string& notifier, const char* msg) { + Instance() + .Send(notifier, "%s", msg); + }, + args); } -PyObject *ConsoleSingleton::sPyTranslatedNotification(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyGetStatus(PyObject* /*self*/, PyObject* args) { - return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) { - Instance().Send(notifier, "%s", msg); - }, args); -} - -PyObject *ConsoleSingleton::sPyGetStatus(PyObject * /*self*/, PyObject *args) -{ - char *pstr1{}; - char *pstr2{}; - if (!PyArg_ParseTuple(args, "ss", &pstr1, &pstr2)) + char* pstr1 {}; + char* pstr2 {}; + if (!PyArg_ParseTuple(args, "ss", &pstr1, &pstr2)) { return nullptr; + } - PY_TRY{ - bool b=false; - ILogger *pObs = Instance().Get(pstr1); - if (!pObs) + PY_TRY + { + bool b = false; + ILogger* pObs = Instance().Get(pstr1); + if (!pObs) { Py_Return; + } - if (strcmp(pstr2,"Log") == 0) + if (strcmp(pstr2, "Log") == 0) { b = pObs->bLog; - else if (strcmp(pstr2,"Wrn") == 0) + } + else if (strcmp(pstr2, "Wrn") == 0) { b = pObs->bWrn; - else if (strcmp(pstr2,"Msg") == 0) + } + else if (strcmp(pstr2, "Msg") == 0) { b = pObs->bMsg; - else if (strcmp(pstr2,"Err") == 0) + } + else if (strcmp(pstr2, "Err") == 0) { b = pObs->bErr; - else if (strcmp(pstr2,"Critical") == 0) + } + else if (strcmp(pstr2, "Critical") == 0) { b = pObs->bCritical; - else if (strcmp(pstr2,"Notification") == 0) + } + else if (strcmp(pstr2, "Notification") == 0) { b = pObs->bNotification; - else - Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or 'Notification')"); + } + else { + Py_Error(Base::PyExc_FC_GeneralError, + "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " + "'Notification')"); + } return PyBool_FromLong(b ? 1 : 0); } PY_CATCH; } -PyObject *ConsoleSingleton::sPySetStatus(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPySetStatus(PyObject* /*self*/, PyObject* args) { - char *pstr1{}; - char *pstr2{}; - PyObject* pyStatus{}; - if (!PyArg_ParseTuple(args, "ssO!", &pstr1, &pstr2, &PyBool_Type, &pyStatus)) + char* pstr1 {}; + char* pstr2 {}; + PyObject* pyStatus {}; + if (!PyArg_ParseTuple(args, "ssO!", &pstr1, &pstr2, &PyBool_Type, &pyStatus)) { return nullptr; + } - PY_TRY{ + PY_TRY + { bool status = asBoolean(pyStatus); - ILogger *pObs = Instance().Get(pstr1); + ILogger* pObs = Instance().Get(pstr1); if (pObs) { - if (strcmp(pstr2,"Log") == 0) + if (strcmp(pstr2, "Log") == 0) { pObs->bLog = status; - else if (strcmp(pstr2,"Wrn") == 0) + } + else if (strcmp(pstr2, "Wrn") == 0) { pObs->bWrn = status; - else if (strcmp(pstr2,"Msg") == 0) + } + else if (strcmp(pstr2, "Msg") == 0) { pObs->bMsg = status; - else if (strcmp(pstr2,"Err") == 0) + } + else if (strcmp(pstr2, "Err") == 0) { pObs->bErr = status; - else if (strcmp(pstr2,"Critical") == 0) + } + else if (strcmp(pstr2, "Critical") == 0) { pObs->bCritical = status; - else if (strcmp(pstr2,"Notification") == 0) + } + else if (strcmp(pstr2, "Notification") == 0) { pObs->bNotification = status; - else - Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or 'Notification')"); + } + else { + Py_Error(Base::PyExc_FC_GeneralError, + "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " + "'Notification')"); + } Py_Return; } else { - Py_Error(Base::PyExc_FC_GeneralError,"Unknown logger type"); + Py_Error(Base::PyExc_FC_GeneralError, "Unknown logger type"); } - } PY_CATCH; } -PyObject *ConsoleSingleton::sPyGetObservers(PyObject * /*self*/, PyObject *args) +PyObject* ConsoleSingleton::sPyGetObservers(PyObject* /*self*/, PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { Py::List list; - for (auto i : Instance()._aclObservers) + for (auto i : Instance()._aclObservers) { list.append(Py::String(i->Name() ? i->Name() : "")); + } return Py::new_reference_to(list); } diff --git a/src/Base/Console.h b/src/Base/Console.h index fcda8f5a2d..45fb9c9443 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -39,10 +39,10 @@ using PyObject = struct _object; using PyMethodDef = struct PyMethodDef; -//FIXME: Even with parameter packs this is necessary for MSYS2 +// FIXME: Even with parameter packs this is necessary for MSYS2 #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif //************************************************************************** @@ -50,11 +50,11 @@ using PyMethodDef = struct PyMethodDef; #ifdef FC_DEBUG /// switch on the logging of python object creation and destruction -# undef FC_LOGPYOBJECTS +#undef FC_LOGPYOBJECTS /// switch on the logging of Feature update and execution -# define FC_LOGFEATUREUPDATE +#define FC_LOGFEATUREUPDATE /// switch on the logging of the Update execution through Doc, App, GuiApp and GuiDoc -# undef FC_LOGUPDATECHAIN +#undef FC_LOGUPDATECHAIN #endif ///////////////////////////////////////////////////////////////////////////////////// @@ -348,129 +348,163 @@ using PyMethodDef = struct PyMethodDef; #define FC_LOGLEVEL_LOG 3 #define FC_LOGLEVEL_TRACE 4 -#define _FC_LOG_LEVEL_INIT(_name,_tag,...) \ - static Base::LogLevel _name(_tag,## __VA_ARGS__); +#define _FC_LOG_LEVEL_INIT(_name, _tag, ...) static Base::LogLevel _name(_tag, ##__VA_ARGS__); #ifndef FC_LOG_INSTANCE -# define FC_LOG_INSTANCE _s_fclvl +#define FC_LOG_INSTANCE _s_fclvl #endif -#define FC_LOG_LEVEL_INIT(_tag,...) \ - _FC_LOG_LEVEL_INIT(FC_LOG_INSTANCE, _tag, ## __VA_ARGS__) +#define FC_LOG_LEVEL_INIT(_tag, ...) _FC_LOG_LEVEL_INIT(FC_LOG_INSTANCE, _tag, ##__VA_ARGS__) -#define __FC_PRINT(_instance,_l,_func,_notifier,_msg,_file,_line) do{\ - if(_instance.isEnabled(_l)) {\ - std::stringstream _str;\ - _instance.prefix(_str,_file,_line) << _msg;\ - if(_instance.add_eol) \ - _str< +#define FC_TIME_CLOCK high_resolution_clock +#define FC_TIME_POINT std::chrono::FC_TIME_CLOCK::time_point +#define FC_DURATION std::chrono::duration -# define _FC_TIME_INIT(_t) _t=std::chrono::FC_TIME_CLOCK::now() -# define FC_TIME_INIT(_t) FC_TIME_POINT _FC_TIME_INIT(_t) -# define FC_TIME_INIT2(_t1,_t2) FC_TIME_INIT(_t1),_t2=_t1 -# define FC_TIME_INIT3(_t1,_t2,_t3) FC_TIME_INIT(_t1),_t2=_t1,_t3=_t1 +#define _FC_TIME_INIT(_t) _t = std::chrono::FC_TIME_CLOCK::now() +#define FC_TIME_INIT(_t) FC_TIME_POINT _FC_TIME_INIT(_t) +#define FC_TIME_INIT2(_t1, _t2) FC_TIME_INIT(_t1), _t2 = _t1 +#define FC_TIME_INIT3(_t1, _t2, _t3) FC_TIME_INIT(_t1), _t2 = _t1, _t3 = _t1 -# define _FC_DURATION_PRINT(_l,_d,_msg) \ - FC_##_l(_msg<< " time: " << _d.count()<<'s'); +#define _FC_DURATION_PRINT(_l, _d, _msg) FC_##_l(_msg << " time: " << _d.count() << 's'); -# define FC_DURATION_MSG(_d,_msg) _FC_DURATION_PRINT(MSG,_d,_msg) -# define FC_DURATION_LOG(_d,_msg) _FC_DURATION_PRINT(LOG,_d,_msg) -# define FC_DURATION_TRACE(_d,_msg) _FC_DURATION_PRINT(TRACE,_d,_msg) +#define FC_DURATION_MSG(_d, _msg) _FC_DURATION_PRINT(MSG, _d, _msg) +#define FC_DURATION_LOG(_d, _msg) _FC_DURATION_PRINT(LOG, _d, _msg) +#define FC_DURATION_TRACE(_d, _msg) _FC_DURATION_PRINT(TRACE, _d, _msg) -# define _FC_TIME_PRINT(_l,_t,_msg) \ - _FC_DURATION_PRINT(_l,Base::GetDuration(_t),_msg); +#define _FC_TIME_PRINT(_l, _t, _msg) _FC_DURATION_PRINT(_l, Base::GetDuration(_t), _msg); -# define FC_TIME_MSG(_t,_msg) _FC_TIME_PRINT(MSG,_t,_msg) -# define FC_TIME_LOG(_t,_msg) _FC_TIME_PRINT(LOG,_t,_msg) -# define FC_TIME_TRACE(_t,_msg) _FC_TIME_PRINT(TRACE,_t,_msg) +#define FC_TIME_MSG(_t, _msg) _FC_TIME_PRINT(MSG, _t, _msg) +#define FC_TIME_LOG(_t, _msg) _FC_TIME_PRINT(LOG, _t, _msg) +#define FC_TIME_TRACE(_t, _msg) _FC_TIME_PRINT(TRACE, _t, _msg) -# define FC_DURATION_DECLARE(_d) FC_DURATION _d -# define FC_DURATION_DECLARE2(_d,_d1) FC_DURATION_DECLARE(_d),_d1 -# define FC_DURATION_DECLARE3(_d,_d1) FC_DURATION_DECLARE2(_d,_d1),_d2 +#define FC_DURATION_DECLARE(_d) FC_DURATION _d +#define FC_DURATION_DECLARE2(_d, _d1) FC_DURATION_DECLARE(_d), _d1 +#define FC_DURATION_DECLARE3(_d, _d1) FC_DURATION_DECLARE2(_d, _d1), _d2 -# define FC_DURATION_INIT(_d) _d=FC_DURATION(0) -# define FC_DURATION_INIT2(_d,_d1) _d=_d1=FC_DURATION(0) -# define FC_DURATION_INIT3(_d,_d1,_d2) _d=_d1=_d2=FC_DURATION(0) +#define FC_DURATION_INIT(_d) _d = FC_DURATION(0) +#define FC_DURATION_INIT2(_d, _d1) _d = _d1 = FC_DURATION(0) +#define FC_DURATION_INIT3(_d, _d1, _d2) _d = _d1 = _d2 = FC_DURATION(0) -# define FC_DURATION_DECL_INIT(_d) FC_DURATION _d(0) -# define FC_DURATION_DECL_INIT2(_d,_d1) FC_DURATION_DECL_INIT(_d),_d1(0) -# define FC_DURATION_DECL_INIT3(_d,_d1) FC_DURATION_DECL_INIT2(_d,_d1),_d3(0) +#define FC_DURATION_DECL_INIT(_d) FC_DURATION _d(0) +#define FC_DURATION_DECL_INIT2(_d, _d1) FC_DURATION_DECL_INIT(_d), _d1(0) +#define FC_DURATION_DECL_INIT3(_d, _d1) FC_DURATION_DECL_INIT2(_d, _d1), _d3(0) -# define FC_DURATION_PLUS(_d,_t) _d += Base::GetDuration(_t) +#define FC_DURATION_PLUS(_d, _t) _d += Base::GetDuration(_t) -#else //FC_LOG_NO_TIMING -# define FC_TIME_POINT -# define _FC_TIME_INIT(...) do{}while(0) -# define FC_TIME_INIT(...) do{}while(0) -# define FC_TIME_INIT2(...) do{}while(0) -# define FC_TIME_INIT3(...) do{}while(0) -# define _FC_DURATION_PRINT(...) do{}while(0) -# define _FC_TIME(_t) do{}while(0) -# define FC_DURATION_PRINT(...) do{}while(0) -# define FC_DURATION -# define FC_DURATION_INIT(...) do{}while(0) -# define FC_DURATION_INIT1(...) do{}while(0) -# define FC_DURATION_INIT2(...) do{}while(0) -# define FC_DURATION_DECLARE(...) -# define FC_DURATION_DECLARE1(...) -# define FC_DURATION_DECLARE2(...) -# define FC_DURATION_DECL_INIT(...) do{}while(0) -# define FC_DURATION_DECL_INIT2(...) do{}while(0) -# define FC_DURATION_DECL_INIT3(...) do{}while(0) -# define FC_DURATION_PLUS(...) do{}while(0) +#else // FC_LOG_NO_TIMING +#define FC_TIME_POINT +#define _FC_TIME_INIT(...) \ + do { \ + } while (0) +#define FC_TIME_INIT(...) \ + do { \ + } while (0) +#define FC_TIME_INIT2(...) \ + do { \ + } while (0) +#define FC_TIME_INIT3(...) \ + do { \ + } while (0) +#define _FC_DURATION_PRINT(...) \ + do { \ + } while (0) +#define _FC_TIME(_t) \ + do { \ + } while (0) +#define FC_DURATION_PRINT(...) \ + do { \ + } while (0) +#define FC_DURATION +#define FC_DURATION_INIT(...) \ + do { \ + } while (0) +#define FC_DURATION_INIT1(...) \ + do { \ + } while (0) +#define FC_DURATION_INIT2(...) \ + do { \ + } while (0) +#define FC_DURATION_DECLARE(...) +#define FC_DURATION_DECLARE1(...) +#define FC_DURATION_DECLARE2(...) +#define FC_DURATION_DECL_INIT(...) \ + do { \ + } while (0) +#define FC_DURATION_DECL_INIT2(...) \ + do { \ + } while (0) +#define FC_DURATION_DECL_INIT3(...) \ + do { \ + } while (0) +#define FC_DURATION_PLUS(...) \ + do { \ + } while (0) -#endif //FC_LOG_NO_TIMING +#endif // FC_LOG_NO_TIMING -//TODO: Get rid of this typedef +// TODO: Get rid of this typedef using ConsoleMsgFlags = unsigned int; -namespace Base { +namespace Base +{ #ifndef FC_LOG_NO_TIMING -inline FC_DURATION GetDuration(FC_TIME_POINT &t) +inline FC_DURATION GetDuration(FC_TIME_POINT& t) { auto tnow = std::chrono::FC_TIME_CLOCK::now(); - auto d = std::chrono::duration_cast(tnow-t); + auto d = std::chrono::duration_cast(tnow - t); t = tnow; return d; } #endif /** Used to identify log level*/ -enum class LogStyle{ +enum class LogStyle +{ Warning, Message, Error, Log, - Critical, // Special message to mark critical notifications - Notification, // Special message for notifications to the user (e.g. educational) + Critical, // Special message to mark critical notifications + Notification, // Special message for notifications to the user (e.g. educational) }; /** Used to indicate the intended recipient of a message (warning, error, ...). @@ -481,10 +515,11 @@ enum class LogStyle{ @see ConsoleSingleton */ -enum class IntendedRecipient { - All, // All recipients, Developers and Users (One notification covers all) - User, // User only (notification intended only for a user) - Developer, // Developer only (notification intended only for a developer) +enum class IntendedRecipient +{ + All, // All recipients, Developers and Users (One notification covers all) + User, // User only (notification intended only for a user) + Developer, // Developer only (notification intended only for a developer) }; /** Used to indicate the translation state of a message (warning, error, ...). @@ -495,10 +530,11 @@ enum class IntendedRecipient { @see ConsoleSingleton */ -enum class ContentType { - Untranslated, // Not translated, but translatable - Translated, // Already translated - Untranslatable, // Cannot and should not be translated (Dynamic content, trace,...) +enum class ContentType +{ + Untranslated, // Not translated, but translatable + Translated, // Already translated + Untranslatable, // Cannot and should not be translated (Dynamic content, trace,...) }; /** The Logger Interface @@ -526,47 +562,49 @@ public: * translated (are untranslatable). Or conversely, may decide not to process already translated * notifications. It is up to the intended behaviour of the observer. */ - virtual void SendLog(const std::string& notifiername, const std::string& msg, LogStyle level, - IntendedRecipient recipient, ContentType content) = 0; + virtual void SendLog(const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content) = 0; /** * Returns whether a LogStyle category is active or not */ - bool isActive(Base::LogStyle category) { - if(category == Base::LogStyle::Log) { - return bLog; + bool isActive(Base::LogStyle category) + { + if (category == Base::LogStyle::Log) { + return bLog; } - else - if(category == Base::LogStyle::Warning) { + else if (category == Base::LogStyle::Warning) { return bWrn; } - else - if(category == Base::LogStyle::Error) { + else if (category == Base::LogStyle::Error) { return bErr; } - else - if(category == Base::LogStyle::Message) { + else if (category == Base::LogStyle::Message) { return bMsg; } - else - if(category == Base::LogStyle::Critical) { + else if (category == Base::LogStyle::Critical) { return bCritical; } - else - if(category == Base::LogStyle::Notification) { + else if (category == Base::LogStyle::Notification) { return bNotification; } return false; } - virtual const char *Name(){return nullptr;} - bool bErr{true}; - bool bMsg{true}; - bool bLog{true}; - bool bWrn{true}; - bool bCritical{true}; - bool bNotification{false}; + virtual const char* Name() + { + return nullptr; + } + bool bErr {true}; + bool bMsg {true}; + bool bLog {true}; + bool bWrn {true}; + bool bCritical {true}; + bool bNotification {false}; }; @@ -664,101 +702,106 @@ public: // exported functions goes here +++++++++++++++++++++++++++++++++++++++ /** Sends a message of type LogStyle (Message, Warning, Error, Log, Critical or Notification). - This function is used by all specific convenience functions (Send(), Message(), Warning(), Error(), Log(), Critical and - UserNotification, without or without notifier id). + This function is used by all specific convenience functions (Send(), Message(), Warning(), + Error(), Log(), Critical and UserNotification, without or without notifier id). Notification can be direct or via queue. */ - template - inline void Send( const std::string & notifiername, const char * pMsg, Args&&... args ); + template + inline void Send(const std::string& notifiername, const char* pMsg, Args&&... args); /// Prints a Message - template - inline void Message (const char * pMsg, Args&&... args); + template + inline void Message(const char* pMsg, Args&&... args); /// Prints a warning Message - template - inline void Warning (const char * pMsg, Args&&... args); + template + inline void Warning(const char* pMsg, Args&&... args); /// Prints a error Message - template - inline void Error (const char * pMsg, Args&&... args); + template + inline void Error(const char* pMsg, Args&&... args); /// Prints a log Message - template - inline void Log (const char * pMsg, Args&&... args); + template + inline void Log(const char* pMsg, Args&&... args); /// Prints a Critical Message - template - inline void Critical (const char * pMsg, Args&&... args); + template + inline void Critical(const char* pMsg, Args&&... args); /// Sends a User Notification - template - inline void UserNotification( const char * pMsg, Args&&... args ); + template + inline void UserNotification(const char* pMsg, Args&&... args); /// Sends an already translated User Notification - template - inline void UserTranslatedNotification( const char * pMsg, Args&&... args ); + template + inline void UserTranslatedNotification(const char* pMsg, Args&&... args); /// Prints a Message with source indication - template - inline void Message (const std::string & notifier, const char * pMsg, Args&&... args); + template + inline void Message(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a warning Message with source indication - template - inline void Warning (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void DeveloperWarning (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void UserWarning (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void TranslatedUserWarning (const std::string & notifier, const char * pMsg, Args&&... args); + template + inline void Warning(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void DeveloperWarning(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void UserWarning(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void + TranslatedUserWarning(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a error Message with source indication - template - inline void Error (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void DeveloperError (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void UserError (const std::string & notifier, const char * pMsg, Args&&... args); - template - inline void TranslatedUserError (const std::string & notifier, const char * pMsg, Args&&... args); + template + inline void Error(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void DeveloperError(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void UserError(const std::string& notifier, const char* pMsg, Args&&... args); + template + inline void TranslatedUserError(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a log Message with source indication - template - inline void Log (const std::string & notifier, const char * pMsg, Args&&... args); + template + inline void Log(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a Critical Message with source indication - template - inline void Critical (const std::string & notifier, const char * pMsg, Args&&... args); + template + inline void Critical(const std::string& notifier, const char* pMsg, Args&&... args); /// Sends a User Notification with source indication - template - inline void UserNotification( const std::string & notifier, const char * pMsg, Args&&... args ); + template + inline void UserNotification(const std::string& notifier, const char* pMsg, Args&&... args); /// Sends an already translated User Notification with source indication - template - inline void UserTranslatedNotification( const std::string & notifier, const char * pMsg, Args&&... args ); + template + inline void + UserTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args); // Notify a message directly to observers - template - inline void Notify(const std::string & notifiername, const std::string & msg); + template + inline void Notify(const std::string& notifiername, const std::string& msg); /// Attaches an Observer to FCConsole - void AttachObserver(ILogger *pcObserver); + void AttachObserver(ILogger* pcObserver); /// Detaches an Observer from FCConsole - void DetachObserver(ILogger *pcObserver); + void DetachObserver(ILogger* pcObserver); /// enumeration for the console modes - enum ConsoleMode{ - Verbose = 1, // suppress Log messages + enum ConsoleMode + { + Verbose = 1, // suppress Log messages }; - enum ConnectionMode { + enum ConnectionMode + { Direct = 0, - Queued =1 + Queued = 1 }; - enum FreeCAD_ConsoleMsgType { - MsgType_Txt = 1, - MsgType_Log = 2, // ConsoleObserverStd sends this and higher to stderr - MsgType_Wrn = 4, - MsgType_Err = 8, - MsgType_Critical = 16, // Special message to notify critical information - MsgType_Notification = 32, // Special message to for notifications to the user + enum FreeCAD_ConsoleMsgType + { + MsgType_Txt = 1, + MsgType_Log = 2, // ConsoleObserverStd sends this and higher to stderr + MsgType_Wrn = 4, + MsgType_Err = 8, + MsgType_Critical = 16, // Special message to notify critical information + MsgType_Notification = 32, // Special message to for notifications to the user }; /// Change mode @@ -771,23 +814,25 @@ public: bool IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const; void SetConnectionMode(ConnectionMode mode); - int *GetLogLevel(const char *tag, bool create=true); + int* GetLogLevel(const char* tag, bool create = true); - void SetDefaultLogLevel(int level) { + void SetDefaultLogLevel(int level) + { _defaultLogLevel = level; } - inline int LogLevel(int level) const{ - return level<0?_defaultLogLevel:level; + inline int LogLevel(int level) const + { + return level < 0 ? _defaultLogLevel : level; } /// singleton - static ConsoleSingleton &Instance(); + static ConsoleSingleton& Instance(); // retrieval of an observer by name - ILogger *Get(const char *Name) const; + ILogger* Get(const char* Name) const; - static PyMethodDef Methods[]; + static PyMethodDef Methods[]; void Refresh(); void EnableRefresh(bool enable); @@ -797,43 +842,49 @@ public: protected: // python exports goes here +++++++++++++++++++++++++++++++++++++++++++ // static python wrapper of the exported functions - static PyObject *sPyLog (PyObject *self,PyObject *args); - static PyObject *sPyMessage (PyObject *self,PyObject *args); - static PyObject *sPyWarning (PyObject *self,PyObject *args); - static PyObject *sPyDeveloperWarning (PyObject *self,PyObject *args); - static PyObject *sPyUserWarning (PyObject *self,PyObject *args); - static PyObject *sPyTranslatedUserWarning (PyObject *self,PyObject *args); - static PyObject *sPyError (PyObject *self,PyObject *args); - static PyObject *sPyDeveloperError (PyObject *self,PyObject *args); - static PyObject *sPyUserError (PyObject *self,PyObject *args); - static PyObject *sPyTranslatedUserError (PyObject *self,PyObject *args); - static PyObject *sPyCritical (PyObject *self,PyObject *args); - static PyObject *sPyNotification (PyObject *self,PyObject *args); - static PyObject *sPyTranslatedNotification (PyObject *self,PyObject *args); - static PyObject *sPySetStatus (PyObject *self,PyObject *args); - static PyObject *sPyGetStatus (PyObject *self,PyObject *args); - static PyObject *sPyGetObservers (PyObject *self,PyObject *args); + static PyObject* sPyLog(PyObject* self, PyObject* args); + static PyObject* sPyMessage(PyObject* self, PyObject* args); + static PyObject* sPyWarning(PyObject* self, PyObject* args); + static PyObject* sPyDeveloperWarning(PyObject* self, PyObject* args); + static PyObject* sPyUserWarning(PyObject* self, PyObject* args); + static PyObject* sPyTranslatedUserWarning(PyObject* self, PyObject* args); + static PyObject* sPyError(PyObject* self, PyObject* args); + static PyObject* sPyDeveloperError(PyObject* self, PyObject* args); + static PyObject* sPyUserError(PyObject* self, PyObject* args); + static PyObject* sPyTranslatedUserError(PyObject* self, PyObject* args); + static PyObject* sPyCritical(PyObject* self, PyObject* args); + static PyObject* sPyNotification(PyObject* self, PyObject* args); + static PyObject* sPyTranslatedNotification(PyObject* self, PyObject* args); + static PyObject* sPySetStatus(PyObject* self, PyObject* args); + static PyObject* sPyGetStatus(PyObject* self, PyObject* args); + static PyObject* sPyGetObservers(PyObject* self, PyObject* args); - bool _bVerbose{true}; - bool _bCanRefresh{true}; - ConnectionMode connectionMode{Direct}; + bool _bVerbose {true}; + bool _bCanRefresh {true}; + ConnectionMode connectionMode {Direct}; // Singleton! ConsoleSingleton(); virtual ~ConsoleSingleton(); private: - void postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, IntendedRecipient recipient, - ContentType content, const std::string& notifiername, const std::string& msg); - void notifyPrivate(LogStyle category, IntendedRecipient recipient, ContentType content, - const std::string& notifiername, const std::string& msg); + void postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg); + void notifyPrivate(LogStyle category, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg); // singleton static void Destruct(); - static ConsoleSingleton *_pcSingleton; + static ConsoleSingleton* _pcSingleton; // observer list - std::set _aclObservers; + std::set _aclObservers; std::map _logLevels; int _defaultLogLevel; @@ -845,65 +896,80 @@ private: * This method is used to gain access to the one and only instance of * the ConsoleSingleton class. */ -inline ConsoleSingleton &Console(){ +inline ConsoleSingleton& Console() +{ return ConsoleSingleton::Instance(); } -inline constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType ConsoleSingleton::getConsoleMsg(Base::LogStyle style) +inline constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType +ConsoleSingleton::getConsoleMsg(Base::LogStyle style) { - constexpr std::array msgTypes { // In order of Base::LogStyle - FreeCAD_ConsoleMsgType::MsgType_Wrn, - FreeCAD_ConsoleMsgType::MsgType_Txt, - FreeCAD_ConsoleMsgType::MsgType_Err, - FreeCAD_ConsoleMsgType::MsgType_Log, - FreeCAD_ConsoleMsgType::MsgType_Critical, - FreeCAD_ConsoleMsgType::MsgType_Notification - }; + constexpr std::array msgTypes {// In order of Base::LogStyle + FreeCAD_ConsoleMsgType::MsgType_Wrn, + FreeCAD_ConsoleMsgType::MsgType_Txt, + FreeCAD_ConsoleMsgType::MsgType_Err, + FreeCAD_ConsoleMsgType::MsgType_Log, + FreeCAD_ConsoleMsgType::MsgType_Critical, + FreeCAD_ConsoleMsgType::MsgType_Notification}; return msgTypes.at(static_cast(style)); } -class BaseExport ConsoleRefreshDisabler { +class BaseExport ConsoleRefreshDisabler +{ public: - ConsoleRefreshDisabler() { + ConsoleRefreshDisabler() + { Console().EnableRefresh(false); } - ~ConsoleRefreshDisabler() { + ~ConsoleRefreshDisabler() + { Console().EnableRefresh(true); } }; /** LogLevel helper class */ -class BaseExport LogLevel { +class BaseExport LogLevel +{ public: std::string tag; - int &lvl; + int& lvl; bool print_tag; int print_src; bool print_time; bool add_eol; bool refresh; - LogLevel(const char *tag, bool print_tag=true, int print_src=0, - bool print_time=false, bool add_eol=true, bool refresh=false) - :tag(tag),lvl(*Console().GetLogLevel(tag)) - ,print_tag(print_tag),print_src(print_src),print_time(print_time) - ,add_eol(add_eol),refresh(refresh) + LogLevel(const char* tag, + bool print_tag = true, + int print_src = 0, + bool print_time = false, + bool add_eol = true, + bool refresh = false) + : tag(tag) + , lvl(*Console().GetLogLevel(tag)) + , print_tag(print_tag) + , print_src(print_src) + , print_time(print_time) + , add_eol(add_eol) + , refresh(refresh) {} - bool isEnabled(int l) { - return l<=level(); + bool isEnabled(int l) + { + return l <= level(); } - int level() const { + int level() const + { return Console().LogLevel(lvl); } - std::stringstream &prefix(std::stringstream &str, const char *src, int line); + std::stringstream& prefix(std::stringstream& str, const char* src, int line); }; -} // namespace Base +} // namespace Base /** Prints a Message * This method issues a Message. @@ -922,152 +988,176 @@ public: * @see UserNotification * @see UserTranslatedNotification */ -template -inline void Base::ConsoleSingleton::Message( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::Message(const char* pMsg, Args&&... args) { Message(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Message( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Message(const std::string& notifier, const char* pMsg, Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Warning( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::Warning(const char* pMsg, Args&&... args) { Warning(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Warning( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Warning(const std::string& notifier, const char* pMsg, Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::DeveloperWarning( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::DeveloperWarning(const std::string& notifier, + const char* pMsg, + Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserWarning( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::UserWarning(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + Send( + notifier, + pMsg, + std::forward(args)...); } -template -inline void Base::ConsoleSingleton::TranslatedUserWarning( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::TranslatedUserWarning(const std::string& notifier, + const char* pMsg, + Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + Send( + notifier, + pMsg, + std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Error( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::Error(const char* pMsg, Args&&... args) { Error(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Error( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Error(const std::string& notifier, const char* pMsg, Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::DeveloperError( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::DeveloperError(const std::string& notifier, + const char* pMsg, + Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserError( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::UserError(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + Send( + notifier, + pMsg, + std::forward(args)...); } -template -inline void Base::ConsoleSingleton::TranslatedUserError( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::TranslatedUserError(const std::string& notifier, + const char* pMsg, + Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + Send( + notifier, + pMsg, + std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Critical( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::Critical(const char* pMsg, Args&&... args) { Critical(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Critical( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Critical(const std::string& notifier, const char* pMsg, Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserNotification( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::UserNotification(const char* pMsg, Args&&... args) { UserNotification(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserNotification( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::UserNotification(const std::string& notifier, + const char* pMsg, + Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserTranslatedNotification( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::UserTranslatedNotification(const char* pMsg, Args&&... args) { UserTranslatedNotification(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::UserTranslatedNotification( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::UserTranslatedNotification(const std::string& notifier, + const char* pMsg, + Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Log( const char * pMsg, Args&&... args ) +template +inline void Base::ConsoleSingleton::Log(const char* pMsg, Args&&... args) { Log(std::string(""), pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Log( const std::string & notifier, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Log(const std::string& notifier, const char* pMsg, Args&&... args) { Send(notifier, pMsg, std::forward(args)...); } -template -inline void Base::ConsoleSingleton::Send( const std::string & notifiername, const char * pMsg, Args&&... args ) +template +inline void +Base::ConsoleSingleton::Send(const std::string& notifiername, const char* pMsg, Args&&... args) { std::string format = fmt::sprintf(pMsg, args...); if (connectionMode == Direct) { - Notify(notifiername,format); + Notify(notifiername, format); } else { @@ -1077,16 +1167,16 @@ inline void Base::ConsoleSingleton::Send( const std::string & notifiername, cons } } -template -inline void Base::ConsoleSingleton::Notify(const std::string & notifiername, const std::string & msg) +template +inline void Base::ConsoleSingleton::Notify(const std::string& notifiername, const std::string& msg) { notifyPrivate(category, recipient, contenttype, notifiername, msg); } #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif -#endif // BASE_CONSOLE_H +#endif // BASE_CONSOLE_H diff --git a/src/Base/ConsoleObserver.cpp b/src/Base/ConsoleObserver.cpp index 27e8122c27..7ad627a239 100644 --- a/src/Base/ConsoleObserver.cpp +++ b/src/Base/ConsoleObserver.cpp @@ -24,11 +24,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# ifdef FC_OS_WIN32 -# include -# endif -# include -# include +#ifdef FC_OS_WIN32 +#include +#endif +#include +#include #endif #include @@ -43,14 +43,15 @@ using namespace Base; //========================================================================= // some special observers -ConsoleObserverFile::ConsoleObserverFile(const char *sFileName) - : cFileStream(Base::FileInfo(sFileName)) // can be in UTF8 +ConsoleObserverFile::ConsoleObserverFile(const char* sFileName) + : cFileStream(Base::FileInfo(sFileName)) // can be in UTF8 { - if (!cFileStream.is_open()) + if (!cFileStream.is_open()) { Console().Warning("Cannot open log file '%s'.\n", sFileName); + } // mark the file as a UTF-8 encoded file unsigned char bom[3] = {0xef, 0xbb, 0xbf}; - cFileStream.write(reinterpret_cast(bom), 3*sizeof(char)); + cFileStream.write(reinterpret_cast(bom), 3 * sizeof(char)); } ConsoleObserverFile::~ConsoleObserverFile() @@ -58,17 +59,21 @@ ConsoleObserverFile::~ConsoleObserverFile() cFileStream.close(); } -void ConsoleObserverFile::SendLog(const std::string& notifiername, const std::string& msg, LogStyle level, - IntendedRecipient recipient, ContentType content) +void ConsoleObserverFile::SendLog(const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content) { - (void) notifiername; + (void)notifiername; // Do not log translated messages, or messages intended only to the user to log file - if(recipient == IntendedRecipient::User || content == ContentType::Translated) + if (recipient == IntendedRecipient::User || content == ContentType::Translated) { return; - + } + std::string prefix; - switch(level){ + switch (level) { case LogStyle::Warning: prefix = "Wrn: "; break; @@ -92,30 +97,35 @@ void ConsoleObserverFile::SendLog(const std::string& notifiername, const std::st cFileStream.flush(); } -ConsoleObserverStd::ConsoleObserverStd() : -# if defined(FC_OS_WIN32) +ConsoleObserverStd::ConsoleObserverStd() + : +#if defined(FC_OS_WIN32) useColorStderr(true) -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - useColorStderr( isatty(STDERR_FILENO) ) -# else +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + useColorStderr(isatty(STDERR_FILENO)) +#else useColorStderr(false) -# endif +#endif { bLog = false; } ConsoleObserverStd::~ConsoleObserverStd() = default; -void ConsoleObserverStd::SendLog(const std::string& notifiername, const std::string& msg, LogStyle level, - IntendedRecipient recipient, ContentType content) +void ConsoleObserverStd::SendLog(const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content) { - (void) notifiername; + (void)notifiername; // Do not log translated messages, or messages intended only to the user to std log - if(recipient == IntendedRecipient::User || content == ContentType::Translated) + if (recipient == IntendedRecipient::User || content == ContentType::Translated) { return; - - switch(level){ + } + + switch (level) { case LogStyle::Warning: this->Warning(msg.c_str()); break; @@ -136,92 +146,100 @@ void ConsoleObserverStd::SendLog(const std::string& notifiername, const std::str } } -void ConsoleObserverStd::Message(const char *sMsg) +void ConsoleObserverStd::Message(const char* sMsg) { - printf("%s",sMsg); + printf("%s", sMsg); } -void ConsoleObserverStd::Warning(const char *sWarn) +void ConsoleObserverStd::Warning(const char* sWarn) { if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_GREEN| FOREGROUND_BLUE); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;33m"); -# endif +#endif } fprintf(stderr, "%s", sWarn); if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE),FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); -# endif +#endif } } -void ConsoleObserverStd::Error (const char *sErr) +void ConsoleObserverStd::Error(const char* sErr) { if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_RED|FOREGROUND_INTENSITY ); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_INTENSITY); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;31m"); -# endif +#endif } fprintf(stderr, "%s", sErr); if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE),FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); -# endif +#endif } } -void ConsoleObserverStd::Log (const char *sErr) +void ConsoleObserverStd::Log(const char* sErr) { if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_RED |FOREGROUND_GREEN); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;36m"); -# endif +#endif } fprintf(stderr, "%s", sErr); if (useColorStderr) { -# if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE),FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); -# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); -# endif +#endif } } -void ConsoleObserverStd::Critical(const char *sCritical) +void ConsoleObserverStd::Critical(const char* sCritical) { if (useColorStderr) { - # if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE); - # elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;33m"); - # endif +#endif } fprintf(stderr, "%s", sCritical); if (useColorStderr) { - # if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE),FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); - # elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_WIN32) + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); +#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); - # endif +#endif } } @@ -232,8 +250,9 @@ RedirectStdOutput::RedirectStdOutput() int RedirectStdOutput::overflow(int c) { - if (c != EOF) + if (c != EOF) { buffer.push_back(static_cast(c)); + } return c; } @@ -254,8 +273,9 @@ RedirectStdLog::RedirectStdLog() int RedirectStdLog::overflow(int c) { - if (c != EOF) + if (c != EOF) { buffer.push_back(static_cast(c)); + } return c; } @@ -276,8 +296,9 @@ RedirectStdError::RedirectStdError() int RedirectStdError::overflow(int c) { - if (c != EOF) + if (c != EOF) { buffer.push_back(static_cast(c)); + } return c; } @@ -292,7 +313,7 @@ int RedirectStdError::sync() //--------------------------------------------------------- -std::stringstream &LogLevel::prefix(std::stringstream &str, const char *src, int line) +std::stringstream& LogLevel::prefix(std::stringstream& str, const char* src, int line) { static FC_TIME_POINT s_tstart; static bool s_timing = false; @@ -302,11 +323,13 @@ std::stringstream &LogLevel::prefix(std::stringstream &str, const char *src, int _FC_TIME_INIT(s_tstart); } auto tnow = std::chrono::FC_TIME_CLOCK::now(); - auto d = std::chrono::duration_cast(tnow-s_tstart); + auto d = std::chrono::duration_cast(tnow - s_tstart); str << d.count() << ' '; } - if (print_tag) str << '<' << tag << "> "; - if (print_src==2) { + if (print_tag) { + str << '<' << tag << "> "; + } + if (print_src == 2) { Base::PyGILStateLocker lock; PyFrameObject* frame = PyEval_GetFrame(); if (frame) { @@ -322,11 +345,11 @@ std::stringstream &LogLevel::prefix(std::stringstream &str, const char *src, int } if (print_src && src && src[0]) { #ifdef FC_OS_WIN32 - const char *_f = std::strrchr(src, '\\'); + const char* _f = std::strrchr(src, '\\'); #else - const char *_f = std::strrchr(src, '/'); + const char* _f = std::strrchr(src, '/'); #endif - str << (_f?_f+1:src)<<"("< -namespace Base { +namespace Base +{ //========================================================================= // some special observers @@ -36,17 +37,28 @@ namespace Base { /** The LoggingConsoleObserver class * This class is used by the main modules to write Console messages and logs to a file */ -class BaseExport ConsoleObserverFile : public ILogger +class BaseExport ConsoleObserverFile: public ILogger { public: - explicit ConsoleObserverFile(const char *sFileName); + explicit ConsoleObserverFile(const char* sFileName); ~ConsoleObserverFile() override; - void SendLog(const std::string& notifiername, const std::string& msg, LogStyle level, - IntendedRecipient recipient, ContentType content) override; - const char* Name() override {return "File";} + void SendLog(const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content) override; + const char* Name() override + { + return "File"; + } -protected: + ConsoleObserverFile(const ConsoleObserverFile&) = delete; + ConsoleObserverFile(ConsoleObserverFile&&) = delete; + ConsoleObserverFile& operator=(const ConsoleObserverFile&) = delete; + ConsoleObserverFile& operator=(ConsoleObserverFile&&) = delete; + +private: Base::ofstream cFileStream; }; @@ -58,17 +70,28 @@ class BaseExport ConsoleObserverStd: public ILogger public: ConsoleObserverStd(); ~ConsoleObserverStd() override; - void SendLog(const std::string& notifiername, const std::string& msg, LogStyle level, - IntendedRecipient recipient, ContentType content) override; - const char* Name() override {return "Console";} -protected: - bool useColorStderr; + void SendLog(const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content) override; + const char* Name() override + { + return "Console"; + } + + ConsoleObserverStd(const ConsoleObserverStd&) = delete; + ConsoleObserverStd(ConsoleObserverStd&&) = delete; + ConsoleObserverStd& operator=(const ConsoleObserverStd&) = delete; + ConsoleObserverStd& operator=(ConsoleObserverStd&&) = delete; + private: - void Warning (const char *sWarn); - void Message (const char *sMsg); - void Error (const char *sErr); - void Log (const char *sLog); - void Critical(const char *sCritical); + bool useColorStderr; + void Warning(const char* sWarn); + void Message(const char* sMsg); + void Error(const char* sErr); + void Log(const char* sLog); + void Critical(const char* sCritical); }; /** The ILoggerBlocker class @@ -78,24 +101,31 @@ private: class BaseExport ILoggerBlocker { public: - // Constructor that will block message types passed as parameter. By default, all types are blocked. - inline explicit ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes = - ConsoleSingleton::MsgType_Txt | ConsoleSingleton::MsgType_Log | ConsoleSingleton::MsgType_Wrn | ConsoleSingleton::MsgType_Err | - ConsoleSingleton::MsgType_Critical | ConsoleSingleton::MsgType_Notification); + // Constructor that will block message types passed as parameter. By default, all types are + // blocked. + inline explicit ILoggerBlocker(const char* co, + ConsoleMsgFlags msgTypes = ConsoleSingleton::MsgType_Txt + | ConsoleSingleton::MsgType_Log + | ConsoleSingleton::MsgType_Wrn + | ConsoleSingleton::MsgType_Err + | ConsoleSingleton::MsgType_Critical + | ConsoleSingleton::MsgType_Notification); // Disable copy & move constructors ILoggerBlocker(ILoggerBlocker const&) = delete; - ILoggerBlocker(ILoggerBlocker const &&) = delete; + ILoggerBlocker(ILoggerBlocker const&&) = delete; // Disable assignment & move-assignment operator ILoggerBlocker& operator=(ILoggerBlocker const&) = delete; ILoggerBlocker& operator=(ILoggerBlocker const&&) = delete; // Destructor that will restore message type settings. inline ~ILoggerBlocker(); + private: - ConsoleMsgFlags msgTypesBlocked = 0; // Stores message types blocked by the blocker - const char* conObs; // Stores console observer name that blocker acts on + ConsoleMsgFlags msgTypesBlocked = 0; // Stores message types blocked by the blocker + const char* conObs; // Stores console observer name that blocker acts on }; -ILoggerBlocker::ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes) : conObs(co) +ILoggerBlocker::ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes) + : conObs(co) { msgTypesBlocked = Console().SetEnabledMsgType(conObs, msgTypes, false); } @@ -104,14 +134,15 @@ ILoggerBlocker::~ILoggerBlocker() { #ifdef FC_DEBUG auto debug = Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); - if (debug != msgTypesBlocked) + if (debug != msgTypesBlocked) { Console().Warning("Enabled message types have been changed while ILoggerBlocker was set\n"); + } #else Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); #endif } -class BaseExport RedirectStdOutput : public std::streambuf +class BaseExport RedirectStdOutput: public std::streambuf { public: RedirectStdOutput(); @@ -124,7 +155,7 @@ private: std::string buffer; }; -class BaseExport RedirectStdError : public std::streambuf +class BaseExport RedirectStdError: public std::streambuf { public: RedirectStdError(); @@ -137,7 +168,7 @@ private: std::string buffer; }; -class BaseExport RedirectStdLog : public std::streambuf +class BaseExport RedirectStdLog: public std::streambuf { public: RedirectStdLog(); @@ -151,6 +182,6 @@ private: }; -} // namespace Base +} // namespace Base -#endif // BASE_CONSOLEOBSERVER_H +#endif // BASE_CONSOLEOBSERVER_H diff --git a/src/Base/Converter.h b/src/Base/Converter.h index fe82becd38..2a7aa40a81 100644 --- a/src/Base/Converter.h +++ b/src/Base/Converter.h @@ -29,52 +29,71 @@ #include "Vector3D.h" -namespace Base { +namespace Base +{ -template -struct vec_traits { }; +template +struct vec_traits +{ +}; -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = Vector3f; using float_type = float; - vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.x, v.y, v.z); } + private: const vec_type& v; }; -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = Vector3d; using float_type = double; - vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.x, v.y, v.z); } + private: const vec_type& v; }; -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = Rotation; using float_type = double; - vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { - float_type q1{},q2{},q3{},q4{}; - v.getValue(q1,q2,q3,q4); + vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { + float_type q1 {}, q2 {}, q3 {}, q4 {}; + v.getValue(q1, q2, q3, q4); return std::make_tuple(q1, q2, q3, q4); } + private: const vec_type& v; }; // type with three floats -template -_Vec make_vec(const std::tuple&& t) { +template +_Vec make_vec(const std::tuple&& t) +{ using traits_type = vec_traits<_Vec>; using float_traits_type = typename traits_type::float_type; return _Vec(float_traits_type(std::get<0>(t)), @@ -83,8 +102,9 @@ _Vec make_vec(const std::tuple&& t) { } // type with four floats -template -_Vec make_vec(const std::tuple&& t) { +template +_Vec make_vec(const std::tuple&& t) +{ using traits_type = vec_traits<_Vec>; using float_traits_type = typename traits_type::float_type; return _Vec(float_traits_type(std::get<0>(t)), @@ -93,7 +113,7 @@ _Vec make_vec(const std::tuple&& float_traits_type(std::get<3>(t))); } -template +template inline _Vec1 convertTo(const _Vec2& v) { using traits_type = vec_traits<_Vec2>; @@ -103,6 +123,6 @@ inline _Vec1 convertTo(const _Vec2& v) return make_vec<_Vec1, float_type>(std::move(tuple)); } -} +} // namespace Base -#endif // BASE_CONVERTER_H +#endif // BASE_CONVERTER_H diff --git a/src/Base/CoordinateSystem.cpp b/src/Base/CoordinateSystem.cpp index f6295bb775..40fe56b1e7 100644 --- a/src/Base/CoordinateSystem.cpp +++ b/src/Base/CoordinateSystem.cpp @@ -31,19 +31,22 @@ using namespace Base; CoordinateSystem::CoordinateSystem() - : axis(Vector3d(), Vector3d(0,0,1)), xdir(1,0,0), ydir(0,1,0) -{ -} + : axis(Vector3d(), Vector3d(0, 0, 1)) + , xdir(1, 0, 0) + , ydir(0, 1, 0) +{} CoordinateSystem::~CoordinateSystem() = default; void CoordinateSystem::setAxes(const Axis& v, const Vector3d& xd) { - if (xd.Sqr() < Base::Vector3d::epsilon()) + if (xd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is null vector"); + } Vector3d yd = v.getDirection() % xd; - if (yd.Sqr() < Base::Vector3d::epsilon()) + if (yd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is parallel to Z direction"); + } ydir = yd; ydir.Normalize(); xdir = ydir % v.getDirection(); @@ -56,11 +59,13 @@ void CoordinateSystem::setAxes(const Axis& v, const Vector3d& xd) void CoordinateSystem::setAxes(const Vector3d& n, const Vector3d& xd) { - if (xd.Sqr() < Base::Vector3d::epsilon()) + if (xd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is null vector"); + } Vector3d yd = n % xd; - if (yd.Sqr() < Base::Vector3d::epsilon()) + if (yd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is parallel to Z direction"); + } ydir = yd; ydir.Normalize(); xdir = ydir % n; @@ -78,8 +83,9 @@ void CoordinateSystem::setAxis(const Axis& v) void CoordinateSystem::setXDirection(const Vector3d& dir) { Vector3d yd = axis.getDirection() % dir; - if (yd.Sqr() < Base::Vector3d::epsilon()) + if (yd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is parallel to Z direction"); + } ydir = yd; ydir.Normalize(); xdir = ydir % axis.getDirection(); @@ -89,8 +95,9 @@ void CoordinateSystem::setXDirection(const Vector3d& dir) void CoordinateSystem::setYDirection(const Vector3d& dir) { Vector3d xd = dir % axis.getDirection(); - if (xd.Sqr() < Base::Vector3d::epsilon()) + if (xd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is parallel to Z direction"); + } xdir = xd; xdir.Normalize(); ydir = axis.getDirection() % xdir; @@ -107,18 +114,35 @@ Placement CoordinateSystem::displacement(const CoordinateSystem& cs) const const Base::Vector3d& a = axis.getBase(); const Base::Vector3d& zdir = axis.getDirection(); Base::Matrix4D At; - At[0][0] = xdir.x; At[1][0] = ydir.x; At[2][0] = zdir.x; - At[0][1] = xdir.y; At[1][1] = ydir.y; At[2][1] = zdir.y; - At[0][2] = xdir.z; At[1][2] = ydir.z; At[2][2] = zdir.z; + At[0][0] = xdir.x; + At[1][0] = ydir.x; + At[2][0] = zdir.x; + At[0][1] = xdir.y; + At[1][1] = ydir.y; + At[2][1] = zdir.y; + At[0][2] = xdir.z; + At[1][2] = ydir.z; + At[2][2] = zdir.z; Base::Vector3d at = At * a; - At[0][3] = -at.x; At[1][3] = -at.y; At[2][3] = -at.z; + At[0][3] = -at.x; + At[1][3] = -at.y; + At[2][3] = -at.z; const Base::Vector3d& b = cs.axis.getBase(); const Base::Vector3d& cszdir = cs.axis.getDirection(); Base::Matrix4D B; - B[0][0] = cs.xdir.x; B[0][1] = cs.ydir.x; B[0][2] = cszdir.x; B[0][3] = b.x; - B[1][0] = cs.xdir.y; B[1][1] = cs.ydir.y; B[1][2] = cszdir.y; B[1][3] = b.y; - B[2][0] = cs.xdir.z; B[2][1] = cs.ydir.z; B[2][2] = cszdir.z; B[2][3] = b.z; + B[0][0] = cs.xdir.x; + B[0][1] = cs.ydir.x; + B[0][2] = cszdir.x; + B[0][3] = b.x; + B[1][0] = cs.xdir.y; + B[1][1] = cs.ydir.y; + B[1][2] = cszdir.y; + B[1][3] = b.y; + B[2][0] = cs.xdir.z; + B[2][1] = cs.ydir.z; + B[2][2] = cszdir.z; + B[2][3] = b.z; Placement PAt(At); Placement PB(B); @@ -149,11 +173,11 @@ void CoordinateSystem::transform(const Rotation& r) void CoordinateSystem::setPlacement(const Placement& p) { - Vector3d zdir(0,0,1); + Vector3d zdir(0, 0, 1); p.getRotation().multVec(zdir, zdir); axis.setBase(p.getPosition()); axis.setDirection(zdir); - p.getRotation().multVec(Vector3d(1,0,0), this->xdir); - p.getRotation().multVec(Vector3d(0,1,0), this->ydir); + p.getRotation().multVec(Vector3d(1, 0, 0), this->xdir); + p.getRotation().multVec(Vector3d(0, 1, 0), this->ydir); } diff --git a/src/Base/CoordinateSystem.h b/src/Base/CoordinateSystem.h index 456c5ed4c4..1757a47f14 100644 --- a/src/Base/CoordinateSystem.h +++ b/src/Base/CoordinateSystem.h @@ -26,7 +26,8 @@ #include "Axis.h" -namespace Base { +namespace Base +{ /** * Describes a right-handed coordinate system in 3D space. \author Werner Mayer @@ -38,8 +39,13 @@ public: * with X axis (1,0,0), with Y axis (0,1,0) and Z axis (0,0,1) */ CoordinateSystem(); + CoordinateSystem(const CoordinateSystem&) = default; + CoordinateSystem(CoordinateSystem&&) = default; ~CoordinateSystem(); + CoordinateSystem& operator=(const CoordinateSystem&) = default; + CoordinateSystem& operator=(CoordinateSystem&&) = default; + /** Sets the main axis. X and Y dir are adjusted accordingly. * The main axis \a v must not be parallel to the X axis */ @@ -53,28 +59,40 @@ public: */ void setAxes(const Vector3d& n, const Vector3d& xd); inline const Axis& getAxis() const - { return axis; } + { + return axis; + } /** The passed vector must not be parallel to the main axis */ void setXDirection(const Vector3d&); inline const Vector3d& getXDirection() const - { return xdir; } + { + return xdir; + } /** The passed vector must not be parallel to the main axis */ void setYDirection(const Vector3d&); inline const Vector3d& getYDirection() const - { return ydir; } + { + return ydir; + } /** Sets the main axis. X and Y dir are adjusted accordingly. * The main axis must not be parallel to the X axis */ void setZDirection(const Vector3d&); inline const Vector3d& getZDirection() const - { return axis.getDirection(); } + { + return axis.getDirection(); + } inline void setPosition(const Vector3d& p) - { axis.setBase(p); } + { + axis.setBase(p); + } inline const Vector3d& getPosition() const - { return axis.getBase(); } + { + return axis.getBase(); + } /** This computes the displacement from this coordinate system to the * given coordinate system \a cs @@ -99,6 +117,6 @@ private: Vector3d ydir; }; -} +} // namespace Base -#endif // BASE_COORDINATESYSTEM_H +#endif // BASE_COORDINATESYSTEM_H diff --git a/src/Base/CoordinateSystemPyImp.cpp b/src/Base/CoordinateSystemPyImp.cpp index 7e6dc5cbcd..82cb6a53ba 100644 --- a/src/Base/CoordinateSystemPyImp.cpp +++ b/src/Base/CoordinateSystemPyImp.cpp @@ -38,7 +38,7 @@ std::string CoordinateSystemPy::representation() const return {""}; } -PyObject *CoordinateSystemPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* CoordinateSystemPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of CoordinateSystemPy and the Twin object return new CoordinateSystemPy(new CoordinateSystem); @@ -50,9 +50,9 @@ int CoordinateSystemPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* CoordinateSystemPy::setAxes(PyObject * args) +PyObject* CoordinateSystemPy::setAxes(PyObject* args) { - PyObject *axis{}, *xdir{}; + PyObject *axis {}, *xdir {}; if (PyArg_ParseTuple(args, "O!O!", &(AxisPy::Type), &axis, &(VectorPy::Type), &xdir)) { getCoordinateSystemPtr()->setAxes(*static_cast(axis)->getAxisPtr(), *static_cast(xdir)->getVectorPtr()); @@ -70,29 +70,31 @@ PyObject* CoordinateSystemPy::setAxes(PyObject * args) return nullptr; } -PyObject* CoordinateSystemPy::displacement(PyObject * args) +PyObject* CoordinateSystemPy::displacement(PyObject* args) { - PyObject *cs{}; - if (!PyArg_ParseTuple(args, "O!", &(CoordinateSystemPy::Type), &cs)) + PyObject* cs {}; + if (!PyArg_ParseTuple(args, "O!", &(CoordinateSystemPy::Type), &cs)) { return nullptr; + } Placement p = getCoordinateSystemPtr()->displacement( *static_cast(cs)->getCoordinateSystemPtr()); return new PlacementPy(new Placement(p)); } -PyObject* CoordinateSystemPy::transformTo(PyObject * args) +PyObject* CoordinateSystemPy::transformTo(PyObject* args) { - PyObject *vec{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) + PyObject* vec {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) { return nullptr; + } Vector3d v = static_cast(vec)->value(); getCoordinateSystemPtr()->transformTo(v); return new VectorPy(new Vector3d(v)); } -PyObject* CoordinateSystemPy::transform(PyObject * args) +PyObject* CoordinateSystemPy::transform(PyObject* args) { - PyObject *plm{}; + PyObject* plm {}; if (PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) { getCoordinateSystemPtr()->transform(*static_cast(plm)->getPlacementPtr()); Py_Return; @@ -108,11 +110,12 @@ PyObject* CoordinateSystemPy::transform(PyObject * args) return nullptr; } -PyObject* CoordinateSystemPy::setPlacement(PyObject * args) +PyObject* CoordinateSystemPy::setPlacement(PyObject* args) { - PyObject *plm{}; - if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) + PyObject* plm {}; + if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) { return nullptr; + } getCoordinateSystemPtr()->setPlacement(*static_cast(plm)->getPlacementPtr()); Py_Return; } @@ -126,7 +129,7 @@ Py::Object CoordinateSystemPy::getAxis() const void CoordinateSystemPy::setAxis(Py::Object arg) { if (PyObject_TypeCheck(arg.ptr(), &(Base::AxisPy::Type))) { - AxisPy *axis = static_cast(arg.ptr()); + AxisPy* axis = static_cast(arg.ptr()); getCoordinateSystemPtr()->setAxis(*axis->getAxisPtr()); return; } @@ -136,7 +139,7 @@ void CoordinateSystemPy::setAxis(Py::Object arg) Py::Object CoordinateSystemPy::getXDirection() const { - return Py::Vector(getCoordinateSystemPtr()->getXDirection()); // NOLINT + return Py::Vector(getCoordinateSystemPtr()->getXDirection()); // NOLINT } void CoordinateSystemPy::setXDirection(Py::Object arg) @@ -146,7 +149,7 @@ void CoordinateSystemPy::setXDirection(Py::Object arg) Py::Object CoordinateSystemPy::getYDirection() const { - return Py::Vector(getCoordinateSystemPtr()->getYDirection()); // NOLINT + return Py::Vector(getCoordinateSystemPtr()->getYDirection()); // NOLINT } void CoordinateSystemPy::setYDirection(Py::Object arg) @@ -156,7 +159,7 @@ void CoordinateSystemPy::setYDirection(Py::Object arg) Py::Object CoordinateSystemPy::getZDirection() const { - return Py::Vector(getCoordinateSystemPtr()->getZDirection()); // NOLINT + return Py::Vector(getCoordinateSystemPtr()->getZDirection()); // NOLINT } void CoordinateSystemPy::setZDirection(Py::Object arg) @@ -166,7 +169,7 @@ void CoordinateSystemPy::setZDirection(Py::Object arg) Py::Object CoordinateSystemPy::getPosition() const { - return Py::Vector(getCoordinateSystemPtr()->getPosition()); // NOLINT + return Py::Vector(getCoordinateSystemPtr()->getPosition()); // NOLINT } void CoordinateSystemPy::setPosition(Py::Object arg) @@ -174,7 +177,7 @@ void CoordinateSystemPy::setPosition(Py::Object arg) getCoordinateSystemPtr()->setPosition(Py::Vector(arg).toVector()); } -PyObject *CoordinateSystemPy::getCustomAttributes(const char* /*attr*/) const +PyObject* CoordinateSystemPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Base/Debugger.cpp b/src/Base/Debugger.cpp index 6d1f987b22..94c6d9c9c6 100644 --- a/src/Base/Debugger.cpp +++ b/src/Base/Debugger.cpp @@ -23,8 +23,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "Debugger.h" @@ -34,9 +34,8 @@ using namespace Base; Debugger::Debugger(QObject* parent) - : QObject(parent), isAttached(false) -{ -} + : QObject(parent) +{} Debugger::~Debugger() = default; @@ -66,8 +65,9 @@ bool Debugger::eventFilter(QObject*, QEvent* event) int Debugger::exec() { - if (isAttached) + if (isAttached) { Base::Console().Message("TO CONTINUE PRESS ANY KEY...\n"); + } return loop.exec(); } diff --git a/src/Base/Debugger.h b/src/Base/Debugger.h index 7f312be423..83096b228b 100644 --- a/src/Base/Debugger.h +++ b/src/Base/Debugger.h @@ -30,7 +30,8 @@ #include #endif -namespace Base { +namespace Base +{ /** This is a utility class to break the application at a point to inspect e.g. the result of an algorithm. @@ -53,18 +54,18 @@ namespace Base { \endcode \author Werner Mayer */ -class BaseExport Debugger : public QObject +class BaseExport Debugger: public QObject { Q_OBJECT public: - Debugger(QObject* parent=nullptr); + Debugger(QObject* parent = nullptr); ~Debugger() override; Debugger(const Debugger&) = delete; Debugger(Debugger&&) = delete; - Debugger& operator= (const Debugger&) = delete; - Debugger& operator= (Debugger&&) = delete; + Debugger& operator=(const Debugger&) = delete; + Debugger& operator=(Debugger&&) = delete; void attach(); void detach(); @@ -75,10 +76,10 @@ public Q_SLOTS: void quit(); private: - bool isAttached; + bool isAttached {false}; QEventLoop loop; }; -} +} // namespace Base -#endif // BASE_DEBUGGER_H +#endif // BASE_DEBUGGER_H diff --git a/src/Base/DualNumber.h b/src/Base/DualNumber.h index 61c5d850de..32bd6efa8a 100644 --- a/src/Base/DualNumber.h +++ b/src/Base/DualNumber.h @@ -25,7 +25,8 @@ #include -namespace Base { +namespace Base +{ /** @@ -40,55 +41,72 @@ class DualNumber public: double re = 0.0; double du = 0.0; + public: DualNumber() = default; DualNumber(double re, double du = 0.0) - : re(re), du(du) + : re(re) + , du(du) {} - DualNumber operator-() const {return {-re,-du};} + DualNumber operator-() const + { + return {-re, -du}; + } }; -inline DualNumber operator+(DualNumber a, DualNumber b){ +inline DualNumber operator+(DualNumber a, DualNumber b) +{ return {a.re + b.re, a.du + b.du}; } -inline DualNumber operator+(DualNumber a, double b){ +inline DualNumber operator+(DualNumber a, double b) +{ return {a.re + b, a.du}; } -inline DualNumber operator+(double a, DualNumber b){ +inline DualNumber operator+(double a, DualNumber b) +{ return {a + b.re, b.du}; } -inline DualNumber operator-(DualNumber a, DualNumber b){ +inline DualNumber operator-(DualNumber a, DualNumber b) +{ return {a.re - b.re, a.du - b.du}; } -inline DualNumber operator-(DualNumber a, double b){ +inline DualNumber operator-(DualNumber a, double b) +{ return {a.re - b, a.du}; } -inline DualNumber operator-(double a, DualNumber b){ +inline DualNumber operator-(double a, DualNumber b) +{ return {a - b.re, -b.du}; } -inline DualNumber operator*(DualNumber a, DualNumber b){ +inline DualNumber operator*(DualNumber a, DualNumber b) +{ return {a.re * b.re, a.re * b.du + a.du * b.re}; } -inline DualNumber operator*(double a, DualNumber b){ +inline DualNumber operator*(double a, DualNumber b) +{ return {a * b.re, a * b.du}; } -inline DualNumber operator*(DualNumber a, double b){ +inline DualNumber operator*(DualNumber a, double b) +{ return {a.re * b, a.du * b}; } -inline DualNumber operator/(DualNumber a, DualNumber b){ +inline DualNumber operator/(DualNumber a, DualNumber b) +{ return {a.re / b.re, (a.du * b.re - a.re * b.du) / (b.re * b.re)}; } -inline DualNumber operator/(DualNumber a, double b){ +inline DualNumber operator/(DualNumber a, double b) +{ return {a.re / b, a.du / b}; } -inline DualNumber pow(DualNumber a, double pw){ +inline DualNumber pow(DualNumber a, double pw) +{ return {std::pow(a.re, pw), pw * std::pow(a.re, pw - 1.0) * a.du}; } -} //namespace +} // namespace Base #endif diff --git a/src/Base/DualQuaternion.cpp b/src/Base/DualQuaternion.cpp index 731d074481..2dc144ad9d 100644 --- a/src/Base/DualQuaternion.cpp +++ b/src/Base/DualQuaternion.cpp @@ -28,79 +28,47 @@ Base::DualQuat Base::operator+(Base::DualQuat a, Base::DualQuat b) { - return { - a.x + b.x, - a.y + b.y, - a.z + b.z, - a.w + b.w - }; + return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; } Base::DualQuat Base::operator-(Base::DualQuat a, Base::DualQuat b) { - return { - a.x - b.x, - a.y - b.y, - a.z - b.z, - a.w - b.w - }; + return {a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; } Base::DualQuat Base::operator*(Base::DualQuat a, Base::DualQuat b) { - return { - a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z, - a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z - }; + return {a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z, + a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z}; } Base::DualQuat Base::operator*(Base::DualQuat a, double b) { - return { - a.x * b, - a.y * b, - a.z * b, - a.w * b - }; + return {a.x * b, a.y * b, a.z * b, a.w * b}; } Base::DualQuat Base::operator*(double a, Base::DualQuat b) { - return { - b.x * a, - b.y * a, - b.z * a, - b.w * a - }; + return {b.x * a, b.y * a, b.z * a, b.w * a}; } Base::DualQuat Base::operator*(Base::DualQuat a, Base::DualNumber b) { - return { - a.x * b, - a.y * b, - a.z * b, - a.w * b - }; + return {a.x * b, a.y * b, a.z * b, a.w * b}; } Base::DualQuat Base::operator*(Base::DualNumber a, Base::DualQuat b) { - return { - b.x * a, - b.y * a, - b.z * a, - b.w * a - }; + return {b.x * a, b.y * a, b.z * a, b.w * a}; } Base::DualQuat::DualQuat(Base::DualQuat re, Base::DualQuat du) - : x(re.x.re, du.x.re), - y(re.y.re, du.y.re), - z(re.z.re, du.z.re), - w(re.w.re, du.w.re) + : x(re.x.re, du.x.re) + , y(re.y.re, du.y.re) + , z(re.z.re, du.z.re) + , w(re.w.re, du.w.re) { assert(re.dual().length() < 1e-12); assert(du.dual().length() < 1e-12); @@ -108,10 +76,7 @@ Base::DualQuat::DualQuat(Base::DualQuat re, Base::DualQuat du) double Base::DualQuat::dot(Base::DualQuat a, Base::DualQuat b) { - return a.x.re * b.x.re + - a.y.re * b.y.re + - a.z.re * b.z.re + - a.w.re * b.w.re ; + return a.x.re * b.x.re + a.y.re * b.y.re + a.z.re * b.z.re + a.w.re * b.w.re; } Base::DualQuat Base::DualQuat::pow(double t, bool shorten) const @@ -135,32 +100,34 @@ Base::DualQuat Base::DualQuat::pow(double t, bool shorten) const * */ double le = this->vec().length(); if (le < 1e-12) { - //special case of no rotation. Interpolate position - return {this->real(), this->dual()*t}; + // special case of no rotation. Interpolate position + return {this->real(), this->dual() * t}; } - double normmult = 1.0/le; + double normmult = 1.0 / le; DualQuat self = *this; - if (shorten){ - if (dot(self, identity()) < -1e-12){ //using negative tolerance instead of zero, for stability in situations the choice is ambiguous (180-degree rotations) + if (shorten) { + if (dot(self, identity()) + < -1e-12) { // using negative tolerance instead of zero, for stability in situations + // the choice is ambiguous (180-degree rotations) self = -self; } } - //to screw coordinates + // to screw coordinates double theta = self.theta(); double pitch = -2.0 * self.w.du * normmult; - DualQuat l = self.real().vec() * normmult; //abusing DualQuat to store vectors. Very handy in this case. - DualQuat m = (self.dual().vec() - pitch/2*cos(theta/2)*l)*normmult; + DualQuat l = self.real().vec() + * normmult; // abusing DualQuat to store vectors. Very handy in this case. + DualQuat m = (self.dual().vec() - pitch / 2 * cos(theta / 2) * l) * normmult; - //interpolate + // interpolate theta *= t; pitch *= t; - //back to quaternion - return { - l * sin(theta/2) + DualQuat(0,0,0,cos(theta/2)), - m * sin(theta/2) + pitch / 2 * cos(theta/2) * l + DualQuat(0,0,0,-pitch/2*sin(theta/2)) - }; + // back to quaternion + return {l * sin(theta / 2) + DualQuat(0, 0, 0, cos(theta / 2)), + m * sin(theta / 2) + pitch / 2 * cos(theta / 2) * l + + DualQuat(0, 0, 0, -pitch / 2 * sin(theta / 2))}; } diff --git a/src/Base/DualQuaternion.h b/src/Base/DualQuaternion.h index 62a85a019f..467c205b17 100644 --- a/src/Base/DualQuaternion.h +++ b/src/Base/DualQuaternion.h @@ -27,7 +27,8 @@ #include -namespace Base { +namespace Base +{ /** * @brief The DualQuat class represents a dual quaternion, as a quaternion of @@ -40,58 +41,98 @@ namespace Base { * where t is quaternion with x,y,z of translation and w of 0, and r is the * rotation quaternion. */ -class BaseExport DualQuat { +class BaseExport DualQuat +{ public: DualNumber x; DualNumber y; DualNumber z; DualNumber w; + public: - ///default constructor: init with zeros + /// default constructor: init with zeros DualQuat() = default; DualQuat(DualNumber x, DualNumber y, DualNumber z, DualNumber w) - : x(x), y(y), z(z), w(w) {} - DualQuat(double x,double y,double z,double w,double dx,double dy,double dz,double dw) - : x(x, dx), y(y, dy), z(z, dz), w(w, dw) {} - DualQuat(double x,double y,double z,double w) - : x(x), y(y), z(z), w(w) {} + : x(x) + , y(y) + , z(z) + , w(w) + {} + DualQuat(double x, double y, double z, double w, double dx, double dy, double dz, double dw) + : x(x, dx) + , y(y, dy) + , z(z, dz) + , w(w, dw) + {} + DualQuat(double x, double y, double z, double w) + : x(x) + , y(y) + , z(z) + , w(w) + {} - ///Builds a dual quaternion from real and dual parts provided as pure real quaternions + /// Builds a dual quaternion from real and dual parts provided as pure real quaternions DualQuat(DualQuat re, DualQuat du); - ///returns dual quaternion for identity placement - static DualQuat identity() {return {0.0, 0.0, 0.0, 1.0};} + /// returns dual quaternion for identity placement + static DualQuat identity() + { + return {0.0, 0.0, 0.0, 1.0}; + } - ///return a copy with dual part zeroed out - DualQuat real() const {return {x.re, y.re, z.re, w.re};} + /// return a copy with dual part zeroed out + DualQuat real() const + { + return {x.re, y.re, z.re, w.re}; + } - ///return a real-only quaternion made from dual part of this quaternion. - DualQuat dual() const {return {x.du, y.du, z.du, w.du};} + /// return a real-only quaternion made from dual part of this quaternion. + DualQuat dual() const + { + return {x.du, y.du, z.du, w.du}; + } - ///conjugate - DualQuat conj() const {return {-x, -y, -z, w};} + /// conjugate + DualQuat conj() const + { + return {-x, -y, -z, w}; + } - ///return vector part (with scalar part zeroed out) - DualQuat vec() const {return {x,y,z,0.0};} + /// return vector part (with scalar part zeroed out) + DualQuat vec() const + { + return {x, y, z, 0.0}; + } - ///magnitude of the quaternion - double length() const {return sqrt(x.re*x.re + y.re*y.re + z.re*z.re + w.re*w.re);} + /// magnitude of the quaternion + double length() const + { + return sqrt(x.re * x.re + y.re * y.re + z.re * z.re + w.re * w.re); + } - ///angle of rotation represented by this quaternion, in radians - double theta() const {return 2.0 * atan2(vec().length(), w.re);} + /// angle of rotation represented by this quaternion, in radians + double theta() const + { + return 2.0 * atan2(vec().length(), w.re); + } - ///dot product between real (rotation) parts of two dual quaternions (to determine if one of them should be negated for shortest interpolation) + /// dot product between real (rotation) parts of two dual quaternions (to determine if one of + /// them should be negated for shortest interpolation) static double dot(DualQuat a, DualQuat b); - ///ScLERP. t=0.0 returns identity, t=1.0 returns this. t can also be outside of 0..1 bounds. + /// ScLERP. t=0.0 returns identity, t=1.0 returns this. t can also be outside of 0..1 bounds. DualQuat pow(double t, bool shorten = true) const; - DualQuat operator-() const {return {-x, -y, -z, -w};} + DualQuat operator-() const + { + return {-x, -y, -z, -w}; + } - //DEBUG - //void print() const { - // Console().Log("%f, %f, %f, %f; %f, %f, %f, %f", x.re,y.re,z.re,w.re, x.du,y.du,z.du, w.du); - //} + // DEBUG + // void print() const { + // Console().Log("%f, %f, %f, %f; %f, %f, %f, %f", x.re,y.re,z.re,w.re, x.du,y.du,z.du, + // w.du); + // } }; BaseExport DualQuat operator+(DualQuat a, DualQuat b); @@ -104,6 +145,6 @@ BaseExport DualQuat operator*(DualQuat a, DualNumber b); BaseExport DualQuat operator*(DualNumber a, DualQuat b); -} //namespace +} // namespace Base #endif diff --git a/src/Base/Exception.cpp b/src/Base/Exception.cpp index 9a84ccfc57..168380d8e9 100644 --- a/src/Base/Exception.cpp +++ b/src/Base/Exception.cpp @@ -34,36 +34,34 @@ FC_LOG_LEVEL_INIT("Exception", true, true) using namespace Base; -TYPESYSTEM_SOURCE(Base::Exception,Base::BaseClass) +TYPESYSTEM_SOURCE(Base::Exception, Base::BaseClass) Exception::Exception() - : _line(0) - , _isTranslatable(false) - , _isReported(false) + : _line(0) + , _isTranslatable(false) + , _isReported(false) { - _sErrMsg = "FreeCAD Exception"; + _sErrMsg = "FreeCAD Exception"; } -Exception::Exception(const Exception &inst) = default; +Exception::Exception(const Exception& inst) = default; -Exception::Exception(const char * sMessage) - : _sErrMsg(sMessage) - , _line(0) - , _isTranslatable(false) - , _isReported(false) -{ -} +Exception::Exception(const char* sMessage) + : _sErrMsg(sMessage) + , _line(0) + , _isTranslatable(false) + , _isReported(false) +{} Exception::Exception(const std::string& sMessage) - : _sErrMsg(sMessage) - , _line(0) - , _isTranslatable(false) - , _isReported(false) -{ -} + : _sErrMsg(sMessage) + , _line(0) + , _isTranslatable(false) + , _isReported(false) +{} -Exception &Exception::operator=(const Exception &inst) +Exception& Exception::operator=(const Exception& inst) { _sErrMsg = inst._sErrMsg; _file = inst._file; @@ -77,25 +75,28 @@ const char* Exception::what() const noexcept return _sErrMsg.c_str(); } -void Exception::ReportException () const +void Exception::ReportException() const { if (!_isReported) { - const char *msg{}; - if (_sErrMsg.empty()) + const char* msg {}; + if (_sErrMsg.empty()) { msg = typeid(*this).name(); - else + } + else { msg = _sErrMsg.c_str(); + } #ifdef FC_DEBUG if (_function.size()) { - _FC_ERR(_file.c_str(),_line, _function << " -- " << msg); - } else + _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); + } + else #endif - _FC_ERR(_file.c_str(),_line,msg); + _FC_ERR(_file.c_str(), _line, msg); _isReported = true; } } -PyObject * Exception::getPyObject() +PyObject* Exception::getPyObject() { Py::Dict edict; edict.setItem("sclassname", Py::String(typeid(*this).name())); @@ -109,34 +110,40 @@ PyObject * Exception::getPyObject() return Py::new_reference_to(edict); } -void Exception::setPyObject( PyObject * pydict) +void Exception::setPyObject(PyObject* pydict) { try { if (pydict && Py::_Dict_Check(pydict)) { Py::Dict edict(pydict); - if (edict.hasKey("sfile")) + if (edict.hasKey("sfile")) { _file = static_cast(Py::String(edict.getItem("sfile"))); + } - if (edict.hasKey("sfunction")) + if (edict.hasKey("sfunction")) { _function = static_cast(Py::String(edict.getItem("sfunction"))); + } - if (edict.hasKey("sErrMsg")) + if (edict.hasKey("sErrMsg")) { _sErrMsg = static_cast(Py::String(edict.getItem("sErrMsg"))); + } - if (edict.hasKey("iline")) + if (edict.hasKey("iline")) { _line = static_cast(Py::Long(edict.getItem("iline"))); - if (edict.hasKey("btranslatable")) + } + if (edict.hasKey("btranslatable")) { _isTranslatable = static_cast(Py::Boolean(edict.getItem("btranslatable"))); - if (edict.hasKey("breported")) + } + if (edict.hasKey("breported")) { _isReported = static_cast(Py::Boolean(edict.getItem("breported"))); + } } } catch (Py::Exception& e) { - e.clear(); // should never happen + e.clear(); // should never happen } } -PyObject * Exception::getPyExceptionType() const +PyObject* Exception::getPyExceptionType() const { return PyExc_FC_GeneralError; } @@ -153,12 +160,11 @@ void Exception::setPyException() const // --------------------------------------------------------- -TYPESYSTEM_SOURCE(Base::AbortException,Base::Exception) +TYPESYSTEM_SOURCE(Base::AbortException, Base::Exception) -AbortException::AbortException(const char * sMessage) - : Exception( sMessage ) -{ -} +AbortException::AbortException(const char* sMessage) + : Exception(sMessage) +{} AbortException::AbortException() { @@ -170,7 +176,7 @@ const char* AbortException::what() const noexcept return Exception::what(); } -PyObject * AbortException::getPyExceptionType() const +PyObject* AbortException::getPyExceptionType() const { return PyExc_FC_FreeCADAbort; } @@ -179,36 +185,31 @@ PyObject * AbortException::getPyExceptionType() const XMLBaseException::XMLBaseException() - : Exception() -{ -} + : Exception() +{} -XMLBaseException::XMLBaseException(const char * sMessage) - : Exception(sMessage) -{ -} +XMLBaseException::XMLBaseException(const char* sMessage) + : Exception(sMessage) +{} XMLBaseException::XMLBaseException(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * XMLBaseException::getPyExceptionType() const +PyObject* XMLBaseException::getPyExceptionType() const { return PyExc_FC_XMLBaseException; } // --------------------------------------------------------- -XMLParseException::XMLParseException(const char * sMessage) - : XMLBaseException(sMessage) -{ -} +XMLParseException::XMLParseException(const char* sMessage) + : XMLBaseException(sMessage) +{} XMLParseException::XMLParseException(const std::string& sMessage) - : XMLBaseException(sMessage) -{ -} + : XMLBaseException(sMessage) +{} XMLParseException::XMLParseException() { @@ -220,22 +221,20 @@ const char* XMLParseException::what() const noexcept return XMLBaseException::what(); } -PyObject * XMLParseException::getPyExceptionType() const +PyObject* XMLParseException::getPyExceptionType() const { return PyExc_FC_XMLParseException; } // --------------------------------------------------------- -XMLAttributeError::XMLAttributeError(const char * sMessage) - : XMLBaseException(sMessage) -{ -} +XMLAttributeError::XMLAttributeError(const char* sMessage) + : XMLBaseException(sMessage) +{} XMLAttributeError::XMLAttributeError(const std::string& sMessage) - : XMLBaseException(sMessage) -{ -} + : XMLBaseException(sMessage) +{} XMLAttributeError::XMLAttributeError() { @@ -247,7 +246,7 @@ const char* XMLAttributeError::what() const noexcept return XMLBaseException::what(); } -PyObject * XMLAttributeError::getPyExceptionType() const +PyObject* XMLAttributeError::getPyExceptionType() const { return PyExc_FC_XMLAttributeError; } @@ -255,25 +254,27 @@ PyObject * XMLAttributeError::getPyExceptionType() const // --------------------------------------------------------- -FileException::FileException(const char * sMessage, const char * sFileName) - : Exception( sMessage ),file(sFileName) +FileException::FileException(const char* sMessage, const char* sFileName) + : Exception(sMessage) + , file(sFileName) { setFileName(sFileName); } -FileException::FileException(const char * sMessage, const FileInfo& File) - : Exception( sMessage ),file(File) +FileException::FileException(const char* sMessage, const FileInfo& File) + : Exception(sMessage) + , file(File) { setFileName(File.filePath().c_str()); } FileException::FileException() - : Exception( "Unknown file exception happened" ) + : Exception("Unknown file exception happened") { _sErrMsgAndFileName = _sErrMsg; } -void FileException::setFileName(const char * sFileName) +void FileException::setFileName(const char* sFileName) { file.setFile(sFileName); _sErrMsgAndFileName = _sErrMsg; @@ -288,9 +289,9 @@ std::string FileException::getFileName() const return file.fileName(); } -FileException & FileException::operator=(const FileException &inst) +FileException& FileException::operator=(const FileException& inst) { - Exception::operator = (inst); + Exception::operator=(inst); file = inst.file; _sErrMsgAndFileName = inst._sErrMsgAndFileName; return *this; @@ -301,43 +302,47 @@ const char* FileException::what() const noexcept return _sErrMsgAndFileName.c_str(); } -void FileException::ReportException () const +void FileException::ReportException() const { if (!_isReported) { - const char *msg{}; - if (_sErrMsgAndFileName.empty()) + const char* msg {}; + if (_sErrMsgAndFileName.empty()) { msg = typeid(*this).name(); - else + } + else { msg = _sErrMsgAndFileName.c_str(); + } #ifdef FC_DEBUG if (_function.size()) { - _FC_ERR(_file.c_str(),_line, _function << " -- " << msg); - } else + _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); + } + else #endif - _FC_ERR(_file.c_str(),_line,msg); + _FC_ERR(_file.c_str(), _line, msg); _isReported = true; } } -PyObject * FileException::getPyObject() +PyObject* FileException::getPyObject() { Py::Dict edict(Exception::getPyObject(), true); edict.setItem("filename", Py::String(this->file.fileName())); return Py::new_reference_to(edict); } -void FileException::setPyObject( PyObject * pydict) +void FileException::setPyObject(PyObject* pydict) { if (pydict) { Exception::setPyObject(pydict); Py::Dict edict(pydict); - if (edict.hasKey("filename")) + if (edict.hasKey("filename")) { setFileName(Py::String(edict.getItem("filename")).as_std_string("utf-8").c_str()); + } } } -PyObject * FileException::getPyExceptionType() const +PyObject* FileException::getPyExceptionType() const { return PyExc_IOError; } @@ -346,21 +351,18 @@ PyObject * FileException::getPyExceptionType() const FileSystemError::FileSystemError() - : Exception() -{ -} + : Exception() +{} -FileSystemError::FileSystemError(const char * sMessage) - : Exception(sMessage) -{ -} +FileSystemError::FileSystemError(const char* sMessage) + : Exception(sMessage) +{} FileSystemError::FileSystemError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * FileSystemError::getPyExceptionType() const +PyObject* FileSystemError::getPyExceptionType() const { return PyExc_IOError; } @@ -369,21 +371,18 @@ PyObject * FileSystemError::getPyExceptionType() const BadFormatError::BadFormatError() - : Exception() -{ -} + : Exception() +{} -BadFormatError::BadFormatError(const char * sMessage) - : Exception(sMessage) -{ -} +BadFormatError::BadFormatError(const char* sMessage) + : Exception(sMessage) +{} BadFormatError::BadFormatError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * BadFormatError::getPyExceptionType() const +PyObject* BadFormatError::getPyExceptionType() const { return PyExc_FC_BadFormatError; } @@ -396,22 +395,22 @@ MemoryException::MemoryException() _sErrMsg = "Not enough memory available"; } -MemoryException::MemoryException(const MemoryException &inst) -#if defined (__GNUC__) - : std::bad_alloc(), Exception(inst) +MemoryException::MemoryException(const MemoryException& inst) +#if defined(__GNUC__) + : std::bad_alloc() + , Exception(inst) #else - : Exception(inst) + : Exception(inst) #endif -{ -} +{} -MemoryException & MemoryException::operator=(const MemoryException &inst) +MemoryException& MemoryException::operator=(const MemoryException& inst) { - Exception::operator = (inst); + Exception::operator=(inst); return *this; } -#if defined (__GNUC__) +#if defined(__GNUC__) const char* MemoryException::what() const noexcept { // call what() of Exception, not of std::bad_alloc @@ -419,7 +418,7 @@ const char* MemoryException::what() const noexcept } #endif -PyObject * MemoryException::getPyExceptionType() const +PyObject* MemoryException::getPyExceptionType() const { return PyExc_MemoryError; } @@ -431,17 +430,15 @@ AccessViolation::AccessViolation() _sErrMsg = "Access violation"; } -AccessViolation::AccessViolation(const char * sMessage) - : Exception(sMessage) -{ -} +AccessViolation::AccessViolation(const char* sMessage) + : Exception(sMessage) +{} AccessViolation::AccessViolation(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *AccessViolation::getPyExceptionType() const +PyObject* AccessViolation::getPyExceptionType() const { return PyExc_OSError; } @@ -453,17 +450,15 @@ AbnormalProgramTermination::AbnormalProgramTermination() _sErrMsg = "Abnormal program termination"; } -AbnormalProgramTermination::AbnormalProgramTermination(const char * sMessage) - : Exception(sMessage) -{ -} +AbnormalProgramTermination::AbnormalProgramTermination(const char* sMessage) + : Exception(sMessage) +{} AbnormalProgramTermination::AbnormalProgramTermination(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *AbnormalProgramTermination::getPyExceptionType() const +PyObject* AbnormalProgramTermination::getPyExceptionType() const { return PyExc_InterruptedError; } @@ -471,21 +466,18 @@ PyObject *AbnormalProgramTermination::getPyExceptionType() const // --------------------------------------------------------- UnknownProgramOption::UnknownProgramOption() - : Exception() -{ -} + : Exception() +{} -UnknownProgramOption::UnknownProgramOption(const char * sMessage) - : Exception(sMessage) -{ -} +UnknownProgramOption::UnknownProgramOption(const char* sMessage) + : Exception(sMessage) +{} UnknownProgramOption::UnknownProgramOption(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *UnknownProgramOption::getPyExceptionType() const +PyObject* UnknownProgramOption::getPyExceptionType() const { return PyExc_FC_UnknownProgramOption; } @@ -493,38 +485,32 @@ PyObject *UnknownProgramOption::getPyExceptionType() const // --------------------------------------------------------- ProgramInformation::ProgramInformation() - : Exception() -{ -} + : Exception() +{} -ProgramInformation::ProgramInformation(const char * sMessage) - : Exception(sMessage) -{ -} +ProgramInformation::ProgramInformation(const char* sMessage) + : Exception(sMessage) +{} ProgramInformation::ProgramInformation(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} // --------------------------------------------------------- TypeError::TypeError() - : Exception() -{ -} + : Exception() +{} -TypeError::TypeError(const char * sMessage) - : Exception(sMessage) -{ -} +TypeError::TypeError(const char* sMessage) + : Exception(sMessage) +{} TypeError::TypeError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *TypeError::getPyExceptionType() const +PyObject* TypeError::getPyExceptionType() const { return PyExc_TypeError; } @@ -532,21 +518,18 @@ PyObject *TypeError::getPyExceptionType() const // --------------------------------------------------------- ValueError::ValueError() - : Exception() -{ -} + : Exception() +{} -ValueError::ValueError(const char * sMessage) - : Exception(sMessage) -{ -} +ValueError::ValueError(const char* sMessage) + : Exception(sMessage) +{} ValueError::ValueError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *ValueError::getPyExceptionType() const +PyObject* ValueError::getPyExceptionType() const { return PyExc_ValueError; } @@ -554,21 +537,18 @@ PyObject *ValueError::getPyExceptionType() const // --------------------------------------------------------- IndexError::IndexError() - : Exception() -{ -} + : Exception() +{} -IndexError::IndexError(const char * sMessage) - : Exception(sMessage) -{ -} +IndexError::IndexError(const char* sMessage) + : Exception(sMessage) +{} IndexError::IndexError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *IndexError::getPyExceptionType() const +PyObject* IndexError::getPyExceptionType() const { return PyExc_IndexError; } @@ -576,21 +556,18 @@ PyObject *IndexError::getPyExceptionType() const // --------------------------------------------------------- NameError::NameError() - : Exception() -{ -} + : Exception() +{} -NameError::NameError(const char * sMessage) - : Exception(sMessage) -{ -} +NameError::NameError(const char* sMessage) + : Exception(sMessage) +{} NameError::NameError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *NameError::getPyExceptionType() const +PyObject* NameError::getPyExceptionType() const { return PyExc_NameError; } @@ -598,21 +575,18 @@ PyObject *NameError::getPyExceptionType() const // --------------------------------------------------------- ImportError::ImportError() - : Exception() -{ -} + : Exception() +{} -ImportError::ImportError(const char * sMessage) - : Exception(sMessage) -{ -} +ImportError::ImportError(const char* sMessage) + : Exception(sMessage) +{} ImportError::ImportError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *ImportError::getPyExceptionType() const +PyObject* ImportError::getPyExceptionType() const { return PyExc_ImportError; } @@ -620,21 +594,18 @@ PyObject *ImportError::getPyExceptionType() const // --------------------------------------------------------- AttributeError::AttributeError() - : Exception() -{ -} + : Exception() +{} -AttributeError::AttributeError(const char * sMessage) - : Exception(sMessage) -{ -} +AttributeError::AttributeError(const char* sMessage) + : Exception(sMessage) +{} AttributeError::AttributeError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *AttributeError::getPyExceptionType() const +PyObject* AttributeError::getPyExceptionType() const { return PyExc_AttributeError; } @@ -642,21 +613,18 @@ PyObject *AttributeError::getPyExceptionType() const // --------------------------------------------------------- RuntimeError::RuntimeError() - : Exception() -{ -} + : Exception() +{} -RuntimeError::RuntimeError(const char * sMessage) - : Exception(sMessage) -{ -} +RuntimeError::RuntimeError(const char* sMessage) + : Exception(sMessage) +{} RuntimeError::RuntimeError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *RuntimeError::getPyExceptionType() const +PyObject* RuntimeError::getPyExceptionType() const { return PyExc_RuntimeError; } @@ -664,21 +632,18 @@ PyObject *RuntimeError::getPyExceptionType() const // --------------------------------------------------------- BadGraphError::BadGraphError() - : RuntimeError("The graph must be a DAG.") -{ -} + : RuntimeError("The graph must be a DAG.") +{} -BadGraphError::BadGraphError(const char * sMessage) - : RuntimeError(sMessage) -{ -} +BadGraphError::BadGraphError(const char* sMessage) + : RuntimeError(sMessage) +{} BadGraphError::BadGraphError(const std::string& sMessage) - : RuntimeError(sMessage) -{ -} + : RuntimeError(sMessage) +{} -PyObject *BadGraphError::getPyExceptionType() const +PyObject* BadGraphError::getPyExceptionType() const { return PyExc_FC_BadGraphError; } @@ -686,21 +651,18 @@ PyObject *BadGraphError::getPyExceptionType() const // --------------------------------------------------------- NotImplementedError::NotImplementedError() - : Exception() -{ -} + : Exception() +{} -NotImplementedError::NotImplementedError(const char * sMessage) - : Exception(sMessage) -{ -} +NotImplementedError::NotImplementedError(const char* sMessage) + : Exception(sMessage) +{} NotImplementedError::NotImplementedError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *NotImplementedError::getPyExceptionType() const +PyObject* NotImplementedError::getPyExceptionType() const { return PyExc_NotImplementedError; } @@ -708,21 +670,18 @@ PyObject *NotImplementedError::getPyExceptionType() const // --------------------------------------------------------- ZeroDivisionError::ZeroDivisionError() - : Exception() -{ -} + : Exception() +{} -ZeroDivisionError::ZeroDivisionError(const char * sMessage) - : Exception(sMessage) -{ -} +ZeroDivisionError::ZeroDivisionError(const char* sMessage) + : Exception(sMessage) +{} ZeroDivisionError::ZeroDivisionError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *ZeroDivisionError::getPyExceptionType() const +PyObject* ZeroDivisionError::getPyExceptionType() const { return PyExc_ZeroDivisionError; } @@ -730,21 +689,18 @@ PyObject *ZeroDivisionError::getPyExceptionType() const // --------------------------------------------------------- ReferenceError::ReferenceError() -: Exception() -{ -} + : Exception() +{} -ReferenceError::ReferenceError(const char * sMessage) - : Exception(sMessage) -{ -} +ReferenceError::ReferenceError(const char* sMessage) + : Exception(sMessage) +{} ReferenceError::ReferenceError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *ReferenceError::getPyExceptionType() const +PyObject* ReferenceError::getPyExceptionType() const { return PyExc_ReferenceError; } @@ -752,21 +708,18 @@ PyObject *ReferenceError::getPyExceptionType() const // --------------------------------------------------------- ExpressionError::ExpressionError() - : Exception() -{ -} + : Exception() +{} -ExpressionError::ExpressionError(const char * sMessage) - : Exception(sMessage) -{ -} +ExpressionError::ExpressionError(const char* sMessage) + : Exception(sMessage) +{} ExpressionError::ExpressionError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * ExpressionError::getPyExceptionType() const +PyObject* ExpressionError::getPyExceptionType() const { return PyExc_FC_ExpressionError; } @@ -774,21 +727,18 @@ PyObject * ExpressionError::getPyExceptionType() const // --------------------------------------------------------- ParserError::ParserError() - : Exception() -{ -} + : Exception() +{} -ParserError::ParserError(const char * sMessage) - : Exception(sMessage) -{ -} +ParserError::ParserError(const char* sMessage) + : Exception(sMessage) +{} ParserError::ParserError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * ParserError::getPyExceptionType() const +PyObject* ParserError::getPyExceptionType() const { return PyExc_FC_ParserError; } @@ -796,21 +746,18 @@ PyObject * ParserError::getPyExceptionType() const // --------------------------------------------------------- UnicodeError::UnicodeError() - : Exception() -{ -} + : Exception() +{} -UnicodeError::UnicodeError(const char * sMessage) - : Exception(sMessage) -{ -} +UnicodeError::UnicodeError(const char* sMessage) + : Exception(sMessage) +{} UnicodeError::UnicodeError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *UnicodeError::getPyExceptionType() const +PyObject* UnicodeError::getPyExceptionType() const { return PyExc_UnicodeError; } @@ -818,21 +765,18 @@ PyObject *UnicodeError::getPyExceptionType() const // --------------------------------------------------------- OverflowError::OverflowError() - : Exception() -{ -} + : Exception() +{} -OverflowError::OverflowError(const char * sMessage) - : Exception(sMessage) -{ -} +OverflowError::OverflowError(const char* sMessage) + : Exception(sMessage) +{} OverflowError::OverflowError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *OverflowError::getPyExceptionType() const +PyObject* OverflowError::getPyExceptionType() const { return PyExc_OverflowError; } @@ -840,21 +784,18 @@ PyObject *OverflowError::getPyExceptionType() const // --------------------------------------------------------- UnderflowError::UnderflowError() - : Exception() -{ -} + : Exception() +{} -UnderflowError::UnderflowError(const char * sMessage) - : Exception(sMessage) -{ -} +UnderflowError::UnderflowError(const char* sMessage) + : Exception(sMessage) +{} UnderflowError::UnderflowError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *UnderflowError::getPyExceptionType() const +PyObject* UnderflowError::getPyExceptionType() const { return PyExc_ArithmeticError; } @@ -862,21 +803,18 @@ PyObject *UnderflowError::getPyExceptionType() const // --------------------------------------------------------- UnitsMismatchError::UnitsMismatchError() - : Exception() -{ -} + : Exception() +{} -UnitsMismatchError::UnitsMismatchError(const char * sMessage) - : Exception(sMessage) -{ -} +UnitsMismatchError::UnitsMismatchError(const char* sMessage) + : Exception(sMessage) +{} UnitsMismatchError::UnitsMismatchError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject *UnitsMismatchError::getPyExceptionType() const +PyObject* UnitsMismatchError::getPyExceptionType() const { return PyExc_ArithmeticError; } @@ -884,21 +822,18 @@ PyObject *UnitsMismatchError::getPyExceptionType() const // --------------------------------------------------------- CADKernelError::CADKernelError() - : Exception() -{ -} + : Exception() +{} -CADKernelError::CADKernelError(const char * sMessage) - : Exception(sMessage) -{ -} +CADKernelError::CADKernelError(const char* sMessage) + : Exception(sMessage) +{} CADKernelError::CADKernelError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * CADKernelError::getPyExceptionType() const +PyObject* CADKernelError::getPyExceptionType() const { return PyExc_FC_CADKernelError; } @@ -906,38 +841,35 @@ PyObject * CADKernelError::getPyExceptionType() const // --------------------------------------------------------- RestoreError::RestoreError() - : Exception() -{ -} + : Exception() +{} -RestoreError::RestoreError(const char * sMessage) - : Exception(sMessage) -{ -} +RestoreError::RestoreError(const char* sMessage) + : Exception(sMessage) +{} RestoreError::RestoreError(const std::string& sMessage) - : Exception(sMessage) -{ -} + : Exception(sMessage) +{} -PyObject * RestoreError::getPyExceptionType() const +PyObject* RestoreError::getPyExceptionType() const { return PyExc_IOError; } // --------------------------------------------------------- -#if defined(__GNUC__) && defined (FC_OS_LINUX) +#if defined(__GNUC__) && defined(FC_OS_LINUX) #include #include SignalException::SignalException() { - memset (&new_action, 0, sizeof (new_action)); + memset(&new_action, 0, sizeof(new_action)); new_action.sa_handler = throw_signal; - sigemptyset (&new_action.sa_mask); + sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; - ok = (sigaction (SIGSEGV, &new_action, &old_action) < 0); + ok = (sigaction(SIGSEGV, &new_action, &old_action) < 0); #ifdef _DEBUG std::cout << "Set new signal handler" << std::endl; #endif @@ -945,7 +877,7 @@ SignalException::SignalException() SignalException::~SignalException() { - sigaction (SIGSEGV, &old_action, nullptr); + sigaction(SIGSEGV, &old_action, nullptr); #ifdef _DEBUG std::cout << "Restore old signal handler" << std::endl; #endif @@ -954,7 +886,6 @@ SignalException::~SignalException() void SignalException::throw_signal(int signum) { std::cerr << "SIGSEGV signal raised: " << signum << std::endl; - throw std::runtime_error ("throw_signal"); + throw std::runtime_error("throw_signal"); } #endif - diff --git a/src/Base/Exception.h b/src/Base/Exception.h index a36a047ff3..c93bf7218b 100644 --- a/src/Base/Exception.h +++ b/src/Base/Exception.h @@ -39,115 +39,224 @@ using PyObject = struct _object; /// If you want to mark text for translation, use the QT_TRANSLATE_NOOP macro /// with the context "Exceptions" and the right throwing macro from below (the one ending in T) /// example: -/// THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions","The multiplicity cannot be increased beyond the degree of the B-Spline.")); +/// THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions","The multiplicity cannot be increased +/// beyond the degree of the B-Spline.")); /// -/// N.B.: The QT_TRANSLATE_NOOP macro won't translate your string. It will just allow lupdate to identify that string for translation so that -/// if you ask for a translation (and the translator have provided one) at that time it gets translated (e.g. in the UI before showing the message -/// of the exception). +/// N.B.: The QT_TRANSLATE_NOOP macro won't translate your string. It will just allow lupdate to +/// identify that string for translation so that if you ask for a translation (and the translator +/// have provided one) at that time it gets translated (e.g. in the UI before showing the message of +/// the exception). #ifdef _MSC_VER -# define THROW(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); throw myexcp;} -# define THROWM(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); throw myexcp;} -# define THROWMF_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); throw myexcp;} +#define THROW(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + throw myexcp; \ + } +#define THROWM(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + throw myexcp; \ + } +#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + throw myexcp; \ + } -# define THROWT(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMT(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMFT_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__FUNCSIG__); myexcp.setTranslatable(true); throw myexcp;} +#define THROWT(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMT(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } #elif defined(__GNUC__) -# define THROW(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); throw myexcp;} -# define THROWM(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); throw myexcp;} -# define THROWMF_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); throw myexcp;} +#define THROW(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + throw myexcp; \ + } +#define THROWM(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + throw myexcp; \ + } +#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + throw myexcp; \ + } -# define THROWT(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMT(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMFT_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__PRETTY_FUNCTION__); myexcp.setTranslatable(true); throw myexcp;} +#define THROWT(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMT(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } #else -# define THROW(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__func__); throw myexcp;} -# define THROWM(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__func__); throw myexcp;} -# define THROWMF_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__func__); throw myexcp;} +#define THROW(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + throw myexcp; \ + } +#define THROWM(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + throw myexcp; \ + } +#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + throw myexcp; \ + } -# define THROWT(exception) {exception myexcp; myexcp.setDebugInformation(__FILE__,__LINE__,__func__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMT(exception, message) {exception myexcp(message); myexcp.setDebugInformation(__FILE__,__LINE__,__func__); myexcp.setTranslatable(true); throw myexcp;} -# define THROWMFT_FILEEXCEPTION(message,filenameorfileinfo) {FileException myexcp(message, filenameorfileinfo); myexcp.setDebugInformation(__FILE__,__LINE__,__func__); myexcp.setTranslatable(true); throw myexcp;} +#define THROWT(exception) \ + { \ + exception myexcp; \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMT(exception, message) \ + { \ + exception myexcp(message); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } +#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ + { \ + FileException myexcp(message, filenameorfileinfo); \ + myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ + myexcp.setTranslatable(true); \ + throw myexcp; \ + } #endif -#define FC_THROWM(_exception,_msg) do {\ - std::stringstream ss;\ - ss << _msg;\ - THROWM(_exception,ss.str().c_str());\ -}while(0) +#define FC_THROWM(_exception, _msg) \ + do { \ + std::stringstream ss; \ + ss << _msg; \ + THROWM(_exception, ss.str().c_str()); \ + } while (0) namespace Base { -class BaseExport Exception : public BaseClass +class BaseExport Exception: public BaseClass { - TYPESYSTEM_HEADER_WITH_OVERRIDE(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: + ~Exception() noexcept override = default; - ~Exception() noexcept override = default; + Exception& operator=(const Exception& inst); - Exception &operator=(const Exception &inst); + virtual const char* what() const noexcept; - virtual const char* what() const noexcept; + /// Reports exception. It includes a mechanism to only report an exception once. + virtual void ReportException() const; - /// Reports exception. It includes a mechanism to only report an exception once. - virtual void ReportException () const; + inline void setMessage(const char* sMessage); + inline void setMessage(const std::string& sMessage); + // what may differ from the message given by the user in + // derived classes + inline std::string getMessage() const; + inline std::string getFile() const; + inline int getLine() const; + inline std::string getFunction() const; + inline bool getTranslatable() const; + inline bool getReported() const + { + return _isReported; + } - inline void setMessage(const char * sMessage); - inline void setMessage(const std::string& sMessage); - // what may differ from the message given by the user in - // derived classes - inline std::string getMessage() const; - inline std::string getFile() const; - inline int getLine() const; - inline std::string getFunction() const; - inline bool getTranslatable() const; - inline bool getReported() const { return _isReported; } + /// setter methods for including debug information + /// intended to use via macro for autofilling of debugging information + inline void + setDebugInformation(const std::string& file, const int line, const std::string& function); - /// setter methods for including debug information - /// intended to use via macro for autofilling of debugging information - inline void setDebugInformation(const std::string & file, const int line, const std::string & function); + inline void setTranslatable(bool translatable); - inline void setTranslatable(bool translatable); + inline void setReported(bool reported) + { + _isReported = reported; + } - inline void setReported(bool reported) { _isReported = reported; } + /// returns a Python dictionary containing the exception data + PyObject* getPyObject() override; + /// returns sets the exception data from a Python dictionary + void setPyObject(PyObject* pydict) override; - /// returns a Python dictionary containing the exception data - PyObject * getPyObject() override; - /// returns sets the exception data from a Python dictionary - void setPyObject( PyObject * pydict) override; - - /// returns the corresponding python exception type - virtual PyObject * getPyExceptionType() const; - /// Sets the Python error indicator and an error message - virtual void setPyException() const; + /// returns the corresponding python exception type + virtual PyObject* getPyExceptionType() const; + /// Sets the Python error indicator and an error message + virtual void setPyException() const; protected: - /* sMessage may be: - * - a UI compliant string susceptible to being translated and shown to the user in the UI - * - a very technical message not intended to be translated or shown to the user in the UI - * The preferred way of throwing an exception is using the macros above. - * This way, the file, line, and function are automatically inserted. */ - Exception(const char * sMessage); - Exception(const std::string& sMessage); - Exception(); - Exception(const Exception &inst); + /* sMessage may be: + * - a UI compliant string susceptible to being translated and shown to the user in the UI + * - a very technical message not intended to be translated or shown to the user in the UI + * The preferred way of throwing an exception is using the macros above. + * This way, the file, line, and function are automatically inserted. */ + Exception(const char* sMessage); + Exception(const std::string& sMessage); + Exception(); + Exception(const Exception& inst); protected: - std::string _sErrMsg; - std::string _file; - int _line; - std::string _function; - bool _isTranslatable; - mutable bool _isReported; + std::string _sErrMsg; + std::string _file; + int _line; + std::string _function; + bool _isTranslatable; + mutable bool _isReported; }; @@ -155,119 +264,121 @@ protected: * The AbortException is thrown if a pending operation was aborted. * @author Werner Mayer */ -class BaseExport AbortException : public Exception +class BaseExport AbortException: public Exception { - TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: - /// Construction - AbortException(const char * sMessage); - /// Construction - AbortException(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); - /// Destruction - ~AbortException() noexcept override = default; - /// Description of the exception - const char* what() const noexcept override; - /// returns the corresponding python exception type - PyObject * getPyExceptionType() const override; +public: + /// Construction + AbortException(const char* sMessage); + /// Construction + AbortException(); + + /// Destruction + ~AbortException() noexcept override = default; + /// Description of the exception + const char* what() const noexcept override; + /// returns the corresponding python exception type + PyObject* getPyExceptionType() const override; }; /** * The XMLBaseException can be used to indicate any kind of XML related errors. * @author Werner Mayer */ -class BaseExport XMLBaseException : public Exception +class BaseExport XMLBaseException: public Exception { public: - /// Construction - XMLBaseException(); - XMLBaseException(const char * sMessage); - XMLBaseException(const std::string& sMessage); + /// Construction + XMLBaseException(); + XMLBaseException(const char* sMessage); + XMLBaseException(const std::string& sMessage); - /// Destruction - ~XMLBaseException() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Destruction + ~XMLBaseException() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The XMLParseException is thrown if parsing an XML failed. * @author Werner Mayer */ -class BaseExport XMLParseException : public XMLBaseException +class BaseExport XMLParseException: public XMLBaseException { public: - /// Construction - XMLParseException(const char * sMessage); - /// Construction - XMLParseException(const std::string& sMessage); - /// Construction - XMLParseException(); + /// Construction + XMLParseException(const char* sMessage); + /// Construction + XMLParseException(const std::string& sMessage); + /// Construction + XMLParseException(); - /// Destruction - ~XMLParseException() noexcept override = default; - /// Description of the exception - const char* what() const noexcept override; - PyObject * getPyExceptionType() const override; + /// Destruction + ~XMLParseException() noexcept override = default; + /// Description of the exception + const char* what() const noexcept override; + PyObject* getPyExceptionType() const override; }; /** * The XMLAttributeError is thrown if a requested attribute doesn't exist. * @author Werner Mayer */ -class BaseExport XMLAttributeError : public XMLBaseException +class BaseExport XMLAttributeError: public XMLBaseException { public: - /// Construction - XMLAttributeError(const char * sMessage); - /// Construction - XMLAttributeError(const std::string& sMessage); - /// Construction - XMLAttributeError(); + /// Construction + XMLAttributeError(const char* sMessage); + /// Construction + XMLAttributeError(const std::string& sMessage); + /// Construction + XMLAttributeError(); - /// Destruction - ~XMLAttributeError() noexcept override = default; - /// Description of the exception - const char* what() const noexcept override; - PyObject * getPyExceptionType() const override; + /// Destruction + ~XMLAttributeError() noexcept override = default; + /// Description of the exception + const char* what() const noexcept override; + PyObject* getPyExceptionType() const override; }; /** File exception handling class * This class is specialized to go with exception thrown in case of File IO Problems. * @author Juergen Riegel */ -class BaseExport FileException : public Exception +class BaseExport FileException: public Exception { public: - /// With massage and file name - FileException(const char * sMessage, const char * sFileName=nullptr); - /// With massage and file name - FileException(const char * sMessage, const FileInfo& File); - /// standard construction - FileException(); - /// Construction - FileException(const FileException&) = default; - /// Destruction - ~FileException() noexcept override = default; - /// Assignment operator - FileException &operator=(const FileException &inst); - /// Description of the exception - const char* what() const noexcept override; - /// Report generation - void ReportException () const override; - /// Get file name for use with translatable message - std::string getFileName() const; - /// returns a Python dictionary containing the exception data - PyObject * getPyObject() override; - /// returns sets the exception data from a Python dictionary - void setPyObject( PyObject * pydict) override; + /// With massage and file name + FileException(const char* sMessage, const char* sFileName = nullptr); + /// With massage and file name + FileException(const char* sMessage, const FileInfo& File); + /// standard construction + FileException(); + /// Construction + FileException(const FileException&) = default; + /// Destruction + ~FileException() noexcept override = default; + /// Assignment operator + FileException& operator=(const FileException& inst); + /// Description of the exception + const char* what() const noexcept override; + /// Report generation + void ReportException() const override; + /// Get file name for use with translatable message + std::string getFileName() const; + /// returns a Python dictionary containing the exception data + PyObject* getPyObject() override; + /// returns sets the exception data from a Python dictionary + void setPyObject(PyObject* pydict) override; + + PyObject* getPyExceptionType() const override; - PyObject * getPyExceptionType() const override; protected: - FileInfo file; - // necessary for what() legacy behaviour as it returns a buffer that - // can not be of a temporary object to be destroyed at end of what() - std::string _sErrMsgAndFileName; - void setFileName(const char * sFileName=nullptr); + FileInfo file; + // necessary for what() legacy behaviour as it returns a buffer that + // can not be of a temporary object to be destroyed at end of what() + std::string _sErrMsgAndFileName; + void setFileName(const char* sFileName = nullptr); }; /** @@ -275,292 +386,292 @@ protected: * e.g. if renaming of a file failed. * @author Werner Mayer */ -class BaseExport FileSystemError : public Exception +class BaseExport FileSystemError: public Exception { public: - /// Construction - FileSystemError(); - FileSystemError(const char * sMessage); - FileSystemError(const std::string& sMessage); - /// Destruction - ~FileSystemError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + FileSystemError(); + FileSystemError(const char* sMessage); + FileSystemError(const std::string& sMessage); + /// Destruction + ~FileSystemError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The BadFormatError can be used to indicate errors in a data structure. * @author Werner Mayer */ -class BaseExport BadFormatError : public Exception +class BaseExport BadFormatError: public Exception { public: - /// Construction - BadFormatError(); - BadFormatError(const char * sMessage); - BadFormatError(const std::string& sMessage); - /// Destruction - ~BadFormatError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + BadFormatError(); + BadFormatError(const char* sMessage); + BadFormatError(const std::string& sMessage); + /// Destruction + ~BadFormatError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The MemoryException is thrown if not enough memory can be allocated. * @author Werner Mayer */ -#if defined (__GNUC__) +#if defined(__GNUC__) // It seems that the calling instance of our new handler expects a bad_alloc exception -class BaseExport MemoryException : public Exception, virtual public std::bad_alloc +class BaseExport MemoryException: public Exception, virtual public std::bad_alloc #else -class BaseExport MemoryException : public Exception +class BaseExport MemoryException: public Exception #endif { public: - /// Construction - MemoryException(); - /// Construction - MemoryException(const MemoryException &inst); - /// Destruction - ~MemoryException() noexcept override = default; - /// Assignment operator - MemoryException &operator=(const MemoryException &inst); -#if defined (__GNUC__) - /// Description of the exception - const char* what() const noexcept override; + /// Construction + MemoryException(); + /// Construction + MemoryException(const MemoryException& inst); + /// Destruction + ~MemoryException() noexcept override = default; + /// Assignment operator + MemoryException& operator=(const MemoryException& inst); +#if defined(__GNUC__) + /// Description of the exception + const char* what() const noexcept override; #endif - PyObject * getPyExceptionType() const override; + PyObject* getPyExceptionType() const override; }; /** * The AccessViolation can be used in an own signal handler. * @author Werner Mayer */ -class BaseExport AccessViolation : public Exception +class BaseExport AccessViolation: public Exception { public: - /// Construction - AccessViolation(); - AccessViolation(const char * sMessage); - AccessViolation(const std::string& sMessage); - /// Destruction - ~AccessViolation() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + AccessViolation(); + AccessViolation(const char* sMessage); + AccessViolation(const std::string& sMessage); + /// Destruction + ~AccessViolation() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The AbnormalProgramTermination can be used in an own signal handler. * @author Werner Mayer */ -class BaseExport AbnormalProgramTermination : public Exception +class BaseExport AbnormalProgramTermination: public Exception { public: - /// Construction - AbnormalProgramTermination(); - /// Construction - AbnormalProgramTermination(const char * sMessage); - AbnormalProgramTermination(const std::string& sMessage); - /// Destruction - ~AbnormalProgramTermination() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + AbnormalProgramTermination(); + /// Construction + AbnormalProgramTermination(const char* sMessage); + AbnormalProgramTermination(const std::string& sMessage); + /// Destruction + ~AbnormalProgramTermination() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The UnknownProgramOption can be used to indicate an unknown program option. * @author Werner Mayer */ -class BaseExport UnknownProgramOption : public Exception +class BaseExport UnknownProgramOption: public Exception { public: - /// Construction - UnknownProgramOption(); - UnknownProgramOption(const char * sMessage); - UnknownProgramOption(const std::string& sMessage); - /// Destruction - ~UnknownProgramOption() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + UnknownProgramOption(); + UnknownProgramOption(const char* sMessage); + UnknownProgramOption(const std::string& sMessage); + /// Destruction + ~UnknownProgramOption() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The ProgramInformation can be used to show information about the program. * @author Werner Mayer */ -class BaseExport ProgramInformation : public Exception +class BaseExport ProgramInformation: public Exception { public: - /// Construction - ProgramInformation(); - ProgramInformation(const char * sMessage); - ProgramInformation(const std::string& sMessage); + /// Construction + ProgramInformation(); + ProgramInformation(const char* sMessage); + ProgramInformation(const std::string& sMessage); - /// Destruction - ~ProgramInformation() noexcept override = default; + /// Destruction + ~ProgramInformation() noexcept override = default; }; /** * The TypeError can be used to indicate the usage of a wrong type. * @author Werner Mayer */ -class BaseExport TypeError : public Exception +class BaseExport TypeError: public Exception { public: - /// Construction - TypeError(); - TypeError(const char * sMessage); - TypeError(const std::string& sMessage); - /// Destruction - ~TypeError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + TypeError(); + TypeError(const char* sMessage); + TypeError(const std::string& sMessage); + /// Destruction + ~TypeError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The ValueError can be used to indicate the usage of a wrong value. * @author Werner Mayer */ -class BaseExport ValueError : public Exception +class BaseExport ValueError: public Exception { public: - /// Construction - ValueError(); - ValueError(const char * sMessage); - ValueError(const std::string& sMessage); - /// Destruction - ~ValueError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ValueError(); + ValueError(const char* sMessage); + ValueError(const std::string& sMessage); + /// Destruction + ~ValueError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The IndexError can be used when a sequence subscript is out of range. * @author Werner Mayer */ -class BaseExport IndexError : public Exception +class BaseExport IndexError: public Exception { public: - /// Construction - IndexError(); - IndexError(const char * sMessage); - IndexError(const std::string& sMessage); - /// Destruction - ~IndexError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + IndexError(); + IndexError(const char* sMessage); + IndexError(const std::string& sMessage); + /// Destruction + ~IndexError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; -class BaseExport NameError : public Exception +class BaseExport NameError: public Exception { public: - /// Construction - NameError(); - NameError(const char * sMessage); - NameError(const std::string& sMessage); - /// Destruction - ~NameError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + NameError(); + NameError(const char* sMessage); + NameError(const std::string& sMessage); + /// Destruction + ~NameError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; -class BaseExport ImportError : public Exception +class BaseExport ImportError: public Exception { public: - /// Construction - ImportError(); - ImportError(const char * sMessage); - ImportError(const std::string& sMessage); - /// Destruction - ~ImportError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ImportError(); + ImportError(const char* sMessage); + ImportError(const std::string& sMessage); + /// Destruction + ~ImportError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The AttributeError can be used to indicate the usage of a wrong value. * @author Werner Mayer */ -class BaseExport AttributeError : public Exception +class BaseExport AttributeError: public Exception { public: - /// Construction - AttributeError(); - AttributeError(const char * sMessage); - AttributeError(const std::string& sMessage); - /// Destruction - ~AttributeError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + AttributeError(); + AttributeError(const char* sMessage); + AttributeError(const std::string& sMessage); + /// Destruction + ~AttributeError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The RuntimeError can be used to indicate an unknown exception at runtime. * @author Werner Mayer */ -class BaseExport RuntimeError : public Exception +class BaseExport RuntimeError: public Exception { public: - /// Construction - RuntimeError(); - RuntimeError(const char * sMessage); - RuntimeError(const std::string& sMessage); - /// Destruction - ~RuntimeError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + RuntimeError(); + RuntimeError(const char* sMessage); + RuntimeError(const std::string& sMessage); + /// Destruction + ~RuntimeError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The BadGraphError can be used to indicate that a graph is e.g. not a DAG. * @author Werner Mayer */ -class BaseExport BadGraphError : public RuntimeError +class BaseExport BadGraphError: public RuntimeError { public: - /// Construction - BadGraphError(); - BadGraphError(const char * sMessage); - BadGraphError(const std::string& sMessage); - /// Destruction - ~BadGraphError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + BadGraphError(); + BadGraphError(const char* sMessage); + BadGraphError(const std::string& sMessage); + /// Destruction + ~BadGraphError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The NotImplementedError can be used to indicate that an invoked function is not implemented. * @author Werner Mayer */ -class BaseExport NotImplementedError : public Exception +class BaseExport NotImplementedError: public Exception { public: - /// Construction - NotImplementedError(); - NotImplementedError(const char * sMessage); - NotImplementedError(const std::string& sMessage); - /// Destruction - ~NotImplementedError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + NotImplementedError(); + NotImplementedError(const char* sMessage); + NotImplementedError(const std::string& sMessage); + /// Destruction + ~NotImplementedError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The ZeroDivisionError can be used to indicate a division by zero. * @author Werner Mayer */ -class BaseExport ZeroDivisionError : public Exception +class BaseExport ZeroDivisionError: public Exception { public: - /// Construction - ZeroDivisionError(); - ZeroDivisionError(const char * sMessage); - ZeroDivisionError(const std::string& sMessage); - /// Destruction - ~ZeroDivisionError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ZeroDivisionError(); + ZeroDivisionError(const char* sMessage); + ZeroDivisionError(const std::string& sMessage); + /// Destruction + ~ZeroDivisionError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The ReferenceError can be used to indicate a reference counter has the wrong value. * @author Werner Mayer */ -class BaseExport ReferenceError : public Exception +class BaseExport ReferenceError: public Exception { public: - /// Construction - ReferenceError(); - ReferenceError(const char * sMessage); - ReferenceError(const std::string& sMessage); - /// Destruction - ~ReferenceError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ReferenceError(); + ReferenceError(const char* sMessage); + ReferenceError(const std::string& sMessage); + /// Destruction + ~ReferenceError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** @@ -568,144 +679,143 @@ public: * to the expression engine. * @author Werner Mayer */ -class BaseExport ExpressionError : public Exception +class BaseExport ExpressionError: public Exception { public: - /// Construction - ExpressionError(); - ExpressionError(const char * sMessage); - ExpressionError(const std::string& sMessage); - /// Destruction - ~ExpressionError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ExpressionError(); + ExpressionError(const char* sMessage); + ExpressionError(const std::string& sMessage); + /// Destruction + ~ExpressionError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The ParserError can be used to indicate the parsing error. * @author Werner Mayer */ -class BaseExport ParserError : public Exception +class BaseExport ParserError: public Exception { public: - /// Construction - ParserError(); - ParserError(const char * sMessage); - ParserError(const std::string& sMessage); - /// Destruction - ~ParserError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + ParserError(); + ParserError(const char* sMessage); + ParserError(const std::string& sMessage); + /// Destruction + ~ParserError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The UnicodeError can be used to indicate unicode encoding/decoding error. * @author Werner Mayer */ -class BaseExport UnicodeError : public Exception +class BaseExport UnicodeError: public Exception { public: - /// Construction - UnicodeError(); - UnicodeError(const char * sMessage); - UnicodeError(const std::string& sMessage); - /// Destruction - ~UnicodeError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + UnicodeError(); + UnicodeError(const char* sMessage); + UnicodeError(const std::string& sMessage); + /// Destruction + ~UnicodeError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The OverflowError can be used to indicate overflows of numbers. * @author Werner Mayer */ -class BaseExport OverflowError : public Exception +class BaseExport OverflowError: public Exception { public: - /// Construction - OverflowError(); - OverflowError(const char * sMessage); - OverflowError(const std::string& sMessage); - /// Destruction - ~OverflowError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + OverflowError(); + OverflowError(const char* sMessage); + OverflowError(const std::string& sMessage); + /// Destruction + ~OverflowError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The UnderflowError can be used to indicate underflows of numbers. * @author Werner Mayer */ -class BaseExport UnderflowError : public Exception +class BaseExport UnderflowError: public Exception { public: - /// Construction - UnderflowError(); - UnderflowError(const char * sMessage); - UnderflowError(const std::string& sMessage); - /// Destruction - ~UnderflowError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + UnderflowError(); + UnderflowError(const char* sMessage); + UnderflowError(const std::string& sMessage); + /// Destruction + ~UnderflowError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; /** * The UnitsMismatchError can be used to indicate that quantities with different units are used. * @author Werner Mayer */ -class BaseExport UnitsMismatchError : public Exception +class BaseExport UnitsMismatchError: public Exception { public: - /// Construction - UnitsMismatchError(); - UnitsMismatchError(const char * sMessage); - UnitsMismatchError(const std::string& sMessage); - /// Destruction - ~UnitsMismatchError() noexcept override = default; - PyObject * getPyExceptionType() const override; + /// Construction + UnitsMismatchError(); + UnitsMismatchError(const char* sMessage); + UnitsMismatchError(const std::string& sMessage); + /// Destruction + ~UnitsMismatchError() noexcept override = default; + PyObject* getPyExceptionType() const override; }; - /* The CADKernelError can be used to indicate an exception originating in the CAD Kernel +/* The CADKernelError can be used to indicate an exception originating in the CAD Kernel * allowing to propagate the error messages of, for example, OCC Standard_Failure exception to * the FreeCAD application without making the FreeCAD application depend on OCC. * @author Abdullah Tahiri */ -class BaseExport CADKernelError : public Exception +class BaseExport CADKernelError: public Exception { public: /// Construction CADKernelError(); - CADKernelError(const char * sMessage); + CADKernelError(const char* sMessage); CADKernelError(const std::string& sMessage); /// Destruction ~CADKernelError() noexcept override = default; - PyObject * getPyExceptionType() const override; + PyObject* getPyExceptionType() const override; }; /* The RestoreError can be used to try to do a best recovery effort when an error during restoring - * occurs. The best recovery effort may be to ignore the element altogether or to insert a placeholder - * depending on where the actual element being restored is used. + * occurs. The best recovery effort may be to ignore the element altogether or to insert a + * placeholder depending on where the actual element being restored is used. * - * For example, if it is part of an array (e.g. PropertyList) and the order in the array is relevant, it - * is better to have a placeholder than to fail to restore the whole array. + * For example, if it is part of an array (e.g. PropertyList) and the order in the array is + * relevant, it is better to have a placeholder than to fail to restore the whole array. */ -class BaseExport RestoreError : public Exception +class BaseExport RestoreError: public Exception { public: /// Construction RestoreError(); - RestoreError(const char * sMessage); + RestoreError(const char* sMessage); RestoreError(const std::string& sMessage); /// Destruction ~RestoreError() noexcept override = default; - PyObject * getPyExceptionType() const override; + PyObject* getPyExceptionType() const override; }; - -inline void Exception::setMessage(const char * sMessage) +inline void Exception::setMessage(const char* sMessage) { - _sErrMsg = sMessage; + _sErrMsg = sMessage; } inline void Exception::setMessage(const std::string& sMessage) { - _sErrMsg = sMessage; + _sErrMsg = sMessage; } inline std::string Exception::getMessage() const @@ -733,7 +843,8 @@ inline bool Exception::getTranslatable() const return _isTranslatable; } -inline void Exception::setDebugInformation(const std::string & file, const int line, const std::string & function) +inline void +Exception::setDebugInformation(const std::string& file, const int line, const std::string& function) { _file = file; _line = line; @@ -745,7 +856,7 @@ inline void Exception::setTranslatable(bool translatable) _isTranslatable = translatable; } -#if defined(__GNUC__) && defined (FC_OS_LINUX) +#if defined(__GNUC__) && defined(FC_OS_LINUX) class SignalException { public: @@ -761,6 +872,6 @@ private: }; #endif -} //namespace Base +} // namespace Base -#endif // BASE_EXCEPTION_H +#endif // BASE_EXCEPTION_H diff --git a/src/Base/ExceptionFactory.cpp b/src/Base/ExceptionFactory.cpp index 40ff217394..0c2f22e61d 100644 --- a/src/Base/ExceptionFactory.cpp +++ b/src/Base/ExceptionFactory.cpp @@ -28,23 +28,25 @@ using namespace Base; -ExceptionFactory* ExceptionFactory::_pcSingleton = nullptr; +ExceptionFactory* ExceptionFactory::_pcSingleton = nullptr; // NOLINT ExceptionFactory& ExceptionFactory::Instance() { - if (!_pcSingleton) + if (!_pcSingleton) { _pcSingleton = new ExceptionFactory; + } return *_pcSingleton; } -void ExceptionFactory::Destruct () +void ExceptionFactory::Destruct() { - if (_pcSingleton) + if (_pcSingleton) { delete _pcSingleton; + } _pcSingleton = nullptr; } -void ExceptionFactory::raiseException (PyObject * pydict) const +void ExceptionFactory::raiseException(PyObject* pydict) const { std::string classname; @@ -55,9 +57,8 @@ void ExceptionFactory::raiseException (PyObject * pydict) const std::map::const_iterator pProd; pProd = _mpcProducers.find(classname.c_str()); - if (pProd != _mpcProducers.end()) - static_cast(pProd->second)->raiseException(pydict); + if (pProd != _mpcProducers.end()) { + static_cast(pProd->second)->raiseException(pydict); + } } } - - diff --git a/src/Base/ExceptionFactory.h b/src/Base/ExceptionFactory.h index d050b46ff3..77e83cfab9 100644 --- a/src/Base/ExceptionFactory.h +++ b/src/Base/ExceptionFactory.h @@ -35,48 +35,49 @@ namespace Base { /// Abstract base class of all exception producers -class BaseExport AbstractExceptionProducer : public AbstractProducer +class BaseExport AbstractExceptionProducer: public AbstractProducer { public: - AbstractExceptionProducer () = default; + AbstractExceptionProducer() = default; // just implement it - void* Produce () const override { + void* Produce() const override + { return nullptr; } - virtual void raiseException(PyObject * pydict) const = 0; + virtual void raiseException(PyObject* pydict) const = 0; }; // -------------------------------------------------------------------- /** The ExceptionFactory */ -class BaseExport ExceptionFactory : public Factory +class BaseExport ExceptionFactory: public Factory { public: static ExceptionFactory& Instance(); - static void Destruct (); + static void Destruct(); - void raiseException(PyObject * pydict) const; + void raiseException(PyObject* pydict) const; private: - static ExceptionFactory* _pcSingleton; + static ExceptionFactory* _pcSingleton; // NOLINT ExceptionFactory() = default; }; /* Producers */ -template -class ExceptionProducer : public AbstractExceptionProducer +template +class ExceptionProducer: public AbstractExceptionProducer { public: - ExceptionProducer () + ExceptionProducer() { ExceptionFactory::Instance().AddProducer(typeid(CLASS).name(), this); } - ~ExceptionProducer () override = default; + ~ExceptionProducer() override = default; - void raiseException(PyObject * pydict) const override + void raiseException(PyObject* pydict) const override { CLASS c; c.setPyObject(pydict); @@ -85,8 +86,7 @@ public: } }; -} //namespace Base +} // namespace Base #endif - diff --git a/src/Base/Factory.cpp b/src/Base/Factory.cpp index d7a1d30311..b970f05e41 100644 --- a/src/Base/Factory.cpp +++ b/src/Base/Factory.cpp @@ -25,7 +25,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "Factory.h" @@ -35,76 +35,78 @@ using namespace Base; -Factory::~Factory () +Factory::~Factory() { - for (auto & it : _mpcProducers) - delete it.second; + for (auto& it : _mpcProducers) { + delete it.second; + } } -void* Factory::Produce (const char *sClassName) const +void* Factory::Produce(const char* sClassName) const { - std::map::const_iterator pProd; + std::map::const_iterator pProd; - pProd = _mpcProducers.find(sClassName); - if (pProd != _mpcProducers.end()) - return pProd->second->Produce(); - else - return nullptr; + pProd = _mpcProducers.find(sClassName); + if (pProd != _mpcProducers.end()) { + return pProd->second->Produce(); + } + else { + return nullptr; + } } -void Factory::AddProducer (const char *sClassName, AbstractProducer *pcProducer) +void Factory::AddProducer(const char* sClassName, AbstractProducer* pcProducer) { - _mpcProducers[sClassName] = pcProducer; + _mpcProducers[sClassName] = pcProducer; } bool Factory::CanProduce(const char* sClassName) const { - return (_mpcProducers.find(sClassName) != _mpcProducers.end()); + return (_mpcProducers.find(sClassName) != _mpcProducers.end()); } std::list Factory::CanProduce() const { - std::list lObjects; + std::list lObjects; - for (const auto & it : _mpcProducers) - { - lObjects.push_back(it.first); - } + for (const auto& it : _mpcProducers) { + lObjects.push_back(it.first); + } - return lObjects; + return lObjects; } // ---------------------------------------------------- -ScriptFactorySingleton* ScriptFactorySingleton::_pcSingleton = nullptr; - +ScriptFactorySingleton* ScriptFactorySingleton::_pcSingleton = nullptr; // NOLINT ScriptFactorySingleton& ScriptFactorySingleton::Instance() { - if (!_pcSingleton) - _pcSingleton = new ScriptFactorySingleton; - return *_pcSingleton; + if (!_pcSingleton) { + _pcSingleton = new ScriptFactorySingleton; + } + return *_pcSingleton; } -void ScriptFactorySingleton::Destruct () +void ScriptFactorySingleton::Destruct() { - if (_pcSingleton) - delete _pcSingleton; - _pcSingleton = nullptr; + if (_pcSingleton) { + delete _pcSingleton; + } + _pcSingleton = nullptr; } -const char* ScriptFactorySingleton::ProduceScript (const char* sScriptName) const +const char* ScriptFactorySingleton::ProduceScript(const char* sScriptName) const { - const char* script = static_cast(Produce(sScriptName)); + const char* script = static_cast(Produce(sScriptName)); - if ( !script ) - { + if (!script) { #ifdef FC_DEBUG - Console().Warning("\"%s\" is not registered\n", sScriptName); + Console().Warning("\"%s\" is not registered\n", sScriptName); #endif - return ""; // no data - } + return ""; // no data + } - return script; + return script; } diff --git a/src/Base/Factory.h b/src/Base/Factory.h index 76d4e7a792..0900569b3f 100644 --- a/src/Base/Factory.h +++ b/src/Base/Factory.h @@ -43,22 +43,21 @@ public: AbstractProducer() = default; virtual ~AbstractProducer() = default; /// overwritten by a concrete producer to produce the needed object - virtual void* Produce () const = 0; + virtual void* Produce() const = 0; }; - /** Base class of all factories - * This class has the purpose to produce instances of classes at runtime - * that are unknown at compile time. It holds a map of so called - * producers which are able to produce an instance of a special class. - * Producer can be registered at runtime through e.g. application modules - */ + * This class has the purpose to produce instances of classes at runtime + * that are unknown at compile time. It holds a map of so called + * producers which are able to produce an instance of a special class. + * Producer can be registered at runtime through e.g. application modules + */ class BaseExport Factory { public: /// Adds a new prducer instance - void AddProducer (const char* sClassName, AbstractProducer *pcProducer); + void AddProducer(const char* sClassName, AbstractProducer* pcProducer); /// returns true if there is a producer for this class registered bool CanProduce(const char* sClassName) const; /// returns a list of all registered producer @@ -66,25 +65,25 @@ public: protected: /// produce a class with the given name - void* Produce (const char* sClassName) const; + void* Produce(const char* sClassName) const; std::map _mpcProducers; /// construction - Factory () = default; + Factory() = default; /// destruction - virtual ~Factory (); + virtual ~Factory(); }; // -------------------------------------------------------------------- /** The ScriptFactorySingleton singleton - */ -class BaseExport ScriptFactorySingleton : public Factory + */ +class BaseExport ScriptFactorySingleton: public Factory { public: static ScriptFactorySingleton& Instance(); - static void Destruct (); + static void Destruct(); - const char* ProduceScript (const char* sScriptName) const; + const char* ProduceScript(const char* sScriptName) const; private: static ScriptFactorySingleton* _pcSingleton; @@ -101,22 +100,23 @@ inline ScriptFactorySingleton& ScriptFactory() // -------------------------------------------------------------------- /** Script Factory - * This class produce Scripts. - * @see Factory - */ + * This class produce Scripts. + * @see Factory + */ class BaseExport ScriptProducer: public AbstractProducer { public: /// Constructor - ScriptProducer (const char* name, const char* script) : mScript(script) + ScriptProducer(const char* name, const char* script) + : mScript(script) { ScriptFactorySingleton::Instance().AddProducer(name, this); } - ~ScriptProducer () override = default; + ~ScriptProducer() override = default; /// Produce an instance - void* Produce () const override + void* Produce() const override { return const_cast(mScript); } @@ -125,8 +125,7 @@ private: const char* mScript; }; -} //namespace Base +} // namespace Base #endif - diff --git a/src/Base/FileInfo.cpp b/src/Base/FileInfo.cpp index 2bb9c71de2..e441b7789f 100644 --- a/src/Base/FileInfo.cpp +++ b/src/Base/FileInfo.cpp @@ -25,18 +25,18 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# if defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) -# include -# include -# elif defined (FC_OS_WIN32) -# include -# include -# endif +#include +#include +#include +#include +#include +#if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#include +#include +#elif defined(FC_OS_WIN32) +#include +#include +#endif #include #include #endif @@ -49,16 +49,16 @@ using namespace Base; #ifndef R_OK -#define R_OK 4 /* Test for read permission */ +#define R_OK 4 /* Test for read permission */ #endif #ifndef W_OK -#define W_OK 2 /* Test for write permission */ +#define W_OK 2 /* Test for write permission */ #endif #ifndef X_OK -#define X_OK 1 /* Test for execute permission */ +#define X_OK 1 /* Test for execute permission */ #endif #ifndef F_OK -#define F_OK 0 /* Test for existence */ +#define F_OK 0 /* Test for existence */ #endif //********************************************************************************** @@ -67,11 +67,11 @@ using namespace Base; #ifdef FC_OS_WIN32 std::string ConvertFromWideString(const std::wstring& string) { - int neededSize = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, 0, 0,0,0); - char * CharString = new char[static_cast(neededSize)]; - WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, CharString, neededSize,0,0); + int neededSize = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, 0, 0, 0, 0); + char* CharString = new char[static_cast(neededSize)]; + WideCharToMultiByte(CP_UTF8, 0, string.c_str(), -1, CharString, neededSize, 0, 0); std::string String(CharString); - delete [] CharString; + delete[] CharString; CharString = NULL; return String; } @@ -82,7 +82,7 @@ std::wstring ConvertToWideString(const std::string& string) wchar_t* wideCharString = new wchar_t[static_cast(neededSize)]; MultiByteToWideChar(CP_UTF8, 0, string.c_str(), -1, wideCharString, neededSize); std::wstring wideString(wideCharString); - delete [] wideCharString; + delete[] wideCharString; wideCharString = NULL; return wideString; } @@ -93,38 +93,40 @@ std::wstring ConvertToWideString(const std::string& string) // FileInfo -FileInfo::FileInfo (const char* _FileName) +FileInfo::FileInfo(const char* _FileName) { setFile(_FileName); } -FileInfo::FileInfo (const std::string &_FileName) +FileInfo::FileInfo(const std::string& _FileName) { setFile(_FileName.c_str()); } -const std::string &FileInfo::getTempPath() +const std::string& FileInfo::getTempPath() { static std::string tempPath; if (tempPath == "") { #ifdef FC_OS_WIN32 wchar_t buf[MAX_PATH + 2]; - GetTempPathW(MAX_PATH + 1,buf); + GetTempPathW(MAX_PATH + 1, buf); int neededSize = WideCharToMultiByte(CP_UTF8, 0, buf, -1, 0, 0, 0, 0); char* dest = new char[static_cast(neededSize)]; - WideCharToMultiByte(CP_UTF8, 0, buf, -1,dest, neededSize, 0, 0); + WideCharToMultiByte(CP_UTF8, 0, buf, -1, dest, neededSize, 0, 0); tempPath = dest; - delete [] dest; + delete[] dest; #else const char* tmp = getenv("TMPDIR"); if (tmp && tmp[0] != '\0') { tempPath = tmp; FileInfo fi(tempPath); - if (tempPath.empty() || !fi.isDir()) // still empty or non-existent + if (tempPath.empty() || !fi.isDir()) { // still empty or non-existent tempPath = "/tmp/"; - else if (tempPath.at(tempPath.size()-1)!='/') + } + else if (tempPath.at(tempPath.size() - 1) != '/') { tempPath.append("/"); + } } else { tempPath = "/tmp/"; @@ -137,28 +139,32 @@ const std::string &FileInfo::getTempPath() std::string FileInfo::getTempFileName(const char* FileName, const char* Path) { - //FIXME: To avoid race conditions we should rather return a file pointer - //than a file name. + // FIXME: To avoid race conditions we should rather return a file pointer + // than a file name. #ifdef FC_OS_WIN32 wchar_t buf[MAX_PATH + 2]; // Path where the file is located std::wstring path; - if (Path) + if (Path) { path = ConvertToWideString(std::string(Path)); - else + } + else { path = ConvertToWideString(getTempPath()); + } // File name in the path std::wstring file; - if (FileName) + if (FileName) { file = ConvertToWideString(std::string(FileName)); - else + } + else { file = L"FCTempFile"; + } // this already creates the file - GetTempFileNameW(path.c_str(),file.c_str(),0,buf); + GetTempFileNameW(path.c_str(), file.c_str(), 0, buf); DeleteFileW(buf); return std::string(ConvertFromWideString(std::wstring(buf))); @@ -166,10 +172,12 @@ std::string FileInfo::getTempFileName(const char* FileName, const char* Path) std::string buf; // Path where the file is located - if (Path) + if (Path) { buf = Path; - else + } + else { buf = getTempPath(); + } // File name in the path if (FileName) { @@ -190,7 +198,7 @@ std::string FileInfo::getTempFileName(const char* FileName, const char* Path) if (id > -1) { FILE* file = fdopen(id, "w"); fclose(file); - vec.pop_back(); // remove '\0' + vec.pop_back(); // remove '\0' std::string str(vec.begin(), vec.end()); buf.swap(str); unlink(buf.c_str()); @@ -230,25 +238,27 @@ void FileInfo::setFile(const char* name) FileName = name; // keep the UNC paths intact - if (FileName.substr(0,2) == std::string("\\\\")) - std::replace(FileName.begin()+2, FileName.end(), '\\', '/'); - else + if (FileName.substr(0, 2) == std::string("\\\\")) { + std::replace(FileName.begin() + 2, FileName.end(), '\\', '/'); + } + else { std::replace(FileName.begin(), FileName.end(), '\\', '/'); + } } -std::string FileInfo::filePath () const +std::string FileInfo::filePath() const { return FileName; } std::string FileInfo::fileName() const { - return FileName.substr(FileName.find_last_of('/')+1); + return FileName.substr(FileName.find_last_of('/') + 1); } std::string FileInfo::dirPath() const { - std::size_t last_pos{}; + std::size_t last_pos {}; std::string retval; last_pos = FileName.find_last_of('/'); if (last_pos != std::string::npos) { @@ -260,7 +270,7 @@ std::string FileInfo::dirPath() const GetCurrentDirectoryW(MAX_PATH, buf); retval = std::string(ConvertFromWideString(std::wstring(buf))); #else - char buf[PATH_MAX+1]; + char buf[PATH_MAX + 1]; const char* cwd = getcwd(buf, PATH_MAX); retval = std::string(cwd ? cwd : "."); #endif @@ -273,10 +283,12 @@ std::string FileInfo::fileNamePure() const std::string temp = fileName(); std::string::size_type pos = temp.find_last_of('.'); - if (pos != std::string::npos) - return temp.substr(0,pos); - else + if (pos != std::string::npos) { + return temp.substr(0, pos); + } + else { return temp; + } } std::wstring FileInfo::toStdWString() const @@ -294,25 +306,27 @@ std::wstring FileInfo::toStdWString() const std::string FileInfo::extension() const { std::string::size_type pos = FileName.find_last_of('.'); - if (pos == std::string::npos) + if (pos == std::string::npos) { return {}; - return FileName.substr(pos+1); + } + return FileName.substr(pos + 1); } std::string FileInfo::completeExtension() const { std::string::size_type pos = FileName.find_first_of('.'); - if (pos == std::string::npos) + if (pos == std::string::npos) { return {}; - return FileName.substr(pos+1); + } + return FileName.substr(pos + 1); } bool FileInfo::hasExtension(const char* Ext) const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) return _stricmp(Ext, extension().c_str()) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - return strcasecmp(Ext,extension().c_str()) == 0; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + return strcasecmp(Ext, extension().c_str()) == 0; #endif } @@ -328,30 +342,30 @@ bool FileInfo::hasExtension(std::initializer_list Exts) const bool FileInfo::exists() const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _waccess(wstr.c_str(), F_OK) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return access(FileName.c_str(), F_OK) == 0; #endif } bool FileInfo::isReadable() const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _waccess(wstr.c_str(), R_OK) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return access(FileName.c_str(), R_OK) == 0; #endif } bool FileInfo::isWritable() const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _waccess(wstr.c_str(), W_OK) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return access(FileName.c_str(), W_OK) == 0; #endif } @@ -360,17 +374,20 @@ bool FileInfo::setPermissions(Permissions perms) { int mode = 0; - if (perms & FileInfo::ReadOnly) + if (perms & FileInfo::ReadOnly) { mode |= S_IREAD; - if (perms & FileInfo::WriteOnly) + } + if (perms & FileInfo::WriteOnly) { mode |= S_IWRITE; + } - if (mode == 0) // bad argument + if (mode == 0) { // bad argument return false; -#if defined (FC_OS_WIN32) + } +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _wchmod(wstr.c_str(), mode) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return chmod(FileName.c_str(), mode) == 0; #endif } @@ -383,12 +400,15 @@ bool FileInfo::isFile() const std::wstring wstr = toStdWString(); FILE* fd = _wfopen(wstr.c_str(), L"rb"); bool ok = (fd != 0); - if (fd) fclose(fd); + if (fd) { + fclose(fd); + } return ok; #else struct stat st; - if(stat(FileName.c_str(), &st) != 0) + if (stat(FileName.c_str(), &st) != 0) { return false; + } return S_ISREG(st.st_mode); #endif } @@ -402,16 +422,19 @@ bool FileInfo::isDir() const if (exists()) { // if we can chdir then it must be a directory, otherwise we assume it // is a file (which doesn't need to be true for any cases) -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); struct _stat st; - if (_wstat(wstr.c_str(), &st) != 0) + if (_wstat(wstr.c_str(), &st) != 0) { return false; + } return ((st.st_mode & _S_IFDIR) != 0); -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - struct stat st{}; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + struct stat st + { + }; if (stat(FileName.c_str(), &st) != 0) { return false; } @@ -420,14 +443,15 @@ bool FileInfo::isDir() const return false; #endif } - else + else { return false; + } // TODO: Check for valid path name - //return true; + // return true; } -unsigned int FileInfo::size () const +unsigned int FileInfo::size() const { // not implemented assert(0); @@ -439,20 +463,21 @@ TimeInfo FileInfo::lastModified() const TimeInfo ti = TimeInfo::null(); if (exists()) { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); struct _stat st; if (_wstat(wstr.c_str(), &st) == 0) { ti.setTime_t(st.st_mtime); } -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - struct stat st{}; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + struct stat st + { + }; if (stat(FileName.c_str(), &st) == 0) { ti.setTime_t(st.st_mtime); } #endif - } return ti; } @@ -462,47 +487,48 @@ TimeInfo FileInfo::lastRead() const TimeInfo ti = TimeInfo::null(); if (exists()) { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); struct _stat st; if (_wstat(wstr.c_str(), &st) == 0) { ti.setTime_t(st.st_atime); } -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - struct stat st{}; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + struct stat st + { + }; if (stat(FileName.c_str(), &st) == 0) { ti.setTime_t(st.st_atime); } #endif - } return ti; } bool FileInfo::deleteFile() const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return ::_wremove(wstr.c_str()) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - return (::remove(FileName.c_str())==0); +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + return (::remove(FileName.c_str()) == 0); #else -# error "FileInfo::deleteFile() not implemented for this platform!" +#error "FileInfo::deleteFile() not implemented for this platform!" #endif } bool FileInfo::renameFile(const char* NewName) { - bool res{}; -#if defined (FC_OS_WIN32) + bool res {}; +#if defined(FC_OS_WIN32) std::wstring oldname = toStdWString(); std::wstring newname = ConvertToWideString(NewName); - res = ::_wrename(oldname.c_str(),newname.c_str()) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) - res = ::rename(FileName.c_str(),NewName) == 0; + res = ::_wrename(oldname.c_str(), newname.c_str()) == 0; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + res = ::rename(FileName.c_str(), NewName) == 0; #else -# error "FileInfo::renameFile() not implemented for this platform!" +#error "FileInfo::renameFile() not implemented for this platform!" #endif if (!res) { int code = errno; @@ -517,11 +543,11 @@ bool FileInfo::renameFile(const char* NewName) bool FileInfo::copyTo(const char* NewName) const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring oldname = toStdWString(); std::wstring newname = ConvertToWideString(NewName); - return CopyFileW(oldname.c_str(),newname.c_str(),true) != 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) + return CopyFileW(oldname.c_str(), newname.c_str(), true) != 0; +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) FileInfo fi1(FileName); FileInfo fi2(NewName); Base::ifstream file(fi1, std::ios::in | std::ios::binary); @@ -530,19 +556,19 @@ bool FileInfo::copyTo(const char* NewName) const file >> copy.rdbuf(); return file.is_open() && copy.is_open(); #else -# error "FileInfo::copyTo() not implemented for this platform!" +#error "FileInfo::copyTo() not implemented for this platform!" #endif } bool FileInfo::createDirectory() const { -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _wmkdir(wstr.c_str()) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return mkdir(FileName.c_str(), 0777) == 0; #else -# error "FileInfo::createDirectory() not implemented for this platform!" +#error "FileInfo::createDirectory() not implemented for this platform!" #endif } @@ -550,8 +576,9 @@ bool FileInfo::createDirectories() const { try { boost::filesystem::path path(stringToPath(FileName)); - if (boost::filesystem::exists(path)) + if (boost::filesystem::exists(path)) { return true; + } boost::filesystem::create_directories(path); return true; } @@ -562,22 +589,24 @@ bool FileInfo::createDirectories() const bool FileInfo::deleteDirectory() const { - if (!isDir()) + if (!isDir()) { return false; -#if defined (FC_OS_WIN32) + } +#if defined(FC_OS_WIN32) std::wstring wstr = toStdWString(); return _wrmdir(wstr.c_str()) == 0; -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) return rmdir(FileName.c_str()) == 0; #else -# error "FileInfo::rmdir() not implemented for this platform!" +#error "FileInfo::rmdir() not implemented for this platform!" #endif } bool FileInfo::deleteDirectoryRecursive() const { - if (!isDir()) + if (!isDir()) { return false; + } std::vector List = getDirectoryContent(); for (Base::FileInfo& fi : List) { @@ -595,7 +624,8 @@ bool FileInfo::deleteDirectoryRecursive() const fi.deleteFile(); } else { - throw Base::FileException("FileInfo::deleteDirectoryRecursive(): Unknown object Type in directory!"); + throw Base::FileException( + "FileInfo::deleteDirectoryRecursive(): Unknown object Type in directory!"); } } return deleteDirectory(); @@ -604,7 +634,7 @@ bool FileInfo::deleteDirectoryRecursive() const std::vector FileInfo::getDirectoryContent() const { std::vector List; -#if defined (FC_OS_WIN32) +#if defined(FC_OS_WIN32) struct _wfinddata_t dentry; intptr_t hFile; @@ -613,32 +643,35 @@ std::vector FileInfo::getDirectoryContent() const std::wstring wstr = toStdWString(); wstr += L"/*"; - if ((hFile = _wfindfirst( wstr.c_str(), &dentry)) == -1L) + if ((hFile = _wfindfirst(wstr.c_str(), &dentry)) == -1L) { return List; + } - while (_wfindnext(hFile, &dentry) == 0) - if (wcscmp(dentry.name,L"..") != 0) - List.push_back(FileInfo(FileName + "/" +ConvertFromWideString(std::wstring(dentry.name)))); + while (_wfindnext(hFile, &dentry) == 0) { + if (wcscmp(dentry.name, L"..") != 0) { + List.push_back( + FileInfo(FileName + "/" + ConvertFromWideString(std::wstring(dentry.name)))); + } + } _findclose(hFile); -#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#elif defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) DIR* dp(nullptr); struct dirent* dentry(nullptr); - if (!(dp = opendir(FileName.c_str()))) - { + if (!(dp = opendir(FileName.c_str()))) { return List; } - while ((dentry = readdir(dp))) - { + while ((dentry = readdir(dp))) { std::string dir = dentry->d_name; - if (dir != "." && dir != "..") + if (dir != "." && dir != "..") { List.emplace_back(FileName + "/" + dir); + } } closedir(dp); #else -# error "FileInfo::getDirectoryContent() not implemented for this platform!" +#error "FileInfo::getDirectoryContent() not implemented for this platform!" #endif return List; } diff --git a/src/Base/FileInfo.h b/src/Base/FileInfo.h index cf29077ea4..4cddf20617 100644 --- a/src/Base/FileInfo.h +++ b/src/Base/FileInfo.h @@ -37,44 +37,49 @@ namespace Base /// When reading and writing a character stream, the incoming data can be dumped into the stream /// unaltered (if it contains only data that is valid in the current XML character set), or it can /// be Base64-encoded. This enum is used by Reader and Writer to distinguish the two cases. -enum class CharStreamFormat { +enum class CharStreamFormat +{ Raw, Base64Encoded }; /** File name unification - * This class handles everything related to file names - * the file names are internal generally UTF-8 encoded on - * all platforms. - */ + * This class handles everything related to file names + * the file names are internal generally UTF-8 encoded on + * all platforms. + */ class BaseExport FileInfo { public: - enum Permissions { + enum Permissions + { WriteOnly = 0x01, ReadOnly = 0x02, ReadWrite = 0x03, }; /// Construction - FileInfo (const char* _FileName=""); - FileInfo (const std::string &_FileName); + FileInfo(const char* _FileName = ""); + FileInfo(const std::string& _FileName); /// Set a new file name void setFile(const char* name); /// Set a new file name - void setFile(const std::string &name){setFile(name.c_str());} + void setFile(const std::string& name) + { + setFile(name.c_str()); + } /** @name extraction of information */ //@{ /// Returns the file name, including the path (which may be absolute or relative). - std::string filePath () const; + std::string filePath() const; /// Returns the dir path name (which may be absolute or relative). - std::string dirPath () const; + std::string dirPath() const; /// Returns the name of the file, excluding the path, including the extension. - std::string fileName () const; + std::string fileName() const; /// Returns the name of the file, excluding the path and the extension. - std::string fileNamePure () const; + std::string fileNamePure() const; /// Convert the path name into a UTF-16 encoded wide string format. /// @note: Use this function on Windows only. std::wstring toStdWString() const; @@ -86,7 +91,7 @@ public: * ext = fi.extension(); // ext = "gz" *@endcode */ - std::string extension () const; + std::string extension() const; /** Returns the complete extension of the file. * The complete extension consists of all characters in the file after (but not including) * the first '.' character. @@ -95,29 +100,29 @@ public: * ext = fi.completeExtension(); // ext = "tar.gz" *@endcode */ - std::string completeExtension () const; + std::string completeExtension() const; /// Checks for a special extension, NOT case sensitive - bool hasExtension (const char* Ext) const; - /// Checks for any of the special extensions, NOT case sensitive - bool hasExtension (std::initializer_list Exts) const; + bool hasExtension(const char* Ext) const; + /// Checks for any of the special extensions, NOT case sensitive + bool hasExtension(std::initializer_list Exts) const; //@} /** @name methods to test the status of the file or dir */ //@{ /// Does the file exist? - bool exists () const; + bool exists() const; /// Checks if the file exist and is readable - bool isReadable () const; + bool isReadable() const; /// Checks if the file exist and is writable - bool isWritable () const; + bool isWritable() const; /// Tries to set the file permission - bool setPermissions (Permissions); + bool setPermissions(Permissions); /// Checks if it is a file (not a directory) - bool isFile () const; + bool isFile() const; /// Checks if it is a directory (not a file) - bool isDir () const; + bool isDir() const; /// The size of the file - unsigned int size () const; + unsigned int size() const; /// Returns the time when the file was last modified. TimeInfo lastModified() const; /// Returns the time when the file was last read (accessed). @@ -127,8 +132,9 @@ public: /** @name Directory management*/ //@{ /// Creates a directory. Returns true if successful; otherwise returns false. - bool createDirectory( ) const; - /// Creates a directory and all its parent directories. Returns true if successful; otherwise returns false. + bool createDirectory() const; + /// Creates a directory and all its parent directories. Returns true if successful; otherwise + /// returns false. bool createDirectories() const; /// Get a list of the directory content std::vector getDirectoryContent() const; @@ -148,20 +154,20 @@ public: /** @name Tools */ //@{ /// Get a unique File Name in the given or (if 0) in the temp path - static std::string getTempFileName(const char* FileName=nullptr, const char* path=nullptr); + static std::string getTempFileName(const char* FileName = nullptr, const char* path = nullptr); /// Get the path to the dir which is considered to temp files - static const std::string &getTempPath(); + static const std::string& getTempPath(); /// Convert from filesystem path to string static std::string pathToString(const boost::filesystem::path& p); /// Convert from string to filesystem path static boost::filesystem::path stringToPath(const std::string& str); //@} -protected: +private: std::string FileName; }; -} //namespace Base +} // namespace Base -#endif // BASE_FILEINFO_H +#endif // BASE_FILEINFO_H diff --git a/src/Base/FileTemplate.cpp b/src/Base/FileTemplate.cpp index 99065f4dda..09da6cf4ff 100644 --- a/src/Base/FileTemplate.cpp +++ b/src/Base/FileTemplate.cpp @@ -63,7 +63,7 @@ ClassTemplate::~ClassTemplate() = default; * @see publicVar() * @return The test results */ -int ClassTemplate::testMe(int /*a*/,const char* /*s*/) +int ClassTemplate::testMe(int /*a*/, const char* /*s*/) { return 0; } @@ -73,6 +73,3 @@ int ClassTemplate::testMe(int /*a*/,const char* /*s*/) //************************************************************************** // Separator for additional classes //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - - diff --git a/src/Base/FileTemplate.h b/src/Base/FileTemplate.h index 52518505f4..f509b8cae9 100644 --- a/src/Base/FileTemplate.h +++ b/src/Base/FileTemplate.h @@ -89,20 +89,21 @@ public: /// Destruction virtual ~ClassTemplate(); - int testMe(int a,const char *s); + int testMe(int a, const char* s); /** * An enum. * More detailed enum description. */ - enum TEnum { + enum TEnum + { TVal1, /**< enum value TVal1. */ TVal2, /**< enum value TVal2. */ TVal3 /**< enum value TVal3. */ } - *enumPtr{nullptr}, /**< enum pointer. Details. */ - enumVar{TVal1}; /**< enum variable. Details. */ + * enumPtr {nullptr}, /**< enum pointer. Details. */ + enumVar {TVal1}; /**< enum variable. Details. */ /** * A pure virtual member. @@ -110,35 +111,34 @@ public: * @param c1 the first argument. * @param c2 the second argument. */ - virtual void testMeToo(char c1,char c2) = 0; + virtual void testMeToo(char c1, char c2) = 0; /** @name a group of methods */ //@{ /// I am method one - virtual void one()=0; + virtual void one() = 0; /// I am method two - virtual void two()=0; + virtual void two() = 0; /// I am method three - virtual void three()=0; + virtual void three() = 0; //@} /** - * a public variable. - * Details. - */ - int publicVar{0}; + * a public variable. + * Details. + */ + int publicVar {0}; /** * a function variable. * Details. */ - int (*handler)(int a,int b){nullptr}; + int (*handler)(int a, int b) {nullptr}; std::string something; }; -} //namespace Base - -#endif // BASE_FILETEMPLATE_H +} // namespace Base +#endif // BASE_FILETEMPLATE_H diff --git a/src/Base/FutureWatcherProgress.cpp b/src/Base/FutureWatcherProgress.cpp index 574353893c..0fbf90c05b 100644 --- a/src/Base/FutureWatcherProgress.cpp +++ b/src/Base/FutureWatcherProgress.cpp @@ -28,16 +28,18 @@ using namespace Base; FutureWatcherProgress::FutureWatcherProgress(const char* text, unsigned int steps) - : seq(text, 100), steps(steps), current(0) -{ -} + : seq(text, 100) + , steps(steps) + , current(0) +{} FutureWatcherProgress::~FutureWatcherProgress() = default; void FutureWatcherProgress::progressValueChanged(int v) { - if (steps == 0) + if (steps == 0) { return; + } unsigned int step = (100 * static_cast(v)) / steps; if (step > current) { current = step; diff --git a/src/Base/FutureWatcherProgress.h b/src/Base/FutureWatcherProgress.h index 2a37cdd7df..d585b511e5 100644 --- a/src/Base/FutureWatcherProgress.h +++ b/src/Base/FutureWatcherProgress.h @@ -31,7 +31,7 @@ namespace Base { -class BaseExport FutureWatcherProgress : public QObject +class BaseExport FutureWatcherProgress: public QObject { Q_OBJECT @@ -41,8 +41,8 @@ public: FutureWatcherProgress(const FutureWatcherProgress&) = delete; FutureWatcherProgress(FutureWatcherProgress&&) = delete; - FutureWatcherProgress& operator= (const FutureWatcherProgress&) = delete; - FutureWatcherProgress& operator= (FutureWatcherProgress&&) = delete; + FutureWatcherProgress& operator=(const FutureWatcherProgress&) = delete; + FutureWatcherProgress& operator=(FutureWatcherProgress&&) = delete; public Q_SLOTS: void progressValueChanged(int value); @@ -51,6 +51,6 @@ private: Base::SequencerLauncher seq; unsigned int steps, current; }; -} +} // namespace Base -#endif // BASE_FUTUREWATCHER_H +#endif // BASE_FUTUREWATCHER_H diff --git a/src/Base/GeometryPyCXX.cpp b/src/Base/GeometryPyCXX.cpp index 3cf5f0486b..33738dafa5 100644 --- a/src/Base/GeometryPyCXX.cpp +++ b/src/Base/GeometryPyCXX.cpp @@ -23,21 +23,21 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "GeometryPyCXX.h" #include "VectorPy.h" -int Py::Vector::Vector_TypeCheck(PyObject * obj) +int Py::Vector::Vector_TypeCheck(PyObject* obj) { return PyObject_TypeCheck(obj, &(Base::VectorPy::Type)); } -bool Py::Vector::accepts (PyObject *obj) const +bool Py::Vector::accepts(PyObject* obj) const { - if (obj && Vector_TypeCheck (obj)) { + if (obj && Vector_TypeCheck(obj)) { return true; } else if (obj && PySequence_Check(obj)) { @@ -47,41 +47,42 @@ bool Py::Vector::accepts (PyObject *obj) const return false; } -Py::Vector::Vector (const Base::Vector3d& v) +Py::Vector::Vector(const Base::Vector3d& v) { set(new Base::VectorPy(v), true); validate(); } -Py::Vector::Vector (const Base::Vector3f& v) +Py::Vector::Vector(const Base::Vector3f& v) { set(new Base::VectorPy(v), true); validate(); } -Py::Vector& Py::Vector::operator= (PyObject* rhsp) +Py::Vector& Py::Vector::operator=(PyObject* rhsp) { - if(ptr() == rhsp) + if (ptr() == rhsp) { return *this; - set (rhsp, false); + } + set(rhsp, false); return *this; } -Py::Vector& Py::Vector::operator= (const Base::Vector3d& v) +Py::Vector& Py::Vector::operator=(const Base::Vector3d& v) { - set (new Base::VectorPy(v), true); + set(new Base::VectorPy(v), true); return *this; } -Py::Vector& Py::Vector::operator= (const Base::Vector3f& v) +Py::Vector& Py::Vector::operator=(const Base::Vector3f& v) { - set (new Base::VectorPy(v), true); + set(new Base::VectorPy(v), true); return *this; } Base::Vector3d Py::Vector::toVector() const { - if (Vector_TypeCheck (ptr())) { + if (Vector_TypeCheck(ptr())) { return static_cast(ptr())->value(); } else { @@ -89,7 +90,8 @@ Base::Vector3d Py::Vector::toVector() const } } -namespace Base { +namespace Base +{ Py::PythonType& Vector2dPy::behaviors() { @@ -101,7 +103,7 @@ PyTypeObject* Vector2dPy::type_object() return Py::PythonClass::type_object(); } -bool Vector2dPy::check( PyObject *p ) +bool Vector2dPy::check(PyObject* p) { return Py::PythonClass::check(p); } @@ -117,14 +119,15 @@ Py::PythonClassObject Vector2dPy::create(double x, double y) Py::Tuple arg(2); arg.setItem(0, Py::Float(x)); arg.setItem(1, Py::Float(y)); - Py::PythonClassObject o = Py::PythonClassObject(class_type.apply(arg, Py::Dict())); + Py::PythonClassObject o = + Py::PythonClassObject(class_type.apply(arg, Py::Dict())); return o; } -Vector2dPy::Vector2dPy(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds) +Vector2dPy::Vector2dPy(Py::PythonClassInstance* self, Py::Tuple& args, Py::Dict& kwds) : Py::PythonClass::PythonClass(self, args, kwds) { - double x=0,y=0; + double x = 0, y = 0; if (!PyArg_ParseTuple(args.ptr(), "|dd", &x, &y)) { throw Py::Exception(); } @@ -141,19 +144,18 @@ Py::Object Vector2dPy::repr() Py::Float y(v.y); std::stringstream str; str << "Vector2 ("; - str << static_cast(x.repr()) << ", " - << static_cast(y.repr()); + str << static_cast(x.repr()) << ", " << static_cast(y.repr()); str << ")"; return Py::String(str.str()); } -Py::Object Vector2dPy::getattro(const Py::String &name_) +Py::Object Vector2dPy::getattro(const Py::String& name_) { // For Py3 either handle __dict__ or implement __dir__ as shown here: // https://stackoverflow.com/questions/48609111/how-is-dir-implemented-exactly-and-how-should-i-know-it // - std::string name( name_.as_std_string( "utf-8" ) ); + std::string name(name_.as_std_string("utf-8")); if (name == "__dict__") { Py::Dict attr; @@ -168,13 +170,13 @@ Py::Object Vector2dPy::getattro(const Py::String &name_) return Py::Float(v.y); } else { - return genericGetAttro( name_ ); + return genericGetAttro(name_); } } -int Vector2dPy::setattro(const Py::String &name_, const Py::Object &value) +int Vector2dPy::setattro(const Py::String& name_, const Py::Object& value) { - std::string name( name_.as_std_string( "utf-8" ) ); + std::string name(name_.as_std_string("utf-8")); if (name == "x" && !value.isNull()) { v.x = static_cast(Py::Float(value)); @@ -185,7 +187,7 @@ int Vector2dPy::setattro(const Py::String &name_, const Py::Object &value) return 0; } else { - return genericSetAttro( name_, value ); + return genericSetAttro(name_, value); } } @@ -219,21 +221,21 @@ Py::Object Vector2dPy::number_float() throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_add( const Py::Object & py) +Py::Object Vector2dPy::number_add(const Py::Object& py) { Vector2d u(Py::toVector2d(py)); u = v + u; return create(u); } -Py::Object Vector2dPy::number_subtract( const Py::Object & py) +Py::Object Vector2dPy::number_subtract(const Py::Object& py) { Vector2d u(Py::toVector2d(py)); u = v - u; return create(u); } -Py::Object Vector2dPy::number_multiply( const Py::Object & py) +Py::Object Vector2dPy::number_multiply(const Py::Object& py) { if (PyObject_TypeCheck(py.ptr(), Vector2dPy::type_object())) { Vector2d u(Py::toVector2d(py)); @@ -249,42 +251,42 @@ Py::Object Vector2dPy::number_multiply( const Py::Object & py) } } -Py::Object Vector2dPy::number_remainder( const Py::Object & ) +Py::Object Vector2dPy::number_remainder(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_divmod( const Py::Object & ) +Py::Object Vector2dPy::number_divmod(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_lshift( const Py::Object & ) +Py::Object Vector2dPy::number_lshift(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_rshift( const Py::Object & ) +Py::Object Vector2dPy::number_rshift(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_and( const Py::Object & ) +Py::Object Vector2dPy::number_and(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_xor( const Py::Object & ) +Py::Object Vector2dPy::number_xor(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_or( const Py::Object & ) +Py::Object Vector2dPy::number_or(const Py::Object&) { throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_power( const Py::Object &, const Py::Object & ) +Py::Object Vector2dPy::number_power(const Py::Object&, const Py::Object&) { throw Py::TypeError("Not defined"); } @@ -381,8 +383,8 @@ PYCXX_VARARGS_METHOD_DECL(Vector2dPy, projectToLine) void Vector2dPy::init_type() { - behaviors().name( "Vector2d" ); - behaviors().doc( "Vector2d class" ); + behaviors().name("Vector2d"); + behaviors().doc("Vector2d class"); behaviors().supportGetattro(); behaviors().supportSetattro(); behaviors().supportRepr(); @@ -405,4 +407,4 @@ void Vector2dPy::init_type() behaviors().readyType(); } -} +} // namespace Base diff --git a/src/Base/GeometryPyCXX.h b/src/Base/GeometryPyCXX.h index 246c9152b9..78602b70b3 100644 --- a/src/Base/GeometryPyCXX.h +++ b/src/Base/GeometryPyCXX.h @@ -37,8 +37,9 @@ #include -namespace Base { -template +namespace Base +{ +template inline Vector3 getVectorFromTuple(PyObject* o) { Py::Sequence tuple(o); @@ -50,32 +51,35 @@ inline Vector3 getVectorFromTuple(PyObject* o) T y = static_cast(Py::Float(tuple[1])); T z = static_cast(Py::Float(tuple[2])); - return Vector3(x,y,z); + return Vector3(x, y, z); } -class BaseExport Vector2dPy : public Py::PythonClass +class BaseExport Vector2dPy: public Py::PythonClass // NOLINT { public: - static Py::PythonType &behaviors(); - static PyTypeObject *type_object(); - static bool check( PyObject *p ); + static Py::PythonType& behaviors(); + static PyTypeObject* type_object(); + static bool check(PyObject* p); static Py::PythonClassObject create(const Vector2d&); static Py::PythonClassObject create(double x, double y); - Vector2dPy(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds); + Vector2dPy(Py::PythonClassInstance* self, Py::Tuple& args, Py::Dict& kwds); ~Vector2dPy() override; static void init_type(); - Py::Object getattro(const Py::String &name_) override; - int setattro(const Py::String &name_, const Py::Object &value) override; + Py::Object getattro(const Py::String& name_) override; + int setattro(const Py::String& name_, const Py::Object& value) override; Py::Object repr() override; - inline const Vector2d& value() const { + inline const Vector2d& value() const + { return v; } - inline void setValue(const Vector2d& n) { + inline void setValue(const Vector2d& n) + { v = n; } - inline void setValue(double x, double y) { + inline void setValue(double x, double y) + { v.x = x; v.y = y; } @@ -88,17 +92,17 @@ public: Py::Object number_invert() override; Py::Object number_int() override; Py::Object number_float() override; - Py::Object number_add( const Py::Object & ) override; - Py::Object number_subtract( const Py::Object & ) override; - Py::Object number_multiply( const Py::Object & ) override; - Py::Object number_remainder( const Py::Object & ) override; - Py::Object number_divmod( const Py::Object & ) override; - Py::Object number_lshift( const Py::Object & ) override; - Py::Object number_rshift( const Py::Object & ) override; - Py::Object number_and( const Py::Object & ) override; - Py::Object number_xor( const Py::Object & ) override; - Py::Object number_or( const Py::Object & ) override; - Py::Object number_power( const Py::Object &, const Py::Object & ) override; + Py::Object number_add(const Py::Object&) override; + Py::Object number_subtract(const Py::Object&) override; + Py::Object number_multiply(const Py::Object&) override; + Py::Object number_remainder(const Py::Object&) override; + Py::Object number_divmod(const Py::Object&) override; + Py::Object number_lshift(const Py::Object&) override; + Py::Object number_rshift(const Py::Object&) override; + Py::Object number_and(const Py::Object&) override; + Py::Object number_xor(const Py::Object&) override; + Py::Object number_or(const Py::Object&) override; + Py::Object number_power(const Py::Object&, const Py::Object&) override; //@} Py::Object isNull(const Py::Tuple&); @@ -118,53 +122,62 @@ private: Vector2d v; }; -} +} // namespace Base -namespace Py { +namespace Py +{ using Vector2d = PythonClassObject; -inline Base::Vector2d toVector2d(PyObject *py) { +inline Base::Vector2d toVector2d(PyObject* py) +{ Base::Vector2dPy* py2d = Py::Vector2d(py).getCxxObject(); return py2d ? py2d->value() : Base::Vector2d(); } -inline Base::Vector2d toVector2d(const Object& py) { +inline Base::Vector2d toVector2d(const Object& py) +{ Base::Vector2dPy* py2d = Py::Vector2d(py).getCxxObject(); return py2d ? py2d->value() : Base::Vector2d(); } // Implementing the vector class in the fashion of the PyCXX library. -class BaseExport Vector : public Object +class BaseExport Vector: public Object // NOLINT { public: - explicit Vector (PyObject *pyob, bool owned): Object(pyob, owned) { + explicit Vector(PyObject* pyob, bool owned) + : Object(pyob, owned) + { validate(); } - Vector (const Vector& ob): Object(*ob) { + Vector(const Vector& ob) + : Object(*ob) + { validate(); } - explicit Vector (const Base::Vector3d&); - explicit Vector (const Base::Vector3f&); - bool accepts (PyObject *pyob) const override; + explicit Vector(const Base::Vector3d&); + explicit Vector(const Base::Vector3f&); + bool accepts(PyObject* pyob) const override; - Vector(const Object& other): Object(other.ptr()) { + Vector(const Object& other) + : Object(other.ptr()) + { validate(); } - Vector& operator= (const Object& rhs) + Vector& operator=(const Object& rhs) { return (*this = *rhs); } - Vector& operator= (const Vector& rhs) + Vector& operator=(const Vector& rhs) { return (*this = *rhs); } - Vector& operator= (PyObject* rhsp); - Vector& operator= (const Base::Vector3d&); - Vector& operator= (const Base::Vector3f&); + Vector& operator=(PyObject* rhsp); + Vector& operator=(const Base::Vector3d&); + Vector& operator=(const Base::Vector3f&); operator Base::Vector3d() const { return toVector(); @@ -173,7 +186,7 @@ public: Base::Vector3d toVector() const; private: - static int Vector_TypeCheck(PyObject *); + static int Vector_TypeCheck(PyObject*); }; /** @@ -188,45 +201,54 @@ private: // The third template parameter is the definition of a pointer to the method // of the Python binding class to return the managed geometric instance. In our // example this is the method RotationPy::getRotationPtr. -template -class GeometryT : public Object +template +class GeometryT: public Object // NOLINT { public: - explicit GeometryT (PyObject *pyob, bool owned): Object(pyob, owned) { + explicit GeometryT(PyObject* pyob, bool owned) + : Object(pyob, owned) + { validate(); } - GeometryT (const GeometryT& ob): Object(*ob) { + GeometryT(const GeometryT& ob) + : Object(*ob) + { validate(); } - explicit GeometryT () + explicit GeometryT() { set(new PyT(new T()), true); validate(); } - explicit GeometryT (const T& v) + explicit GeometryT(const T& v) { set(new PyT(new T(v)), true); validate(); } - GeometryT(const Object& other): Object(other.ptr()) { + GeometryT(const Object& other) + : Object(other.ptr()) + { validate(); } - bool accepts (PyObject *pyob) const override { - return pyob && Geometry_TypeCheck (pyob); + bool accepts(PyObject* pyob) const override + { + return pyob && Geometry_TypeCheck(pyob); } - GeometryT& operator= (const Object& rhs) + GeometryT& operator=(const Object& rhs) { return (*this = *rhs); } - GeometryT& operator= (PyObject* rhsp) + GeometryT& operator=(PyObject* rhsp) { - if(ptr() == rhsp) return *this; - set (rhsp, false); + if (ptr() == rhsp) { + return *this; + } + set(rhsp, false); return *this; } - GeometryT& operator= (const T& v) + GeometryT& operator=(const T& v) { - set (new PyT(v), true); + set(new PyT(v), true); return *this; } const T& getValue() const @@ -248,22 +270,20 @@ public: } private: - static int Geometry_TypeCheck(PyObject * obj) + static int Geometry_TypeCheck(PyObject* obj) { return PyObject_TypeCheck(obj, &(PyT::Type)); } }; // PyCXX wrapper classes Py::Matrix, Py::Rotation, Py::Placement, ... -using BoundingBox = GeometryT; -using Matrix = GeometryT; -using Rotation = GeometryT; -using Placement = GeometryT; +using BoundingBox = + GeometryT; +using Matrix = GeometryT; +using Rotation = GeometryT; +using Placement = + GeometryT; -} +} // namespace Py -#endif // PY_GEOMETRYPY_H +#endif // PY_GEOMETRYPY_H diff --git a/src/Base/Handle.cpp b/src/Base/Handle.cpp index 4d55ee2ed8..b64d10d7d2 100644 --- a/src/Base/Handle.cpp +++ b/src/Base/Handle.cpp @@ -25,8 +25,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include @@ -40,14 +40,14 @@ using namespace Base; // Construction/Destruction Handled::Handled() - : _lRefCount(new QAtomicInt(0)) -{ -} + : _lRefCount(new QAtomicInt(0)) +{} Handled::~Handled() { - if (static_cast(*_lRefCount) != 0) + if (static_cast(*_lRefCount) != 0) { std::cerr << "Reference counter of deleted object is not zero!!!!!" << std::endl; + } delete _lRefCount; } @@ -67,7 +67,7 @@ void Handled::unref() const int Handled::unrefNoDelete() const { int res = _lRefCount->deref(); - assert(res>=0); + assert(res >= 0); return res; } @@ -76,7 +76,7 @@ int Handled::getRefCount() const return static_cast(*_lRefCount); } -Handled& Handled::operator = (const Handled&) +Handled& Handled::operator=(const Handled&) { // we must not assign _lRefCount return *this; diff --git a/src/Base/Handle.h b/src/Base/Handle.h index a6f67cc2be..a67754dfb4 100644 --- a/src/Base/Handle.h +++ b/src/Base/Handle.h @@ -40,7 +40,7 @@ namespace Base * Only able to instantiate with a class inheriting * Base::Handled. */ -template +template class Reference { public: @@ -48,18 +48,25 @@ public: // construction & destruction /** Pointer and default constructor */ - Reference() : _toHandle(nullptr) { - } + Reference() + : _toHandle(nullptr) + {} - Reference(T* p) : _toHandle(p) { - if (_toHandle) + Reference(T* p) + : _toHandle(p) + { + if (_toHandle) { _toHandle->ref(); + } } /** Copy constructor */ - Reference(const Reference& p) : _toHandle(p._toHandle) { - if (_toHandle) + Reference(const Reference& p) + : _toHandle(p._toHandle) + { + if (_toHandle) { _toHandle->ref(); + } } /** destructor @@ -67,51 +74,64 @@ public: * in case of the last one, the referenced object to * be destructed! */ - ~Reference() { - if (_toHandle) + ~Reference() + { + if (_toHandle) { _toHandle->unref(); + } } //************************************************************************** // operator implementation /** Assign operator from a pointer */ - Reference & operator=(T* p) { + Reference& operator=(T* p) + { // check if we want to reassign the same object - if (_toHandle == p) + if (_toHandle == p) { return *this; - if (_toHandle) + } + if (_toHandle) { _toHandle->unref(); + } _toHandle = p; - if (_toHandle) + if (_toHandle) { _toHandle->ref(); + } return *this; } /** Assign operator from a handle */ - Reference & operator=(const Reference& p) { + Reference& operator=(const Reference& p) + { // check if we want to reassign the same object - if (_toHandle == p._toHandle) + if (_toHandle == p._toHandle) { return *this; - if (_toHandle) + } + if (_toHandle) { _toHandle->unref(); + } _toHandle = p._toHandle; - if (_toHandle) + if (_toHandle) { _toHandle->ref(); + } return *this; } /** Dereference operator */ - T& operator*() const { + T& operator*() const + { return *_toHandle; } /** Dereference operator */ - T* operator->() const { + T* operator->() const + { return _toHandle; } - operator T*() const { + operator T*() const + { return _toHandle; } @@ -119,24 +139,28 @@ public: // checking on the state /// Test if it handles something - bool isValid() const { + bool isValid() const + { return _toHandle != nullptr; } /// Test if it does not handle anything - bool isNull() const { + bool isNull() const + { return _toHandle == nullptr; } /// Get number of references on the object, including this one - int getRefCount() const { - if (_toHandle) + int getRefCount() const + { + if (_toHandle) { return _toHandle->getRefCount(); + } return 0; } private: - T *_toHandle; /** the pointer to the handled object */ + T* _toHandle; /** the pointer to the handled object */ }; /** Handled class @@ -153,16 +177,16 @@ public: int unrefNoDelete() const; int getRefCount() const; - Handled& operator = (const Handled&); + Handled& operator=(const Handled&); Handled(const Handled&) = delete; Handled(Handled&&) = delete; - Handled& operator = (Handled&&) = delete; + Handled& operator=(Handled&&) = delete; private: QAtomicInt* _lRefCount; }; -} // namespace Base +} // namespace Base -#endif // BASE_HANDLE_H +#endif // BASE_HANDLE_H diff --git a/src/Base/InputSource.cpp b/src/Base/InputSource.cpp index e1ef01219d..ca1ff34386 100644 --- a/src/Base/InputSource.cpp +++ b/src/Base/InputSource.cpp @@ -50,15 +50,19 @@ using namespace std; struct StdInputStream::TextCodec { QTextCodec::ConverterState state; - TextCodec() { + TextCodec() + { state.flags |= QTextCodec::IgnoreHeader; state.flags |= QTextCodec::ConvertInvalidToNull; } - void validateBytes(XMLByte* const toFill, std::streamsize len) { - QTextCodec *textCodec = QTextCodec::codecForName("UTF-8"); + void validateBytes(XMLByte* const toFill, std::streamsize len) + { + QTextCodec* textCodec = QTextCodec::codecForName("UTF-8"); if (textCodec) { - const QString text = textCodec->toUnicode(reinterpret_cast(toFill), static_cast(len), &state); + const QString text = textCodec->toUnicode(reinterpret_cast(toFill), + static_cast(len), + &state); if (state.invalidChars > 0) { // In case invalid characters were found decode back to 'utf-8' and replace // them with '?' @@ -67,7 +71,7 @@ struct StdInputStream::TextCodec // we have to go through the array and replace '\0' with '?'. std::streamsize pos = 0; QByteArray ba = textCodec->fromUnicode(text); - for (int i=0; i(toFill), static_cast(len)); + void validateBytes(XMLByte* const toFill, std::streamsize len) + { + QByteArray encodedString(reinterpret_cast(toFill), static_cast(len)); auto toUtf16 = QStringDecoder(QStringDecoder::Utf8); QString text = toUtf16(encodedString); if (toUtf16.hasError()) { @@ -92,7 +97,7 @@ struct StdInputStream::TextCodec std::streamsize pos = 0; auto fromUtf16 = QStringEncoder(QStringEncoder::Utf8); QByteArray ba = fromUtf16(text); - for (int i=0; i(stream.tellg()); + return static_cast(stream.tellg()); } -XMLSize_t StdInputStream::readBytes(XMLByte* const toFill, const XMLSize_t maxToRead) +XMLSize_t StdInputStream::readBytes(XMLByte* const toFill, const XMLSize_t maxToRead) { - // - // Read up to the maximum bytes requested. We return the number - // actually read. - // + // + // Read up to the maximum bytes requested. We return the number + // actually read. + // - stream.read(reinterpret_cast(toFill), static_cast(maxToRead)); - std::streamsize len = stream.gcount(); + stream.read(reinterpret_cast(toFill), static_cast(maxToRead)); + std::streamsize len = stream.gcount(); - codec->validateBytes(toFill, len); + codec->validateBytes(toFill, len); - return static_cast(len); + return static_cast(len); } // --------------------------------------------------------------------------- // StdInputSource: Constructors and Destructor // --------------------------------------------------------------------------- -StdInputSource::StdInputSource ( std::istream& Stream, const char* filePath, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager ) - : InputSource(manager),stream(Stream) +StdInputSource::StdInputSource(std::istream& Stream, + const char* filePath, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager) + : InputSource(manager) + , stream(Stream) { - // we have to set the file name in case an error occurs - XStr tmpBuf(filePath); - setSystemId(tmpBuf.unicodeForm()); + // we have to set the file name in case an error occurs + XStr tmpBuf(filePath); + setSystemId(tmpBuf.unicodeForm()); } @@ -157,7 +166,6 @@ StdInputSource::~StdInputSource() = default; // --------------------------------------------------------------------------- BinInputStream* StdInputSource::makeStream() const { - StdInputStream* retStrm = new StdInputStream(stream /*, getMemoryManager()*/); - return retStrm; + StdInputStream* retStrm = new StdInputStream(stream /*, getMemoryManager()*/); + return retStrm; } - diff --git a/src/Base/InputSource.h b/src/Base/InputSource.h index 0b09e5f022..a5fe42630c 100644 --- a/src/Base/InputSource.h +++ b/src/Base/InputSource.h @@ -34,61 +34,69 @@ XERCES_CPP_NAMESPACE_BEGIN - class BinInputStream; +class BinInputStream; XERCES_CPP_NAMESPACE_END namespace Base { -class BaseExport StdInputStream : public XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream +class BaseExport StdInputStream: public XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream { -public : - StdInputStream ( std::istream& Stream, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager ); - ~StdInputStream() override; +public: + StdInputStream(std::istream& Stream, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = + XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager); + ~StdInputStream() override; - // ----------------------------------------------------------------------- - // Implementation of the input stream interface - // ----------------------------------------------------------------------- - XMLFilePos curPos() const override; - XMLSize_t readBytes( XMLByte* const toFill, const XMLSize_t maxToRead ) override; - const XMLCh* getContentType() const override {return nullptr;} + // ----------------------------------------------------------------------- + // Implementation of the input stream interface + // ----------------------------------------------------------------------- + XMLFilePos curPos() const override; + XMLSize_t readBytes(XMLByte* const toFill, const XMLSize_t maxToRead) override; + const XMLCh* getContentType() const override + { + return nullptr; + } - // ----------------------------------------------------------------------- - // Unimplemented constructors and operators - // ----------------------------------------------------------------------- - StdInputStream(const StdInputStream&) = delete; - StdInputStream& operator=(const StdInputStream&) = delete; - -private : - // ----------------------------------------------------------------------- - // Private data members - // - // fSource - // The source file that we represent. The FileHandle type is defined - // per platform. - // ----------------------------------------------------------------------- - std::istream &stream; - struct TextCodec; - std::unique_ptr codec; -}; - - -class BaseExport StdInputSource : public XERCES_CPP_NAMESPACE_QUALIFIER InputSource -{ -public : - StdInputSource ( std::istream& Stream, const char* filePath, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager ); - ~StdInputSource() override; - - XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const override; - - StdInputSource(const StdInputSource&) = delete; - StdInputSource& operator=(const StdInputSource&) = delete; + // ----------------------------------------------------------------------- + // Unimplemented constructors and operators + // ----------------------------------------------------------------------- + StdInputStream(const StdInputStream&) = delete; + StdInputStream& operator=(const StdInputStream&) = delete; private: - std::istream &stream; + // ----------------------------------------------------------------------- + // Private data members + // + // fSource + // The source file that we represent. The FileHandle type is defined + // per platform. + // ----------------------------------------------------------------------- + std::istream& stream; + struct TextCodec; + std::unique_ptr codec; }; -} -#endif // BASE_IINPUTSOURCE_H +class BaseExport StdInputSource: public XERCES_CPP_NAMESPACE_QUALIFIER InputSource +{ +public: + StdInputSource(std::istream& Stream, + const char* filePath, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = + XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager); + ~StdInputSource() override; + + XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const override; + + StdInputSource(const StdInputSource&) = delete; + StdInputSource& operator=(const StdInputSource&) = delete; + +private: + std::istream& stream; +}; + +} // namespace Base + +#endif // BASE_IINPUTSOURCE_H diff --git a/src/Base/Interpreter.cpp b/src/Base/Interpreter.cpp index 00c621d780..7f788e847c 100644 --- a/src/Base/Interpreter.cpp +++ b/src/Base/Interpreter.cpp @@ -25,8 +25,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "Interpreter.h" @@ -38,12 +38,13 @@ #include "Stream.h" -char format2[1024]; //Warning! Can't go over 512 characters!!! +char format2[1024]; // Warning! Can't go over 512 characters!!! unsigned int format2_len = 1024; using namespace Base; -PyException::PyException(const Py::Object &obj) { +PyException::PyException(const Py::Object& obj) +{ _sErrMsg = obj.as_string(); // WARNING: we are assuming that python type object will never be // destroyed, so we don't keep reference here to save book-keeping in @@ -56,12 +57,12 @@ PyException::PyException(const Py::Object &obj) { PyException::PyException() { - PP_Fetch_Error_Text(); /* fetch (and clear) exception */ + PP_Fetch_Error_Text(); /* fetch (and clear) exception */ setPyObject(PP_PyDict_Object); std::string prefix = PP_last_error_type; /* exception name text */ - std::string error = PP_last_error_info; /* exception data text */ + std::string error = PP_last_error_info; /* exception data text */ _sErrMsg = error; _errorType = prefix; @@ -75,16 +76,15 @@ PyException::PyException() // our copy constructor and destructor Py_DECREF(PP_last_exception_type); PP_last_exception_type = nullptr; - } - _stackTrace = PP_last_error_trace; /* exception traceback text */ + _stackTrace = PP_last_error_trace; /* exception traceback text */ // This should be done in the constructor because when doing // in the destructor it's not always clear when it is called // and thus may clear a Python exception when it should not. PyGILStateLocker locker; - PyErr_Clear(); // must be called to keep Python interpreter in a valid state (Werner) + PyErr_Clear(); // must be called to keep Python interpreter in a valid state (Werner) } PyException::~PyException() noexcept = default; @@ -96,7 +96,8 @@ void PyException::ThrowException() myexcp.raiseException(); } -void PyException::raiseException() { +void PyException::raiseException() +{ PyGILStateLocker locker; if (PP_PyDict_Object) { // delete the Python dict upon destruction of edict @@ -104,11 +105,12 @@ void PyException::raiseException() { PP_PyDict_Object = nullptr; std::string exceptionname; - if (_exceptionType == Base::PyExc_FC_FreeCADAbort) - edict.setItem("sclassname", - Py::String(typeid(Base::AbortException).name())); - if (_isReported) + if (_exceptionType == Base::PyExc_FC_FreeCADAbort) { + edict.setItem("sclassname", Py::String(typeid(Base::AbortException).name())); + } + if (_isReported) { edict.setItem("breported", Py::True()); + } Base::ExceptionFactory::Instance().raiseException(edict.ptr()); } @@ -121,24 +123,25 @@ void PyException::raiseException() { throw *this; } -void PyException::ReportException () const +void PyException::ReportException() const { if (!_isReported) { _isReported = true; // set sys.last_vars to make post-mortem debugging work PyGILStateLocker locker; PySys_SetObject("last_traceback", PP_last_traceback); - Base::Console().DeveloperError("pyException","%s%s: %s\n", - _stackTrace.c_str(), _errorType.c_str(), what()); + Base::Console().DeveloperError("pyException", + "%s%s: %s\n", + _stackTrace.c_str(), + _errorType.c_str(), + what()); } } void PyException::setPyException() const { std::stringstream str; - str << getStackTrace() - << getErrorType() - << ": " << what(); + str << getStackTrace() << getErrorType() << ": " << what(); PyErr_SetString(getPyExceptionType(), str.str().c_str()); } @@ -156,8 +159,8 @@ SystemExitException::SystemExitException() // sys.exit() | 1 | "System Exit" long int errCode = 1; - std::string errMsg = "System exit"; - PyObject *type{}, *value{}, *traceback{}, *code{}; + std::string errMsg = "System exit"; + PyObject *type {}, *value {}, *traceback {}, *code {}; PyGILStateLocker locker; PyErr_Fetch(&type, &value, &traceback); @@ -166,21 +169,22 @@ SystemExitException::SystemExitException() if (value) { code = PyObject_GetAttrString(value, "code"); if (code && value != Py_None) { - Py_DECREF(value); - value = code; + Py_DECREF(value); + value = code; } if (PyLong_Check(value)) { errCode = PyLong_AsLong(value); } else { - const char *str = PyUnicode_AsUTF8(value); - if (str) + const char* str = PyUnicode_AsUTF8(value); + if (str) { errMsg = errMsg + ": " + str; + } } } - _sErrMsg = errMsg; + _sErrMsg = errMsg; _exitCode = errCode; } @@ -188,15 +192,15 @@ SystemExitException::SystemExitException() // Fixes #0000831: python print causes File descriptor error on windows // NOLINTNEXTLINE -class PythonStdOutput : public Py::PythonExtension +class PythonStdOutput: public Py::PythonExtension { public: static void init_type() { behaviors().name("PythonStdOutput"); behaviors().doc("Python standard output"); - add_varargs_method("write",&PythonStdOutput::write,"write()"); - add_varargs_method("flush",&PythonStdOutput::flush,"flush()"); + add_varargs_method("write", &PythonStdOutput::write, "write()"); + add_varargs_method("flush", &PythonStdOutput::flush, "flush()"); } PythonStdOutput() = default; @@ -222,26 +226,29 @@ InterpreterSingleton::InterpreterSingleton() InterpreterSingleton::~InterpreterSingleton() = default; -std::string InterpreterSingleton::runString(const char *sCmd) +std::string InterpreterSingleton::runString(const char* sCmd) { - PyObject *module{}, *dict{}, *presult{}; /* "exec code in d, d" */ + PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ PyGILStateLocker locker; - module = PP_Load_Module("__main__"); /* get module, init python */ - if (!module) - throw PyException(); /* not incref'd */ - dict = PyModule_GetDict(module); /* get dict namespace */ - if (!dict) - throw PyException(); /* not incref'd */ + module = PP_Load_Module("__main__"); /* get module, init python */ + if (!module) { + throw PyException(); /* not incref'd */ + } + dict = PyModule_GetDict(module); /* get dict namespace */ + if (!dict) { + throw PyException(); /* not incref'd */ + } presult = PyRun_String(sCmd, Py_file_input, dict, dict); /* eval direct */ if (!presult) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); + } else { PyException::ThrowException(); - return {}; // just to quieten code analyzers + return {}; // just to quieten code analyzers } } @@ -268,7 +275,9 @@ std::string InterpreterSingleton::runString(const char *sCmd) * if the error occurs after changing it inside the script. */ -std::string InterpreterSingleton::runStringWithKey(const char *psCmd, const char *key, const char *key_initial_value) +std::string InterpreterSingleton::runStringWithKey(const char* psCmd, + const char* key, + const char* key_initial_value) { PyGILStateLocker locker; Py::Module module("__main__"); @@ -277,46 +286,52 @@ std::string InterpreterSingleton::runStringWithKey(const char *psCmd, const char Py::String initial_value(key_initial_value); localDictionary.setItem(key, initial_value); - PyObject* presult = PyRun_String(psCmd, Py_file_input, globalDictionary.ptr(), localDictionary.ptr()); + PyObject* presult = + PyRun_String(psCmd, Py_file_input, globalDictionary.ptr(), localDictionary.ptr()); if (!presult) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } else { PyException::ThrowException(); - return {}; // just to quieten code analyzers + return {}; // just to quieten code analyzers } } Py_DECREF(presult); Py::Object key_return_value = localDictionary.getItem(key); - if (!key_return_value.isString()) + if (!key_return_value.isString()) { key_return_value = key_return_value.str(); + } Py::Bytes str = Py::String(key_return_value).encode("utf-8", "~E~"); std::string result = static_cast(str); return result; } -Py::Object InterpreterSingleton::runStringObject(const char *sCmd) +Py::Object InterpreterSingleton::runStringObject(const char* sCmd) { - PyObject *module{}, *dict{}, *presult{}; /* "exec code in d, d" */ + PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ PyGILStateLocker locker; - module = PP_Load_Module("__main__"); /* get module, init python */ - if (!module) - throw PyException(); /* not incref'd */ - dict = PyModule_GetDict(module); /* get dict namespace */ - if (!dict) - throw PyException(); /* not incref'd */ + module = PP_Load_Module("__main__"); /* get module, init python */ + if (!module) { + throw PyException(); /* not incref'd */ + } + dict = PyModule_GetDict(module); /* get dict namespace */ + if (!dict) { + throw PyException(); /* not incref'd */ + } presult = PyRun_String(sCmd, Py_eval_input, dict, dict); /* eval direct */ if (!presult) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); - else + } + else { throw PyException(); + } } return Py::asObject(presult); @@ -325,21 +340,23 @@ Py::Object InterpreterSingleton::runStringObject(const char *sCmd) void InterpreterSingleton::systemExit() { /* This code is taken from the original Python code */ - PyObject *exception{}, *value{}, *tb{}; + PyObject *exception {}, *value {}, *tb {}; int exitcode = 0; PyErr_Fetch(&exception, &value, &tb); fflush(stdout); - if (!value || value == Py_None) - goto done; // NOLINT + if (!value || value == Py_None) { + goto done; // NOLINT + } if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ - PyObject *code = PyObject_GetAttrString(value, "code"); + PyObject* code = PyObject_GetAttrString(value, "code"); if (code) { Py_DECREF(value); value = code; - if (value == Py_None) - goto done; // NOLINT + if (value == Py_None) { + goto done; // NOLINT + } } /* If we failed to dig out the 'code' attribute, just let the else clause below print the error. */ @@ -364,17 +381,19 @@ done: /* NOTREACHED */ } -void InterpreterSingleton::runInteractiveString(const char *sCmd) +void InterpreterSingleton::runInteractiveString(const char* sCmd) { - PyObject *module{}, *dict{}, *presult{}; /* "exec code in d, d" */ + PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ PyGILStateLocker locker; - module = PP_Load_Module("__main__"); /* get module, init python */ - if (!module) - throw PyException(); /* not incref'd */ - dict = PyModule_GetDict(module); /* get dict namespace */ - if (!dict) - throw PyException(); /* not incref'd */ + module = PP_Load_Module("__main__"); /* get module, init python */ + if (!module) { + throw PyException(); /* not incref'd */ + } + dict = PyModule_GetDict(module); /* get dict namespace */ + if (!dict) { + throw PyException(); /* not incref'd */ + } presult = PyRun_String(sCmd, Py_single_input, dict, dict); /* eval direct */ if (!presult) { @@ -383,45 +402,48 @@ void InterpreterSingleton::runInteractiveString(const char *sCmd) } /* get latest python exception information */ /* and print the error to the error output */ - PyObject *errobj{}, *errdata{}, *errtraceback{}; + PyObject *errobj {}, *errdata {}, *errtraceback {}; PyErr_Fetch(&errobj, &errdata, &errtraceback); - RuntimeError exc(""); // do not use PyException since this clears the error indicator + RuntimeError exc(""); // do not use PyException since this clears the error indicator if (errdata) { - if (PyUnicode_Check(errdata)) + if (PyUnicode_Check(errdata)) { exc.setMessage(PyUnicode_AsUTF8(errdata)); + } } PyErr_Restore(errobj, errdata, errtraceback); - if (PyErr_Occurred()) + if (PyErr_Occurred()) { PyErr_Print(); + } throw exc; } - else + else { Py_DECREF(presult); + } } -void InterpreterSingleton::runFile(const char*pxFileName, bool local) +void InterpreterSingleton::runFile(const char* pxFileName, bool local) { #ifdef FC_OS_WIN32 FileInfo fi(pxFileName); - FILE *fp = _wfopen(fi.toStdWString().c_str(),L"r"); + FILE* fp = _wfopen(fi.toStdWString().c_str(), L"r"); #else - FILE *fp = fopen(pxFileName,"r"); + FILE* fp = fopen(pxFileName, "r"); #endif if (fp) { PyGILStateLocker locker; - PyObject *module{}, *dict{}; + PyObject *module {}, *dict {}; module = PyImport_AddModule("__main__"); dict = PyModule_GetDict(module); if (local) { dict = PyDict_Copy(dict); } else { - Py_INCREF(dict); // avoid to further distinguish between local and global dict + Py_INCREF(dict); // avoid to further distinguish between local and global dict } if (!PyDict_GetItemString(dict, "__file__")) { - PyObject *pyObj = PyUnicode_FromString(pxFileName); + PyObject* pyObj = PyUnicode_FromString(pxFileName); if (!pyObj) { fclose(fp); Py_DECREF(dict); @@ -436,15 +458,17 @@ void InterpreterSingleton::runFile(const char*pxFileName, bool local) Py_DECREF(pyObj); } - PyObject *result = PyRun_File(fp, pxFileName, Py_file_input, dict, dict); + PyObject* result = PyRun_File(fp, pxFileName, Py_file_input, dict, dict); fclose(fp); Py_DECREF(dict); if (!result) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); - else + } + else { throw PyException(); + } } Py_DECREF(result); } @@ -456,17 +480,19 @@ void InterpreterSingleton::runFile(const char*pxFileName, bool local) bool InterpreterSingleton::loadModule(const char* psModName) { // buffer acrobatics - //PyBuf ModName(psModName); - PyObject *module{}; + // PyBuf ModName(psModName); + PyObject* module {}; PyGILStateLocker locker; module = PP_Load_Module(psModName); if (!module) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); - else + } + else { throw PyException(); + } } return true; @@ -482,22 +508,23 @@ void InterpreterSingleton::cleanupModules() { // This is only needed to make the address sanitizer happy #if defined(__has_feature) -# if __has_feature(address_sanitizer) +#if __has_feature(address_sanitizer) for (auto it : _modules) { delete it; } _modules.clear(); -# endif +#endif #endif } -void InterpreterSingleton::addType(PyTypeObject* Type,PyObject* Module, const char * Name) +void InterpreterSingleton::addType(PyTypeObject* Type, PyObject* Module, const char* Name) { // NOTE: To finish the initialization of our own type objects we must // call PyType_Ready, otherwise we run into a segmentation fault, later on. // This function is responsible for adding inherited slots from a type's base class. - if (PyType_Ready(Type) < 0) + if (PyType_Ready(Type) < 0) { return; + } PyModule_AddObject(Module, Name, Base::getTypeAsObject(Type)); } @@ -509,14 +536,14 @@ void InterpreterSingleton::addPythonPath(const char* Path) } #if PY_VERSION_HEX < 0x030b0000 -const char* InterpreterSingleton::init(int argc,char *argv[]) +const char* InterpreterSingleton::init(int argc, char* argv[]) { if (!Py_IsInitialized()) { - Py_SetProgramName(Py_DecodeLocale(argv[0],nullptr)); - // There is a serious bug in VS from 2010 until 2013 where the file descriptor for stdin, stdout or stderr - // returns a valid value for GUI applications (i.e. subsystem = Windows) where it shouldn't. - // This causes Python to fail during initialization. - // A workaround is to use freopen on stdin, stdout and stderr. See the class Redirection inside main() + Py_SetProgramName(Py_DecodeLocale(argv[0], nullptr)); + // There is a serious bug in VS from 2010 until 2013 where the file descriptor for stdin, + // stdout or stderr returns a valid value for GUI applications (i.e. subsystem = Windows) + // where it shouldn't. This causes Python to fail during initialization. A workaround is to + // use freopen on stdin, stdout and stderr. See the class Redirection inside main() // https://bugs.python.org/issue17797#msg197474 // Py_Initialize(); @@ -524,14 +551,15 @@ const char* InterpreterSingleton::init(int argc,char *argv[]) if (virtualenv) { PyRun_SimpleString( "# Check for virtualenv, and activate if present.\n" - "# See https://virtualenv.pypa.io/en/latest/userguide/#using-virtualenv-without-bin-python\n" + "# See " + "https://virtualenv.pypa.io/en/latest/userguide/" + "#using-virtualenv-without-bin-python\n" "import os\n" "import sys\n" "base_path = os.getenv(\"VIRTUAL_ENV\")\n" "if not base_path is None:\n" " activate_this = os.path.join(base_path, \"bin\", \"activate_this.py\")\n" - " exec(open(activate_this).read(), {'__file__':activate_this})\n" - ); + " exec(open(activate_this).read(), {'__file__':activate_this})\n"); } #if PY_VERSION_HEX < 0x03090000 @@ -539,9 +567,9 @@ const char* InterpreterSingleton::init(int argc,char *argv[]) #endif size_t size = argc; - static std::vector _argv(size); + static std::vector _argv(size); for (int i = 0; i < argc; i++) { - _argv[i] = Py_DecodeLocale(argv[i],nullptr); + _argv[i] = Py_DecodeLocale(argv[i], nullptr); } PySys_SetArgv(argc, _argv.data()); PythonStdOutput::init_type(); @@ -549,11 +577,12 @@ const char* InterpreterSingleton::init(int argc,char *argv[]) } PyGILStateLocker lock; - return Py_EncodeLocale(Py_GetPath(),nullptr); + return Py_EncodeLocale(Py_GetPath(), nullptr); } #else -namespace { -void initInterpreter(int argc,char *argv[]) +namespace +{ +void initInterpreter(int argc, char* argv[]) { PyStatus status; PyConfig config; @@ -576,18 +605,18 @@ void initInterpreter(int argc,char *argv[]) if (virtualenv) { PyRun_SimpleString( "# Check for virtualenv, and activate if present.\n" - "# See https://virtualenv.pypa.io/en/latest/userguide/#using-virtualenv-without-bin-python\n" + "# See " + "https://virtualenv.pypa.io/en/latest/userguide/#using-virtualenv-without-bin-python\n" "import os\n" "import sys\n" "base_path = os.getenv(\"VIRTUAL_ENV\")\n" "if not base_path is None:\n" " activate_this = os.path.join(base_path, \"bin\", \"activate_this.py\")\n" - " exec(open(activate_this).read(), {'__file__':activate_this})\n" - ); + " exec(open(activate_this).read(), {'__file__':activate_this})\n"); } } -} -const char* InterpreterSingleton::init(int argc,char *argv[]) +} // namespace +const char* InterpreterSingleton::init(int argc, char* argv[]) { try { if (!Py_IsInitialized()) { @@ -598,7 +627,7 @@ const char* InterpreterSingleton::init(int argc,char *argv[]) } PyGILStateLocker lock; - return Py_EncodeLocale(Py_GetPath(),nullptr); + return Py_EncodeLocale(Py_GetPath(), nullptr); } catch (const Base::Exception& e) { e.ReportException(); @@ -617,7 +646,7 @@ void InterpreterSingleton::replaceStdOutput() int InterpreterSingleton::cleanup(void (*func)()) { - return Py_AtExit( func ); + return Py_AtExit(func); } void InterpreterSingleton::finalize() @@ -631,14 +660,14 @@ void InterpreterSingleton::finalize() } } -void InterpreterSingleton::runStringArg(const char * psCom,...) +void InterpreterSingleton::runStringArg(const char* psCom, ...) { // va stuff va_list namelessVars; va_start(namelessVars, psCom); // Get the "..." vars int len = vsnprintf(format2, format2_len, psCom, namelessVars); va_end(namelessVars); - if ( len == -1 ) { + if (len == -1) { // argument too long assert(false); } @@ -649,13 +678,14 @@ void InterpreterSingleton::runStringArg(const char * psCom,...) // Singleton: -InterpreterSingleton * InterpreterSingleton::_pcSingleton = nullptr; +InterpreterSingleton* InterpreterSingleton::_pcSingleton = nullptr; -InterpreterSingleton & InterpreterSingleton::Instance() +InterpreterSingleton& InterpreterSingleton::Instance() { // not initialized! - if (!_pcSingleton) + if (!_pcSingleton) { _pcSingleton = new InterpreterSingleton(); + } return *_pcSingleton; } @@ -667,7 +697,7 @@ void InterpreterSingleton::Destruct() _pcSingleton = nullptr; } -int InterpreterSingleton::runCommandLine(const char *prompt) +int InterpreterSingleton::runCommandLine(const char* prompt) { PyGILStateLocker locker; return PP_Run_Command_Line(prompt); @@ -677,51 +707,57 @@ int InterpreterSingleton::runCommandLine(const char *prompt) * Runs a member method of an object with no parameter and no return value * void (void). There are other methods to run with returns */ -void InterpreterSingleton::runMethodVoid(PyObject *pobject, const char *method) +void InterpreterSingleton::runMethodVoid(PyObject* pobject, const char* method) { PyGILStateLocker locker; - if (PP_Run_Method(pobject , // object - method, // run method - nullptr, // no return type - nullptr, // so no return object - "()") // no arguments - != 0) + if (PP_Run_Method(pobject, // object + method, // run method + nullptr, // no return type + nullptr, // so no return object + "()") // no arguments + != 0) { throw PyException(/*"Error running InterpreterSingleton::RunMethodVoid()"*/); - + } } -PyObject* InterpreterSingleton::runMethodObject(PyObject *pobject, const char *method) +PyObject* InterpreterSingleton::runMethodObject(PyObject* pobject, const char* method) { - PyObject *pcO{}; + PyObject* pcO {}; PyGILStateLocker locker; - if (PP_Run_Method(pobject , // object - method, // run method - "O", // return type - &pcO, // return object - "()") // no arguments - != 0) + if (PP_Run_Method(pobject, // object + method, // run method + "O", // return type + &pcO, // return object + "()") // no arguments + != 0) { throw PyException(); + } return pcO; } -void InterpreterSingleton::runMethod(PyObject *pobject, const char *method, - const char *resfmt, void *cresult, /* convert to c/c++ */ - const char *argfmt, ... ) /* convert to python */ +void InterpreterSingleton::runMethod(PyObject* pobject, + const char* method, + const char* resfmt, + void* cresult, /* convert to c/c++ */ + const char* argfmt, + ...) /* convert to python */ { - PyObject *pmeth{}, *pargs{}, *presult{}; - va_list argslist; /* "pobject.method(args)" */ + PyObject *pmeth {}, *pargs {}, *presult {}; + va_list argslist; /* "pobject.method(args)" */ va_start(argslist, argfmt); PyGILStateLocker locker; pmeth = PyObject_GetAttrString(pobject, method); - if (!pmeth) { /* get callable object */ + if (!pmeth) { /* get callable object */ va_end(argslist); - throw AttributeError("Error running InterpreterSingleton::RunMethod() method not defined"); /* bound method? has self */ + throw AttributeError( + "Error running InterpreterSingleton::RunMethod() method not defined"); /* bound method? + has self */ } - pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ + pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ va_end(argslist); if (!pargs) { @@ -730,31 +766,35 @@ void InterpreterSingleton::runMethod(PyObject *pobject, const char *method, } #if PY_VERSION_HEX < 0x03090000 - presult = PyEval_CallObject(pmeth, pargs); /* run interpreter */ + presult = PyEval_CallObject(pmeth, pargs); /* run interpreter */ #else - presult = PyObject_CallObject(pmeth, pargs); /* run interpreter */ + presult = PyObject_CallObject(pmeth, pargs); /* run interpreter */ #endif Py_DECREF(pmeth); Py_DECREF(pargs); - if (PP_Convert_Result(presult, resfmt, cresult)!= 0) { - if ( PyErr_Occurred() ) + if (PP_Convert_Result(presult, resfmt, cresult) != 0) { + if (PyErr_Occurred()) { PyErr_Print(); - throw RuntimeError("Error running InterpreterSingleton::RunMethod() exception in called method"); + } + throw RuntimeError( + "Error running InterpreterSingleton::RunMethod() exception in called method"); } } -PyObject * InterpreterSingleton::getValue(const char * key, const char * result_var) +PyObject* InterpreterSingleton::getValue(const char* key, const char* result_var) { - PyObject *module{}, *dict{}, *presult{}; /* "exec code in d, d" */ + PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ PyGILStateLocker locker; - module = PP_Load_Module("__main__"); /* get module, init python */ - if (!module) - throw PyException(); /* not incref'd */ - dict = PyModule_GetDict(module); /* get dict namespace */ - if (!dict) - throw PyException(); /* not incref'd */ + module = PP_Load_Module("__main__"); /* get module, init python */ + if (!module) { + throw PyException(); /* not incref'd */ + } + dict = PyModule_GetDict(module); /* get dict namespace */ + if (!dict) { + throw PyException(); /* not incref'd */ + } presult = PyRun_String(key, Py_file_input, dict, dict); /* eval direct */ @@ -768,45 +808,41 @@ PyObject * InterpreterSingleton::getValue(const char * key, const char * result_ void InterpreterSingleton::dbgObserveFile(const char* sFileName) { - if (sFileName) + if (sFileName) { _cDebugFileName = sFileName; - else + } + else { _cDebugFileName = ""; + } } void InterpreterSingleton::dbgSetBreakPoint(unsigned int /*uiLineNumber*/) -{ - -} +{} void InterpreterSingleton::dbgUnsetBreakPoint(unsigned int /*uiLineNumber*/) -{ - -} +{} void InterpreterSingleton::dbgStep() -{ - -} +{} const std::string InterpreterSingleton::strToPython(const char* Str) { std::string result; - const char *It=Str; + const char* It = Str; while (*It != '\0') { switch (*It) { - case '\\': - result += "\\\\"; - break; - case '\"': - result += "\\\""; - break; - case '\'': - result += "\\\'"; - break; - default: - result += *It; + case '\\': + result += "\\\\"; + break; + case '\"': + result += "\\\""; + break; + case '\'': + result += "\\\'"; + break; + default: + result += *It; } It++; } @@ -827,8 +863,9 @@ int getSWIGVersionFromModule(const std::string& module) try { // Get the module and check its __file__ attribute Py::Dict dict(PyImport_GetModuleDict()); - if (!dict.hasKey(module)) + if (!dict.hasKey(module)) { return 0; + } Py::Module mod(module); Py::String file(mod.getAttr("__file__")); std::string filename = (std::string)file; @@ -847,7 +884,7 @@ int getSWIGVersionFromModule(const std::string& module) int major = std::atoi(what[1].first); int minor = std::atoi(what[2].first); int micro = std::atoi(what[3].first); - int version = (major<<16)+(minor<<8)+micro; + int version = (major << 16) + (minor << 8) + micro; moduleMap[module] = version; return version; } @@ -865,18 +902,22 @@ int getSWIGVersionFromModule(const std::string& module) } #if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) -namespace Swig_python { +namespace Swig_python +{ extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); extern void cleanupSWIG_T(const char* TypeName); extern int getSWIGPointerTypeObj_T(const char* TypeName, PyTypeObject** ptr); -} +} // namespace Swig_python #endif -PyObject* InterpreterSingleton::createSWIGPointerObj(const char* Module, const char* TypeName, void* Pointer, int own) +PyObject* InterpreterSingleton::createSWIGPointerObj(const char* Module, + const char* TypeName, + void* Pointer, + int own) { int result = 0; - PyObject* proxy=nullptr; + PyObject* proxy = nullptr; PyGILStateLocker locker; (void)Module; #if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) @@ -885,17 +926,22 @@ PyObject* InterpreterSingleton::createSWIGPointerObj(const char* Module, const c (void)TypeName; (void)Pointer; (void)own; - result = -1; // indicates error + result = -1; // indicates error #endif - if (result == 0) + if (result == 0) { return proxy; + } // none of the SWIG's succeeded throw Base::RuntimeError("No SWIG wrapped library loaded"); } -bool InterpreterSingleton::convertSWIGPointerObj(const char* Module, const char* TypeName, PyObject* obj, void** ptr, int flags) +bool InterpreterSingleton::convertSWIGPointerObj(const char* Module, + const char* TypeName, + PyObject* obj, + void** ptr, + int flags) { int result = 0; PyGILStateLocker locker; @@ -907,11 +953,12 @@ bool InterpreterSingleton::convertSWIGPointerObj(const char* Module, const char* (void)obj; (void)ptr; (void)flags; - result = -1; // indicates error + result = -1; // indicates error #endif - if (result == 0) + if (result == 0) { return true; + } // none of the SWIG's succeeded throw Base::RuntimeError("No SWIG wrapped library loaded"); @@ -937,11 +984,12 @@ PyTypeObject* InterpreterSingleton::getSWIGPointerTypeObj(const char* Module, co result = Swig_python::getSWIGPointerTypeObj_T(TypeName, &proxy); #else (void)TypeName; - result = -1; // indicates error + result = -1; // indicates error #endif - if (result == 0) + if (result == 0) { return proxy; + } // none of the SWIG's succeeded throw Base::RuntimeError("No SWIG wrapped library loaded"); diff --git a/src/Base/Interpreter.h b/src/Base/Interpreter.h index 2655a25423..1a9535cd0b 100644 --- a/src/Base/Interpreter.h +++ b/src/Base/Interpreter.h @@ -24,12 +24,12 @@ #ifndef BASE_INTERPRETER_H #define BASE_INTERPRETER_H -#if defined (_POSIX_C_SOURCE) -# undef _POSIX_C_SOURCE -#endif // (re-)defined in pyconfig.h -#if defined (_XOPEN_SOURCE) -# undef _XOPEN_SOURCE -#endif // (re-)defined in pyconfig.h +#if defined(_POSIX_C_SOURCE) +#undef _POSIX_C_SOURCE +#endif // (re-)defined in pyconfig.h +#if defined(_XOPEN_SOURCE) +#undef _XOPEN_SOURCE +#endif // (re-)defined in pyconfig.h #ifdef FC_OS_MACOSX #undef toupper @@ -55,15 +55,15 @@ * * See FeaturePythonImp::init() for example usage */ -#define FC_PY_GetCallable(_pyobj,_name,_var) \ - do {\ - _var = Py::Object();\ - if(PyObject_HasAttrString(_pyobj, _name)) {\ - Py::Object _obj(PyObject_GetAttrString (_pyobj, _name), true);\ - if(_obj.isCallable())\ - _var = _obj;\ - }\ - }while(0) +#define FC_PY_GetCallable(_pyobj, _name, _var) \ + do { \ + _var = Py::Object(); \ + if (PyObject_HasAttrString(_pyobj, _name)) { \ + Py::Object _obj(PyObject_GetAttrString(_pyobj, _name), true); \ + if (_obj.isCallable()) \ + _var = _obj; \ + } \ + } while (0) /** Helper macro to obtain attribute from an object * @@ -73,26 +73,27 @@ * * See FeaturePythonImp::init() for example usage */ -#define FC_PY_GetObject(_pyobj,_name,_var) \ - do {\ - _var = Py::Object();\ - if(PyObject_HasAttrString(_pyobj, _name))\ - _var = Py::asObject(PyObject_GetAttrString (_pyobj, _name));\ - }while(0) +#define FC_PY_GetObject(_pyobj, _name, _var) \ + do { \ + _var = Py::Object(); \ + if (PyObject_HasAttrString(_pyobj, _name)) \ + _var = Py::asObject(PyObject_GetAttrString(_pyobj, _name)); \ + } while (0) -namespace Base { +namespace Base +{ - using std::string; - using std::vector; +using std::string; +using std::vector; -class BaseExport PyException : public Exception +class BaseExport PyException: public Exception { public: /// constructor does the whole job PyException(); - PyException(const Py::Object &obj); + PyException(const Py::Object& obj); ~PyException() noexcept override; void raiseException(); @@ -103,30 +104,43 @@ public: static void ThrowException(); /// this function returns the stack trace - const std::string &getStackTrace() const {return _stackTrace;} - const std::string &getErrorType() const {return _errorType;} - PyObject *getPyExceptionType() const override {return _exceptionType;} - void ReportException () const override; + const std::string& getStackTrace() const + { + return _stackTrace; + } + const std::string& getErrorType() const + { + return _errorType; + } + PyObject* getPyExceptionType() const override + { + return _exceptionType; + } + void ReportException() const override; /// Sets the Python error indicator and an error message void setPyException() const override; protected: std::string _stackTrace; std::string _errorType; - PyObject *_exceptionType; + PyObject* _exceptionType; }; -inline Py::Object pyCall(PyObject *callable, PyObject *args=nullptr) { - PyObject *result = PyObject_CallObject(callable, args); - if(!result) +inline Py::Object pyCall(PyObject* callable, PyObject* args = nullptr) +{ + PyObject* result = PyObject_CallObject(callable, args); + if (!result) { throw Py::Exception(); + } return Py::asObject(result); } -inline Py::Object pyCallWithKeywords(PyObject *callable, PyObject *args, PyObject *kwds=nullptr) { - PyObject *result = PyObject_Call(callable, args, kwds); - if(!result) +inline Py::Object pyCallWithKeywords(PyObject* callable, PyObject* args, PyObject* kwds = nullptr) +{ + PyObject* result = PyObject_Call(callable, args, kwds); + if (!result) { throw Py::Exception(); + } return Py::asObject(result); } @@ -135,12 +149,15 @@ inline Py::Object pyCallWithKeywords(PyObject *callable, PyObject *args, PyObjec * was thrown. * @author Werner Mayer */ -class BaseExport SystemExitException : public Exception +class BaseExport SystemExitException: public Exception { public: SystemExitException(); ~SystemExitException() noexcept override = default; - long getExitCode() const { return _exitCode;} + long getExitCode() const + { + return _exitCode; + } protected: long _exitCode; @@ -210,26 +227,32 @@ public: /** @name execution methods */ //@{ - /// Run a statement on the python interpreter and gives back a string with the representation of the result. - std::string runString(const char *psCmd); + /// Run a statement on the python interpreter and gives back a string with the representation of + /// the result. + std::string runString(const char* psCmd); /// Run a statement on the python interpreter with a key for exchanging strings - std::string runStringWithKey(const char *psCmd, const char *key, const char *key_initial_value=""); + std::string + runStringWithKey(const char* psCmd, const char* key, const char* key_initial_value = ""); /// Run a statement on the python interpreter and return back the result object. - Py::Object runStringObject(const char *sCmd); - /// Run a statement on the python interpreter and gives back a string with the representation of the result. - void runInteractiveString(const char *psCmd); + Py::Object runStringObject(const char* sCmd); + /// Run a statement on the python interpreter and gives back a string with the representation of + /// the result. + void runInteractiveString(const char* psCmd); /// Run file (script) on the python interpreter - void runFile(const char*pxFileName, bool local); + void runFile(const char* pxFileName, bool local); /// Run a statement with arguments on the python interpreter - void runStringArg(const char * psCom,...); + void runStringArg(const char* psCom, ...); /// runs a python object method with no return value and no arguments - void runMethodVoid(PyObject *pobject, const char *method); + void runMethodVoid(PyObject* pobject, const char* method); /// runs a python object method which returns a arbitrary object - PyObject* runMethodObject(PyObject *pobject, const char *method); + PyObject* runMethodObject(PyObject* pobject, const char* method); /// runs a python method with arbitrary params - void runMethod(PyObject *pobject, const char *method, - const char *resfmt=nullptr, void *cresult=nullptr, - const char *argfmt="()", ... ); + void runMethod(PyObject* pobject, + const char* method, + const char* resfmt = nullptr, + void* cresult = nullptr, + const char* argfmt = "()", + ...); //@} /** @name Module handling @@ -240,7 +263,7 @@ public: bool loadModule(const char* psModName); /// Add an additional python path void addPythonPath(const char* Path); - static void addType(PyTypeObject* Type,PyObject* Module, const char * Name); + static void addType(PyTypeObject* Type, PyObject* Module, const char* Name); /// Add a module and return a PyObject to it PyObject* addModule(Py::ExtensionModuleBase*); /// Clean-up registered modules @@ -250,11 +273,12 @@ public: /** @name Cleanup */ //@{ - /** Register a cleanup function to be called by finalize(). The cleanup function will be called with no - * arguments and should return no value. At most 32 cleanup functions can be registered. When the registration - * is successful 0 is returned; on failure -1 is returned. The cleanup function registered last is called - * first. Each cleanup function will be called at most once. Since Python's internal finalization will have - * completed before the cleanup function, no Python APIs should be called by \a func. + /** Register a cleanup function to be called by finalize(). The cleanup function will be called + * with no arguments and should return no value. At most 32 cleanup functions can be registered. + * When the registration is successful 0 is returned; on failure -1 is returned. The cleanup + * function registered last is called first. Each cleanup function will be called at most once. + * Since Python's internal finalization will have completed before the cleanup function, no + * Python APIs should be called by \a func. */ int cleanup(void (*func)()); /** This calls the registered cleanup functions. @see cleanup() for more details. */ @@ -267,10 +291,10 @@ public: */ //@{ /// init the interpreter and returns the module search path - const char* init(int argc,char *argv[]); - int runCommandLine(const char *prompt); + const char* init(int argc, char* argv[]); + int runCommandLine(const char* prompt); void replaceStdOutput(); - static InterpreterSingleton &Instance(); + static InterpreterSingleton& Instance(); static void Destruct(); //@} @@ -280,8 +304,13 @@ public: */ //@{ /// generate a SWIG object - PyObject* createSWIGPointerObj(const char* Modole, const char* TypeName, void* Pointer, int own); - bool convertSWIGPointerObj(const char* Module, const char* TypeName, PyObject* obj, void** ptr, int flags); + PyObject* + createSWIGPointerObj(const char* Modole, const char* TypeName, void* Pointer, int own); + bool convertSWIGPointerObj(const char* Module, + const char* TypeName, + PyObject* obj, + void** ptr, + int flags); void cleanupSWIG(const char* TypeName); PyTypeObject* getSWIGPointerTypeObj(const char* Module, const char* TypeName); //@} @@ -290,7 +319,7 @@ public: */ //@{ /// sets the file name which should be debugged - void dbgObserveFile(const char* sFileName=""); + void dbgObserveFile(const char* sFileName = ""); /// sets a break point to a special line number in the current file void dbgSetBreakPoint(unsigned int uiLineNumber); /// unsets a break point to a special line number in the current file @@ -305,14 +334,17 @@ public: //@{ /// replaces all char with escapes for usage in python console static const std::string strToPython(const char* Str); - static const std::string strToPython(const std::string &Str){return strToPython(Str.c_str());} + static const std::string strToPython(const std::string& Str) + { + return strToPython(Str.c_str()); + } //@} - PyObject *getValue(const char *key, const char *result_var); + PyObject* getValue(const char* key, const char* result_var); protected: // singleton - static InterpreterSingleton *_pcSingleton; + static InterpreterSingleton* _pcSingleton; private: std::string _cDebugFileName; @@ -325,11 +357,11 @@ private: * This method is used to gain access to the one and only instance of * the InterpreterSingleton class. */ -inline InterpreterSingleton &Interpreter() +inline InterpreterSingleton& Interpreter() { return InterpreterSingleton::Instance(); } -} //namespace Base +} // namespace Base -#endif // BASE_INTERPRETER_H +#endif // BASE_INTERPRETER_H diff --git a/src/Base/Matrix.cpp b/src/Base/Matrix.cpp index c6a870eddf..655623ba41 100644 --- a/src/Base/Matrix.cpp +++ b/src/Base/Matrix.cpp @@ -23,8 +23,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "Matrix.h" @@ -33,59 +33,71 @@ using namespace Base; -Matrix4D::Matrix4D () - : dMtrx4D{{1.,0.,0.,0.}, - {0.,1.,0.,0.}, - {0.,0.,1.,0.}, - {0.,0.,0.,1.}} -{ -} +// clang-format off +Matrix4D::Matrix4D() + : dMtrx4D {{1., 0., 0., 0.}, + {0., 1., 0., 0.}, + {0., 0., 1., 0.}, + {0., 0., 0., 1.}} +{} -Matrix4D::Matrix4D (float a11, float a12, float a13, float a14, - float a21, float a22, float a23, float a24, - float a31, float a32, float a33, float a34, - float a41, float a42, float a43, float a44) - : dMtrx4D{{a11,a12,a13,a14}, - {a21,a22,a23,a24}, - {a31,a32,a33,a34}, - {a41,a42,a43,a44}} -{ -} +Matrix4D::Matrix4D(float a11, float a12, float a13, float a14, + float a21, float a22, float a23, float a24, + float a31, float a32, float a33, float a34, + float a41, float a42, float a43, float a44) + : dMtrx4D {{a11, a12, a13, a14}, + {a21, a22, a23, a24}, + {a31, a32, a33, a34}, + {a41, a42, a43, a44}} +{} -Matrix4D::Matrix4D (double a11, double a12, double a13, double a14, - double a21, double a22, double a23, double a24, - double a31, double a32, double a33, double a34, - double a41, double a42, double a43, double a44 ) - : dMtrx4D{{a11,a12,a13,a14}, - {a21,a22,a23,a24}, - {a31,a32,a33,a34}, - {a41,a42,a43,a44}} -{ -} +Matrix4D::Matrix4D(double a11, double a12, double a13, double a14, + double a21, double a22, double a23, double a24, + double a31, double a32, double a33, double a34, + double a41, double a42, double a43, double a44) + : dMtrx4D {{a11, a12, a13, a14}, + {a21, a22, a23, a24}, + {a31, a32, a33, a34}, + {a41, a42, a43, a44}} +{} +// clang-format on -Matrix4D::Matrix4D (const Matrix4D& mat) : Matrix4D() +Matrix4D::Matrix4D(const Matrix4D& mat) + : Matrix4D() { (*this) = mat; } -Matrix4D::Matrix4D (const Vector3f& rclBase, const Vector3f& rclDir, float fAngle) - : Matrix4D() +Matrix4D::Matrix4D(const Vector3f& rclBase, const Vector3f& rclDir, float fAngle) + : Matrix4D() { - this->rotLine(rclBase,rclDir,fAngle); + this->rotLine(rclBase, rclDir, fAngle); } -Matrix4D::Matrix4D (const Vector3d& rclBase, const Vector3d& rclDir, double fAngle) - : Matrix4D() +Matrix4D::Matrix4D(const Vector3d& rclBase, const Vector3d& rclDir, double fAngle) + : Matrix4D() { - this->rotLine(rclBase,rclDir,fAngle); + this->rotLine(rclBase, rclDir, fAngle); } -void Matrix4D::setToUnity () +void Matrix4D::setToUnity() { - dMtrx4D[0][0] = 1.0; dMtrx4D[0][1] = 0.0; dMtrx4D[0][2] = 0.0; dMtrx4D[0][3] = 0.0; - dMtrx4D[1][0] = 0.0; dMtrx4D[1][1] = 1.0; dMtrx4D[1][2] = 0.0; dMtrx4D[1][3] = 0.0; - dMtrx4D[2][0] = 0.0; dMtrx4D[2][1] = 0.0; dMtrx4D[2][2] = 1.0; dMtrx4D[2][3] = 0.0; - dMtrx4D[3][0] = 0.0; dMtrx4D[3][1] = 0.0; dMtrx4D[3][2] = 0.0; dMtrx4D[3][3] = 1.0; + dMtrx4D[0][0] = 1.0; + dMtrx4D[0][1] = 0.0; + dMtrx4D[0][2] = 0.0; + dMtrx4D[0][3] = 0.0; + dMtrx4D[1][0] = 0.0; + dMtrx4D[1][1] = 1.0; + dMtrx4D[1][2] = 0.0; + dMtrx4D[1][3] = 0.0; + dMtrx4D[2][0] = 0.0; + dMtrx4D[2][1] = 0.0; + dMtrx4D[2][2] = 1.0; + dMtrx4D[2][3] = 0.0; + dMtrx4D[3][0] = 0.0; + dMtrx4D[3][1] = 0.0; + dMtrx4D[3][2] = 0.0; + dMtrx4D[3][3] = 1.0; } bool Matrix4D::isUnity() const @@ -115,41 +127,54 @@ bool Matrix4D::isUnity(double tol) const void Matrix4D::nullify() { - dMtrx4D[0][0] = 0.0; dMtrx4D[0][1] = 0.0; dMtrx4D[0][2] = 0.0; dMtrx4D[0][3] = 0.0; - dMtrx4D[1][0] = 0.0; dMtrx4D[1][1] = 0.0; dMtrx4D[1][2] = 0.0; dMtrx4D[1][3] = 0.0; - dMtrx4D[2][0] = 0.0; dMtrx4D[2][1] = 0.0; dMtrx4D[2][2] = 0.0; dMtrx4D[2][3] = 0.0; - dMtrx4D[3][0] = 0.0; dMtrx4D[3][1] = 0.0; dMtrx4D[3][2] = 0.0; dMtrx4D[3][3] = 0.0; + dMtrx4D[0][0] = 0.0; + dMtrx4D[0][1] = 0.0; + dMtrx4D[0][2] = 0.0; + dMtrx4D[0][3] = 0.0; + dMtrx4D[1][0] = 0.0; + dMtrx4D[1][1] = 0.0; + dMtrx4D[1][2] = 0.0; + dMtrx4D[1][3] = 0.0; + dMtrx4D[2][0] = 0.0; + dMtrx4D[2][1] = 0.0; + dMtrx4D[2][2] = 0.0; + dMtrx4D[2][3] = 0.0; + dMtrx4D[3][0] = 0.0; + dMtrx4D[3][1] = 0.0; + dMtrx4D[3][2] = 0.0; + dMtrx4D[3][3] = 0.0; } bool Matrix4D::isNull() const { - //NOLINTBEGIN + // NOLINTBEGIN for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { - if (dMtrx4D[i][j] != 0.0) + if (dMtrx4D[i][j] != 0.0) { return false; + } } } - //NOLINTEND + // NOLINTEND return true; } double Matrix4D::determinant() const { - double fA0 = dMtrx4D[0][0]*dMtrx4D[1][1] - dMtrx4D[0][1]*dMtrx4D[1][0]; - double fA1 = dMtrx4D[0][0]*dMtrx4D[1][2] - dMtrx4D[0][2]*dMtrx4D[1][0]; - double fA2 = dMtrx4D[0][0]*dMtrx4D[1][3] - dMtrx4D[0][3]*dMtrx4D[1][0]; - double fA3 = dMtrx4D[0][1]*dMtrx4D[1][2] - dMtrx4D[0][2]*dMtrx4D[1][1]; - double fA4 = dMtrx4D[0][1]*dMtrx4D[1][3] - dMtrx4D[0][3]*dMtrx4D[1][1]; - double fA5 = dMtrx4D[0][2]*dMtrx4D[1][3] - dMtrx4D[0][3]*dMtrx4D[1][2]; - double fB0 = dMtrx4D[2][0]*dMtrx4D[3][1] - dMtrx4D[2][1]*dMtrx4D[3][0]; - double fB1 = dMtrx4D[2][0]*dMtrx4D[3][2] - dMtrx4D[2][2]*dMtrx4D[3][0]; - double fB2 = dMtrx4D[2][0]*dMtrx4D[3][3] - dMtrx4D[2][3]*dMtrx4D[3][0]; - double fB3 = dMtrx4D[2][1]*dMtrx4D[3][2] - dMtrx4D[2][2]*dMtrx4D[3][1]; - double fB4 = dMtrx4D[2][1]*dMtrx4D[3][3] - dMtrx4D[2][3]*dMtrx4D[3][1]; - double fB5 = dMtrx4D[2][2]*dMtrx4D[3][3] - dMtrx4D[2][3]*dMtrx4D[3][2]; - double fDet = fA0*fB5-fA1*fB4+fA2*fB3+fA3*fB2-fA4*fB1+fA5*fB0; + double fA0 = dMtrx4D[0][0] * dMtrx4D[1][1] - dMtrx4D[0][1] * dMtrx4D[1][0]; + double fA1 = dMtrx4D[0][0] * dMtrx4D[1][2] - dMtrx4D[0][2] * dMtrx4D[1][0]; + double fA2 = dMtrx4D[0][0] * dMtrx4D[1][3] - dMtrx4D[0][3] * dMtrx4D[1][0]; + double fA3 = dMtrx4D[0][1] * dMtrx4D[1][2] - dMtrx4D[0][2] * dMtrx4D[1][1]; + double fA4 = dMtrx4D[0][1] * dMtrx4D[1][3] - dMtrx4D[0][3] * dMtrx4D[1][1]; + double fA5 = dMtrx4D[0][2] * dMtrx4D[1][3] - dMtrx4D[0][3] * dMtrx4D[1][2]; + double fB0 = dMtrx4D[2][0] * dMtrx4D[3][1] - dMtrx4D[2][1] * dMtrx4D[3][0]; + double fB1 = dMtrx4D[2][0] * dMtrx4D[3][2] - dMtrx4D[2][2] * dMtrx4D[3][0]; + double fB2 = dMtrx4D[2][0] * dMtrx4D[3][3] - dMtrx4D[2][3] * dMtrx4D[3][0]; + double fB3 = dMtrx4D[2][1] * dMtrx4D[3][2] - dMtrx4D[2][2] * dMtrx4D[3][1]; + double fB4 = dMtrx4D[2][1] * dMtrx4D[3][3] - dMtrx4D[2][3] * dMtrx4D[3][1]; + double fB5 = dMtrx4D[2][2] * dMtrx4D[3][3] - dMtrx4D[2][3] * dMtrx4D[3][2]; + double fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; return fDet; } @@ -165,24 +190,24 @@ double Matrix4D::determinant3() const return det; } -void Matrix4D::move (const Vector3f& vec) +void Matrix4D::move(const Vector3f& vec) { move(convertTo(vec)); } -void Matrix4D::move (const Vector3d& vec) +void Matrix4D::move(const Vector3d& vec) { dMtrx4D[0][3] += vec.x; dMtrx4D[1][3] += vec.y; dMtrx4D[2][3] += vec.z; } -void Matrix4D::scale (const Vector3f& vec) +void Matrix4D::scale(const Vector3f& vec) { scale(convertTo(vec)); } -void Matrix4D::scale (const Vector3d& vec) +void Matrix4D::scale(const Vector3d& vec) { Matrix4D clMat; @@ -192,44 +217,50 @@ void Matrix4D::scale (const Vector3d& vec) (*this) = clMat * (*this); } -void Matrix4D::rotX (double fAngle) +void Matrix4D::rotX(double fAngle) { Matrix4D clMat; - double fsin{}; - double fcos{}; + double fsin {}; + double fcos {}; - fsin = sin (fAngle); - fcos = cos (fAngle); - clMat.dMtrx4D[1][1] = fcos; clMat.dMtrx4D[2][2] = fcos; - clMat.dMtrx4D[1][2] = -fsin; clMat.dMtrx4D[2][1] = fsin; + fsin = sin(fAngle); + fcos = cos(fAngle); + clMat.dMtrx4D[1][1] = fcos; + clMat.dMtrx4D[2][2] = fcos; + clMat.dMtrx4D[1][2] = -fsin; + clMat.dMtrx4D[2][1] = fsin; (*this) = clMat * (*this); } -void Matrix4D::rotY (double fAngle) +void Matrix4D::rotY(double fAngle) { Matrix4D clMat; - double fsin{}; - double fcos{}; + double fsin {}; + double fcos {}; - fsin = sin (fAngle); - fcos = cos (fAngle); - clMat.dMtrx4D[0][0] = fcos; clMat.dMtrx4D[2][2] = fcos; - clMat.dMtrx4D[2][0] = -fsin; clMat.dMtrx4D[0][2] = fsin; + fsin = sin(fAngle); + fcos = cos(fAngle); + clMat.dMtrx4D[0][0] = fcos; + clMat.dMtrx4D[2][2] = fcos; + clMat.dMtrx4D[2][0] = -fsin; + clMat.dMtrx4D[0][2] = fsin; (*this) = clMat * (*this); } -void Matrix4D::rotZ (double fAngle) +void Matrix4D::rotZ(double fAngle) { Matrix4D clMat; - double fsin{}; - double fcos{}; + double fsin {}; + double fcos {}; - fsin = sin (fAngle); - fcos = cos (fAngle); - clMat.dMtrx4D[0][0] = fcos; clMat.dMtrx4D[1][1] = fcos; - clMat.dMtrx4D[0][1] = -fsin; clMat.dMtrx4D[1][0] = fsin; + fsin = sin(fAngle); + fcos = cos(fAngle); + clMat.dMtrx4D[0][0] = fcos; + clMat.dMtrx4D[1][1] = fcos; + clMat.dMtrx4D[0][1] = -fsin; + clMat.dMtrx4D[1][0] = fsin; (*this) = clMat * (*this); } @@ -242,12 +273,12 @@ void Matrix4D::rotLine(const Vector3d& vec, double fAngle) Matrix4D clMC; Matrix4D clMRot; Vector3d clRotAxis(vec); - double fcos{}; - double fsin{}; + double fcos {}; + double fsin {}; // set all entries to "0" for (short iz = 0; iz < 4; iz++) { - for (short is = 0; is < 4; is++) { + for (short is = 0; is < 4; is++) { clMA.dMtrx4D[iz][is] = 0; clMB.dMtrx4D[iz][is] = 0; clMC.dMtrx4D[iz][is] = 0; @@ -261,32 +292,32 @@ void Matrix4D::rotLine(const Vector3d& vec, double fAngle) fcos = cos(fAngle); fsin = sin(fAngle); - clMA.dMtrx4D[0][0] = (1-fcos) * clRotAxis.x * clRotAxis.x; - clMA.dMtrx4D[0][1] = (1-fcos) * clRotAxis.x * clRotAxis.y; - clMA.dMtrx4D[0][2] = (1-fcos) * clRotAxis.x * clRotAxis.z; - clMA.dMtrx4D[1][0] = (1-fcos) * clRotAxis.x * clRotAxis.y; - clMA.dMtrx4D[1][1] = (1-fcos) * clRotAxis.y * clRotAxis.y; - clMA.dMtrx4D[1][2] = (1-fcos) * clRotAxis.y * clRotAxis.z; - clMA.dMtrx4D[2][0] = (1-fcos) * clRotAxis.x * clRotAxis.z; - clMA.dMtrx4D[2][1] = (1-fcos) * clRotAxis.y * clRotAxis.z; - clMA.dMtrx4D[2][2] = (1-fcos) * clRotAxis.z * clRotAxis.z; + clMA.dMtrx4D[0][0] = (1 - fcos) * clRotAxis.x * clRotAxis.x; + clMA.dMtrx4D[0][1] = (1 - fcos) * clRotAxis.x * clRotAxis.y; + clMA.dMtrx4D[0][2] = (1 - fcos) * clRotAxis.x * clRotAxis.z; + clMA.dMtrx4D[1][0] = (1 - fcos) * clRotAxis.x * clRotAxis.y; + clMA.dMtrx4D[1][1] = (1 - fcos) * clRotAxis.y * clRotAxis.y; + clMA.dMtrx4D[1][2] = (1 - fcos) * clRotAxis.y * clRotAxis.z; + clMA.dMtrx4D[2][0] = (1 - fcos) * clRotAxis.x * clRotAxis.z; + clMA.dMtrx4D[2][1] = (1 - fcos) * clRotAxis.y * clRotAxis.z; + clMA.dMtrx4D[2][2] = (1 - fcos) * clRotAxis.z * clRotAxis.z; clMB.dMtrx4D[0][0] = fcos; clMB.dMtrx4D[1][1] = fcos; clMB.dMtrx4D[2][2] = fcos; clMC.dMtrx4D[0][1] = -fsin * clRotAxis.z; - clMC.dMtrx4D[0][2] = fsin * clRotAxis.y; - clMC.dMtrx4D[1][0] = fsin * clRotAxis.z; + clMC.dMtrx4D[0][2] = fsin * clRotAxis.y; + clMC.dMtrx4D[1][0] = fsin * clRotAxis.z; clMC.dMtrx4D[1][2] = -fsin * clRotAxis.x; clMC.dMtrx4D[2][0] = -fsin * clRotAxis.y; - clMC.dMtrx4D[2][1] = fsin * clRotAxis.x; + clMC.dMtrx4D[2][1] = fsin * clRotAxis.x; for (short iz = 0; iz < 3; iz++) { - for (short is = 0; is < 3; is++) - clMRot.dMtrx4D[iz][is] = clMA.dMtrx4D[iz][is] + - clMB.dMtrx4D[iz][is] + - clMC.dMtrx4D[iz][is]; + for (short is = 0; is < 3; is++) { + clMRot.dMtrx4D[iz][is] = + clMA.dMtrx4D[iz][is] + clMB.dMtrx4D[iz][is] + clMC.dMtrx4D[iz][is]; + } } (*this) = clMRot * (*this); @@ -309,21 +340,25 @@ void Matrix4D::rotLine(const Vector3f& rclBase, const Vector3f& rclDir, float fA { Vector3d pnt = convertTo(rclBase); Vector3d dir = convertTo(rclDir); - rotLine(pnt,dir,static_cast(fAngle)); + rotLine(pnt, dir, static_cast(fAngle)); } /** - * If this matrix describes a rotation around an arbitrary axis with a translation (in axis direction) - * then the base point of the axis, its direction, the rotation angle and the translation part get calculated. - * In this case the return value is set to true, if this matrix doesn't describe a rotation false is returned. + * If this matrix describes a rotation around an arbitrary axis with a translation (in axis + * direction) then the base point of the axis, its direction, the rotation angle and the translation + * part get calculated. In this case the return value is set to true, if this matrix doesn't + * describe a rotation false is returned. * - * The translation vector can be calculated with \a fTranslation * \a rclDir, whereas the length of \a rclDir - * is normalized to 1. + * The translation vector can be calculated with \a fTranslation * \a rclDir, whereas the length of + * \a rclDir is normalized to 1. * - * Note: In case the \a fTranslation part is zero then passing \a rclBase, \a rclDir and \a rfAngle to a new - * matrix object creates an identical matrix. + * Note: In case the \a fTranslation part is zero then passing \a rclBase, \a rclDir and \a rfAngle + * to a new matrix object creates an identical matrix. */ -bool Matrix4D::toAxisAngle (Vector3f& rclBase, Vector3f& rclDir, float& rfAngle, float& fTranslation) const +bool Matrix4D::toAxisAngle(Vector3f& rclBase, + Vector3f& rclDir, + float& rfAngle, + float& fTranslation) const { Vector3d pnt = convertTo(rclBase); Vector3d dir = convertTo(rclDir); @@ -341,319 +376,329 @@ bool Matrix4D::toAxisAngle (Vector3f& rclBase, Vector3f& rclDir, float& rfAngle, return ok; } -bool Matrix4D::toAxisAngle (Vector3d& rclBase, Vector3d& rclDir, double& rfAngle, double& fTranslation) const +bool Matrix4D::toAxisAngle(Vector3d& rclBase, + Vector3d& rclDir, + double& rfAngle, + double& fTranslation) const { - // First check if the 3x3 submatrix is orthogonal - for ( int i=0; i<3; i++ ) { - // length must be one - if ( fabs(dMtrx4D[0][i]*dMtrx4D[0][i]+dMtrx4D[1][i]*dMtrx4D[1][i]+dMtrx4D[2][i]*dMtrx4D[2][i]-1.0) > 0.01 ) - return false; - // scalar product with other rows must be zero - if ( fabs(dMtrx4D[0][i]*dMtrx4D[0][(i+1)%3]+dMtrx4D[1][i]*dMtrx4D[1][(i+1)%3]+dMtrx4D[2][i]*dMtrx4D[2][(i+1)%3]) > 0.01 ) - return false; - } - - // Okay, the 3x3 matrix is orthogonal. - // Note: The section to get the rotation axis and angle was taken from WildMagic Library. - // - // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. - // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where - // I is the identity and - // - // +- -+ - // P = | 0 -z +y | - // | +z 0 -x | - // | -y +x 0 | - // +- -+ - // - // If A > 0, R represents a counterclockwise rotation about the axis in - // the sense of looking from the tip of the axis vector towards the - // origin. Some algebra will show that - // - // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P - // - // In the event that A = pi, R-R^t = 0 which prevents us from extracting - // the axis through P. Instead note that R = I+2*P^2 when A = pi, so - // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and - // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, - // it does not matter which sign you choose on the square roots. - // - // For more details see also http://www.math.niu.edu/~rusin/known-math/97/rotations - - double fTrace = dMtrx4D[0][0] + dMtrx4D[1][1] + dMtrx4D[2][2]; - double fCos = 0.5*(fTrace-1.0); - rfAngle = acos(fCos); // in [0,PI] - - if ( rfAngle > 0.0 ) - { - if ( rfAngle < D_PI ) - { - rclDir.x = (dMtrx4D[2][1]-dMtrx4D[1][2]); - rclDir.y = (dMtrx4D[0][2]-dMtrx4D[2][0]); - rclDir.z = (dMtrx4D[1][0]-dMtrx4D[0][1]); - rclDir.Normalize(); + // First check if the 3x3 submatrix is orthogonal + for (int i = 0; i < 3; i++) { + // length must be one + if (fabs(dMtrx4D[0][i] * dMtrx4D[0][i] + dMtrx4D[1][i] * dMtrx4D[1][i] + + dMtrx4D[2][i] * dMtrx4D[2][i] - 1.0) + > 0.01) { + return false; + } + // scalar product with other rows must be zero + if (fabs(dMtrx4D[0][i] * dMtrx4D[0][(i + 1) % 3] + dMtrx4D[1][i] * dMtrx4D[1][(i + 1) % 3] + + dMtrx4D[2][i] * dMtrx4D[2][(i + 1) % 3]) + > 0.01) { + return false; + } } - else - { - // angle is PI - double fHalfInverse{}; - if ( dMtrx4D[0][0] >= dMtrx4D[1][1] ) - { - // r00 >= r11 - if ( dMtrx4D[0][0] >= dMtrx4D[2][2] ) - { - // r00 is maximum diagonal term - rclDir.x = (0.5*sqrt(dMtrx4D[0][0] - dMtrx4D[1][1] - dMtrx4D[2][2] + 1.0)); - fHalfInverse = 0.5/rclDir.x; - rclDir.y = (fHalfInverse*dMtrx4D[0][1]); - rclDir.z = (fHalfInverse*dMtrx4D[0][2]); + + // Okay, the 3x3 matrix is orthogonal. + // Note: The section to get the rotation axis and angle was taken from WildMagic Library. + // + // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. + // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where + // I is the identity and + // + // +- -+ + // P = | 0 -z +y | + // | +z 0 -x | + // | -y +x 0 | + // +- -+ + // + // If A > 0, R represents a counterclockwise rotation about the axis in + // the sense of looking from the tip of the axis vector towards the + // origin. Some algebra will show that + // + // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P + // + // In the event that A = pi, R-R^t = 0 which prevents us from extracting + // the axis through P. Instead note that R = I+2*P^2 when A = pi, so + // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and + // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, + // it does not matter which sign you choose on the square roots. + // + // For more details see also http://www.math.niu.edu/~rusin/known-math/97/rotations + + double fTrace = dMtrx4D[0][0] + dMtrx4D[1][1] + dMtrx4D[2][2]; + double fCos = 0.5 * (fTrace - 1.0); + rfAngle = acos(fCos); // in [0,PI] + + if (rfAngle > 0.0) { + if (rfAngle < D_PI) { + rclDir.x = (dMtrx4D[2][1] - dMtrx4D[1][2]); + rclDir.y = (dMtrx4D[0][2] - dMtrx4D[2][0]); + rclDir.z = (dMtrx4D[1][0] - dMtrx4D[0][1]); + rclDir.Normalize(); } - else - { - // r22 is maximum diagonal term - rclDir.z = (0.5*sqrt(dMtrx4D[2][2] - dMtrx4D[0][0] - dMtrx4D[1][1] + 1.0)); - fHalfInverse = 0.5/rclDir.z; - rclDir.x = (fHalfInverse*dMtrx4D[0][2]); - rclDir.y = (fHalfInverse*dMtrx4D[1][2]); + else { + // angle is PI + double fHalfInverse {}; + if (dMtrx4D[0][0] >= dMtrx4D[1][1]) { + // r00 >= r11 + if (dMtrx4D[0][0] >= dMtrx4D[2][2]) { + // r00 is maximum diagonal term + rclDir.x = (0.5 * sqrt(dMtrx4D[0][0] - dMtrx4D[1][1] - dMtrx4D[2][2] + 1.0)); + fHalfInverse = 0.5 / rclDir.x; + rclDir.y = (fHalfInverse * dMtrx4D[0][1]); + rclDir.z = (fHalfInverse * dMtrx4D[0][2]); + } + else { + // r22 is maximum diagonal term + rclDir.z = (0.5 * sqrt(dMtrx4D[2][2] - dMtrx4D[0][0] - dMtrx4D[1][1] + 1.0)); + fHalfInverse = 0.5 / rclDir.z; + rclDir.x = (fHalfInverse * dMtrx4D[0][2]); + rclDir.y = (fHalfInverse * dMtrx4D[1][2]); + } + } + else { + // r11 > r00 + if (dMtrx4D[1][1] >= dMtrx4D[2][2]) { + // r11 is maximum diagonal term + rclDir.y = (0.5 * sqrt(dMtrx4D[1][1] - dMtrx4D[0][0] - dMtrx4D[2][2] + 1.0)); + fHalfInverse = 0.5 / rclDir.y; + rclDir.x = (fHalfInverse * dMtrx4D[0][1]); + rclDir.z = (fHalfInverse * dMtrx4D[1][2]); + } + else { + // r22 is maximum diagonal term + rclDir.z = (0.5 * sqrt(dMtrx4D[2][2] - dMtrx4D[0][0] - dMtrx4D[1][1] + 1.0)); + fHalfInverse = 0.5 / rclDir.z; + rclDir.x = (fHalfInverse * dMtrx4D[0][2]); + rclDir.y = (fHalfInverse * dMtrx4D[1][2]); + } + } } - } - else - { - // r11 > r00 - if ( dMtrx4D[1][1] >= dMtrx4D[2][2] ) - { - // r11 is maximum diagonal term - rclDir.y = (0.5*sqrt(dMtrx4D[1][1] - dMtrx4D[0][0] - dMtrx4D[2][2] + 1.0)); - fHalfInverse = 0.5/rclDir.y; - rclDir.x = (fHalfInverse*dMtrx4D[0][1]); - rclDir.z = (fHalfInverse*dMtrx4D[1][2]); - } - else - { - // r22 is maximum diagonal term - rclDir.z = (0.5*sqrt(dMtrx4D[2][2] - dMtrx4D[0][0] - dMtrx4D[1][1] + 1.0)); - fHalfInverse = 0.5/rclDir.z; - rclDir.x = (fHalfInverse*dMtrx4D[0][2]); - rclDir.y = (fHalfInverse*dMtrx4D[1][2]); - } - } } - } - else - { - // The angle is 0 and the matrix is the identity. Any axis will - // work, so just use the x-axis. - rclDir.x = 1.0; - rclDir.y = 0.0; - rclDir.z = 0.0; - rclBase.x = 0.0; - rclBase.y = 0.0; - rclBase.z = 0.0; - } + else { + // The angle is 0 and the matrix is the identity. Any axis will + // work, so just use the x-axis. + rclDir.x = 1.0; + rclDir.y = 0.0; + rclDir.z = 0.0; + rclBase.x = 0.0; + rclBase.y = 0.0; + rclBase.z = 0.0; + } - // This is the translation part in axis direction - fTranslation = (dMtrx4D[0][3]*rclDir.x+dMtrx4D[1][3]*rclDir.y+dMtrx4D[2][3]*rclDir.z); - Vector3d cPnt(dMtrx4D[0][3],dMtrx4D[1][3],dMtrx4D[2][3]); - cPnt = cPnt - fTranslation * rclDir; + // This is the translation part in axis direction + fTranslation = (dMtrx4D[0][3] * rclDir.x + dMtrx4D[1][3] * rclDir.y + dMtrx4D[2][3] * rclDir.z); + Vector3d cPnt(dMtrx4D[0][3], dMtrx4D[1][3], dMtrx4D[2][3]); + cPnt = cPnt - fTranslation * rclDir; - // This is the base point of the rotation axis - if ( rfAngle > 0.0 ) - { - double factor = 0.5*(1.0+fTrace)/sin(rfAngle); - rclBase.x = (0.5*(cPnt.x+factor*(rclDir.y*cPnt.z-rclDir.z*cPnt.y))); - rclBase.y = (0.5*(cPnt.y+factor*(rclDir.z*cPnt.x-rclDir.x*cPnt.z))); - rclBase.z = (0.5*(cPnt.z+factor*(rclDir.x*cPnt.y-rclDir.y*cPnt.x))); - } + // This is the base point of the rotation axis + if (rfAngle > 0.0) { + double factor = 0.5 * (1.0 + fTrace) / sin(rfAngle); + rclBase.x = (0.5 * (cPnt.x + factor * (rclDir.y * cPnt.z - rclDir.z * cPnt.y))); + rclBase.y = (0.5 * (cPnt.y + factor * (rclDir.z * cPnt.x - rclDir.x * cPnt.z))); + rclBase.z = (0.5 * (cPnt.z + factor * (rclDir.x * cPnt.y - rclDir.y * cPnt.x))); + } - return true; + return true; } -void Matrix4D::transform (const Vector3f& vec, const Matrix4D& mat) +void Matrix4D::transform(const Vector3f& vec, const Matrix4D& mat) { move(-vec); (*this) = mat * (*this); move(vec); } -void Matrix4D::transform (const Vector3d& vec, const Matrix4D& mat) +void Matrix4D::transform(const Vector3d& vec, const Matrix4D& mat) { move(-vec); (*this) = mat * (*this); move(vec); } -void Matrix4D::inverse () +void Matrix4D::inverse() { - Matrix4D clInvTrlMat; - Matrix4D clInvRotMat; + Matrix4D clInvTrlMat; + Matrix4D clInvRotMat; - /**** Herausnehmen und Inversion der TranslationsMatrix - aus der TransformationMatrix ****/ - for (short iz = 0 ;iz < 3; iz++) { - clInvTrlMat.dMtrx4D[iz][3] = -dMtrx4D[iz][3]; - } - - /**** Herausnehmen und Inversion der RotationsMatrix - aus der TransformationMatrix ****/ - for (short iz = 0 ;iz < 3; iz++) { - for (short is = 0 ;is < 3; is++) { - clInvRotMat.dMtrx4D[iz][is] = dMtrx4D[is][iz]; + /**** Herausnehmen und Inversion der TranslationsMatrix + aus der TransformationMatrix ****/ + for (short iz = 0; iz < 3; iz++) { + clInvTrlMat.dMtrx4D[iz][3] = -dMtrx4D[iz][3]; } - } - /**** inv(M) = inv(Mtrl * Mrot) = inv(Mrot) * inv(Mtrl) ****/ - (*this) = clInvRotMat * clInvTrlMat; + /**** Herausnehmen und Inversion der RotationsMatrix + aus der TransformationMatrix ****/ + for (short iz = 0; iz < 3; iz++) { + for (short is = 0; is < 3; is++) { + clInvRotMat.dMtrx4D[iz][is] = dMtrx4D[is][iz]; + } + } + + /**** inv(M) = inv(Mtrl * Mrot) = inv(Mrot) * inv(Mtrl) ****/ + (*this) = clInvRotMat * clInvTrlMat; } -using Matrix = double *; +using Matrix = double*; void Matrix_gauss(Matrix a, Matrix b) { - int ipiv[4], indxr[4], indxc[4]; - int i{},j{},k{},l{},ll{}; - int irow=0, icol=0; - double big{}, pivinv{}; - double dum{}; - for (j = 0; j < 4; j++) - ipiv[j] = 0; - for (i = 0; i < 4; i++) { - big = 0; + int ipiv[4], indxr[4], indxc[4]; + int i {}, j {}, k {}, l {}, ll {}; + int irow = 0, icol = 0; + double big {}, pivinv {}; + double dum {}; for (j = 0; j < 4; j++) { - if (ipiv[j] != 1) { - for (k = 0; k < 4; k++) { - if (ipiv[k] == 0) { - if (fabs(a[4*j+k]) >= big) { - big = fabs(a[4*j+k]); - irow = j; - icol = k; - } - } else if (ipiv[k] > 1) - return; /* Singular matrix */ - } - } + ipiv[j] = 0; } - ipiv[icol] = ipiv[icol]+1; - if (irow != icol) { - for (l = 0; l < 4; l++) { - dum = a[4*irow+l]; - a[4*irow+l] = a[4*icol+l]; - a[4*icol+l] = dum; - } - for (l = 0; l < 4; l++) { - dum = b[4*irow+l]; - b[4*irow+l] = b[4*icol+l]; - b[4*icol+l] = dum; - } + for (i = 0; i < 4; i++) { + big = 0; + for (j = 0; j < 4; j++) { + if (ipiv[j] != 1) { + for (k = 0; k < 4; k++) { + if (ipiv[k] == 0) { + if (fabs(a[4 * j + k]) >= big) { + big = fabs(a[4 * j + k]); + irow = j; + icol = k; + } + } + else if (ipiv[k] > 1) { + return; /* Singular matrix */ + } + } + } + } + ipiv[icol] = ipiv[icol] + 1; + if (irow != icol) { + for (l = 0; l < 4; l++) { + dum = a[4 * irow + l]; + a[4 * irow + l] = a[4 * icol + l]; + a[4 * icol + l] = dum; + } + for (l = 0; l < 4; l++) { + dum = b[4 * irow + l]; + b[4 * irow + l] = b[4 * icol + l]; + b[4 * icol + l] = dum; + } + } + indxr[i] = irow; + indxc[i] = icol; + if (a[4 * icol + icol] == 0.0) { + return; + } + pivinv = 1.0 / a[4 * icol + icol]; + a[4 * icol + icol] = 1.0; + for (l = 0; l < 4; l++) { + a[4 * icol + l] = a[4 * icol + l] * pivinv; + } + for (l = 0; l < 4; l++) { + b[4 * icol + l] = b[4 * icol + l] * pivinv; + } + for (ll = 0; ll < 4; ll++) { + if (ll != icol) { + dum = a[4 * ll + icol]; + a[4 * ll + icol] = 0; + for (l = 0; l < 4; l++) { + a[4 * ll + l] = a[4 * ll + l] - a[4 * icol + l] * dum; + } + for (l = 0; l < 4; l++) { + b[4 * ll + l] = b[4 * ll + l] - b[4 * icol + l] * dum; + } + } + } } - indxr[i] = irow; - indxc[i] = icol; - if (a[4*icol+icol] == 0.0) - return; - pivinv = 1.0/a[4*icol+icol]; - a[4*icol+icol] = 1.0; - for (l = 0; l < 4; l++) - a[4*icol+l] = a[4*icol+l]*pivinv; - for (l = 0; l < 4; l++) - b[4*icol+l] = b[4*icol+l]*pivinv; - for (ll = 0; ll < 4; ll++) { - if (ll != icol) { - dum = a[4*ll+icol]; - a[4*ll+icol] = 0; - for (l = 0; l < 4; l++) - a[4*ll+l] = a[4*ll+l] - a[4*icol+l]*dum; - for (l = 0; l < 4; l++) - b[4*ll+l] = b[4*ll+l] - b[4*icol+l]*dum; - } + for (l = 3; l >= 0; l--) { + if (indxr[l] != indxc[l]) { + for (k = 0; k < 4; k++) { + dum = a[4 * k + indxr[l]]; + a[4 * k + indxr[l]] = a[4 * k + indxc[l]]; + a[4 * k + indxc[l]] = dum; + } + } } - } - for (l = 3; l >= 0; l--) { - if (indxr[l] != indxc[l]) { - for (k = 0; k < 4; k++) { - dum = a[4*k+indxr[l]]; - a[4*k+indxr[l]] = a[4*k+indxc[l]]; - a[4*k+indxc[l]] = dum; - } - } - } } -void Matrix4D::inverseOrthogonal() +void Matrix4D::inverseOrthogonal() { - Base::Vector3d vec(dMtrx4D[0][3],dMtrx4D[1][3],dMtrx4D[2][3]); + Base::Vector3d vec(dMtrx4D[0][3], dMtrx4D[1][3], dMtrx4D[2][3]); transpose(); - vec = this->operator * (vec); - dMtrx4D[0][3] = -vec.x; dMtrx4D[3][0] = 0; - dMtrx4D[1][3] = -vec.y; dMtrx4D[3][1] = 0; - dMtrx4D[2][3] = -vec.z; dMtrx4D[3][2] = 0; + vec = this->operator*(vec); + dMtrx4D[0][3] = -vec.x; + dMtrx4D[3][0] = 0; + dMtrx4D[1][3] = -vec.y; + dMtrx4D[3][1] = 0; + dMtrx4D[2][3] = -vec.z; + dMtrx4D[3][2] = 0; } -void Matrix4D::inverseGauss () +void Matrix4D::inverseGauss() { - double matrix [16]; - double inversematrix [16] = { 1 ,0 ,0 ,0 , - 0 ,1 ,0 ,0 , - 0 ,0 ,1 ,0 , - 0 ,0 ,0 ,1 }; - getGLMatrix(matrix); + double matrix[16]; + double inversematrix[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; + getGLMatrix(matrix); - Matrix_gauss(matrix,inversematrix); + Matrix_gauss(matrix, inversematrix); - setGLMatrix(inversematrix); + setGLMatrix(inversematrix); } -void Matrix4D::getMatrix (double dMtrx[16]) const +void Matrix4D::getMatrix(double dMtrx[16]) const { for (short iz = 0; iz < 4; iz++) { for (short is = 0; is < 4; is++) { - dMtrx[ 4*iz + is ] = dMtrx4D[iz][is]; + dMtrx[4 * iz + is] = dMtrx4D[iz][is]; } } } -void Matrix4D::setMatrix (const double dMtrx[16]) +void Matrix4D::setMatrix(const double dMtrx[16]) { for (short iz = 0; iz < 4; iz++) { for (short is = 0; is < 4; is++) { - dMtrx4D[iz][is] = dMtrx[ 4*iz + is ]; + dMtrx4D[iz][is] = dMtrx[4 * iz + is]; } } } -void Matrix4D::getGLMatrix (double dMtrx[16]) const +void Matrix4D::getGLMatrix(double dMtrx[16]) const { for (short iz = 0; iz < 4; iz++) { for (short is = 0; is < 4; is++) { - dMtrx[ iz + 4*is ] = dMtrx4D[iz][is]; + dMtrx[iz + 4 * is] = dMtrx4D[iz][is]; } } } -void Matrix4D::setGLMatrix (const double dMtrx[16]) +void Matrix4D::setGLMatrix(const double dMtrx[16]) { for (short iz = 0; iz < 4; iz++) { for (short is = 0; is < 4; is++) { - dMtrx4D[iz][is] = dMtrx[ iz + 4*is ]; + dMtrx4D[iz][is] = dMtrx[iz + 4 * is]; } } } -unsigned long Matrix4D::getMemSpace () +unsigned long Matrix4D::getMemSpace() { return sizeof(Matrix4D); } -void Matrix4D::Print () const +void Matrix4D::Print() const { - //NOLINTBEGIN + // NOLINTBEGIN for (short i = 0; i < 4; i++) { - printf("%9.3f %9.3f %9.3f %9.3f\n", dMtrx4D[i][0], dMtrx4D[i][1], dMtrx4D[i][2], dMtrx4D[i][3]); + printf("%9.3f %9.3f %9.3f %9.3f\n", + dMtrx4D[i][0], + dMtrx4D[i][1], + dMtrx4D[i][2], + dMtrx4D[i][3]); } - //NOLINTEND + // NOLINTEND } -void Matrix4D::transpose () +void Matrix4D::transpose() { - double dNew[4][4]; + double dNew[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { @@ -665,80 +710,79 @@ void Matrix4D::transpose () } - // write the 12 double of the matrix in a stream std::string Matrix4D::toString() const { - std::stringstream str; - //NOLINTBEGIN - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) - str << dMtrx4D[i][j] << " "; - } - //NOLINTEND + std::stringstream str; + // NOLINTBEGIN + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + str << dMtrx4D[i][j] << " "; + } + } + // NOLINTEND - return str.str(); + return str.str(); } // read the 12 double of the matrix from a stream -void Matrix4D::fromString(const std::string &str) +void Matrix4D::fromString(const std::string& str) { - std::stringstream input; - input.str(str); + std::stringstream input; + input.str(str); - //NOLINTBEGIN - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) - input >> dMtrx4D[i][j]; - } - //NOLINTEND + // NOLINTBEGIN + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + input >> dMtrx4D[i][j]; + } + } + // NOLINTEND } // Analyse the a transformation Matrix and describe the transformation std::string Matrix4D::analyse() const { - const double eps=1.0e-06; - bool hastranslation = (dMtrx4D[0][3] != 0.0 || - dMtrx4D[1][3] != 0.0 || dMtrx4D[2][3] != 0.0); + const double eps = 1.0e-06; + bool hastranslation = (dMtrx4D[0][3] != 0.0 || dMtrx4D[1][3] != 0.0 || dMtrx4D[2][3] != 0.0); const Base::Matrix4D unityMatrix = Base::Matrix4D(); std::string text; - if (*this == unityMatrix) - { + if (*this == unityMatrix) { text = "Unity Matrix"; } - else - { - if (dMtrx4D[3][0] != 0.0 || dMtrx4D[3][1] != 0.0 || - dMtrx4D[3][2] != 0.0 || dMtrx4D[3][3] != 1.0) - { + else { + if (dMtrx4D[3][0] != 0.0 || dMtrx4D[3][1] != 0.0 || dMtrx4D[3][2] != 0.0 + || dMtrx4D[3][3] != 1.0) { text = "Projection"; } - else //translation and affine + else // translation and affine { - if (dMtrx4D[0][1] == 0.0 && dMtrx4D[0][2] == 0.0 && - dMtrx4D[1][0] == 0.0 && dMtrx4D[1][2] == 0.0 && - dMtrx4D[2][0] == 0.0 && dMtrx4D[2][1] == 0.0) //scaling + if (dMtrx4D[0][1] == 0.0 && dMtrx4D[0][2] == 0.0 && dMtrx4D[1][0] == 0.0 + && dMtrx4D[1][2] == 0.0 && dMtrx4D[2][0] == 0.0 && dMtrx4D[2][1] == 0.0) // scaling { std::ostringstream stringStream; - stringStream << "Scale [" << dMtrx4D[0][0] << ", " << - dMtrx4D[1][1] << ", " << dMtrx4D[2][2] << "]"; + stringStream << "Scale [" << dMtrx4D[0][0] << ", " << dMtrx4D[1][1] << ", " + << dMtrx4D[2][2] << "]"; text = stringStream.str(); } - else - { + else { Base::Matrix4D sub; - sub[0][0] = dMtrx4D[0][0]; sub[0][1] = dMtrx4D[0][1]; - sub[0][2] = dMtrx4D[0][2]; sub[1][0] = dMtrx4D[1][0]; - sub[1][1] = dMtrx4D[1][1]; sub[1][2] = dMtrx4D[1][2]; - sub[2][0] = dMtrx4D[2][0]; sub[2][1] = dMtrx4D[2][1]; + sub[0][0] = dMtrx4D[0][0]; + sub[0][1] = dMtrx4D[0][1]; + sub[0][2] = dMtrx4D[0][2]; + sub[1][0] = dMtrx4D[1][0]; + sub[1][1] = dMtrx4D[1][1]; + sub[1][2] = dMtrx4D[1][2]; + sub[2][0] = dMtrx4D[2][0]; + sub[2][1] = dMtrx4D[2][1]; sub[2][2] = dMtrx4D[2][2]; Base::Matrix4D trp = sub; trp.transpose(); trp = trp * sub; bool ortho = true; - for (unsigned short i=0; i<4 && ortho; i++) { - for (unsigned short j=0; j<4 && ortho; j++) { + for (unsigned short i = 0; i < 4 && ortho; i++) { + for (unsigned short j = 0; j < 4 && ortho; j++) { if (i != j) { if (fabs(trp[i][j]) > eps) { ortho = false; @@ -749,36 +793,32 @@ std::string Matrix4D::analyse() const } double determinant = sub.determinant(); - if (ortho) - { - if (fabs(determinant-1.0)(o)->value(); @@ -85,20 +90,22 @@ int MatrixPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *o1{}; - PyObject *o2{}; - PyObject *o3{}; - PyObject *o4{}; - if (PyArg_ParseTuple(args, "O!O!O!|O!", &(Base::VectorPy::Type), &o1 - , &(Base::VectorPy::Type), &o2 - , &(Base::VectorPy::Type), &o3 - , &(Base::VectorPy::Type), &o4)) { + PyObject* o1 {}; + PyObject* o2 {}; + PyObject* o3 {}; + PyObject* o4 {}; + if (PyArg_ParseTuple(args, "O!O!O!|O!", + &(Base::VectorPy::Type), &o1, + &(Base::VectorPy::Type), &o2, + &(Base::VectorPy::Type), &o3, + &(Base::VectorPy::Type), &o4)) { Base::Vector3d v1 = Py::Vector(o1, false).toVector(); Base::Vector3d v2 = Py::Vector(o2, false).toVector(); Base::Vector3d v3 = Py::Vector(o3, false).toVector(); Base::Vector3d v4; - if (o4) + if (o4) { v4 = Py::Vector(o4, false).toVector(); + } MatrixPy::PointerType ptr = this->getMatrixPtr(); (*ptr)[0][0] = v1.x; @@ -119,12 +126,13 @@ int MatrixPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } + // clang-format on PyErr_SetString(PyExc_TypeError, "Base.Matrix, four Base.Vector or up to 16 floats expected"); return -1; } -PyObject* MatrixPy::number_add_handler(PyObject *self, PyObject *other) +PyObject* MatrixPy::number_add_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(MatrixPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Matrix"); @@ -136,10 +144,10 @@ PyObject* MatrixPy::number_add_handler(PyObject *self, PyObject *other) } Base::Matrix4D a = static_cast(self)->value(); Base::Matrix4D b = static_cast(other)->value(); - return new MatrixPy(a+b); + return new MatrixPy(a + b); } -PyObject* MatrixPy::number_subtract_handler(PyObject *self, PyObject *other) +PyObject* MatrixPy::number_subtract_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(MatrixPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Matrix"); @@ -151,34 +159,34 @@ PyObject* MatrixPy::number_subtract_handler(PyObject *self, PyObject *other) } Base::Matrix4D a = static_cast(self)->value(); Base::Matrix4D b = static_cast(other)->value(); - return new MatrixPy(a-b); + return new MatrixPy(a - b); } -PyObject* MatrixPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* MatrixPy::number_multiply_handler(PyObject* self, PyObject* other) { if (PyObject_TypeCheck(self, &(MatrixPy::Type))) { Base::Matrix4D a = static_cast(self)->value(); if (PyObject_TypeCheck(other, &(VectorPy::Type))) { auto b = static_cast(other)->value(); - return new VectorPy(a*b); + return new VectorPy(a * b); } if (PyObject_TypeCheck(other, &(RotationPy::Type))) { auto r = static_cast(other)->value(); Matrix4D b; r.getValue(b); - return new MatrixPy(a*b); + return new MatrixPy(a * b); } if (PyObject_TypeCheck(other, &(PlacementPy::Type))) { auto b = static_cast(other)->value(); - return new MatrixPy(a*b.toMatrix()); + return new MatrixPy(a * b.toMatrix()); } if (PyObject_TypeCheck(other, &(MatrixPy::Type))) { Base::Matrix4D b = static_cast(other)->value(); - return new MatrixPy(a*b); + return new MatrixPy(a * b); } if (PyNumber_Check(other)) { @@ -191,14 +199,11 @@ PyObject* MatrixPy::number_multiply_handler(PyObject *self, PyObject *other) return nullptr; } -PyObject * MatrixPy::number_power_handler (PyObject* self, PyObject* other, PyObject* arg) +PyObject* MatrixPy::number_power_handler(PyObject* self, PyObject* other, PyObject* arg) { if (!PyObject_TypeCheck(self, &(MatrixPy::Type)) || - !PyLong_Check(other) - || arg != Py_None - ) - { + !PyLong_Check(other) || arg != Py_None) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } @@ -206,12 +211,14 @@ PyObject * MatrixPy::number_power_handler (PyObject* self, PyObject* other, PyOb Base::Matrix4D a = static_cast(self)->value(); long b = Py::Int(other); - if (b == 0) + if (b == 0) { return new MatrixPy(Matrix4D()); + } if (b < 0) { - if (fabs(a.determinant()) > DBL_EPSILON) + if (fabs(a.determinant()) > DBL_EPSILON) { a.inverseGauss(); + } else { PyErr_SetString(PyExc_RuntimeError, "Cannot invert singular matrix"); return nullptr; @@ -220,31 +227,30 @@ PyObject * MatrixPy::number_power_handler (PyObject* self, PyObject* other, PyOb } auto res = a; - for (--b;b;--b) + for (--b; b; --b) { res *= a; + } return new MatrixPy(res); } -PyObject* MatrixPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* MatrixPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(MatrixPy::Type)) && - PyObject_TypeCheck(w, &(MatrixPy::Type))) { + if (PyObject_TypeCheck(v, &(MatrixPy::Type)) && PyObject_TypeCheck(w, &(MatrixPy::Type))) { Matrix4D m1 = static_cast(v)->value(); Matrix4D m2 = static_cast(w)->value(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for Matrix"); + PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Matrix"); return nullptr; } else if (op == Py_EQ) { - res = (m1 == m2) ? Py_True : Py_False; //NOLINT + res = (m1 == m2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } else { - res = (m1 != m2) ? Py_True : Py_False; //NOLINT + res = (m1 != m2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } @@ -256,14 +262,14 @@ PyObject* MatrixPy::richCompare(PyObject *v, PyObject *w, int op) } } -PyObject* MatrixPy::move(PyObject * args) +PyObject* MatrixPy::move(PyObject* args) { - double x{},y{},z{}; + double x {}, y {}, z {}; Base::Vector3d vec; - PyObject *pcVecObj{}; + PyObject* pcVecObj {}; - do { // dummy do..while for cascaded if - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { + do { // dummy do..while for cascaded if + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { vec.x = x; vec.y = y; vec.z = z; @@ -271,39 +277,40 @@ PyObject* MatrixPy::move(PyObject * args) } // clears the error from previous PyArg_ParseTuple() PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", - &PyTuple_Type, &pcVecObj)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &pcVecObj)) { vec = getVectorFromTuple(pcVecObj); break; } // clears the error from previous PyArg_ParseTuple() PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!;three floats, or a tuple, or a vector is needed", - &(Base::VectorPy::Type), &pcVecObj)) { - Base::VectorPy *pcObject = static_cast(pcVecObj); + if (PyArg_ParseTuple(args, + "O!;three floats, or a tuple, or a vector is needed", + &(Base::VectorPy::Type), + &pcVecObj)) { + Base::VectorPy* pcObject = static_cast(pcVecObj); Base::Vector3d* val = pcObject->getVectorPtr(); - vec.Set(val->x,val->y,val->z); + vec.Set(val->x, val->y, val->z); break; } return nullptr; - } - while(false); + } while (false); - PY_TRY { + PY_TRY + { getMatrixPtr()->move(vec); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::scale(PyObject * args) +PyObject* MatrixPy::scale(PyObject* args) { - double x{},y{},z{}; + double x {}, y {}, z {}; Base::Vector3d vec; - PyObject *pcVecObj{}; + PyObject* pcVecObj {}; - do { // dummy do..while for cascaded if - if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { + do { // dummy do..while for cascaded if + if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { vec.x = x; vec.y = y; vec.z = z; @@ -323,43 +330,48 @@ PyObject* MatrixPy::scale(PyObject * args) } // clears the error from previous PyArg_ParseTuple() PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!;one or three floats, or a tuple, or a vector is needed", - &(Base::VectorPy::Type), &pcVecObj)) { - Base::VectorPy *pcObject = static_cast(pcVecObj); + if (PyArg_ParseTuple(args, + "O!;one or three floats, or a tuple, or a vector is needed", + &(Base::VectorPy::Type), + &pcVecObj)) { + Base::VectorPy* pcObject = static_cast(pcVecObj); Base::Vector3d* val = pcObject->getVectorPtr(); - vec.Set(val->x,val->y,val->z); + vec.Set(val->x, val->y, val->z); break; } return nullptr; - } - while(false); + } while (false); - PY_TRY { + PY_TRY + { getMatrixPtr()->scale(vec); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::hasScale(PyObject * args) +PyObject* MatrixPy::hasScale(PyObject* args) { - double tol=0; - if (!PyArg_ParseTuple(args, "|d", &tol)) + double tol = 0; + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; + } ScaleType type = getMatrixPtr()->hasScale(tol); Py::Module mod("FreeCAD"); - return Py::new_reference_to(mod.callMemberFunction("ScaleType", Py::TupleN(Py::Int(static_cast(type))))); + return Py::new_reference_to( + mod.callMemberFunction("ScaleType", Py::TupleN(Py::Int(static_cast(type))))); } -PyObject* MatrixPy::decompose(PyObject * args) +PyObject* MatrixPy::decompose(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) - return nullptr; + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } auto ms = getMatrixPtr()->decompose(); Py::Tuple tuple(4); - for (int i=0; i<4; i++) { + for (int i = 0; i < 4; i++) { tuple.setItem(i, Py::Matrix(ms[i])); } return Py::new_reference_to(tuple); @@ -367,7 +379,8 @@ PyObject* MatrixPy::decompose(PyObject * args) PyObject* MatrixPy::nullify() { - PY_TRY { + PY_TRY + { getMatrixPtr()->nullify(); Py_Return; } @@ -376,7 +389,8 @@ PyObject* MatrixPy::nullify() PyObject* MatrixPy::isNull() { - PY_TRY { + PY_TRY + { bool ok = getMatrixPtr()->isNull(); return Py::new_reference_to(Py::Boolean(ok)); } @@ -385,49 +399,60 @@ PyObject* MatrixPy::isNull() PyObject* MatrixPy::unity() { - PY_TRY { + PY_TRY + { getMatrixPtr()->setToUnity(); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::isUnity(PyObject * args) +PyObject* MatrixPy::isUnity(PyObject* args) { double tol = 0.0; - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; - PY_TRY { + } + + PY_TRY + { bool ok = getMatrixPtr()->isUnity(tol); return Py::new_reference_to(Py::Boolean(ok)); } PY_CATCH; } -PyObject* MatrixPy::transform(PyObject * args) +PyObject* MatrixPy::transform(PyObject* args) { Base::Vector3d vec; Matrix4D mat; - PyObject *pcVecObj{}, *pcMatObj{}; + PyObject *pcVecObj {}, *pcMatObj {}; - if (!PyArg_ParseTuple(args, "O!O!: a transform point (Vector) and a transform matrix (Matrix) is needed", - &(Base::VectorPy::Type), &pcVecObj, &(MatrixPy::Type), &pcMatObj)) + if (!PyArg_ParseTuple( + args, + "O!O!: a transform point (Vector) and a transform matrix (Matrix) is needed", + &(Base::VectorPy::Type), + &pcVecObj, + &(MatrixPy::Type), + &pcMatObj)) { return nullptr; + } - Base::VectorPy *pcObject = static_cast(pcVecObj); + Base::VectorPy* pcObject = static_cast(pcVecObj); Base::Vector3d* val = pcObject->getVectorPtr(); - vec.Set(val->x,val->y,val->z); + vec.Set(val->x, val->y, val->z); mat = *(static_cast(pcMatObj)->getMatrixPtr()); - getMatrixPtr()->transform(vec,mat); + getMatrixPtr()->transform(vec, mat); Py_Return; } -PyObject* MatrixPy::col(PyObject * args) +PyObject* MatrixPy::col(PyObject* args) { - int index{}; - if (!PyArg_ParseTuple(args, "i", &index)) + int index {}; + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } if (index < 0 || index > 3) { PyErr_SetString(PyExc_ValueError, "Index expected in the range [0, 3]"); @@ -439,12 +464,13 @@ PyObject* MatrixPy::col(PyObject * args) return Py::new_reference_to(Py::Vector(v)); } -PyObject* MatrixPy::setCol(PyObject * args) +PyObject* MatrixPy::setCol(PyObject* args) { - int index{}; - PyObject* o{}; - if (!PyArg_ParseTuple(args, "iO!", &index, &(VectorPy::Type), &o)) + int index {}; + PyObject* o {}; + if (!PyArg_ParseTuple(args, "iO!", &index, &(VectorPy::Type), &o)) { return nullptr; + } if (index < 0 || index > 3) { PyErr_SetString(PyExc_ValueError, "Index expected in the range [0, 3]"); @@ -457,11 +483,12 @@ PyObject* MatrixPy::setCol(PyObject * args) Py_Return; } -PyObject* MatrixPy::row(PyObject * args) +PyObject* MatrixPy::row(PyObject* args) { - int index{}; - if (!PyArg_ParseTuple(args, "i", &index)) + int index {}; + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } if (index < 0 || index > 3) { PyErr_SetString(PyExc_ValueError, "Index expected in the range [0, 3]"); @@ -473,12 +500,13 @@ PyObject* MatrixPy::row(PyObject * args) return Py::new_reference_to(Py::Vector(v)); } -PyObject* MatrixPy::setRow(PyObject * args) +PyObject* MatrixPy::setRow(PyObject* args) { - int index{}; - PyObject* o{}; - if (!PyArg_ParseTuple(args, "iO!", &index, &(VectorPy::Type), &o)) + int index {}; + PyObject* o {}; + if (!PyArg_ParseTuple(args, "iO!", &index, &(VectorPy::Type), &o)) { return nullptr; + } if (index < 0 || index > 3) { PyErr_SetString(PyExc_ValueError, "Index expected in the range [0, 3]"); @@ -498,11 +526,12 @@ PyObject* MatrixPy::diagonal() return Py::new_reference_to(Py::Vector(v)); } -PyObject* MatrixPy::setDiagonal(PyObject * args) +PyObject* MatrixPy::setDiagonal(PyObject* args) { - PyObject* o{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &o)) + PyObject* o {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &o)) { return nullptr; + } Base::Vector3d v = Py::Vector(o, false).toVector(); Matrix4D* mat = getMatrixPtr(); @@ -510,13 +539,13 @@ PyObject* MatrixPy::setDiagonal(PyObject * args) Py_Return; } -PyObject* MatrixPy::rotateX(PyObject * args) +PyObject* MatrixPy::rotateX(PyObject* args) { double angle = 0; do { - PyObject *object{}; - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { - Quantity *q = static_cast(object)->getQuantityPtr(); + PyObject* object {}; + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { + Quantity* q = static_cast(object)->getQuantityPtr(); if (q->getUnit() == Base::Unit::Angle) { angle = q->getValueAs(Base::Quantity::Radian); break; @@ -530,23 +559,23 @@ PyObject* MatrixPy::rotateX(PyObject * args) PyErr_SetString(PyExc_TypeError, "For angle either float or Quantity expected"); return nullptr; - } - while (false); + } while (false); - PY_TRY { + PY_TRY + { getMatrixPtr()->rotX(angle); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::rotateY(PyObject * args) +PyObject* MatrixPy::rotateY(PyObject* args) { double angle = 0; do { - PyObject *object{}; - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { - Quantity *q = static_cast(object)->getQuantityPtr(); + PyObject* object {}; + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { + Quantity* q = static_cast(object)->getQuantityPtr(); if (q->getUnit() == Base::Unit::Angle) { angle = q->getValueAs(Base::Quantity::Radian); break; @@ -560,23 +589,23 @@ PyObject* MatrixPy::rotateY(PyObject * args) PyErr_SetString(PyExc_TypeError, "For angle either float or Quantity expected"); return nullptr; - } - while (false); + } while (false); - PY_TRY { + PY_TRY + { getMatrixPtr()->rotY(angle); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::rotateZ(PyObject * args) +PyObject* MatrixPy::rotateZ(PyObject* args) { double angle = 0; do { - PyObject *object{}; - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { - Quantity *q = static_cast(object)->getQuantityPtr(); + PyObject* object {}; + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { + Quantity* q = static_cast(object)->getQuantityPtr(); if (q->getUnit() == Base::Unit::Angle) { angle = q->getValueAs(Base::Quantity::Radian); break; @@ -590,19 +619,19 @@ PyObject* MatrixPy::rotateZ(PyObject * args) PyErr_SetString(PyExc_TypeError, "For angle either float or Quantity expected"); return nullptr; - } - while (false); + } while (false); - PY_TRY { + PY_TRY + { getMatrixPtr()->rotZ(angle); Py_Return; } PY_CATCH; } -PyObject* MatrixPy::multiply(PyObject * args) +PyObject* MatrixPy::multiply(PyObject* args) { - PyObject* o{}; + PyObject* o {}; if (PyArg_ParseTuple(args, "O!", &(MatrixPy::Type), &o)) { Matrix4D mat = (*getMatrixPtr()) * static_cast(o)->value(); return new MatrixPy(new Matrix4D(mat)); @@ -618,11 +647,12 @@ PyObject* MatrixPy::multiply(PyObject * args) return nullptr; } -PyObject* MatrixPy::multVec(PyObject * args) +PyObject* MatrixPy::multVec(PyObject* args) { - PyObject *obj{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } Base::Vector3d vec(static_cast(obj)->value()); getMatrixPtr()->multVec(vec, vec); @@ -631,7 +661,8 @@ PyObject* MatrixPy::multVec(PyObject * args) PyObject* MatrixPy::invert() { - PY_TRY { + PY_TRY + { if (fabs(getMatrixPtr()->determinant()) > DBL_EPSILON) { getMatrixPtr()->inverseGauss(); Py_Return; @@ -646,7 +677,8 @@ PyObject* MatrixPy::invert() PyObject* MatrixPy::inverse() { - PY_TRY { + PY_TRY + { if (fabs(getMatrixPtr()->determinant()) > DBL_EPSILON) { Base::Matrix4D m = *getMatrixPtr(); m.inverseGauss(); @@ -665,11 +697,12 @@ PyObject* MatrixPy::determinant() return PyFloat_FromDouble(getMatrixPtr()->determinant()); } -PyObject* MatrixPy::submatrix(PyObject * args) +PyObject* MatrixPy::submatrix(PyObject* args) { - int dim{}; - if (!PyArg_ParseTuple(args, "i", &dim)) + int dim {}; + if (!PyArg_ParseTuple(args, "i", &dim)) { return nullptr; + } if (dim < 1 || dim > 4) { PyErr_SetString(PyExc_IndexError, "Dimension out of range"); @@ -678,33 +711,41 @@ PyObject* MatrixPy::submatrix(PyObject * args) const Base::Matrix4D& mat = *getMatrixPtr(); Base::Matrix4D sub; - switch (dim) - { - case 1: - sub[0][0] = mat[0][0]; - break; - case 2: - sub[0][0] = mat[0][0]; sub[0][1] = mat[0][1]; - sub[1][0] = mat[1][0]; sub[1][1] = mat[1][1]; - break; - case 3: - sub[0][0] = mat[0][0]; sub[0][1] = mat[0][1]; sub[0][2] = mat[0][2]; - sub[1][0] = mat[1][0]; sub[1][1] = mat[1][1]; sub[1][2] = mat[1][2]; - sub[2][0] = mat[2][0]; sub[2][1] = mat[2][1]; sub[2][2] = mat[2][2]; - break; - default: - sub = mat; - break; + switch (dim) { + case 1: + sub[0][0] = mat[0][0]; + break; + case 2: + sub[0][0] = mat[0][0]; + sub[0][1] = mat[0][1]; + sub[1][0] = mat[1][0]; + sub[1][1] = mat[1][1]; + break; + case 3: + sub[0][0] = mat[0][0]; + sub[0][1] = mat[0][1]; + sub[0][2] = mat[0][2]; + sub[1][0] = mat[1][0]; + sub[1][1] = mat[1][1]; + sub[1][2] = mat[1][2]; + sub[2][0] = mat[2][0]; + sub[2][1] = mat[2][1]; + sub[2][2] = mat[2][2]; + break; + default: + sub = mat; + break; } return new MatrixPy(sub); } -PyObject* MatrixPy::isOrthogonal(PyObject * args) +PyObject* MatrixPy::isOrthogonal(PyObject* args) { - double eps=1.0e-06; - if (!PyArg_ParseTuple(args, "|d",&eps)) + double eps = 1.0e-06; + if (!PyArg_ParseTuple(args, "|d", &eps)) { return nullptr; + } const Base::Matrix4D& mat = *getMatrixPtr(); Base::Matrix4D trp = mat; @@ -713,16 +754,16 @@ PyObject* MatrixPy::isOrthogonal(PyObject * args) bool ok = true; double mult = trp[0][0]; - for (unsigned short i=0; i<4 && ok; i++) { - for (unsigned short j=0; j<4 && ok; j++) { + for (unsigned short i = 0; i < 4 && ok; i++) { + for (unsigned short j = 0; j < 4 && ok; j++) { if (i != j) { if (fabs(trp[i][j]) > eps) { ok = false; break; } } - else { // the main diagonal - if (fabs(trp[i][j]-mult) > eps) { + else { // the main diagonal + if (fabs(trp[i][j] - mult) > eps) { ok = false; break; } @@ -735,7 +776,8 @@ PyObject* MatrixPy::isOrthogonal(PyObject * args) PyObject* MatrixPy::transposed() { - PY_TRY { + PY_TRY + { Base::Matrix4D m = *getMatrixPtr(); m.transpose(); return new MatrixPy(m); @@ -745,7 +787,8 @@ PyObject* MatrixPy::transposed() PyObject* MatrixPy::transpose() { - PY_TRY { + PY_TRY + { getMatrixPtr()->transpose(); Py_Return; } @@ -754,7 +797,8 @@ PyObject* MatrixPy::transpose() PyObject* MatrixPy::analyze() { - PY_TRY { + PY_TRY + { std::string type = getMatrixPtr()->analyse(); return PyUnicode_FromString(type.c_str()); } @@ -767,7 +811,7 @@ Py::Float MatrixPy::getA11() const return Py::Float(val); } -void MatrixPy::setA11(Py::Float arg) +void MatrixPy::setA11(Py::Float arg) { (*this->getMatrixPtr())[0][0] = static_cast(arg); } @@ -778,7 +822,7 @@ Py::Float MatrixPy::getA12() const return Py::Float(val); } -void MatrixPy::setA12(Py::Float arg) +void MatrixPy::setA12(Py::Float arg) { (*this->getMatrixPtr())[0][1] = static_cast(arg); } @@ -789,7 +833,7 @@ Py::Float MatrixPy::getA13() const return Py::Float(val); } -void MatrixPy::setA13(Py::Float arg) +void MatrixPy::setA13(Py::Float arg) { (*this->getMatrixPtr())[0][2] = static_cast(arg); } @@ -800,7 +844,7 @@ Py::Float MatrixPy::getA14() const return Py::Float(val); } -void MatrixPy::setA14(Py::Float arg) +void MatrixPy::setA14(Py::Float arg) { (*this->getMatrixPtr())[0][3] = static_cast(arg); } @@ -811,7 +855,7 @@ Py::Float MatrixPy::getA21() const return Py::Float(val); } -void MatrixPy::setA21(Py::Float arg) +void MatrixPy::setA21(Py::Float arg) { (*this->getMatrixPtr())[1][0] = static_cast(arg); } @@ -822,7 +866,7 @@ Py::Float MatrixPy::getA22() const return Py::Float(val); } -void MatrixPy::setA22(Py::Float arg) +void MatrixPy::setA22(Py::Float arg) { (*this->getMatrixPtr())[1][1] = static_cast(arg); } @@ -833,7 +877,7 @@ Py::Float MatrixPy::getA23() const return Py::Float(val); } -void MatrixPy::setA23(Py::Float arg) +void MatrixPy::setA23(Py::Float arg) { (*this->getMatrixPtr())[1][2] = static_cast(arg); } @@ -844,7 +888,7 @@ Py::Float MatrixPy::getA24() const return Py::Float(val); } -void MatrixPy::setA24(Py::Float arg) +void MatrixPy::setA24(Py::Float arg) { (*this->getMatrixPtr())[1][3] = static_cast(arg); } @@ -855,7 +899,7 @@ Py::Float MatrixPy::getA31() const return Py::Float(val); } -void MatrixPy::setA31(Py::Float arg) +void MatrixPy::setA31(Py::Float arg) { (*this->getMatrixPtr())[2][0] = static_cast(arg); } @@ -866,7 +910,7 @@ Py::Float MatrixPy::getA32() const return Py::Float(val); } -void MatrixPy::setA32(Py::Float arg) +void MatrixPy::setA32(Py::Float arg) { (*this->getMatrixPtr())[2][1] = static_cast(arg); } @@ -877,7 +921,7 @@ Py::Float MatrixPy::getA33() const return Py::Float(val); } -void MatrixPy::setA33(Py::Float arg) +void MatrixPy::setA33(Py::Float arg) { (*this->getMatrixPtr())[2][2] = static_cast(arg); } @@ -888,7 +932,7 @@ Py::Float MatrixPy::getA34() const return Py::Float(val); } -void MatrixPy::setA34(Py::Float arg) +void MatrixPy::setA34(Py::Float arg) { (*this->getMatrixPtr())[2][3] = static_cast(arg); } @@ -899,7 +943,7 @@ Py::Float MatrixPy::getA41() const return Py::Float(val); } -void MatrixPy::setA41(Py::Float arg) +void MatrixPy::setA41(Py::Float arg) { (*this->getMatrixPtr())[3][0] = static_cast(arg); } @@ -910,7 +954,7 @@ Py::Float MatrixPy::getA42() const return Py::Float(val); } -void MatrixPy::setA42(Py::Float arg) +void MatrixPy::setA42(Py::Float arg) { (*this->getMatrixPtr())[3][1] = static_cast(arg); } @@ -921,7 +965,7 @@ Py::Float MatrixPy::getA43() const return Py::Float(val); } -void MatrixPy::setA43(Py::Float arg) +void MatrixPy::setA43(Py::Float arg) { (*this->getMatrixPtr())[3][2] = static_cast(arg); } @@ -932,7 +976,7 @@ Py::Float MatrixPy::getA44() const return Py::Float(val); } -void MatrixPy::setA44(Py::Float arg) +void MatrixPy::setA44(Py::Float arg) { (*this->getMatrixPtr())[3][3] = static_cast(arg); } @@ -942,7 +986,7 @@ Py::Sequence MatrixPy::getA() const double mat[16]; this->getMatrixPtr()->getMatrix(mat); Py::Tuple tuple(16); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { tuple[i] = Py::Float(mat[i]); } return std::move(tuple); @@ -953,7 +997,7 @@ void MatrixPy::setA(Py::Sequence arg) double mat[16]; this->getMatrixPtr()->getMatrix(mat); - int index=0; + int index = 0; for (Py::Sequence::iterator it = arg.begin(); it != arg.end() && index < 16; ++it) { mat[index++] = static_cast(Py::Float(*it)); } @@ -961,7 +1005,7 @@ void MatrixPy::setA(Py::Sequence arg) this->getMatrixPtr()->setMatrix(mat); } -PyObject *MatrixPy::getCustomAttributes(const char* /*attr*/) const +PyObject* MatrixPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -971,25 +1015,25 @@ int MatrixPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject * MatrixPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_divide_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_remainder_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_negative_handler (PyObject* self) +PyObject* MatrixPy::number_negative_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(MatrixPy::Type))) { PyErr_SetString(PyExc_TypeError, "arg must be Matrix"); @@ -1000,7 +1044,7 @@ PyObject * MatrixPy::number_negative_handler (PyObject* self) return new MatrixPy(a * -1); } -PyObject * MatrixPy::number_positive_handler (PyObject* self) +PyObject* MatrixPy::number_positive_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(MatrixPy::Type))) { PyErr_SetString(PyExc_TypeError, "arg must be Matrix"); @@ -1011,60 +1055,60 @@ PyObject * MatrixPy::number_positive_handler (PyObject* self) return new MatrixPy(a); } -PyObject * MatrixPy::number_absolute_handler (PyObject* /*self*/) +PyObject* MatrixPy::number_absolute_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -int MatrixPy::number_nonzero_handler (PyObject* /*self*/) +int MatrixPy::number_nonzero_handler(PyObject* /*self*/) { return 1; } -PyObject * MatrixPy::number_invert_handler (PyObject* /*self*/) +PyObject* MatrixPy::number_invert_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_lshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_rshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_and_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_xor_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* MatrixPy::number_or_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_int_handler (PyObject * /*self*/) +PyObject* MatrixPy::number_int_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * MatrixPy::number_float_handler (PyObject * /*self*/) +PyObject* MatrixPy::number_float_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; diff --git a/src/Base/MemDebug.cpp b/src/Base/MemDebug.cpp index 532d7f71de..59b4e02724 100644 --- a/src/Base/MemDebug.cpp +++ b/src/Base/MemDebug.cpp @@ -40,10 +40,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# ifdef _MSC_VER -# include -# include -# endif +#ifdef _MSC_VER +#include +#include +#endif #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... @@ -70,20 +70,26 @@ using namespace Base; class MemDebug { public: - /// Construction - MemDebug(); - /// Destruction - virtual ~MemDebug(); + /// Construction + MemDebug(); + /// Destruction + virtual ~MemDebug(); protected: - static FILE *logFile; + static FILE* logFile; - /** @name static callbacks for the Crt */ - //@{ - static void __cdecl sDumpClientHook(void * pUserData, size_t nBytes); - static int __cdecl sAllocHook(int nAllocType, void* pvData, size_t nSize,int nBlockUse,long lRequest,const unsigned char * szFileName,int nLine); - static int sReportHook(int nRptType,char *szMsg,int *retVal); - //@} + /** @name static callbacks for the Crt */ + //@{ + static void __cdecl sDumpClientHook(void* pUserData, size_t nBytes); + static int __cdecl sAllocHook(int nAllocType, + void* pvData, + size_t nSize, + int nBlockUse, + long lRequest, + const unsigned char* szFileName, + int nLine); + static int sReportHook(int nRptType, char* szMsg, int* retVal); + //@} }; // the one and only MemDebug instance. @@ -92,10 +98,10 @@ MemDebug cSingelton; #endif -#define SET_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)) -#define CLEAR_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag(~(a) & _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)) +#define SET_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)) +#define CLEAR_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag(~(a)&_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)) -FILE *MemDebug::logFile = NULL; +FILE* MemDebug::logFile = NULL; //************************************************************************** // Construction/Destruction @@ -103,52 +109,56 @@ FILE *MemDebug::logFile = NULL; MemDebug::MemDebug() { - //_CrtMemState checkPt1; - char timeStr[15], dateStr[15]; // Used to set up log file + //_CrtMemState checkPt1; + char timeStr[15], dateStr[15]; // Used to set up log file - // Send all reports to STDOUT, since this example is a console app - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE ); - _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR ); - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE ); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR ); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE ); - _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR ); + // Send all reports to STDOUT, since this example is a console app + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); - // Set the debug heap to report memory leaks when the process terminates, - // and to keep freed blocks in the linked list. - SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF ); + // Set the debug heap to report memory leaks when the process terminates, + // and to keep freed blocks in the linked list. + SET_CRT_DEBUG_FIELD(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF); - // Open a log file for the hook functions to use - if ( logFile != NULL ) - throw std::runtime_error("Base::MemDebug::MemDebug():38: Don't call the constructor by your self!"); + // Open a log file for the hook functions to use + if (logFile != NULL) { + throw std::runtime_error( + "Base::MemDebug::MemDebug():38: Don't call the constructor by your self!"); + } - fopen_s( &logFile, "MemLog.txt", "w" ); - if ( logFile == NULL ) - throw std::runtime_error("Base::MemDebug::MemDebug():41: File IO Error. Can't open log file..."); - _strtime_s( timeStr, 15 ); - _strdate_s( dateStr, 15 ); + fopen_s(&logFile, "MemLog.txt", "w"); + if (logFile == NULL) { + throw std::runtime_error( + "Base::MemDebug::MemDebug():41: File IO Error. Can't open log file..."); + } + _strtime_s(timeStr, 15); + _strdate_s(dateStr, 15); - fprintf( logFile, + fprintf(logFile, "Memory Allocation Log File for FreeCAD, run at %s on %s.\n", - timeStr, dateStr ); - fputs( "-------------------------------------------------------------------\n", logFile ); - - // Install the hook functions - _CrtSetDumpClient( sDumpClientHook ); - _CrtSetAllocHook( sAllocHook ); - _CrtSetReportHook( sReportHook ); + timeStr, + dateStr); + fputs("-------------------------------------------------------------------\n", logFile); + // Install the hook functions + _CrtSetDumpClient(sDumpClientHook); + _CrtSetAllocHook(sAllocHook); + _CrtSetReportHook(sReportHook); } MemDebug::~MemDebug() { - _CrtMemDumpAllObjectsSince( NULL ); - //_CrtCheckMemory( ); + _CrtMemDumpAllObjectsSince(NULL); + //_CrtCheckMemory( ); - // This fflush needs to be removed... - fflush( logFile ); - fclose( logFile ); + // This fflush needs to be removed... + fflush(logFile); + fclose(logFile); } @@ -166,16 +176,17 @@ MemDebug::~MemDebug() to return zero, which causes execution to continue. If we want the function to start the debugger, we should have _CrtDbgReport return one. */ -int MemDebug::sReportHook(int nRptType,char *szMsg,int *retVal) +int MemDebug::sReportHook(int nRptType, char* szMsg, int* retVal) { - const char *RptTypes[] = { "Warning", "Error", "Assert" }; + const char* RptTypes[] = {"Warning", "Error", "Assert"}; - if ( ( nRptType > 0 ) || ( strstr( szMsg, "HEAP CORRUPTION DETECTED" ) ) ) - fprintf( logFile, "%s: %s", RptTypes[nRptType], szMsg ); + if ((nRptType > 0) || (strstr(szMsg, "HEAP CORRUPTION DETECTED"))) { + fprintf(logFile, "%s: %s", RptTypes[nRptType], szMsg); + } - retVal = 0; + retVal = 0; - return( 7 ); // Allow the report to be made as usual (True = 7, False = 0) + return (7); // Allow the report to be made as usual (True = 7, False = 0) } /* ALLOCATION HOOK FUNCTION @@ -183,37 +194,44 @@ int MemDebug::sReportHook(int nRptType,char *szMsg,int *retVal) An allocation hook function can have many, many different uses. This one simply logs each allocation operation in a file. */ -int __cdecl MemDebug::sAllocHook( - int nAllocType, - void * pvData, - size_t nSize, - int nBlockUse, - long lRequest, - const unsigned char * szFileName, - int nLine - ) +int __cdecl MemDebug::sAllocHook(int nAllocType, + void* pvData, + size_t nSize, + int nBlockUse, + long lRequest, + const unsigned char* szFileName, + int nLine) { - const char *operation[] = { " :", "Alloc :", "Realloc:", "Free :" }; - const char *blockType[] = { "Free", "Normal", "CRT", "Ignore", "Client" }; + const char* operation[] = {" :", "Alloc :", "Realloc:", "Free :"}; + const char* blockType[] = {"Free", "Normal", "CRT", "Ignore", "Client"}; - if ( nBlockUse == _CRT_BLOCK ) // Ignore internal C runtime library allocations - return( 7 ); // (True = 7, False = 0) + if (nBlockUse == _CRT_BLOCK) { // Ignore internal C runtime library allocations + return (7); // (True = 7, False = 0) + } - _ASSERT( ( nAllocType > 0 ) && ( nAllocType < 4 ) ); - _ASSERT( ( nBlockUse >= 0 ) && ( nBlockUse < 5 ) ); + _ASSERT((nAllocType > 0) && (nAllocType < 4)); + _ASSERT((nBlockUse >= 0) && (nBlockUse < 5)); - if( nBlockUse !=4 ) - return(7); + if (nBlockUse != 4) { + return (7); + } - fprintf( logFile, + fprintf(logFile, "%s (#%7d) %12Iu byte (%s) in %s line %d", - operation[nAllocType],lRequest, nSize, blockType[nBlockUse],szFileName, nLine); - if ( pvData != NULL ) - fprintf( logFile, " at %p\n", pvData ); - else - fprintf( logFile, "\n" ); + operation[nAllocType], + lRequest, + nSize, + blockType[nBlockUse], + szFileName, + nLine); + if (pvData != NULL) { + fprintf(logFile, " at %p\n", pvData); + } + else { + fprintf(logFile, "\n"); + } - return( 7 ); // Allow the memory operation to proceed (True = 7, False = 0) + return (7); // Allow the memory operation to proceed (True = 7, False = 0) } @@ -224,15 +242,11 @@ int __cdecl MemDebug::sAllocHook( below also checks the data in several ways, and reports corruption or inconsistency as an assertion failure. */ -void __cdecl MemDebug::sDumpClientHook( - void * pUserData, - size_t nBytes - ) +void __cdecl MemDebug::sDumpClientHook(void* pUserData, size_t nBytes) { - long requestNumber=0; - _CrtIsMemoryBlock(pUserData,(unsigned int)nBytes,&requestNumber,NULL,NULL); - fprintf( logFile, "Leak : (#%7d) %12Iu bytes (%p) \n", requestNumber, nBytes, pUserData ); - + long requestNumber = 0; + _CrtIsMemoryBlock(pUserData, (unsigned int)nBytes, &requestNumber, NULL, NULL); + fprintf(logFile, "Leak : (#%7d) %12Iu bytes (%p) \n", requestNumber, nBytes, pUserData); } // ----------------------------------------------------- @@ -240,26 +254,28 @@ void __cdecl MemDebug::sDumpClientHook( MemCheck::MemCheck() { // Store a memory checkpoint in the s1 memory-state structure - _CrtMemCheckpoint( &s1 ); + _CrtMemCheckpoint(&s1); } MemCheck::~MemCheck() { // Store a 2nd memory checkpoint in s2 - _CrtMemCheckpoint( &s2 ); - if ( _CrtMemDifference( &s3, &s1, &s2 ) ) - _CrtMemDumpStatistics( &s3 ); + _CrtMemCheckpoint(&s2); + if (_CrtMemDifference(&s3, &s1, &s2)) { + _CrtMemDumpStatistics(&s3); + } } void MemCheck::setNextCheckpoint() { // Store a 2nd memory checkpoint in s2 - _CrtMemCheckpoint( &s2 ); - if ( _CrtMemDifference( &s3, &s1, &s2 ) ) - _CrtMemDumpStatistics( &s3 ); + _CrtMemCheckpoint(&s2); + if (_CrtMemDifference(&s3, &s1, &s2)) { + _CrtMemDumpStatistics(&s3); + } // Store a memory checkpoint in the s1 memory-state structure - _CrtMemCheckpoint( &s1 ); + _CrtMemCheckpoint(&s1); } bool MemCheck::checkMemory() diff --git a/src/Base/MemDebug.h b/src/Base/MemDebug.h index 4ef8ce5f43..054a0e693c 100644 --- a/src/Base/MemDebug.h +++ b/src/Base/MemDebug.h @@ -50,7 +50,6 @@ private: #endif -} //namespace Base - -#endif // BASE_MEMDEBUG_H +} // namespace Base +#endif // BASE_MEMDEBUG_H diff --git a/src/Base/Mutex.cpp b/src/Base/Mutex.cpp index 5913e2e4b5..e3d07c4a4e 100644 --- a/src/Base/Mutex.cpp +++ b/src/Base/Mutex.cpp @@ -26,12 +26,11 @@ #include "Mutex.h" -#if QT_VERSION < QT_VERSION_CHECK(5,14,0) -QRecursiveMutex::QRecursiveMutex() : QMutex(QMutex::Recursive) -{ -} +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) +QRecursiveMutex::QRecursiveMutex() + : QMutex(QMutex::Recursive) +{} QRecursiveMutex::~QRecursiveMutex() -{ -} +{} #endif diff --git a/src/Base/Mutex.h b/src/Base/Mutex.h index 6c8ddee7fe..e65db63092 100644 --- a/src/Base/Mutex.h +++ b/src/Base/Mutex.h @@ -27,8 +27,8 @@ #include #include -#if QT_VERSION < QT_VERSION_CHECK(5,14,0) -class BaseExport QRecursiveMutex : public QMutex +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) +class BaseExport QRecursiveMutex: public QMutex { public: QRecursiveMutex(); @@ -36,4 +36,4 @@ public: }; #endif -#endif // BASE_MUTEX_H +#endif // BASE_MUTEX_H diff --git a/src/Base/Observer.cpp b/src/Base/Observer.cpp index 26813b28ff..db9098e188 100644 --- a/src/Base/Observer.cpp +++ b/src/Base/Observer.cpp @@ -26,9 +26,10 @@ #include "Observer.h" -namespace Base { +namespace Base +{ template class BaseExport Observer; template class BaseExport Subject; -} //namespace Base +} // namespace Base diff --git a/src/Base/Observer.h b/src/Base/Observer.h index 8b3db6c2c1..92220939db 100644 --- a/src/Base/Observer.h +++ b/src/Base/Observer.h @@ -35,7 +35,8 @@ namespace Base { -template class Subject; +template +class Subject; /** Observer class @@ -45,49 +46,50 @@ template class Subject; * Attach itself to the observed object. * @see FCSubject */ -template +template class Observer { public: + /** + * A constructor. + * No special function so far. + */ + Observer() = default; - /** - * A constructor. - * No special function so far. - */ - Observer() = default; + /** + * A destructor. + * No special function so far. + */ + virtual ~Observer() = default; - /** - * A destructor. - * No special function so far. - */ - virtual ~Observer() = default; + /** + * This method need to be reimplemented from the concrete Observer + * and get called by the observed class + * @param rCaller a reference to the calling object + * @param rcReason + * \todo undocumented parameter 2 + */ + virtual void OnChange(Subject<_MessageType>& rCaller, _MessageType rcReason) = 0; - /** - * This method need to be reimplemented from the concrete Observer - * and get called by the observed class - * @param rCaller a reference to the calling object - * @param rcReason - * \todo undocumented parameter 2 - */ - virtual void OnChange(Subject<_MessageType>& rCaller, _MessageType rcReason) = 0; + /** + * This method need to be reimplemented from the concrete Observer + * and get called by the observed class + * @param rCaller a reference to the calling object + */ + virtual void OnDestroy(Subject<_MessageType>& rCaller) + { + (void)rCaller; + } - /** - * This method need to be reimplemented from the concrete Observer - * and get called by the observed class - * @param rCaller a reference to the calling object - */ - virtual void OnDestroy(Subject<_MessageType>& rCaller) { - (void)rCaller; - } - - /** - * This method can be reimplemented from the concrete Observer - * and returns the name of the observer. Needed to use the Get - * Method of the Subject. - */ - virtual const char *Name() { - return nullptr; - } + /** + * This method can be reimplemented from the concrete Observer + * and returns the name of the observer. Needed to use the Get + * Method of the Subject. + */ + virtual const char* Name() + { + return nullptr; + } }; /** Subject class @@ -97,143 +99,150 @@ public: * Attach itself to the observed object. * @see FCObserver */ -template +template class Subject { public: + using ObserverType = Observer<_MessageType>; + using MessageType = _MessageType; + using SubjectType = Subject<_MessageType>; - using ObserverType = Observer<_MessageType>; - using MessageType = _MessageType; - using SubjectType = Subject<_MessageType>; + /** + * A constructor. + * No special function so far. + */ + Subject() = default; - /** - * A constructor. - * No special function so far. - */ - Subject() = default; - - /** - * A destructor. - * No special function so far. - */ - virtual ~Subject() - { - if (_ObserverSet.size() > 0) + /** + * A destructor. + * No special function so far. + */ + virtual ~Subject() { - Base::Console().DeveloperWarning(std::string("~Subject()"), - "Not detached all observers yet\n"); + if (_ObserverSet.size() > 0) { + Base::Console().DeveloperWarning(std::string("~Subject()"), + "Not detached all observers yet\n"); + } } - } - /** Attach an Observer - * Attach an Observer to the list of Observers which get - * called when Notify is called. - * @param ToObserv A pointer to a concrete Observer - * @see Notify - */ - void Attach(Observer<_MessageType> *ToObserv) - { + /** Attach an Observer + * Attach an Observer to the list of Observers which get + * called when Notify is called. + * @param ToObserv A pointer to a concrete Observer + * @see Notify + */ + void Attach(Observer<_MessageType>* ToObserv) + { #ifdef FC_DEBUG - size_t count = _ObserverSet.size(); - _ObserverSet.insert(ToObserv); - if ( _ObserverSet.size() == count ) { - Base::Console().DeveloperWarning(std::string("Subject::Attach"), - "Observer %p already attached\n", - static_cast(ToObserv)); - } + size_t count = _ObserverSet.size(); + _ObserverSet.insert(ToObserv); + if (_ObserverSet.size() == count) { + Base::Console().DeveloperWarning(std::string("Subject::Attach"), + "Observer %p already attached\n", + static_cast(ToObserv)); + } #else - _ObserverSet.insert(ToObserv); + _ObserverSet.insert(ToObserv); #endif - } + } - /** Detach an Observer - * Detach an Observer from the list of Observers which get - * called when Notify is called. - * @param ToObserv A pointer to a concrete Observer - * @see Notify - */ - void Detach(Observer<_MessageType> *ToObserv) - { + /** Detach an Observer + * Detach an Observer from the list of Observers which get + * called when Notify is called. + * @param ToObserv A pointer to a concrete Observer + * @see Notify + */ + void Detach(Observer<_MessageType>* ToObserv) + { #ifdef FC_DEBUG - size_t count = _ObserverSet.size(); - _ObserverSet.erase(ToObserv); - if (_ObserverSet.size() == count) { - Base::Console().DeveloperWarning(std::string("Subject::Detach"), - "Observer %p already detached\n", - static_cast(ToObserv)); - } + size_t count = _ObserverSet.size(); + _ObserverSet.erase(ToObserv); + if (_ObserverSet.size() == count) { + Base::Console().DeveloperWarning(std::string("Subject::Detach"), + "Observer %p already detached\n", + static_cast(ToObserv)); + } #else - _ObserverSet.erase(ToObserv); + _ObserverSet.erase(ToObserv); #endif - } - - /** Notify all Observers - * Send a message to all Observers attached to this subject. - * The Message depends on the implementation of a concrete - * Oberserver and Subject. - * @see Notify - */ - void Notify(_MessageType rcReason) - { - for(typename std::set * >::iterator Iter=_ObserverSet.begin();Iter!=_ObserverSet.end();++Iter) - { - try { - (*Iter)->OnChange(*this,rcReason); // send OnChange-signal - } catch (Base::Exception &e) { - Base::Console().Error("Unhandled Base::Exception caught when notifying observer.\n" - "The error message is: %s\n", e.what()); - } catch (std::exception &e) { - Base::Console().Error("Unhandled std::exception caught when notifying observer\n" - "The error message is: %s\n", e.what()); - } catch (...) { - Base::Console().Error("Unhandled unknown exception caught in when notifying observer.\n"); - } - } - } - - /** Get an Observer by name - * Get a observer by name if the observer reimplements the Name() mthode. - * @see Observer - */ - Observer<_MessageType> * Get(const char *Name) - { - const char* OName = nullptr; - for(typename std::set * >::iterator Iter=_ObserverSet.begin();Iter!=_ObserverSet.end();++Iter) - { - OName = (*Iter)->Name(); // get the name - if(OName && strcmp(OName,Name) == 0) - return *Iter; } - return nullptr; - } + /** Notify all Observers + * Send a message to all Observers attached to this subject. + * The Message depends on the implementation of a concrete + * Oberserver and Subject. + * @see Notify + */ + void Notify(_MessageType rcReason) + { + for (typename std::set*>::iterator Iter = _ObserverSet.begin(); + Iter != _ObserverSet.end(); + ++Iter) { + try { + (*Iter)->OnChange(*this, rcReason); // send OnChange-signal + } + catch (Base::Exception& e) { + Base::Console().Error("Unhandled Base::Exception caught when notifying observer.\n" + "The error message is: %s\n", + e.what()); + } + catch (std::exception& e) { + Base::Console().Error("Unhandled std::exception caught when notifying observer\n" + "The error message is: %s\n", + e.what()); + } + catch (...) { + Base::Console().Error( + "Unhandled unknown exception caught in when notifying observer.\n"); + } + } + } - /** Clears the list of all registered observers. - * @note Using this function in your code may be an indication of design problems. - */ - void ClearObserver() - { - _ObserverSet.clear(); - } + /** Get an Observer by name + * Get a observer by name if the observer reimplements the Name() mthode. + * @see Observer + */ + Observer<_MessageType>* Get(const char* Name) + { + const char* OName = nullptr; + for (typename std::set*>::iterator Iter = _ObserverSet.begin(); + Iter != _ObserverSet.end(); + ++Iter) { + OName = (*Iter)->Name(); // get the name + if (OName && strcmp(OName, Name) == 0) { + return *Iter; + } + } + + return nullptr; + } + + /** Clears the list of all registered observers. + * @note Using this function in your code may be an indication of design problems. + */ + void ClearObserver() + { + _ObserverSet.clear(); + } protected: - /// Vector of attached observers - std::set *> _ObserverSet; + /// Vector of attached observers + std::set*> _ObserverSet; }; // Workaround for MSVC -#if defined (FreeCADBase_EXPORTS) && defined(_MSC_VER) -# define Base_EXPORT +#if defined(FreeCADBase_EXPORTS) && defined(_MSC_VER) +#define Base_EXPORT #else -# define Base_EXPORT BaseExport +#define Base_EXPORT BaseExport #endif extern template class Base_EXPORT Observer; extern template class Base_EXPORT Subject; -} //namespace Base +} // namespace Base -#endif // BASE_OBSERVER_H +#endif // BASE_OBSERVER_H diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index 01d3d02db9..6e671273de 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -25,23 +25,23 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #ifdef FC_OS_LINUX -# include +#include #endif #include @@ -72,7 +72,7 @@ using namespace Base; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -class DOMTreeErrorReporter : public ErrorHandler +class DOMTreeErrorReporter: public ErrorHandler { public: // ----------------------------------------------------------------------- @@ -104,14 +104,13 @@ public: // method. Its used by the main code to suppress output if there are // errors. // ----------------------------------------------------------------------- - bool fSawErrors{false}; + bool fSawErrors {false}; }; -class DOMPrintFilter : public DOMLSSerializerFilter +class DOMPrintFilter: public DOMLSSerializerFilter { public: - /** @name Constructors */ explicit DOMPrintFilter(ShowType whatToShow = DOMNodeFilter::SHOW_ALL); //@{ @@ -124,31 +123,31 @@ public: FilterAction acceptNode(const XERCES_CPP_NAMESPACE_QUALIFIER DOMNode*) const override; //@{ - ShowType getWhatToShow() const override { + ShowType getWhatToShow() const override + { return fWhatToShow; } // unimplemented copy ctor and assignment operator DOMPrintFilter(const DOMPrintFilter&) = delete; - DOMPrintFilter & operator = (const DOMPrintFilter&) = delete; + DOMPrintFilter& operator=(const DOMPrintFilter&) = delete; - ShowType fWhatToShow; + ShowType fWhatToShow; }; -class DOMPrintErrorHandler : public DOMErrorHandler +class DOMPrintErrorHandler: public DOMErrorHandler { public: - DOMPrintErrorHandler() = default; ~DOMPrintErrorHandler() override = default; /** @name The error handler interface */ bool handleError(const DOMError& domError) override; - void resetErrors() {} + void resetErrors() + {} /* Unimplemented constructors and operators */ explicit DOMPrintErrorHandler(const DOMErrorHandler&) = delete; void operator=(const DOMErrorHandler&) = delete; - }; @@ -169,30 +168,36 @@ inline bool DOMTreeErrorReporter::getSawErrors() const /** Default construction - */ -ParameterGrp::ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *GroupNode, + */ +ParameterGrp::ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode, const char* sName, - ParameterGrp *Parent) - : Base::Handled(), Subject() - , _pGroupNode(GroupNode) - , _Parent(Parent) + ParameterGrp* Parent) + : Base::Handled() + , Subject() + , _pGroupNode(GroupNode) + , _Parent(Parent) { - if (sName) _cName=sName; - if (_Parent) _Manager = _Parent->_Manager; + if (sName) { + _cName = sName; + } + if (_Parent) { + _Manager = _Parent->_Manager; + } } /** Destruction - * complete destruction of the object - */ + * complete destruction of the object + */ ParameterGrp::~ParameterGrp() { - for (auto &v : _GroupMap) { + for (auto& v : _GroupMap) { v.second->_Parent = nullptr; v.second->_Manager = nullptr; } - if (_Detached && _pGroupNode) + if (_Detached && _pGroupNode) { _pGroupNode->release(); + } } //************************************************************************** @@ -200,8 +205,9 @@ ParameterGrp::~ParameterGrp() void ParameterGrp::copyTo(Base::Reference Grp) { - if (Grp == this) + if (Grp == this) { return; + } // delete previous content Grp->Clear(true); @@ -212,44 +218,51 @@ void ParameterGrp::copyTo(Base::Reference Grp) void ParameterGrp::insertTo(Base::Reference Grp) { - if (Grp == this) + if (Grp == this) { return; + } // copy group - std::vector > Grps = GetGroups(); - std::vector >::iterator It1; - for (It1 = Grps.begin();It1 != Grps.end();++It1) + std::vector> Grps = GetGroups(); + std::vector>::iterator It1; + for (It1 = Grps.begin(); It1 != Grps.end(); ++It1) { (*It1)->insertTo(Grp->GetGroup((*It1)->GetGroupName())); + } // copy strings - std::vector > StringMap = GetASCIIMap(); - std::vector >::iterator It2; - for (It2 = StringMap.begin();It2 != StringMap.end();++It2) - Grp->SetASCII(It2->first.c_str(),It2->second.c_str()); + std::vector> StringMap = GetASCIIMap(); + std::vector>::iterator It2; + for (It2 = StringMap.begin(); It2 != StringMap.end(); ++It2) { + Grp->SetASCII(It2->first.c_str(), It2->second.c_str()); + } // copy bool - std::vector > BoolMap = GetBoolMap(); - std::vector >::iterator It3; - for (It3 = BoolMap.begin();It3 != BoolMap.end();++It3) - Grp->SetBool(It3->first.c_str(),It3->second); + std::vector> BoolMap = GetBoolMap(); + std::vector>::iterator It3; + for (It3 = BoolMap.begin(); It3 != BoolMap.end(); ++It3) { + Grp->SetBool(It3->first.c_str(), It3->second); + } // copy int - std::vector > IntMap = GetIntMap(); - std::vector >::iterator It4; - for (It4 = IntMap.begin();It4 != IntMap.end();++It4) - Grp->SetInt(It4->first.c_str(),It4->second); + std::vector> IntMap = GetIntMap(); + std::vector>::iterator It4; + for (It4 = IntMap.begin(); It4 != IntMap.end(); ++It4) { + Grp->SetInt(It4->first.c_str(), It4->second); + } // copy float - std::vector > FloatMap = GetFloatMap(); - std::vector >::iterator It5; - for (It5 = FloatMap.begin();It5 != FloatMap.end();++It5) - Grp->SetFloat(It5->first.c_str(),It5->second); + std::vector> FloatMap = GetFloatMap(); + std::vector>::iterator It5; + for (It5 = FloatMap.begin(); It5 != FloatMap.end(); ++It5) { + Grp->SetFloat(It5->first.c_str(), It5->second); + } // copy uint - std::vector > UIntMap = GetUnsignedMap(); - std::vector >::iterator It6; - for (It6 = UIntMap.begin();It6 != UIntMap.end();++It6) - Grp->SetUnsigned(It6->first.c_str(),It6->second); + std::vector> UIntMap = GetUnsignedMap(); + std::vector>::iterator It6; + for (It6 = UIntMap.begin(); It6 != UIntMap.end(); ++It6) { + Grp->SetUnsigned(It6->first.c_str(), It6->second); + } } void ParameterGrp::exportTo(const char* FileName) @@ -268,8 +281,9 @@ void ParameterGrp::importFrom(const char* FileName) { auto Mngr = ParameterManager::Create(); - if (Mngr->LoadDocument(FileName) != 1) + if (Mngr->LoadDocument(FileName) != 1) { throw FileException("ParameterGrp::import() cannot load document", FileName); + } Mngr->copyTo(Base::Reference(this)); } @@ -278,8 +292,9 @@ void ParameterGrp::insert(const char* FileName) { auto Mngr = ParameterManager::Create(); - if (Mngr->LoadDocument(FileName) != 1) + if (Mngr->LoadDocument(FileName) != 1) { throw FileException("ParameterGrp::import() cannot load document", FileName); + } Mngr->insertTo(Base::Reference(this)); } @@ -288,54 +303,68 @@ void ParameterGrp::revert(const char* FileName) { auto Mngr = ParameterManager::Create(); - if (Mngr->LoadDocument(FileName) != 1) + if (Mngr->LoadDocument(FileName) != 1) { throw FileException("ParameterGrp::revert() cannot load document", FileName); + } revert(Base::Reference(Mngr)); } void ParameterGrp::revert(Base::Reference Grp) { - if (Grp == this) + if (Grp == this) { return; + } - for (auto &grp : Grp->GetGroups()) { - if (HasGroup(grp->GetGroupName())) + for (auto& grp : Grp->GetGroups()) { + if (HasGroup(grp->GetGroupName())) { GetGroup(grp->GetGroupName())->revert(grp); + } } - for (const auto &v : Grp->GetASCIIMap()) { - if (GetASCII(v.first.c_str(), v.second.c_str()) == v.second) + for (const auto& v : Grp->GetASCIIMap()) { + if (GetASCII(v.first.c_str(), v.second.c_str()) == v.second) { RemoveASCII(v.first.c_str()); + } } - for (const auto &v : Grp->GetBoolMap()) { - if (GetBool(v.first.c_str(), v.second) == v.second) + for (const auto& v : Grp->GetBoolMap()) { + if (GetBool(v.first.c_str(), v.second) == v.second) { RemoveBool(v.first.c_str()); + } } - for (const auto &v : Grp->GetIntMap()) { - if (GetInt(v.first.c_str(), v.second) == v.second) + for (const auto& v : Grp->GetIntMap()) { + if (GetInt(v.first.c_str(), v.second) == v.second) { RemoveInt(v.first.c_str()); + } } - for (const auto &v : Grp->GetUnsignedMap()) { - if (GetUnsigned(v.first.c_str(), v.second) == v.second) + for (const auto& v : Grp->GetUnsignedMap()) { + if (GetUnsigned(v.first.c_str(), v.second) == v.second) { RemoveUnsigned(v.first.c_str()); + } } - for (const auto &v : Grp->GetFloatMap()) { - if (GetFloat(v.first.c_str(), v.second) == v.second) + for (const auto& v : Grp->GetFloatMap()) { + if (GetFloat(v.first.c_str(), v.second) == v.second) { RemoveFloat(v.first.c_str()); + } } } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * -ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name) +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* +ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name) { - if (XMLString::compareString(Start->getNodeName(), XStr("FCParamGroup").unicodeForm()) != 0 && - XMLString::compareString(Start->getNodeName(), XStr("FCParameters").unicodeForm()) != 0) { - Base::Console().Warning("CreateElement: %s cannot have the element %s of type %s\n", StrX(Start->getNodeName()).c_str(), Name, Type); + if (XMLString::compareString(Start->getNodeName(), XStr("FCParamGroup").unicodeForm()) != 0 + && XMLString::compareString(Start->getNodeName(), XStr("FCParameters").unicodeForm()) + != 0) { + Base::Console().Warning("CreateElement: %s cannot have the element %s of type %s\n", + StrX(Start->getNodeName()).c_str(), + Name, + Type); return nullptr; } @@ -344,10 +373,10 @@ ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, co _Parent->_GetGroup(_cName.c_str()); } - XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *pDocument = Start->getOwnerDocument(); + XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDocument = Start->getOwnerDocument(); auto pcElem = pDocument->createElement(XStr(Type).unicodeForm()); - pcElem-> setAttribute(XStr("Name").unicodeForm(), XStr(Name).unicodeForm()); + pcElem->setAttribute(XStr("Name").unicodeForm(), XStr(Name).unicodeForm()); Start->appendChild(pcElem); return pcElem; @@ -355,16 +384,18 @@ ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, co Base::Reference ParameterGrp::GetGroup(const char* Name) { - if (!Name) + if (!Name) { throw Base::ValueError("Empty group name"); + } Base::Reference hGrp = this; std::vector tokens; boost::split(tokens, Name, boost::is_any_of("/")); - for (auto &token : tokens) { + for (auto& token : tokens) { boost::trim(token); - if (token.empty()) + if (token.empty()) { continue; + } hGrp = hGrp->_GetGroup(token.c_str()); if (!hGrp) { // The group is clearing. Return some dummy group to avoid caller @@ -374,8 +405,9 @@ Base::Reference ParameterGrp::GetGroup(const char* Name) break; } } - if (hGrp == this) + if (hGrp == this) { throw Base::ValueError("Empty group name"); + } return hGrp; } @@ -383,29 +415,33 @@ Base::Reference ParameterGrp::_GetGroup(const char* Name) { Base::Reference rParamGrp; if (!_pGroupNode) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { FC_WARN("Adding group " << Name << " in an orphan group " << _cName); + } return rParamGrp; } if (_Clearing) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { FC_WARN("Adding group " << Name << " while clearing " << GetPath()); + } return rParamGrp; } - DOMElement *pcTemp{}; + DOMElement* pcTemp {}; // search if Group node already there - pcTemp = FindElement(_pGroupNode,"FCParamGroup",Name); + pcTemp = FindElement(_pGroupNode, "FCParamGroup", Name); // already created? - if (!(rParamGrp=_GroupMap[Name]).isValid()) { - if (!pcTemp) - pcTemp = CreateElement(_pGroupNode,"FCParamGroup",Name); + if (!(rParamGrp = _GroupMap[Name]).isValid()) { + if (!pcTemp) { + pcTemp = CreateElement(_pGroupNode, "FCParamGroup", Name); + } // create and register handle - rParamGrp = Base::Reference (new ParameterGrp(pcTemp,Name,this)); + rParamGrp = Base::Reference(new ParameterGrp(pcTemp, Name, this)); _GroupMap[Name] = rParamGrp; - } else if (!pcTemp) { + } + else if (!pcTemp) { _pGroupNode->appendChild(rParamGrp->_pGroupNode); rParamGrp->_Detached = false; if (this->_Detached && this->_Parent) { @@ -415,8 +451,9 @@ Base::Reference ParameterGrp::_GetGroup(const char* Name) } } - if (!pcTemp && !this->_Detached) + if (!pcTemp && !this->_Detached) { _Notify(ParamType::FCGroup, Name, Name); + } return rParamGrp; } @@ -424,35 +461,40 @@ Base::Reference ParameterGrp::_GetGroup(const char* Name) std::string ParameterGrp::GetPath() const { std::string path; - if (_Parent && _Parent != _Manager) + if (_Parent && _Parent != _Manager) { path = _Parent->GetPath(); - if (path.size() && _cName.size()) + } + if (path.size() && _cName.size()) { path += "/"; + } path += _cName; return path; } -std::vector > ParameterGrp::GetGroups() +std::vector> ParameterGrp::GetGroups() { Base::Reference rParamGrp; - std::vector > vrParamGrp; + std::vector> vrParamGrp; - if (!_pGroupNode) + if (!_pGroupNode) { return vrParamGrp; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCParamGroup"); + DOMElement* pcTemp = FindElement(_pGroupNode, "FCParamGroup"); while (pcTemp) { - Name = StrX(pcTemp->getAttributes()->getNamedItem(XStr("Name").unicodeForm())->getNodeValue()).c_str(); + Name = + StrX(pcTemp->getAttributes()->getNamedItem(XStr("Name").unicodeForm())->getNodeValue()) + .c_str(); // already created? - if (!(rParamGrp=_GroupMap[Name]).isValid()) { - rParamGrp = Base::Reference (new ParameterGrp(pcTemp,Name.c_str(),this)); + if (!(rParamGrp = _GroupMap[Name]).isValid()) { + rParamGrp = Base::Reference(new ParameterGrp(pcTemp, Name.c_str(), this)); _GroupMap[Name] = rParamGrp; } - vrParamGrp.push_back( rParamGrp ); + vrParamGrp.push_back(rParamGrp); // go to next - pcTemp = FindNextElement(pcTemp,"FCParamGroup"); + pcTemp = FindNextElement(pcTemp, "FCParamGroup"); } return vrParamGrp; @@ -461,186 +503,211 @@ std::vector > ParameterGrp::GetGroups() /// test if this group is empty bool ParameterGrp::IsEmpty() const { - if ( _pGroupNode && _pGroupNode->getFirstChild() ) + if (_pGroupNode && _pGroupNode->getFirstChild()) { return false; - else + } + else { return true; + } } /// test if a special sub group is in this group bool ParameterGrp::HasGroup(const char* Name) const { - if (_GroupMap.find(Name) != _GroupMap.end()) + if (_GroupMap.find(Name) != _GroupMap.end()) { return true; + } - if (_pGroupNode && FindElement(_pGroupNode,"FCParamGroup",Name) != nullptr) + if (_pGroupNode && FindElement(_pGroupNode, "FCParamGroup", Name) != nullptr) { return true; + } return false; } -const char *ParameterGrp::TypeName(ParamType Type) +const char* ParameterGrp::TypeName(ParamType Type) { - switch(Type) { - case ParamType::FCBool: - return "FCBool"; - case ParamType::FCInt: - return "FCInt"; - case ParamType::FCUInt: - return "FCUInt"; - case ParamType::FCText: - return "FCText"; - case ParamType::FCFloat: - return "FCFloat"; - case ParamType::FCGroup: - return "FCParamGroup"; - default: - return nullptr; + switch (Type) { + case ParamType::FCBool: + return "FCBool"; + case ParamType::FCInt: + return "FCInt"; + case ParamType::FCUInt: + return "FCUInt"; + case ParamType::FCText: + return "FCText"; + case ParamType::FCFloat: + return "FCFloat"; + case ParamType::FCGroup: + return "FCParamGroup"; + default: + return nullptr; } } -ParameterGrp::ParamType ParameterGrp::TypeValue(const char *Name) +ParameterGrp::ParamType ParameterGrp::TypeValue(const char* Name) { if (Name) { - if (boost::equals(Name, "FCBool")) + if (boost::equals(Name, "FCBool")) { return ParamType::FCBool; - if (boost::equals(Name, "FCInt")) + } + if (boost::equals(Name, "FCInt")) { return ParamType::FCInt; - if (boost::equals(Name, "FCUInt")) + } + if (boost::equals(Name, "FCUInt")) { return ParamType::FCUInt; - if (boost::equals(Name, "FCText")) + } + if (boost::equals(Name, "FCText")) { return ParamType::FCText; - if (boost::equals(Name, "FCFloat")) + } + if (boost::equals(Name, "FCFloat")) { return ParamType::FCFloat; - if (boost::equals(Name, "FCParamGroup")) + } + if (boost::equals(Name, "FCParamGroup")) { return ParamType::FCGroup; + } } return ParamType::FCInvalid; } -void ParameterGrp::SetAttribute(ParamType Type, const char *Name, const char *Value) +void ParameterGrp::SetAttribute(ParamType Type, const char* Name, const char* Value) { - switch(Type) { - case ParamType::FCBool: - case ParamType::FCInt: - case ParamType::FCUInt: - case ParamType::FCFloat: - return _SetAttribute(Type, Name, Value); - case ParamType::FCText: - return SetASCII(Name, Value); - case ParamType::FCGroup: - RenameGrp(Name, Value); - break; - default: - break; + switch (Type) { + case ParamType::FCBool: + case ParamType::FCInt: + case ParamType::FCUInt: + case ParamType::FCFloat: + return _SetAttribute(Type, Name, Value); + case ParamType::FCText: + return SetASCII(Name, Value); + case ParamType::FCGroup: + RenameGrp(Name, Value); + break; + default: + break; } } -void ParameterGrp::RemoveAttribute(ParamType Type, const char *Name) +void ParameterGrp::RemoveAttribute(ParamType Type, const char* Name) { - switch(Type) { - case ParamType::FCBool: - return RemoveBool(Name); - case ParamType::FCInt: - return RemoveInt(Name); - case ParamType::FCUInt: - return RemoveUnsigned(Name); - case ParamType::FCText: - return RemoveASCII(Name); - case ParamType::FCFloat: - return RemoveFloat(Name); - case ParamType::FCGroup: - return RemoveGrp(Name); - default: - break; + switch (Type) { + case ParamType::FCBool: + return RemoveBool(Name); + case ParamType::FCInt: + return RemoveInt(Name); + case ParamType::FCUInt: + return RemoveUnsigned(Name); + case ParamType::FCText: + return RemoveASCII(Name); + case ParamType::FCFloat: + return RemoveFloat(Name); + case ParamType::FCGroup: + return RemoveGrp(Name); + default: + break; } } -const char * -ParameterGrp::GetAttribute(ParamType Type, - const char *Name, - std::string &Value, - const char *Default) const +const char* ParameterGrp::GetAttribute(ParamType Type, + const char* Name, + std::string& Value, + const char* Default) const { - if (!_pGroupNode) + if (!_pGroupNode) { return Default; + } - const char *T = TypeName(Type); - if (!T) + const char* T = TypeName(Type); + if (!T) { return Default; + } - DOMElement *pcElem = FindElement(_pGroupNode,T,Name); - if (!pcElem) + DOMElement* pcElem = FindElement(_pGroupNode, T, Name); + if (!pcElem) { return Default; + } - if (Type == ParamType::FCText) + if (Type == ParamType::FCText) { Value = GetASCII(Name, Default); - else if (Type != ParamType::FCGroup) + } + else if (Type != ParamType::FCGroup) { Value = StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(); + } return Value.c_str(); } std::vector> -ParameterGrp::GetAttributeMap(ParamType Type, const char *sFilter) const +ParameterGrp::GetAttributeMap(ParamType Type, const char* sFilter) const { std::vector> res; - if (!_pGroupNode) + if (!_pGroupNode) { return res; + } - const char *T = TypeName(Type); - if (!T) + const char* T = TypeName(Type); + if (!T) { return res; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode, T); - while ( pcTemp) { - Name = StrX(static_cast( - pcTemp)->getAttributes()->getNamedItem( - XStr("Name").unicodeForm())->getNodeValue()).c_str(); + DOMElement* pcTemp = FindElement(_pGroupNode, T); + while (pcTemp) { + Name = StrX(static_cast(pcTemp) + ->getAttributes() + ->getNamedItem(XStr("Name").unicodeForm()) + ->getNodeValue()) + .c_str(); // check on filter condition - if (!sFilter || Name.find(sFilter)!= std::string::npos) { - if (Type == ParamType::FCGroup) + if (!sFilter || Name.find(sFilter) != std::string::npos) { + if (Type == ParamType::FCGroup) { res.emplace_back(Name, std::string()); - else - res.emplace_back(Name, StrX(static_cast(pcTemp)->getAttribute( - XStr("Value").unicodeForm())).c_str()); + } + else { + res.emplace_back(Name, + StrX(static_cast(pcTemp)->getAttribute( + XStr("Value").unicodeForm())) + .c_str()); + } } - pcTemp = FindNextElement(pcTemp,T); + pcTemp = FindNextElement(pcTemp, T); } return res; } -void ParameterGrp::_Notify(ParamType Type, const char *Name, const char *Value) +void ParameterGrp::_Notify(ParamType Type, const char* Name, const char* Value) { - if (_Manager) + if (_Manager) { _Manager->signalParamChanged(this, Type, Name, Value); + } } -void ParameterGrp::_SetAttribute(ParamType T, const char *Name, const char *Value) -{ - const char *Type = TypeName(T); - if (!Type) +void ParameterGrp::_SetAttribute(ParamType T, const char* Name, const char* Value) +{ + const char* Type = TypeName(T); + if (!Type) { return; + } if (!_pGroupNode) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) - FC_WARN("Setting attribute " << Type << ":" - << Name << " in an orphan group " << _cName); + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { + FC_WARN("Setting attribute " << Type << ":" << Name << " in an orphan group " + << _cName); + } return; } if (_Clearing) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) - FC_WARN("Adding attribute " << Type << ":" - << Name << " while clearing " << GetPath()); + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { + FC_WARN("Adding attribute " << Type << ":" << Name << " while clearing " << GetPath()); + } return; } // find or create the Element - DOMElement *pcElem = FindOrCreateElement(_pGroupNode,Type,Name); + DOMElement* pcElem = FindOrCreateElement(_pGroupNode, Type, Name); if (pcElem) { XStr attr("Value"); // set the value only if different - if (strcmp(StrX(pcElem->getAttribute(attr.unicodeForm())).c_str(),Value)!=0) { + if (strcmp(StrX(pcElem->getAttribute(attr.unicodeForm())).c_str(), Value) != 0) { pcElem->setAttribute(attr.unicodeForm(), XStr(Value).unicodeForm()); // trigger observer _Notify(T, Name, Value); @@ -653,69 +720,79 @@ void ParameterGrp::_SetAttribute(ParamType T, const char *Name, const char *Valu bool ParameterGrp::GetBool(const char* Name, bool bPreset) const { - if (!_pGroupNode) + if (!_pGroupNode) { return bPreset; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCBool",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCBool", Name); // if not return preset - if (!pcElem) + if (!pcElem) { return bPreset; + } // if yes check the value and return - if (strcmp(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(),"1")) + if (strcmp(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { return false; - else + } + else { return true; + } } -void ParameterGrp::SetBool(const char* Name, bool bValue) +void ParameterGrp::SetBool(const char* Name, bool bValue) { - _SetAttribute(ParamType::FCBool, Name, bValue?"1":"0"); + _SetAttribute(ParamType::FCBool, Name, bValue ? "1" : "0"); } -std::vector ParameterGrp::GetBools(const char * sFilter) const +std::vector ParameterGrp::GetBools(const char* sFilter) const { - std::vector vrValues; - if (!_pGroupNode) + std::vector vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCBool"); - while ( pcTemp) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCBool"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (!sFilter || Name.find(sFilter)!= std::string::npos) { - if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),"1")) + if (!sFilter || Name.find(sFilter) != std::string::npos) { + if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { vrValues.push_back(false); - else + } + else { vrValues.push_back(true); + } } - pcTemp = FindNextElement(pcTemp,"FCBool"); + pcTemp = FindNextElement(pcTemp, "FCBool"); } return vrValues; } -std::vector > ParameterGrp::GetBoolMap(const char * sFilter) const +std::vector> ParameterGrp::GetBoolMap(const char* sFilter) const { - std::vector > vrValues; - if (!_pGroupNode) + std::vector> vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCBool"); - while ( pcTemp) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCBool"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),"1")) + if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { vrValues.emplace_back(Name, false); - else + } + else { vrValues.emplace_back(Name, true); + } } - pcTemp = FindNextElement(pcTemp,"FCBool"); + pcTemp = FindNextElement(pcTemp, "FCBool"); } return vrValues; @@ -723,63 +800,69 @@ std::vector > ParameterGrp::GetBoolMap(const char * long ParameterGrp::GetInt(const char* Name, long lPreset) const { - if (!_pGroupNode) + if (!_pGroupNode) { return lPreset; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCInt",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCInt", Name); // if not return preset - if (!pcElem) + if (!pcElem) { return lPreset; + } // if yes check the value and return - return atol (StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str()); + return atol(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str()); } -void ParameterGrp::SetInt(const char* Name, long lValue) +void ParameterGrp::SetInt(const char* Name, long lValue) { char cBuf[256]; - sprintf(cBuf,"%li",lValue); + sprintf(cBuf, "%li", lValue); _SetAttribute(ParamType::FCInt, Name, cBuf); } -std::vector ParameterGrp::GetInts(const char * sFilter) const +std::vector ParameterGrp::GetInts(const char* sFilter) const { - std::vector vrValues; - if (!_pGroupNode) + std::vector vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCInt") ; - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCInt"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.push_back(atol(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()) ); + vrValues.push_back( + atol(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str())); } - pcTemp = FindNextElement(pcTemp,"FCInt") ; + pcTemp = FindNextElement(pcTemp, "FCInt"); } return vrValues; } -std::vector > ParameterGrp::GetIntMap(const char * sFilter) const +std::vector> ParameterGrp::GetIntMap(const char* sFilter) const { - std::vector > vrValues; - if (!_pGroupNode) + std::vector> vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCInt") ; - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCInt"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.emplace_back(Name, - ( atol (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); + vrValues.emplace_back( + Name, + (atol(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); } - pcTemp = FindNextElement(pcTemp,"FCInt") ; + pcTemp = FindNextElement(pcTemp, "FCInt"); } return vrValues; @@ -787,63 +870,74 @@ std::vector > ParameterGrp::GetIntMap(const char * s unsigned long ParameterGrp::GetUnsigned(const char* Name, unsigned long lPreset) const { - if (!_pGroupNode) + if (!_pGroupNode) { return lPreset; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCUInt",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCUInt", Name); // if not return preset - if (!pcElem) + if (!pcElem) { return lPreset; + } // if yes check the value and return - return strtoul (StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(),nullptr,10); + return strtoul(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(), nullptr, 10); } -void ParameterGrp::SetUnsigned(const char* Name, unsigned long lValue) +void ParameterGrp::SetUnsigned(const char* Name, unsigned long lValue) { char cBuf[256]; - sprintf(cBuf,"%lu",lValue); + sprintf(cBuf, "%lu", lValue); _SetAttribute(ParamType::FCUInt, Name, cBuf); } -std::vector ParameterGrp::GetUnsigneds(const char * sFilter) const +std::vector ParameterGrp::GetUnsigneds(const char* sFilter) const { - std::vector vrValues; - if (!_pGroupNode) + std::vector vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCUInt"); - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCUInt"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.push_back( strtoul (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),nullptr,10) ); + vrValues.push_back( + strtoul(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), + nullptr, + 10)); } - pcTemp = FindNextElement(pcTemp,"FCUInt") ; + pcTemp = FindNextElement(pcTemp, "FCUInt"); } return vrValues; } -std::vector > ParameterGrp::GetUnsignedMap(const char * sFilter) const +std::vector> +ParameterGrp::GetUnsignedMap(const char* sFilter) const { - std::vector > vrValues; - if (!_pGroupNode) + std::vector> vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCUInt"); - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCUInt"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.emplace_back(Name, - ( strtoul (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),nullptr,10) )); + vrValues.emplace_back( + Name, + (strtoul(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), + nullptr, + 10))); } - pcTemp = FindNextElement(pcTemp,"FCUInt"); + pcTemp = FindNextElement(pcTemp, "FCUInt"); } return vrValues; @@ -851,101 +945,110 @@ std::vector > ParameterGrp::GetUnsignedMap( double ParameterGrp::GetFloat(const char* Name, double dPreset) const { - if (!_pGroupNode) + if (!_pGroupNode) { return dPreset; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCFloat",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCFloat", Name); // if not return preset - if (!pcElem) + if (!pcElem) { return dPreset; + } // if yes check the value and return - return atof (StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str()); + return atof(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str()); } -void ParameterGrp::SetFloat(const char* Name, double dValue) +void ParameterGrp::SetFloat(const char* Name, double dValue) { char cBuf[256]; - sprintf(cBuf,"%.12f",dValue); // use %.12f instead of %f to handle values < 1.0e-6 + sprintf(cBuf, "%.12f", dValue); // use %.12f instead of %f to handle values < 1.0e-6 _SetAttribute(ParamType::FCFloat, Name, cBuf); } -std::vector ParameterGrp::GetFloats(const char * sFilter) const +std::vector ParameterGrp::GetFloats(const char* sFilter) const { - std::vector vrValues; - if (!_pGroupNode) + std::vector vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCFloat") ; - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCFloat"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.push_back( atof (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()) ); + vrValues.push_back( + atof(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str())); } - pcTemp = FindNextElement(pcTemp,"FCFloat"); + pcTemp = FindNextElement(pcTemp, "FCFloat"); } return vrValues; } -std::vector > ParameterGrp::GetFloatMap(const char * sFilter) const +std::vector> ParameterGrp::GetFloatMap(const char* sFilter) const { - std::vector > vrValues; - if (!_pGroupNode) + std::vector> vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCFloat") ; - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCFloat"); + while (pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.emplace_back(Name, - ( atof (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); + vrValues.emplace_back( + Name, + (atof(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); } - pcTemp = FindNextElement(pcTemp,"FCFloat"); + pcTemp = FindNextElement(pcTemp, "FCFloat"); } return vrValues; } -void ParameterGrp::SetASCII(const char* Name, const char *sValue) +void ParameterGrp::SetASCII(const char* Name, const char* sValue) { if (!_pGroupNode) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) - FC_WARN("Setting attribute " << "FCText:" - << Name << " in an orphan group " << _cName); + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { + FC_WARN("Setting attribute " + << "FCText:" << Name << " in an orphan group " << _cName); + } return; } if (_Clearing) { - if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) - FC_WARN("Adding attribute " << "FCText:" - << Name << " while clearing " << GetPath()); + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { + FC_WARN("Adding attribute " + << "FCText:" << Name << " while clearing " << GetPath()); + } return; } bool isNew = false; - DOMElement *pcElem = FindElement(_pGroupNode,"FCText",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCText", Name); if (!pcElem) { - pcElem = CreateElement(_pGroupNode,"FCText",Name); + pcElem = CreateElement(_pGroupNode, "FCText", Name); isNew = true; } if (pcElem) { // and set the value - DOMNode *pcElem2 = pcElem->getFirstChild(); + DOMNode* pcElem2 = pcElem->getFirstChild(); if (!pcElem2) { - XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *pDocument = _pGroupNode->getOwnerDocument(); - DOMText *pText = pDocument->createTextNode(XUTF8Str(sValue).unicodeForm()); + XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDocument = _pGroupNode->getOwnerDocument(); + DOMText* pText = pDocument->createTextNode(XUTF8Str(sValue).unicodeForm()); pcElem->appendChild(pText); - if (isNew || sValue[0]!=0) + if (isNew || sValue[0] != 0) { _Notify(ParamType::FCText, Name, sValue); + } } - else if (strcmp(StrXUTF8(pcElem2->getNodeValue()).c_str(), sValue)!=0) { + else if (strcmp(StrXUTF8(pcElem2->getNodeValue()).c_str(), sValue) != 0) { pcElem2->setNodeValue(XUTF8Str(sValue).unicodeForm()); _Notify(ParamType::FCText, Name, sValue); } @@ -954,73 +1057,85 @@ void ParameterGrp::SetASCII(const char* Name, const char *sValue) } } -std::string ParameterGrp::GetASCII(const char* Name, const char * pPreset) const +std::string ParameterGrp::GetASCII(const char* Name, const char* pPreset) const { - if (!_pGroupNode) + if (!_pGroupNode) { return pPreset ? pPreset : ""; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCText",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCText", Name); // if not return preset if (!pcElem) { - if (!pPreset) + if (!pPreset) { return {}; + } return {pPreset}; } // if yes check the value and return - DOMNode *pcElem2 = pcElem->getFirstChild(); - if (pcElem2) + DOMNode* pcElem2 = pcElem->getFirstChild(); + if (pcElem2) { return {StrXUTF8(pcElem2->getNodeValue()).c_str()}; + } return {}; } -std::vector ParameterGrp::GetASCIIs(const char * sFilter) const +std::vector ParameterGrp::GetASCIIs(const char* sFilter) const { - std::vector vrValues; - if (!_pGroupNode) + std::vector vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCText"); - while ( pcTemp ) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCText"); + while (pcTemp) { Name = StrXUTF8(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { // retrieve the text element - DOMNode *pcElem2 = pcTemp->getFirstChild(); - if (pcElem2) - vrValues.emplace_back(StrXUTF8(pcElem2->getNodeValue()).c_str() ); - else - vrValues.emplace_back(""); // For a string, an empty value is possible and allowed + DOMNode* pcElem2 = pcTemp->getFirstChild(); + if (pcElem2) { + vrValues.emplace_back(StrXUTF8(pcElem2->getNodeValue()).c_str()); + } + else { + vrValues.emplace_back(""); // For a string, an empty value is possible and allowed + } } - pcTemp = FindNextElement(pcTemp,"FCText"); + pcTemp = FindNextElement(pcTemp, "FCText"); } return vrValues; } -std::vector > ParameterGrp::GetASCIIMap(const char * sFilter) const +std::vector> +ParameterGrp::GetASCIIMap(const char* sFilter) const { - std::vector > vrValues; - if (!_pGroupNode) + std::vector> vrValues; + if (!_pGroupNode) { return vrValues; + } std::string Name; - DOMElement *pcTemp = FindElement(_pGroupNode,"FCText"); - while ( pcTemp) { + DOMElement* pcTemp = FindElement(_pGroupNode, "FCText"); + while (pcTemp) { Name = StrXUTF8(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { // retrieve the text element - DOMNode *pcElem2 = pcTemp->getFirstChild(); - if (pcElem2) + DOMNode* pcElem2 = pcTemp->getFirstChild(); + if (pcElem2) { vrValues.emplace_back(Name, std::string(StrXUTF8(pcElem2->getNodeValue()).c_str())); - else - vrValues.emplace_back(Name, std::string()); // For a string, an empty value is possible and allowed + } + else { + vrValues.emplace_back( + Name, + std::string()); // For a string, an empty value is possible and allowed + } } - pcTemp = FindNextElement(pcTemp,"FCText"); + pcTemp = FindNextElement(pcTemp, "FCText"); } return vrValues; @@ -1031,14 +1146,16 @@ std::vector > ParameterGrp::GetASCIIMap(const void ParameterGrp::RemoveASCII(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCText",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCText", Name); // if not return - if (!pcElem) + if (!pcElem) { return; + } DOMNode* node = _pGroupNode->removeChild(pcElem); node->release(); @@ -1050,14 +1167,16 @@ void ParameterGrp::RemoveASCII(const char* Name) void ParameterGrp::RemoveBool(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCBool",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCBool", Name); // if not return - if (!pcElem) + if (!pcElem) { return; + } DOMNode* node = _pGroupNode->removeChild(pcElem); node->release(); @@ -1070,33 +1189,37 @@ void ParameterGrp::RemoveBool(const char* Name) void ParameterGrp::RemoveFloat(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCFloat",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCFloat", Name); // if not return - if (!pcElem) + if (!pcElem) { return; + } DOMNode* node = _pGroupNode->removeChild(pcElem); node->release(); // trigger observer - _Notify(ParamType::FCFloat,Name, nullptr); + _Notify(ParamType::FCFloat, Name, nullptr); Notify(Name); } void ParameterGrp::RemoveInt(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCInt",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCInt", Name); // if not return - if (!pcElem) + if (!pcElem) { return; + } DOMNode* node = _pGroupNode->removeChild(pcElem); node->release(); @@ -1108,14 +1231,16 @@ void ParameterGrp::RemoveInt(const char* Name) void ParameterGrp::RemoveUnsigned(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode,"FCUInt",Name); + DOMElement* pcElem = FindElement(_pGroupNode, "FCUInt", Name); // if not return - if (!pcElem) + if (!pcElem) { return; + } DOMNode* node = _pGroupNode->removeChild(pcElem); node->release(); @@ -1127,12 +1252,14 @@ void ParameterGrp::RemoveUnsigned(const char* Name) void ParameterGrp::RemoveGrp(const char* Name) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } auto it = _GroupMap.find(Name); - if (it == _GroupMap.end()) + if (it == _GroupMap.end()) { return; + } // If this or any of its children is referenced by an observer we do not // delete the handle, just in case the group is later added again, or else @@ -1156,15 +1283,18 @@ void ParameterGrp::RemoveGrp(const char* Name) bool ParameterGrp::RenameGrp(const char* OldName, const char* NewName) { - if (!_pGroupNode) + if (!_pGroupNode) { return false; + } auto it = _GroupMap.find(OldName); - if (it == _GroupMap.end()) + if (it == _GroupMap.end()) { return false; + } auto jt = _GroupMap.find(NewName); - if (jt != _GroupMap.end()) + if (jt != _GroupMap.end()) { return false; + } // rename group handle _GroupMap[NewName] = _GroupMap[OldName]; @@ -1172,9 +1302,10 @@ bool ParameterGrp::RenameGrp(const char* OldName, const char* NewName) _GroupMap[NewName]->_cName = NewName; // check if Element in group - DOMElement *pcElem = FindElement(_pGroupNode, "FCParamGroup", OldName); - if (pcElem) - pcElem-> setAttribute(XStr("Name").unicodeForm(), XStr(NewName).unicodeForm()); + DOMElement* pcElem = FindElement(_pGroupNode, "FCParamGroup", OldName); + if (pcElem) { + pcElem->setAttribute(XStr("Name").unicodeForm(), XStr(NewName).unicodeForm()); + } _Notify(ParamType::FCGroup, NewName, OldName); return true; @@ -1182,8 +1313,9 @@ bool ParameterGrp::RenameGrp(const char* OldName, const char* NewName) void ParameterGrp::Clear(bool notify) { - if (!_pGroupNode) + if (!_pGroupNode) { return; + } Base::StateLocker guard(_Clearing); @@ -1192,7 +1324,7 @@ void ParameterGrp::Clear(bool notify) _Notify(ParamType::FCGroup, nullptr, nullptr); // checking on references - for (auto it = _GroupMap.begin();it!=_GroupMap.end();) { + for (auto it = _GroupMap.begin(); it != _GroupMap.end();) { // If a group handle is referenced by some observer, then do not remove // it but clear it, so that any existing observer can still get // notification if the group is later on add back. We do remove the @@ -1203,8 +1335,9 @@ void ParameterGrp::Clear(bool notify) it->second->_Detached = true; _pGroupNode->removeChild(it->second->_pGroupNode); } - if (!it->second->ShouldRemove()) + if (!it->second->ShouldRemove()) { ++it; + } else { it->second->_Parent = nullptr; it->second->_Manager = nullptr; @@ -1214,20 +1347,26 @@ void ParameterGrp::Clear(bool notify) // Remove the rest of non-group nodes; std::vector> params; - for (DOMNode *child = _pGroupNode->getFirstChild(), *next = child; child != nullptr; child = next) { + for (DOMNode *child = _pGroupNode->getFirstChild(), *next = child; child != nullptr; + child = next) { next = next->getNextSibling(); ParamType type = TypeValue(StrX(child->getNodeName()).c_str()); - if (type != ParamType::FCInvalid && type != ParamType::FCGroup) - params.emplace_back(type, StrX(child->getAttributes()->getNamedItem( - XStr("Name").unicodeForm())->getNodeValue()).c_str()); - DOMNode *node = _pGroupNode->removeChild(child); + if (type != ParamType::FCInvalid && type != ParamType::FCGroup) { + params.emplace_back(type, + StrX(child->getAttributes() + ->getNamedItem(XStr("Name").unicodeForm()) + ->getNodeValue()) + .c_str()); + } + DOMNode* node = _pGroupNode->removeChild(child); node->release(); } - for (auto &v : params) { + for (auto& v : params) { _Notify(v.first, v.second.c_str(), nullptr); - if (notify) + if (notify) { Notify(v.second.c_str()); + } } // trigger observer @@ -1239,36 +1378,47 @@ void ParameterGrp::Clear(bool notify) bool ParameterGrp::ShouldRemove() const { - if (this->getRefCount() > 1) + if (this->getRefCount() > 1) { return false; + } for (const auto& it : _GroupMap) { bool ok = it.second->ShouldRemove(); - if (!ok) + if (!ok) { return false; + } } return true; } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* +ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name) const { - if (XMLString::compareString(Start->getNodeName(), XStr("FCParamGroup").unicodeForm()) != 0 && - XMLString::compareString(Start->getNodeName(), XStr("FCParameters").unicodeForm()) != 0) { - Base::Console().Warning("FindElement: %s cannot have the element %s of type %s\n", StrX(Start->getNodeName()).c_str(), Name, Type); + if (XMLString::compareString(Start->getNodeName(), XStr("FCParamGroup").unicodeForm()) != 0 + && XMLString::compareString(Start->getNodeName(), XStr("FCParameters").unicodeForm()) + != 0) { + Base::Console().Warning("FindElement: %s cannot have the element %s of type %s\n", + StrX(Start->getNodeName()).c_str(), + Name, + Type); return nullptr; } - for (DOMNode *clChild = Start->getFirstChild(); clChild != nullptr; clChild = clChild->getNextSibling()) { + for (DOMNode* clChild = Start->getFirstChild(); clChild != nullptr; + clChild = clChild->getNextSibling()) { if (clChild->getNodeType() == DOMNode::ELEMENT_NODE) { // the right node Type - if (!strcmp(Type,StrX(clChild->getNodeName()).c_str())) { + if (!strcmp(Type, StrX(clChild->getNodeName()).c_str())) { if (clChild->getAttributes()->getLength() > 0) { if (Name) { DOMNode* attr = FindAttribute(clChild, "Name"); - if (attr && !strcmp(Name,StrX(attr->getNodeValue()).c_str())) + if (attr && !strcmp(Name, StrX(attr->getNodeValue()).c_str())) { return static_cast(clChild); + } } - else + else { return static_cast(clChild); - + } } } } @@ -1276,16 +1426,18 @@ XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *ParameterGrp::FindElement(XERCES_CPP_ return nullptr; } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *ParameterGrp::FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *Prev, const char* Type) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* +ParameterGrp::FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, const char* Type) const { - DOMNode *clChild = Prev; - if (!clChild) + DOMNode* clChild = Prev; + if (!clChild) { return nullptr; + } while ((clChild = clChild->getNextSibling()) != nullptr) { if (clChild->getNodeType() == DOMNode::ELEMENT_NODE) { // the right node Type - if (!strcmp(Type,StrX(clChild->getNodeName()).c_str())) { + if (!strcmp(Type, StrX(clChild->getNodeName()).c_str())) { return static_cast(clChild); } } @@ -1293,17 +1445,22 @@ XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *ParameterGrp::FindNextElement(XERCES_ return nullptr; } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *ParameterGrp::FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name) +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* +ParameterGrp::FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name) { // first try to find it - DOMElement *pcElem = FindElement(Start,Type,Name); - if (pcElem) + DOMElement* pcElem = FindElement(Start, Type, Name); + if (pcElem) { return pcElem; + } - return CreateElement(Start,Type,Name); + return CreateElement(Start, Type, Name); } -XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *ParameterGrp::FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *Node, const char* Name) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* +ParameterGrp::FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, const char* Name) const { DOMNamedNodeMap* attr = Node->getAttributes(); if (attr) { @@ -1312,26 +1469,29 @@ XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *ParameterGrp::FindAttribute(XERCES_CPP_N return nullptr; } -std::vector > -ParameterGrp::GetParameterNames(const char * sFilter) const +std::vector> +ParameterGrp::GetParameterNames(const char* sFilter) const { - std::vector > res; - if (!_pGroupNode) + std::vector> res; + if (!_pGroupNode) { return res; + } std::string Name; - for (DOMNode *clChild = _pGroupNode->getFirstChild(); - clChild != nullptr; clChild = clChild->getNextSibling()) { + for (DOMNode* clChild = _pGroupNode->getFirstChild(); clChild != nullptr; + clChild = clChild->getNextSibling()) { if (clChild->getNodeType() == DOMNode::ELEMENT_NODE) { StrX type(clChild->getNodeName()); ParamType Type = TypeValue(type.c_str()); if (Type != ParamType::FCInvalid && Type != ParamType::FCGroup) { if (clChild->getAttributes()->getLength() > 0) { - StrX name(clChild->getAttributes()->getNamedItem( - XStr("Name").unicodeForm())->getNodeValue()); - if (!sFilter || strstr(name.c_str(), sFilter)) + StrX name(clChild->getAttributes() + ->getNamedItem(XStr("Name").unicodeForm()) + ->getNodeValue()); + if (!sFilter || strstr(name.c_str(), sFilter)) { res.emplace_back(Type, name.c_str()); + } } } } @@ -1342,36 +1502,42 @@ ParameterGrp::GetParameterNames(const char * sFilter) const void ParameterGrp::NotifyAll() { // get all ints and notify - std::vector > IntMap = GetIntMap(); - for (const auto & it : IntMap) + std::vector> IntMap = GetIntMap(); + for (const auto& it : IntMap) { Notify(it.first.c_str()); + } // get all booleans and notify - std::vector > BoolMap = GetBoolMap(); - for (const auto & it : BoolMap) + std::vector> BoolMap = GetBoolMap(); + for (const auto& it : BoolMap) { Notify(it.first.c_str()); + } // get all Floats and notify - std::vector > FloatMap = GetFloatMap(); - for (const auto & it : FloatMap) + std::vector> FloatMap = GetFloatMap(); + for (const auto& it : FloatMap) { Notify(it.first.c_str()); + } // get all strings and notify - std::vector > StringMap = GetASCIIMap(); - for (const auto & it : StringMap) + std::vector> StringMap = GetASCIIMap(); + for (const auto& it : StringMap) { Notify(it.first.c_str()); + } // get all uints and notify - std::vector > UIntMap = GetUnsignedMap(); - for (const auto & it : UIntMap) + std::vector> UIntMap = GetUnsignedMap(); + for (const auto& it : UIntMap) { Notify(it.first.c_str()); + } } void ParameterGrp::_Reset() { _pGroupNode = nullptr; - for (auto &v : _GroupMap) + for (auto& v : _GroupMap) { v.second->_Reset(); + } } //************************************************************************** @@ -1379,9 +1545,8 @@ void ParameterGrp::_Reset() // ParameterSerializer //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ParameterSerializer::ParameterSerializer(const std::string& fn) - : filename(fn) -{ -} + : filename(fn) +{} ParameterSerializer::~ParameterSerializer() = default; @@ -1405,13 +1570,13 @@ bool ParameterSerializer::LoadOrCreateDocument(ParameterManager& mgr) // ParameterManager //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static XercesDOMParser::ValSchemes gValScheme = XercesDOMParser::Val_Auto; +static XercesDOMParser::ValSchemes gValScheme = XercesDOMParser::Val_Auto; //************************************************************************** // Construction/Destruction /** Default construction - */ + */ ParameterManager::ParameterManager() { _Manager = this; @@ -1419,64 +1584,64 @@ ParameterManager::ParameterManager() // initialize the XML system Init(); -// --------------------------------------------------------------------------- -// Local data -// -// gXmlFile -// The path to the file to parser. Set via command line. -// -// gDoNamespaces -// Indicates whether namespace processing should be done. -// -// gDoSchema -// Indicates whether schema processing should be done. -// -// gSchemaFullChecking -// Indicates whether full schema constraint checking should be done. -// -// gDoCreate -// Indicates whether entity reference nodes needs to be created or not. -// Defaults to false. -// -// gOutputEncoding -// The encoding we are to output in. If not set on the command line, -// then it is defaults to the encoding of the input XML file. -// -// gMyEOLSequence -// The end of line sequence we are to output. -// -// gSplitCdataSections -// Indicates whether split-cdata-sections is to be enabled or not. -// -// gDiscardDefaultContent -// Indicates whether default content is discarded or not. -// -// gUseFilter -// Indicates if user wants to plug in the DOMPrintFilter. -// -// gValScheme -// Indicates what validation scheme to use. It defaults to 'auto', but -// can be set via the -v= command. -// -// --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // Local data + // + // gXmlFile + // The path to the file to parser. Set via command line. + // + // gDoNamespaces + // Indicates whether namespace processing should be done. + // + // gDoSchema + // Indicates whether schema processing should be done. + // + // gSchemaFullChecking + // Indicates whether full schema constraint checking should be done. + // + // gDoCreate + // Indicates whether entity reference nodes needs to be created or not. + // Defaults to false. + // + // gOutputEncoding + // The encoding we are to output in. If not set on the command line, + // then it is defaults to the encoding of the input XML file. + // + // gMyEOLSequence + // The end of line sequence we are to output. + // + // gSplitCdataSections + // Indicates whether split-cdata-sections is to be enabled or not. + // + // gDiscardDefaultContent + // Indicates whether default content is discarded or not. + // + // gUseFilter + // Indicates if user wants to plug in the DOMPrintFilter. + // + // gValScheme + // Indicates what validation scheme to use. It defaults to 'auto', but + // can be set via the -v= command. + // + // --------------------------------------------------------------------------- - gDoNamespaces = false; - gDoSchema = false; - gSchemaFullChecking = false; - gDoCreate = true; + gDoNamespaces = false; + gDoSchema = false; + gSchemaFullChecking = false; + gDoCreate = true; - gOutputEncoding = nullptr; - gMyEOLSequence = nullptr; + gOutputEncoding = nullptr; + gMyEOLSequence = nullptr; - gSplitCdataSections = true; + gSplitCdataSections = true; gDiscardDefaultContent = true; - gUseFilter = true; - gFormatPrettyPrint = true; + gUseFilter = true; + gFormatPrettyPrint = true; } /** Destruction - * complete destruction of the object - */ + * complete destruction of the object + */ ParameterManager::~ParameterManager() { _Reset(); @@ -1502,10 +1667,9 @@ void ParameterManager::Init() #else std::stringstream err; #endif - char *pMsg = XMLString::transcode(toCatch.getMessage()); + char* pMsg = XMLString::transcode(toCatch.getMessage()); err << "Error during Xerces-c Initialization.\n" - << " Exception message:" - << pMsg; + << " Exception message:" << pMsg; XMLString::release(&pMsg); throw XMLBaseException(err.str().c_str()); } @@ -1524,8 +1688,9 @@ void ParameterManager::Terminate() void ParameterManager::SetSerializer(ParameterSerializer* ps) { - if (paramSerializer != ps) + if (paramSerializer != ps) { delete paramSerializer; + } paramSerializer = ps; } @@ -1534,7 +1699,7 @@ bool ParameterManager::HasSerializer() const return (paramSerializer != nullptr); } -const std::string & ParameterManager::GetSerializeFileName() const +const std::string& ParameterManager::GetSerializeFileName() const { static const std::string _dummy; return paramSerializer ? paramSerializer->GetFileName() : _dummy; @@ -1542,24 +1707,29 @@ const std::string & ParameterManager::GetSerializeFileName() const int ParameterManager::LoadDocument() { - if (paramSerializer) + if (paramSerializer) { return paramSerializer->LoadDocument(*this); - else + } + else { return -1; + } } bool ParameterManager::LoadOrCreateDocument() { - if (paramSerializer) + if (paramSerializer) { return paramSerializer->LoadOrCreateDocument(*this); - else + } + else { return false; + } } void ParameterManager::SaveDocument() const { - if (paramSerializer) + if (paramSerializer) { paramSerializer->SaveDocument(*this); + } } //************************************************************************** @@ -1578,13 +1748,14 @@ bool ParameterManager::LoadOrCreateDocument(const char* sFileName) } } -int ParameterManager::LoadDocument(const char* sFileName) +int ParameterManager::LoadDocument(const char* sFileName) { Base::FileInfo file(sFileName); try { -#if defined (FC_OS_WIN32) - LocalFileInputSource inputSource(reinterpret_cast(file.toStdWString().c_str())); +#if defined(FC_OS_WIN32) + LocalFileInputSource inputSource( + reinterpret_cast(file.toStdWString().c_str())); #else LocalFileInputSource inputSource(XStr(file.filePath().c_str()).unicodeForm()); #endif @@ -1607,14 +1778,14 @@ int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSou // The parser will call back to methods of the ErrorHandler if it // discovers errors during the course of parsing the XML document. // - XercesDOMParser *parser = new XercesDOMParser; + XercesDOMParser* parser = new XercesDOMParser; parser->setValidationScheme(gValScheme); parser->setDoNamespaces(gDoNamespaces); parser->setDoSchema(gDoSchema); parser->setValidationSchemaFullChecking(gSchemaFullChecking); parser->setCreateEntityReferenceNodes(gDoCreate); - DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); + DOMTreeErrorReporter* errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); // @@ -1627,14 +1798,14 @@ int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSou } catch (const XMLException& e) { - std::cerr << "An error occurred during parsing\n Message: " - << StrX(e.getMessage()) << std::endl; + std::cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) + << std::endl; errorsOccured = true; } catch (const DOMException& e) { - std::cerr << "A DOM error occurred during parsing\n DOMException code: " - << e.code << std::endl; + std::cerr << "A DOM error occurred during parsing\n DOMException code: " << e.code + << std::endl; errorsOccured = true; } @@ -1653,22 +1824,25 @@ int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSou delete parser; delete errReporter; - if (!_pDocument) + if (!_pDocument) { throw XMLBaseException("Malformed Parameter document: Invalid document"); + } DOMElement* rootElem = _pDocument->getDocumentElement(); - if (!rootElem) + if (!rootElem) { throw XMLBaseException("Malformed Parameter document: Root group not found"); + } - _pGroupNode = FindElement(rootElem,"FCParamGroup","Root"); + _pGroupNode = FindElement(rootElem, "FCParamGroup", "Root"); - if (!_pGroupNode) + if (!_pGroupNode) { throw XMLBaseException("Malformed Parameter document: Root group not found"); + } return 1; } -void ParameterManager::SaveDocument(const char* sFileName) const +void ParameterManager::SaveDocument(const char* sFileName) const { Base::FileInfo file(sFileName); @@ -1680,32 +1854,33 @@ void ParameterManager::SaveDocument(const char* sFileName) const // LocalFileFormatTarget prints the resultant XML stream // to a file once it receives any thing from the serializer. // -#if defined (FC_OS_WIN32) - XMLFormatTarget *myFormTarget = new LocalFileFormatTarget (reinterpret_cast(file.toStdWString().c_str())); +#if defined(FC_OS_WIN32) + XMLFormatTarget* myFormTarget = + new LocalFileFormatTarget(reinterpret_cast(file.toStdWString().c_str())); #else - XMLFormatTarget *myFormTarget = new LocalFileFormatTarget (file.filePath().c_str()); + XMLFormatTarget* myFormTarget = new LocalFileFormatTarget(file.filePath().c_str()); #endif SaveDocument(myFormTarget); delete myFormTarget; } catch (XMLException& e) { - std::cerr << "An error occurred during creation of output transcoder. Msg is:" - << std::endl - << StrX(e.getMessage()) << std::endl; + std::cerr << "An error occurred during creation of output transcoder. Msg is:" << std::endl + << StrX(e.getMessage()) << std::endl; } } -void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const +void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const { try { - std::unique_ptr myFilter; - std::unique_ptr myErrorHandler; + std::unique_ptr myFilter; + std::unique_ptr myErrorHandler; // get a serializer, an instance of DOMWriter XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); - DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); - DOMLSSerializer *theSerializer = static_cast(impl)->createLSSerializer(); + DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr); + DOMLSSerializer* theSerializer = + static_cast(impl)->createLSSerializer(); // set user specified end of line sequence and output encoding theSerializer->setNewLine(gMyEOLSequence); @@ -1715,16 +1890,13 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const // do the serialization through DOMWriter::writeNode(); // if (_pDocument) { - DOMLSOutput *theOutput = static_cast(impl)->createLSOutput(); + DOMLSOutput* theOutput = static_cast(impl)->createLSOutput(); theOutput->setEncoding(gOutputEncoding); if (gUseFilter) { myFilter = std::make_unique( - DOMNodeFilter::SHOW_ELEMENT | - DOMNodeFilter::SHOW_ATTRIBUTE | - DOMNodeFilter::SHOW_DOCUMENT_TYPE | - DOMNodeFilter::SHOW_TEXT - ); + DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE + | DOMNodeFilter::SHOW_DOCUMENT_TYPE | DOMNodeFilter::SHOW_TEXT); theSerializer->setFilter(myFilter.get()); } @@ -1734,14 +1906,18 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const config->setParameter(XMLUni::fgDOMErrorHandler, myErrorHandler.get()); // set feature if the serializer supports the feature/mode - if (config->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections)) + if (config->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections)) { config->setParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections); + } - if (config->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent)) + if (config->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, + gDiscardDefaultContent)) { config->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent); + } - if (config->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint)) + if (config->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint)) { config->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint); + } theOutput->setByteStream(pFormatTarget); theSerializer->write(_pDocument, theOutput); @@ -1752,21 +1928,20 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const theSerializer->release(); } catch (XMLException& e) { - std::cerr << "An error occurred during creation of output transcoder. Msg is:" - << std::endl - << StrX(e.getMessage()) << std::endl; + std::cerr << "An error occurred during creation of output transcoder. Msg is:" << std::endl + << StrX(e.getMessage()) << std::endl; } } -void ParameterManager::CreateDocument() +void ParameterManager::CreateDocument() { // creating a document from screatch - DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XStr("Core").unicodeForm()); + DOMImplementation* impl = + DOMImplementationRegistry::getDOMImplementation(XStr("Core").unicodeForm()); delete _pDocument; - _pDocument = impl->createDocument( - nullptr, // root element namespace URI. - XStr("FCParameters").unicodeForm(), // root element name - nullptr); // document type object (DTD). + _pDocument = impl->createDocument(nullptr, // root element namespace URI. + XStr("FCParameters").unicodeForm(), // root element name + nullptr); // document type object (DTD). // creating the node for the root group DOMElement* rootElem = _pDocument->getDocumentElement(); @@ -1775,10 +1950,11 @@ void ParameterManager::CreateDocument() rootElem->appendChild(_pGroupNode); } -void ParameterManager::CheckDocument() const +void ParameterManager::CheckDocument() const { - if (!_pDocument) + if (!_pDocument) { return; + } try { // @@ -1798,9 +1974,12 @@ void ParameterManager::CheckDocument() const // Either load the XSD file from disk or use the built-in string // const char* xsdFile = "..."; std::string xsdStr(xmlSchemeString); - MemBufInputSource xsdFile(reinterpret_cast(xsdStr.c_str()), xsdStr.size(), "Parameter.xsd"); + MemBufInputSource xsdFile(reinterpret_cast(xsdStr.c_str()), + xsdStr.size(), + "Parameter.xsd"); - // See http://apache-xml-project.6118.n7.nabble.com/validating-xml-with-xsd-schema-td17515.html + // See + // http://apache-xml-project.6118.n7.nabble.com/validating-xml-with-xsd-schema-td17515.html // XercesDOMParser parser; Grammar* grammar = parser.loadGrammar(xsdFile, Grammar::SchemaGrammarType, true); @@ -1810,8 +1989,8 @@ void ParameterManager::CheckDocument() const } parser.setExternalNoNamespaceSchemaLocation("Parameter.xsd"); - //parser.setExitOnFirstFatalError(true); - //parser.setValidationConstraintFatal(true); + // parser.setExitOnFirstFatalError(true); + // parser.setValidationConstraintFatal(true); parser.cacheGrammarFromParse(true); parser.setValidationScheme(XercesDOMParser::Val_Auto); parser.setDoNamespaces(true); @@ -1822,13 +2001,13 @@ void ParameterManager::CheckDocument() const parser.parse(xmlFile); if (parser.getErrorCount() > 0) { - Base::Console().Error("Unexpected XML structure detected: %zu errors\n", parser.getErrorCount()); + Base::Console().Error("Unexpected XML structure detected: %zu errors\n", + parser.getErrorCount()); } } catch (XMLException& e) { - std::cerr << "An error occurred while checking document. Msg is:" - << std::endl - << StrX(e.getMessage()) << std::endl; + std::cerr << "An error occurred while checking document. Msg is:" << std::endl + << StrX(e.getMessage()) << std::endl; } } @@ -1848,19 +2027,17 @@ void DOMTreeErrorReporter::warning(const SAXParseException&) void DOMTreeErrorReporter::error(const SAXParseException& toCatch) { fSawErrors = true; - std::cerr << "Error at file \"" << StrX(toCatch.getSystemId()) - << "\", line " << toCatch.getLineNumber() - << ", column " << toCatch.getColumnNumber() - << "\n Message: " << StrX(toCatch.getMessage()) << std::endl; + std::cerr << "Error at file \"" << StrX(toCatch.getSystemId()) << "\", line " + << toCatch.getLineNumber() << ", column " << toCatch.getColumnNumber() + << "\n Message: " << StrX(toCatch.getMessage()) << std::endl; } void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch) { fSawErrors = true; - std::cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId()) - << "\", line " << toCatch.getLineNumber() - << ", column " << toCatch.getColumnNumber() - << "\n Message: " << StrX(toCatch.getMessage()) << std::endl; + std::cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId()) << "\", line " + << toCatch.getLineNumber() << ", column " << toCatch.getColumnNumber() + << "\n Message: " << StrX(toCatch.getMessage()) << std::endl; } void DOMTreeErrorReporter::resetErrors() @@ -1875,16 +2052,15 @@ void DOMTreeErrorReporter::resetErrors() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DOMPrintFilter::DOMPrintFilter(ShowType whatToShow) : fWhatToShow(whatToShow) -{ -} +{} DOMPrintFilter::FilterAction DOMPrintFilter::acceptNode(const DOMNode* node) const { if (XMLString::compareString(node->getNodeName(), XStr("FCParameters").unicodeForm()) == 0) { // This node is supposed to have a single FCParamGroup and two text nodes. // Over time it can happen that the text nodes collect extra newlines. - const DOMNodeList* children = node->getChildNodes(); - for (XMLSize_t i=0; igetLength(); i++) { + const DOMNodeList* children = node->getChildNodes(); + for (XMLSize_t i = 0; i < children->getLength(); i++) { DOMNode* child = children->item(i); if (child->getNodeType() == DOMNode::TEXT_NODE) { child->setNodeValue(XStr("\n").unicodeForm()); @@ -1900,13 +2076,15 @@ DOMPrintFilter::FilterAction DOMPrintFilter::acceptNode(const DOMNode* node) con auto parent = node->getParentNode(); if (parent && XMLString::compareString(parent->getNodeName(), - XStr("FCParamGroup").unicodeForm()) == 0) + XStr("FCParamGroup").unicodeForm()) + == 0) { return DOMNodeFilter::FILTER_REJECT; + } return DOMNodeFilter::FILTER_ACCEPT; } case DOMNode::DOCUMENT_TYPE_NODE: case DOMNode::DOCUMENT_NODE: { - return DOMNodeFilter::FILTER_REJECT;// no effect + return DOMNodeFilter::FILTER_REJECT; // no effect } default: { return DOMNodeFilter::FILTER_ACCEPT; @@ -1920,11 +2098,11 @@ DOMPrintFilter::FilterAction DOMPrintFilter::acceptNode(const DOMNode* node) con //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -bool DOMPrintErrorHandler::handleError(const DOMError &domError) +bool DOMPrintErrorHandler::handleError(const DOMError& domError) { // Display whatever error message passed from the serializer - char *msg = XMLString::transcode(domError.getMessage()); - std::cout< +class BaseExport ParameterGrp: public Base::Handled, public Base::Subject { public: /** @name copy and insertation */ @@ -117,7 +117,7 @@ public: /// get a handle to a sub group or create one Base::Reference GetGroup(const char* Name); /// get a vector of all sub groups in this group - std::vector > GetGroups(); + std::vector> GetGroups(); /// test if this group is empty bool IsEmpty() const; /// test if a special sub group is in this group @@ -135,7 +135,8 @@ public: /** @name methods for generic attribute handling */ //@{ - enum class ParamType { + enum class ParamType + { FCInvalid = 0, FCText = 1, FCBool = 2, @@ -144,34 +145,32 @@ public: FCFloat = 5, FCGroup = 6, }; - static const char *TypeName(ParamType type); - static ParamType TypeValue(const char *); - void SetAttribute(ParamType Type, const char *Name, const char *Value); - void RemoveAttribute(ParamType Type, const char *Name); - const char *GetAttribute(ParamType Type, - const char *Name, - std::string &Value, - const char *Default) const; + static const char* TypeName(ParamType type); + static ParamType TypeValue(const char*); + void SetAttribute(ParamType Type, const char* Name, const char* Value); + void RemoveAttribute(ParamType Type, const char* Name); + const char* + GetAttribute(ParamType Type, const char* Name, std::string& Value, const char* Default) const; std::vector> - GetAttributeMap(ParamType Type, const char * sFilter = nullptr) const; + GetAttributeMap(ParamType Type, const char* sFilter = nullptr) const; /** Return the type and name of all parameters with optional filter * @param sFilter only strings which name includes sFilter are put in the vector * @return std::vector of pair(type, name) */ - std::vector> - GetParameterNames(const char * sFilter = nullptr) const; + std::vector> + GetParameterNames(const char* sFilter = nullptr) const; //@} /** @name methods for bool handling */ //@{ /// read bool values or give default - bool GetBool(const char* Name, bool bPreset=false) const; + bool GetBool(const char* Name, bool bPreset = false) const; /// set a bool value void SetBool(const char* Name, bool bValue); /// get a vector of all bool values in this group - std::vector GetBools(const char * sFilter = nullptr) const; + std::vector GetBools(const char* sFilter = nullptr) const; /// get a map with all bool values and the keys of this group - std::vector > GetBoolMap(const char * sFilter = nullptr) const; + std::vector> GetBoolMap(const char* sFilter = nullptr) const; /// remove a bool value from this group void RemoveBool(const char* Name); //@} @@ -179,13 +178,13 @@ public: /** @name methods for Int handling */ //@{ /// read bool values or give default - long GetInt(const char* Name, long lPreset=0) const; + long GetInt(const char* Name, long lPreset = 0) const; /// set a int value void SetInt(const char* Name, long lValue); /// get a vector of all int values in this group - std::vector GetInts(const char * sFilter = nullptr) const; + std::vector GetInts(const char* sFilter = nullptr) const; /// get a map with all int values and the keys of this group - std::vector > GetIntMap(const char * sFilter = nullptr) const; + std::vector> GetIntMap(const char* sFilter = nullptr) const; /// remove a int value from this group void RemoveInt(const char* Name); //@} @@ -193,13 +192,14 @@ public: /** @name methods for Unsigned Int handling */ //@{ /// read uint values or give default - unsigned long GetUnsigned(const char* Name, unsigned long lPreset=0) const; + unsigned long GetUnsigned(const char* Name, unsigned long lPreset = 0) const; /// set a uint value void SetUnsigned(const char* Name, unsigned long lValue); /// get a vector of all uint values in this group - std::vector GetUnsigneds(const char * sFilter = nullptr) const; + std::vector GetUnsigneds(const char* sFilter = nullptr) const; /// get a map with all uint values and the keys of this group - std::vector > GetUnsignedMap(const char * sFilter = nullptr) const; + std::vector> + GetUnsignedMap(const char* sFilter = nullptr) const; /// remove a uint value from this group void RemoveUnsigned(const char* Name); //@} @@ -208,28 +208,29 @@ public: /** @name methods for Float handling */ //@{ /// set a float value - double GetFloat(const char* Name, double dPreset=0.0) const; + double GetFloat(const char* Name, double dPreset = 0.0) const; /// read float values or give default void SetFloat(const char* Name, double dValue); /// get a vector of all float values in this group - std::vector GetFloats(const char * sFilter = nullptr) const; + std::vector GetFloats(const char* sFilter = nullptr) const; /// get a map with all float values and the keys of this group - std::vector > GetFloatMap(const char * sFilter = nullptr) const; + std::vector> GetFloatMap(const char* sFilter = nullptr) const; /// remove a float value from this group void RemoveFloat(const char* Name); //@} - - /** @name methods for String handling */ //@{ /// set a string value - void SetASCII(const char* Name, const char *sValue); + void SetASCII(const char* Name, const char* sValue); /// set a string value - void SetASCII(const char* Name, const std::string &sValue) { SetASCII(Name, sValue.c_str()); } + void SetASCII(const char* Name, const std::string& sValue) + { + SetASCII(Name, sValue.c_str()); + } /// read a string values - std::string GetASCII(const char* Name, const char * pPreset=nullptr) const; + std::string GetASCII(const char* Name, const char* pPreset = nullptr) const; /// remove a string value from this group void RemoveASCII(const char* Name); /** Return all string elements in this group as a vector of strings @@ -237,34 +238,42 @@ public: * @param sFilter only strings which name includes sFilter are put in the vector * @return std::vector of std::strings */ - std::vector GetASCIIs(const char * sFilter = nullptr) const; + std::vector GetASCIIs(const char* sFilter = nullptr) const; /// Same as GetASCIIs() but with key,value map - std::vector > GetASCIIMap(const char * sFilter = nullptr) const; + std::vector> + GetASCIIMap(const char* sFilter = nullptr) const; //@} friend class ParameterManager; /// returns the name - const char* GetGroupName() const { + const char* GetGroupName() const + { return _cName.c_str(); } /// return the full path of this group std::string GetPath() const; - void GetPath(std::string &) const; + void GetPath(std::string&) const; /** Notifies all observers for all entries except of sub-groups. */ void NotifyAll(); - ParameterGrp *Parent() const {return _Parent;} - ParameterManager *Manager() const {return _Manager;} + ParameterGrp* Parent() const + { + return _Parent; + } + ParameterManager* Manager() const + { + return _Manager; + } protected: /// constructor is protected (handle concept) - ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *GroupNode=nullptr, - const char* sName=nullptr, - ParameterGrp *Parent=nullptr); + ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode = nullptr, + const char* sName = nullptr, + ParameterGrp* Parent = nullptr); /// destructor is protected (handle concept) ~ParameterGrp() override; /// helper function for GetGroup @@ -273,10 +282,11 @@ protected: void _Reset(); - void _SetAttribute(ParamType Type, const char *Name, const char *Value); - void _Notify(ParamType Type, const char *Name, const char *Value); + void _SetAttribute(ParamType Type, const char* Name, const char* Value); + void _Notify(ParamType Type, const char* Name, const char* Value); - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *Prev, const char* Type) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* + FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, const char* Type) const; /** Find an element specified by Type and Name * Search in the parent element Start for the first occurrence of an @@ -284,29 +294,39 @@ protected: * the pointer to that element, otherwise NULL * If the names not given it returns the first occurrence of Type. */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name=nullptr) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* + FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name = nullptr) const; /** Find an element specified by Type and Name or create it if not found * Search in the parent element Start for the first occurrence of an * element of Type and with the attribute Name=Name. On success it returns * the pointer to that element, otherwise it creates the element and returns the pointer. */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name); + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* + FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name); - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *Start, const char* Type, const char* Name); + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* + CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name); /** Find an attribute specified by Name */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *Node, const char* Name) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* + FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, const char* Name) const; /// DOM Node of the Base node of this group - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *_pGroupNode; + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* _pGroupNode; /// the own name std::string _cName; /// map of already exported groups - std::map > _GroupMap; - ParameterGrp * _Parent = nullptr; - ParameterManager *_Manager = nullptr; + std::map> _GroupMap; + ParameterGrp* _Parent = nullptr; + ParameterManager* _Manager = nullptr; /// Means this group xml element has not been added to its parent yet. bool _Detached = false; /** Indicate this group is currently being cleared @@ -332,7 +352,10 @@ public: virtual void SaveDocument(const ParameterManager&); virtual int LoadDocument(ParameterManager&); virtual bool LoadOrCreateDocument(ParameterManager&); - const std::string &GetFileName() const {return filename;} + const std::string& GetFileName() const + { + return filename; + } protected: std::string filename; @@ -343,7 +366,7 @@ protected: * Does loading, saving and handling the DOM document. * @see ParameterGrp */ -class BaseExport ParameterManager : public ParameterGrp +class BaseExport ParameterManager: public ParameterGrp { public: /// Create a reference counted ParameterManager @@ -354,7 +377,7 @@ public: /** Signal on parameter changes * * The signal is triggered on adding, removing, renaming or modifying on - * all individual parameters and group. The signature of the signal is + * all individual parameters and group. The signature of the signal is * \code * void (ParameterGrp *param, ParamType type, const char *name, const char *value) * \endcode @@ -373,53 +396,53 @@ public: * - Group removal: both 'name' and 'value' are empty * - Group rename: 'name' is the new name, and 'value' is the old name */ - boost::signals2::signal signalParamChanged; + boost::signals2::signal + signalParamChanged; - int LoadDocument(const char* sFileName); - int LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSource&); - bool LoadOrCreateDocument(const char* sFileName); - void SaveDocument(const char* sFileName) const; - void SaveDocument(XERCES_CPP_NAMESPACE_QUALIFIER XMLFormatTarget* pFormatTarget) const; - void CreateDocument(); - void CheckDocument() const; + int LoadDocument(const char* sFileName); + int LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSource&); + bool LoadOrCreateDocument(const char* sFileName); + void SaveDocument(const char* sFileName) const; + void SaveDocument(XERCES_CPP_NAMESPACE_QUALIFIER XMLFormatTarget* pFormatTarget) const; + void CreateDocument(); + void CheckDocument() const; /** @name Parameter serialization */ //@{ /// Sets a serializer. The ParameterManager takes ownership of the serializer. - void SetSerializer(ParameterSerializer*); + void SetSerializer(ParameterSerializer*); /// Returns true if a serializer is set, otherwise false is returned. - bool HasSerializer() const; + bool HasSerializer() const; /// Returns the filename of the serialize. - const std::string & GetSerializeFileName() const; + const std::string& GetSerializeFileName() const; /// Loads an XML document by calling the serializer's load method. - int LoadDocument(); + int LoadDocument(); /// Loads or creates an XML document by calling the serializer's load method. - bool LoadOrCreateDocument(); + bool LoadOrCreateDocument(); /// Saves an XML document by calling the serializer's save method. - void SaveDocument() const; + void SaveDocument() const; //@} private: + XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* _pDocument {nullptr}; + ParameterSerializer* paramSerializer {nullptr}; - XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *_pDocument{nullptr}; - ParameterSerializer * paramSerializer{nullptr}; - - bool gDoNamespaces ; - bool gDoSchema ; - bool gSchemaFullChecking ; - bool gDoCreate ; + bool gDoNamespaces; + bool gDoSchema; + bool gSchemaFullChecking; + bool gDoCreate; - const XMLCh* gOutputEncoding ; - const XMLCh* gMyEOLSequence ; + const XMLCh* gOutputEncoding; + const XMLCh* gMyEOLSequence; - bool gSplitCdataSections ; - bool gDiscardDefaultContent; - bool gUseFilter ; - bool gFormatPrettyPrint ; + bool gSplitCdataSections; + bool gDiscardDefaultContent; + bool gUseFilter; + bool gFormatPrettyPrint; private: ParameterManager(); @@ -427,8 +450,8 @@ private: }; /** python wrapper function -*/ -BaseExport PyObject* GetPyObject( const Base::Reference &hcParamGrp); + */ +BaseExport PyObject* GetPyObject(const Base::Reference& hcParamGrp); -#endif // BASE__PARAMETER_H +#endif // BASE__PARAMETER_H diff --git a/src/Base/ParameterPy.cpp b/src/Base/ParameterPy.cpp index f07e56fcbf..d17c816e2a 100644 --- a/src/Base/ParameterPy.cpp +++ b/src/Base/ParameterPy.cpp @@ -25,17 +25,17 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# ifdef FC_OS_WIN32 -# include -# endif -# include -# include -# include -# include +#ifdef FC_OS_WIN32 +#include +#endif +#include +#include +#include +#include #endif #ifdef FC_OS_LINUX -# include +#include #endif #include "Parameter.h" @@ -43,26 +43,28 @@ #include "Interpreter.h" -namespace Base { +namespace Base +{ -class ParameterGrpObserver : public ParameterGrp::ObserverType +class ParameterGrpObserver: public ParameterGrp::ObserverType { public: explicit ParameterGrpObserver(const Py::Object& obj) { inst = obj; } - ParameterGrpObserver(const Py::Object& obj, const Py::Object &callable, ParameterGrp *target) - : callable(callable), _target(target), inst(obj) - { - } + ParameterGrpObserver(const Py::Object& obj, const Py::Object& callable, ParameterGrp* target) + : callable(callable) + , _target(target) + , inst(obj) + {} ~ParameterGrpObserver() override { Base::PyGILStateLocker lock; inst = Py::None(); callable = Py::None(); } - void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) override + void OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::MessageType Reason) override { Base::PyGILStateLocker lock; try { @@ -72,12 +74,13 @@ public: Py::Tuple args(2); args.setItem(0, Py::asObject(GetPyObject(hGrp))); // A Reason of null indicates to clear the parameter group - if (Reason && Reason[0] != '\0') + if (Reason && Reason[0] != '\0') { args.setItem(1, Py::String(Reason)); + } method.apply(args); } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.ReportException(); } } @@ -89,7 +92,7 @@ public: public: Py::Object callable; boost::signals2::scoped_connection conn; - ParameterGrp *_target = nullptr; // no reference counted, do not access + ParameterGrp* _target = nullptr; // no reference counted, do not access private: Py::Object inst; @@ -97,12 +100,12 @@ private: using ParameterGrpObserverList = std::list; -class ParameterGrpPy : public Py::PythonExtension +class ParameterGrpPy: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods - explicit ParameterGrpPy(const Base::Reference &rcParamGrp); + explicit ParameterGrpPy(const Base::Reference& rcParamGrp); ~ParameterGrpPy() override; Py::Object repr() override; @@ -173,20 +176,22 @@ void ParameterGrpPy::init_type() behaviors().supportSetattr(); behaviors().readyType(); - add_varargs_method("GetGroup",&ParameterGrpPy::getGroup,"GetGroup(str)"); - add_varargs_method("GetGroupName",&ParameterGrpPy::getGroupName,"GetGroupName()"); - add_varargs_method("GetGroups",&ParameterGrpPy::getGroups,"GetGroups()"); - add_varargs_method("RemGroup",&ParameterGrpPy::remGroup,"RemGroup(str)"); - add_varargs_method("HasGroup",&ParameterGrpPy::hasGroup,"HasGroup(str)"); + add_varargs_method("GetGroup", &ParameterGrpPy::getGroup, "GetGroup(str)"); + add_varargs_method("GetGroupName", &ParameterGrpPy::getGroupName, "GetGroupName()"); + add_varargs_method("GetGroups", &ParameterGrpPy::getGroups, "GetGroups()"); + add_varargs_method("RemGroup", &ParameterGrpPy::remGroup, "RemGroup(str)"); + add_varargs_method("HasGroup", &ParameterGrpPy::hasGroup, "HasGroup(str)"); - add_varargs_method("Manager",&ParameterGrpPy::getManager,"Manager()"); - add_varargs_method("Parent",&ParameterGrpPy::getParent,"Parent()"); + add_varargs_method("Manager", &ParameterGrpPy::getManager, "Manager()"); + add_varargs_method("Parent", &ParameterGrpPy::getParent, "Parent()"); - add_varargs_method("IsEmpty",&ParameterGrpPy::isEmpty,"IsEmpty()"); - add_varargs_method("Clear",&ParameterGrpPy::clear,"Clear()"); + add_varargs_method("IsEmpty", &ParameterGrpPy::isEmpty, "IsEmpty()"); + add_varargs_method("Clear", &ParameterGrpPy::clear, "Clear()"); - add_varargs_method("Attach",&ParameterGrpPy::attach,"Attach()"); - add_varargs_method("AttachManager",&ParameterGrpPy::attachManager, + add_varargs_method("Attach", &ParameterGrpPy::attach, "Attach()"); + add_varargs_method( + "AttachManager", + &ParameterGrpPy::attachManager, "AttachManager(observer) -- attach parameter manager for notification\n\n" "This method attaches a user defined observer to the manager (i.e. the root)\n" "of the current parameter group to receive notification of all its parameters\n" @@ -204,52 +209,52 @@ void ParameterGrpPy::init_type() "* Group creation: both 'name' and 'value' contain the name of the new group\n" "* Group removal: both 'name' and 'value' are empty\n" "* Group rename: 'name' is the new name, and 'value' is the old name"); - add_varargs_method("Detach",&ParameterGrpPy::detach,"Detach()"); - add_varargs_method("Notify",&ParameterGrpPy::notify,"Notify()"); - add_varargs_method("NotifyAll",&ParameterGrpPy::notifyAll,"NotifyAll()"); + add_varargs_method("Detach", &ParameterGrpPy::detach, "Detach()"); + add_varargs_method("Notify", &ParameterGrpPy::notify, "Notify()"); + add_varargs_method("NotifyAll", &ParameterGrpPy::notifyAll, "NotifyAll()"); - add_varargs_method("SetBool",&ParameterGrpPy::setBool,"SetBool()"); - add_varargs_method("GetBool",&ParameterGrpPy::getBool,"GetBool()"); - add_varargs_method("GetBools",&ParameterGrpPy::getBools,"GetBools()"); - add_varargs_method("RemBool",&ParameterGrpPy::remBool,"RemBool()"); + add_varargs_method("SetBool", &ParameterGrpPy::setBool, "SetBool()"); + add_varargs_method("GetBool", &ParameterGrpPy::getBool, "GetBool()"); + add_varargs_method("GetBools", &ParameterGrpPy::getBools, "GetBools()"); + add_varargs_method("RemBool", &ParameterGrpPy::remBool, "RemBool()"); - add_varargs_method("SetInt",&ParameterGrpPy::setInt,"SetInt()"); - add_varargs_method("GetInt",&ParameterGrpPy::getInt,"GetInt()"); - add_varargs_method("GetInts",&ParameterGrpPy::getInts,"GetInts()"); - add_varargs_method("RemInt",&ParameterGrpPy::remInt,"RemInt()"); + add_varargs_method("SetInt", &ParameterGrpPy::setInt, "SetInt()"); + add_varargs_method("GetInt", &ParameterGrpPy::getInt, "GetInt()"); + add_varargs_method("GetInts", &ParameterGrpPy::getInts, "GetInts()"); + add_varargs_method("RemInt", &ParameterGrpPy::remInt, "RemInt()"); - add_varargs_method("SetUnsigned",&ParameterGrpPy::setUnsigned,"SetUnsigned()"); - add_varargs_method("GetUnsigned",&ParameterGrpPy::getUnsigned,"GetUnsigned()"); - add_varargs_method("GetUnsigneds",&ParameterGrpPy::getUnsigneds,"GetUnsigneds()"); - add_varargs_method("RemUnsigned",&ParameterGrpPy::remUnsigned,"RemUnsigned()"); + add_varargs_method("SetUnsigned", &ParameterGrpPy::setUnsigned, "SetUnsigned()"); + add_varargs_method("GetUnsigned", &ParameterGrpPy::getUnsigned, "GetUnsigned()"); + add_varargs_method("GetUnsigneds", &ParameterGrpPy::getUnsigneds, "GetUnsigneds()"); + add_varargs_method("RemUnsigned", &ParameterGrpPy::remUnsigned, "RemUnsigned()"); - add_varargs_method("SetFloat",&ParameterGrpPy::setFloat,"SetFloat()"); - add_varargs_method("GetFloat",&ParameterGrpPy::getFloat,"GetFloat()"); - add_varargs_method("GetFloats",&ParameterGrpPy::getFloats,"GetFloats()"); - add_varargs_method("RemFloat",&ParameterGrpPy::remFloat,"RemFloat()"); + add_varargs_method("SetFloat", &ParameterGrpPy::setFloat, "SetFloat()"); + add_varargs_method("GetFloat", &ParameterGrpPy::getFloat, "GetFloat()"); + add_varargs_method("GetFloats", &ParameterGrpPy::getFloats, "GetFloats()"); + add_varargs_method("RemFloat", &ParameterGrpPy::remFloat, "RemFloat()"); - add_varargs_method("SetString",&ParameterGrpPy::setString,"SetString()"); - add_varargs_method("GetString",&ParameterGrpPy::getString,"GetString()"); - add_varargs_method("GetStrings",&ParameterGrpPy::getStrings,"GetStrings()"); - add_varargs_method("RemString",&ParameterGrpPy::remString,"RemString()"); + add_varargs_method("SetString", &ParameterGrpPy::setString, "SetString()"); + add_varargs_method("GetString", &ParameterGrpPy::getString, "GetString()"); + add_varargs_method("GetStrings", &ParameterGrpPy::getStrings, "GetStrings()"); + add_varargs_method("RemString", &ParameterGrpPy::remString, "RemString()"); - add_varargs_method("Import",&ParameterGrpPy::importFrom,"Import()"); - add_varargs_method("Insert",&ParameterGrpPy::insert,"Insert()"); - add_varargs_method("Export",&ParameterGrpPy::exportTo,"Export()"); + add_varargs_method("Import", &ParameterGrpPy::importFrom, "Import()"); + add_varargs_method("Insert", &ParameterGrpPy::insert, "Insert()"); + add_varargs_method("Export", &ParameterGrpPy::exportTo, "Export()"); - add_varargs_method("GetContents",&ParameterGrpPy::getContents,"GetContents()"); + add_varargs_method("GetContents", &ParameterGrpPy::getContents, "GetContents()"); } -ParameterGrpPy::ParameterGrpPy(const Base::Reference &rcParamGrp) - : _cParamGrp(rcParamGrp) -{ -} +ParameterGrpPy::ParameterGrpPy(const Base::Reference& rcParamGrp) + : _cParamGrp(rcParamGrp) +{} ParameterGrpPy::~ParameterGrpPy() { for (ParameterGrpObserver* obs : _observers) { - if (!obs->_target) + if (!obs->_target) { _cParamGrp->Detach(obs); + } delete obs; } } @@ -263,9 +268,10 @@ Py::Object ParameterGrpPy::repr() Py::Object ParameterGrpPy::importFrom(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->importFrom(pstr); return Py::None(); @@ -273,9 +279,10 @@ Py::Object ParameterGrpPy::importFrom(const Py::Tuple& args) Py::Object ParameterGrpPy::insert(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->insert(pstr); return Py::None(); @@ -283,9 +290,10 @@ Py::Object ParameterGrpPy::insert(const Py::Tuple& args) Py::Object ParameterGrpPy::exportTo(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->exportTo(pstr); return Py::None(); @@ -293,16 +301,17 @@ Py::Object ParameterGrpPy::exportTo(const Py::Tuple& args) Py::Object ParameterGrpPy::getGroup(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } try { // get the Handle of the wanted group Base::Reference handle = _cParamGrp->GetGroup(pstr); if (handle.isValid()) { // create a python wrapper class - ParameterGrpPy *pcParamGrp = new ParameterGrpPy(handle); + ParameterGrpPy* pcParamGrp = new ParameterGrpPy(handle); // increment the ref count return Py::asObject(pcParamGrp); } @@ -318,14 +327,15 @@ Py::Object ParameterGrpPy::getGroup(const Py::Tuple& args) Py::Object ParameterGrpPy::getManager(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } // get the Handle of the wanted group Base::Reference handle = _cParamGrp->Manager(); if (handle.isValid()) { // create a python wrapper class - ParameterGrpPy *pcParamGrp = new ParameterGrpPy(handle); + ParameterGrpPy* pcParamGrp = new ParameterGrpPy(handle); // increment the ref count return Py::asObject(pcParamGrp); } @@ -335,14 +345,15 @@ Py::Object ParameterGrpPy::getManager(const Py::Tuple& args) Py::Object ParameterGrpPy::getParent(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } // get the Handle of the wanted group Base::Reference handle = _cParamGrp->Parent(); if (handle.isValid()) { // create a python wrapper class - ParameterGrpPy *pcParamGrp = new ParameterGrpPy(handle); + ParameterGrpPy* pcParamGrp = new ParameterGrpPy(handle); // increment the ref count return Py::asObject(pcParamGrp); } @@ -352,8 +363,9 @@ Py::Object ParameterGrpPy::getParent(const Py::Tuple& args) Py::Object ParameterGrpPy::getGroupName(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } // get the Handle of the wanted group std::string name = _cParamGrp->GetGroupName(); @@ -362,11 +374,12 @@ Py::Object ParameterGrpPy::getGroupName(const Py::Tuple& args) Py::Object ParameterGrpPy::getGroups(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } // get the Handle of the wanted group - std::vector > handle = _cParamGrp->GetGroups(); + std::vector> handle = _cParamGrp->GetGroups(); Py::List list; for (const auto& it : handle) { list.append(Py::String(it->GetGroupName())); @@ -377,32 +390,35 @@ Py::Object ParameterGrpPy::getGroups(const Py::Tuple& args) Py::Object ParameterGrpPy::setBool(const Py::Tuple& args) { - char *pstr = nullptr; - int Bool = 0; - if (!PyArg_ParseTuple(args.ptr(), "si", &pstr,&Bool)) + char* pstr = nullptr; + int Bool = 0; + if (!PyArg_ParseTuple(args.ptr(), "si", &pstr, &Bool)) { throw Py::Exception(); + } - _cParamGrp->SetBool(pstr,Bool!=0); + _cParamGrp->SetBool(pstr, Bool != 0); return Py::None(); } Py::Object ParameterGrpPy::getBool(const Py::Tuple& args) { - char *pstr = nullptr; - int Bool=0; - if (!PyArg_ParseTuple(args.ptr(), "s|i", &pstr,&Bool)) + char* pstr = nullptr; + int Bool = 0; + if (!PyArg_ParseTuple(args.ptr(), "s|i", &pstr, &Bool)) { throw Py::Exception(); + } - return Py::Boolean(_cParamGrp->GetBool(pstr,Bool!=0)); + return Py::Boolean(_cParamGrp->GetBool(pstr, Bool != 0)); } Py::Object ParameterGrpPy::getBools(const Py::Tuple& args) { - char *filter=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) + char* filter = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) { throw Py::Exception(); + } - std::vector > map = _cParamGrp->GetBoolMap(filter); + std::vector> map = _cParamGrp->GetBoolMap(filter); Py::List list; for (const auto& it : map) { list.append(Py::String(it.first)); @@ -413,31 +429,34 @@ Py::Object ParameterGrpPy::getBools(const Py::Tuple& args) Py::Object ParameterGrpPy::setInt(const Py::Tuple& args) { - char *pstr = nullptr; - int Int = 0; - if (!PyArg_ParseTuple(args.ptr(), "si", &pstr,&Int)) + char* pstr = nullptr; + int Int = 0; + if (!PyArg_ParseTuple(args.ptr(), "si", &pstr, &Int)) { throw Py::Exception(); + } - _cParamGrp->SetInt(pstr,Int); + _cParamGrp->SetInt(pstr, Int); return Py::None(); } Py::Object ParameterGrpPy::getInt(const Py::Tuple& args) { - char *pstr = nullptr; - int Int=0; - if (!PyArg_ParseTuple(args.ptr(), "s|i", &pstr,&Int)) + char* pstr = nullptr; + int Int = 0; + if (!PyArg_ParseTuple(args.ptr(), "s|i", &pstr, &Int)) { throw Py::Exception(); - return Py::Long(_cParamGrp->GetInt(pstr,Int)); + } + return Py::Long(_cParamGrp->GetInt(pstr, Int)); } Py::Object ParameterGrpPy::getInts(const Py::Tuple& args) { - char *filter=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) + char* filter = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) { throw Py::Exception(); + } - std::vector > map = _cParamGrp->GetIntMap(filter); + std::vector> map = _cParamGrp->GetIntMap(filter); Py::List list; for (const auto& it : map) { list.append(Py::String(it.first)); @@ -448,31 +467,34 @@ Py::Object ParameterGrpPy::getInts(const Py::Tuple& args) Py::Object ParameterGrpPy::setUnsigned(const Py::Tuple& args) { - char *pstr = nullptr; - unsigned int UInt = 0; - if (!PyArg_ParseTuple(args.ptr(), "sI", &pstr,&UInt)) + char* pstr = nullptr; + unsigned int UInt = 0; + if (!PyArg_ParseTuple(args.ptr(), "sI", &pstr, &UInt)) { throw Py::Exception(); + } - _cParamGrp->SetUnsigned(pstr,UInt); + _cParamGrp->SetUnsigned(pstr, UInt); return Py::None(); } Py::Object ParameterGrpPy::getUnsigned(const Py::Tuple& args) { - char *pstr = nullptr; - unsigned int UInt=0; - if (!PyArg_ParseTuple(args.ptr(), "s|I", &pstr,&UInt)) + char* pstr = nullptr; + unsigned int UInt = 0; + if (!PyArg_ParseTuple(args.ptr(), "s|I", &pstr, &UInt)) { throw Py::Exception(); - return Py::Long(_cParamGrp->GetUnsigned(pstr,UInt)); + } + return Py::Long(_cParamGrp->GetUnsigned(pstr, UInt)); } Py::Object ParameterGrpPy::getUnsigneds(const Py::Tuple& args) { - char *filter=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) + char* filter = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) { throw Py::Exception(); + } - std::vector > map = _cParamGrp->GetUnsignedMap(filter); + std::vector> map = _cParamGrp->GetUnsignedMap(filter); Py::List list; for (const auto& it : map) { list.append(Py::String(it.first)); @@ -483,32 +505,35 @@ Py::Object ParameterGrpPy::getUnsigneds(const Py::Tuple& args) Py::Object ParameterGrpPy::setFloat(const Py::Tuple& args) { - char *pstr = nullptr; - double Float{}; - if (!PyArg_ParseTuple(args.ptr(), "sd", &pstr,&Float)) + char* pstr = nullptr; + double Float {}; + if (!PyArg_ParseTuple(args.ptr(), "sd", &pstr, &Float)) { throw Py::Exception(); + } - _cParamGrp->SetFloat(pstr,Float); + _cParamGrp->SetFloat(pstr, Float); return Py::None(); } Py::Object ParameterGrpPy::getFloat(const Py::Tuple& args) { - char *pstr = nullptr; - double Float=0.0; - if (!PyArg_ParseTuple(args.ptr(), "s|d", &pstr,&Float)) + char* pstr = nullptr; + double Float = 0.0; + if (!PyArg_ParseTuple(args.ptr(), "s|d", &pstr, &Float)) { throw Py::Exception(); + } - return Py::Float(_cParamGrp->GetFloat(pstr,Float)); + return Py::Float(_cParamGrp->GetFloat(pstr, Float)); } Py::Object ParameterGrpPy::getFloats(const Py::Tuple& args) { - char *filter=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) + char* filter = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) { throw Py::Exception(); + } - std::vector > map = _cParamGrp->GetFloatMap(filter); + std::vector> map = _cParamGrp->GetFloatMap(filter); Py::List list; for (const auto& it : map) { list.append(Py::String(it.first)); @@ -519,32 +544,35 @@ Py::Object ParameterGrpPy::getFloats(const Py::Tuple& args) Py::Object ParameterGrpPy::setString(const Py::Tuple& args) { - char *pstr = nullptr; - char * str = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "ss", &pstr,&str)) + char* pstr = nullptr; + char* str = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "ss", &pstr, &str)) { throw Py::Exception(); + } - _cParamGrp->SetASCII(pstr,str); + _cParamGrp->SetASCII(pstr, str); return Py::None(); } Py::Object ParameterGrpPy::getString(const Py::Tuple& args) { - char *pstr = nullptr; - char * str=""; - if (!PyArg_ParseTuple(args.ptr(), "s|s", &pstr,&str)) + char* pstr = nullptr; + char* str = ""; + if (!PyArg_ParseTuple(args.ptr(), "s|s", &pstr, &str)) { throw Py::Exception(); + } - return Py::String(_cParamGrp->GetASCII(pstr,str)); + return Py::String(_cParamGrp->GetASCII(pstr, str)); } Py::Object ParameterGrpPy::getStrings(const Py::Tuple& args) { - char *filter=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) + char* filter = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &filter)) { throw Py::Exception(); + } - std::vector > map = _cParamGrp->GetASCIIMap(filter); + std::vector> map = _cParamGrp->GetASCIIMap(filter); Py::List list; for (const auto& it : map) { list.append(Py::String(it.first)); @@ -555,9 +583,10 @@ Py::Object ParameterGrpPy::getStrings(const Py::Tuple& args) Py::Object ParameterGrpPy::remInt(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveInt(pstr); return Py::None(); @@ -565,9 +594,10 @@ Py::Object ParameterGrpPy::remInt(const Py::Tuple& args) Py::Object ParameterGrpPy::remUnsigned(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveUnsigned(pstr); return Py::None(); @@ -575,9 +605,10 @@ Py::Object ParameterGrpPy::remUnsigned(const Py::Tuple& args) Py::Object ParameterGrpPy::remBool(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveBool(pstr); return Py::None(); @@ -585,9 +616,10 @@ Py::Object ParameterGrpPy::remBool(const Py::Tuple& args) Py::Object ParameterGrpPy::remGroup(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveGrp(pstr); return Py::None(); @@ -595,9 +627,10 @@ Py::Object ParameterGrpPy::remGroup(const Py::Tuple& args) Py::Object ParameterGrpPy::remFloat(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveFloat(pstr); return Py::None(); @@ -605,9 +638,10 @@ Py::Object ParameterGrpPy::remFloat(const Py::Tuple& args) Py::Object ParameterGrpPy::remString(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->RemoveASCII(pstr); return Py::None(); @@ -615,8 +649,9 @@ Py::Object ParameterGrpPy::remString(const Py::Tuple& args) Py::Object ParameterGrpPy::clear(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } _cParamGrp->Clear(); return Py::None(); @@ -624,17 +659,19 @@ Py::Object ParameterGrpPy::clear(const Py::Tuple& args) Py::Object ParameterGrpPy::isEmpty(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(_cParamGrp->IsEmpty()); } Py::Object ParameterGrpPy::hasGroup(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } return Py::Boolean(_cParamGrp->HasGroup(pstr)); } @@ -642,12 +679,14 @@ Py::Object ParameterGrpPy::hasGroup(const Py::Tuple& args) Py::Object ParameterGrpPy::attach(const Py::Tuple& args) { PyObject* obj = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) + if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) { throw Py::Exception(); + } Py::Object o(obj); - if (!o.hasAttr(std::string("onChange"))) + if (!o.hasAttr(std::string("onChange"))) { throw Py::TypeError("Object has no onChange attribute"); + } for (ParameterGrpObserver* it : _observers) { if (it->isEqual(o)) { @@ -665,19 +704,23 @@ Py::Object ParameterGrpPy::attach(const Py::Tuple& args) Py::Object ParameterGrpPy::attachManager(const Py::Tuple& args) { PyObject* obj = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) + if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) { throw Py::Exception(); + } - if (!_cParamGrp->Manager()) + if (!_cParamGrp->Manager()) { throw Py::RuntimeError("Parameter has no manager"); + } Py::Object o(obj); - if (!o.hasAttr(std::string("slotParamChanged"))) + if (!o.hasAttr(std::string("slotParamChanged"))) { throw Py::TypeError("Object has no slotParamChanged attribute"); + } Py::Object attr(o.getAttr("slotParamChanged")); - if (!attr.isCallable()) + if (!attr.isCallable()) { throw Py::TypeError("Object has no slotParamChanged callable attribute"); + } for (ParameterGrpObserver* it : _observers) { if (it->isEqual(o)) { @@ -686,20 +729,25 @@ Py::Object ParameterGrpPy::attachManager(const Py::Tuple& args) } ParameterGrpObserver* obs = new ParameterGrpObserver(o, attr, _cParamGrp); - obs->conn = _cParamGrp->Manager()->signalParamChanged.connect( - [obs](ParameterGrp *Param, ParameterGrp::ParamType Type, const char *Name, const char *Value) { - if (!Param) return; + obs->conn = + _cParamGrp->Manager()->signalParamChanged.connect([obs](ParameterGrp* Param, + ParameterGrp::ParamType Type, + const char* Name, + const char* Value) { + if (!Param) { + return; + } for (auto p = Param; p; p = p->Parent()) { if (p == obs->_target) { Base::PyGILStateLocker lock; - Py::TupleN args( - Py::asObject(new ParameterGrpPy(Param)), - Py::String(ParameterGrp::TypeName(Type)), - Py::String(Name ? Name : ""), - Py::String(Value ? Value : "")); + Py::TupleN args(Py::asObject(new ParameterGrpPy(Param)), + Py::String(ParameterGrp::TypeName(Type)), + Py::String(Name ? Name : ""), + Py::String(Value ? Value : "")); try { Py::Callable(obs->callable).apply(args); - } catch (Py::Exception &) { + } + catch (Py::Exception&) { Base::PyException e; e.ReportException(); } @@ -715,12 +763,14 @@ Py::Object ParameterGrpPy::attachManager(const Py::Tuple& args) Py::Object ParameterGrpPy::detach(const Py::Tuple& args) { PyObject* obj = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) + if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) { throw Py::Exception(); + } Py::Object o(obj); - if (!o.hasAttr(std::string("onChange"))) + if (!o.hasAttr(std::string("onChange"))) { throw Py::TypeError("Object has no onChange attribute"); + } for (ParameterGrpObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) { if ((*it)->isEqual(o)) { @@ -737,9 +787,10 @@ Py::Object ParameterGrpPy::detach(const Py::Tuple& args) Py::Object ParameterGrpPy::notify(const Py::Tuple& args) { - char *pstr = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) + char* pstr = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "s", &pstr)) { throw Py::Exception(); + } _cParamGrp->Notify(pstr); return Py::None(); @@ -747,8 +798,9 @@ Py::Object ParameterGrpPy::notify(const Py::Tuple& args) Py::Object ParameterGrpPy::notifyAll(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } _cParamGrp->NotifyAll(); return Py::None(); @@ -756,71 +808,73 @@ Py::Object ParameterGrpPy::notifyAll(const Py::Tuple& args) Py::Object ParameterGrpPy::getContents(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } - if (_cParamGrp->IsEmpty()) + if (_cParamGrp->IsEmpty()) { return Py::None(); + } Py::List list; // filling up Text nodes - std::vector > mcTextMap = _cParamGrp->GetASCIIMap(); - for (const auto & it : mcTextMap) { + std::vector> mcTextMap = _cParamGrp->GetASCIIMap(); + for (const auto& it : mcTextMap) { Py::Tuple t2(3); - t2.setItem(0,Py::String("String")); - t2.setItem(1,Py::String(it.first.c_str())); - t2.setItem(2,Py::String(it.second.c_str())); + t2.setItem(0, Py::String("String")); + t2.setItem(1, Py::String(it.first.c_str())); + t2.setItem(2, Py::String(it.second.c_str())); list.append(t2); } // filling up Int nodes - std::vector > mcIntMap = _cParamGrp->GetIntMap(); - for (const auto & it : mcIntMap) { + std::vector> mcIntMap = _cParamGrp->GetIntMap(); + for (const auto& it : mcIntMap) { Py::Tuple t3(3); - t3.setItem(0,Py::String("Integer")); - t3.setItem(1,Py::String(it.first.c_str())); - t3.setItem(2,Py::Long(it.second)); + t3.setItem(0, Py::String("Integer")); + t3.setItem(1, Py::String(it.first.c_str())); + t3.setItem(2, Py::Long(it.second)); list.append(t3); } // filling up Float nodes - std::vector > mcFloatMap = _cParamGrp->GetFloatMap(); - for (const auto & it : mcFloatMap) { + std::vector> mcFloatMap = _cParamGrp->GetFloatMap(); + for (const auto& it : mcFloatMap) { Py::Tuple t4(3); - t4.setItem(0,Py::String("Float")); - t4.setItem(1,Py::String(it.first.c_str())); - t4.setItem(2,Py::Float(it.second)); + t4.setItem(0, Py::String("Float")); + t4.setItem(1, Py::String(it.first.c_str())); + t4.setItem(2, Py::Float(it.second)); list.append(t4); } // filling up bool nodes - std::vector > mcBoolMap = _cParamGrp->GetBoolMap(); - for (const auto & it : mcBoolMap) { + std::vector> mcBoolMap = _cParamGrp->GetBoolMap(); + for (const auto& it : mcBoolMap) { Py::Tuple t5(3); - t5.setItem(0,Py::String("Boolean")); - t5.setItem(1,Py::String(it.first.c_str())); - t5.setItem(2,Py::Boolean(it.second)); + t5.setItem(0, Py::String("Boolean")); + t5.setItem(1, Py::String(it.first.c_str())); + t5.setItem(2, Py::Boolean(it.second)); list.append(t5); } // filling up UInt nodes - std::vector > mcUIntMap = _cParamGrp->GetUnsignedMap(); - for (const auto & it : mcUIntMap) { + std::vector> mcUIntMap = _cParamGrp->GetUnsignedMap(); + for (const auto& it : mcUIntMap) { Py::Tuple t6(3); - t6.setItem(0,Py::String("Unsigned Long")); - t6.setItem(1,Py::String(it.first.c_str())); - t6.setItem(2,Py::Long(it.second)); + t6.setItem(0, Py::String("Unsigned Long")); + t6.setItem(1, Py::String(it.first.c_str())); + t6.setItem(2, Py::Long(it.second)); list.append(t6); } return list; } -} // namespace Base +} // namespace Base /** python wrapper function -*/ -PyObject* GetPyObject(const Base::Reference &hcParamGrp) + */ +PyObject* GetPyObject(const Base::Reference& hcParamGrp) { static bool init = false; if (!init) { diff --git a/src/Base/Parser.bat b/src/Base/Parser.bat index 9a8ced0a87..d5620b88f4 100644 --- a/src/Base/Parser.bat +++ b/src/Base/Parser.bat @@ -1,2 +1,2 @@ C:\cygwin\bin\flex.exe -oQuantityLexer.c QuantityParser.l -C:\cygwin\bin\bison -oQuantityParser.c QuantityParser.y \ No newline at end of file +C:\cygwin\bin\bison -oQuantityParser.c QuantityParser.y diff --git a/src/Base/Persistence.cpp b/src/Base/Persistence.cpp index 5a97ef649a..094b85767f 100644 --- a/src/Base/Persistence.cpp +++ b/src/Base/Persistence.cpp @@ -37,66 +37,72 @@ using namespace Base; -TYPESYSTEM_SOURCE_ABSTRACT(Base::Persistence,Base::BaseClass) +TYPESYSTEM_SOURCE_ABSTRACT(Base::Persistence, Base::BaseClass) //************************************************************************** // Construction/Destruction - //************************************************************************** // separator for other implementation aspects -unsigned int Persistence::getMemSize () const +unsigned int Persistence::getMemSize() const { // you have to implement this method in all descending classes! assert(0); return 0; } -void Persistence::Save (Writer &/*writer*/) const +void Persistence::Save(Writer& /*writer*/) const { // you have to implement this method in all descending classes! assert(0); } -void Persistence::Restore(XMLReader &/*reader*/) +void Persistence::Restore(XMLReader& /*reader*/) { // you have to implement this method in all descending classes! assert(0); } -void Persistence::SaveDocFile (Writer &/*writer*/) const -{ -} +void Persistence::SaveDocFile(Writer& /*writer*/) const +{} -void Persistence::RestoreDocFile(Reader &/*reader*/) -{ -} +void Persistence::RestoreDocFile(Reader& /*reader*/) +{} std::string Persistence::encodeAttribute(const std::string& str) { std::string tmp; for (char it : str) { - if (it == '<') + if (it == '<') { tmp += "<"; - else if (it == '\"') + } + else if (it == '\"') { tmp += """; - else if (it == '\'') + } + else if (it == '\'') { tmp += "'"; - else if (it == '&') + } + else if (it == '&') { tmp += "&"; - else if (it == '>') + } + else if (it == '>') { tmp += ">"; - else if (it == '\r') + } + else if (it == '\r') { tmp += " "; - else if (it == '\n') + } + else if (it == '\n') { tmp += " "; - else if (it == '\t') + } + else if (it == '\t') { tmp += " "; - else + } + else { tmp += it; + } } return tmp; @@ -104,16 +110,17 @@ std::string Persistence::encodeAttribute(const std::string& str) void Persistence::dumpToStream(std::ostream& stream, int compression) { - //we need to close the zipstream to get a good result, the only way to do this is to delete the ZipWriter. - //Hence the scope... + // we need to close the zipstream to get a good result, the only way to do this is to delete the + // ZipWriter. Hence the scope... { - //create the writer + // create the writer Base::ZipWriter writer(stream); writer.setLevel(compression); writer.putNextEntry("Persistence.xml"); writer.setMode("BinaryBrep"); - //save the content (we need to encapsulate it with xml tags to be able to read single element xmls like happen for properties) + // save the content (we need to encapsulate it with xml tags to be able to read single + // element xmls like happen for properties) writer.Stream() << "" << std::endl; Save(writer); writer.Stream() << ""; @@ -126,8 +133,9 @@ void Persistence::restoreFromStream(std::istream& stream) zipios::ZipInputStream zipstream(stream); Base::XMLReader reader("", zipstream); - if (!reader.isValid()) + if (!reader.isValid()) { throw Base::ValueError("Unable to construct reader"); + } reader.readElement("Content"); Restore(reader); diff --git a/src/Base/Persistence.h b/src/Base/Persistence.h index 75deac6212..1e6b4b6205 100644 --- a/src/Base/Persistence.h +++ b/src/Base/Persistence.h @@ -33,17 +33,17 @@ class Writer; class XMLReader; /// Persistence class and root of the type system -class BaseExport Persistence : public BaseClass +class BaseExport Persistence: public BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER(); public: /** This method is used to get the size of objects * It is not meant to have the exact size, it is more or less an estimation * which runs fast! Is it two bytes or a GB? */ - virtual unsigned int getMemSize () const = 0; + virtual unsigned int getMemSize() const = 0; /** This method is used to save properties to an XML document. * A good example you'll find in PropertyStandard.cpp, e.g. the vector: * \code @@ -60,7 +60,7 @@ public: * is written. This means closing tags and writing UTF-8. * @see Base::Writer */ - virtual void Save (Writer &/*writer*/) const = 0; + virtual void Save(Writer& /*writer*/) const = 0; /** This method is used to restore properties from an XML document. * It uses the XMLReader class, which bases on SAX, to read the in Save() * written information. Again the Vector as an example: @@ -76,7 +76,7 @@ public: * } * \endcode */ - virtual void Restore(XMLReader &/*reader*/) = 0; + virtual void Restore(XMLReader& /*reader*/) = 0; /** This method is used to save large amounts of data to a binary file. * Sometimes it makes no sense to write property data as XML. In case the * amount of data is too big or the data type has a more effective way to @@ -93,24 +93,25 @@ public: * MeshCore::MeshDocXML saver(*_pcMesh); * saver.Save(writer); * }else{ - * writer << writer.ind() << "" << std::endl; + * writer << writer.ind() << "" << std::endl; * } * \endcode - * The writer.isForceXML() is an indication to force you to write XML. Regardless of size and effectiveness. - * The second part informs the Base::writer through writer.addFile("MeshKernel.bms", this) that this object - * wants to write a file with the given name. The method addFile() returns a unique name that then is written - * in the XML stream. - * This allows your RestoreDocFile() method to identify and read the file again. - * Later your SaveDocFile() method is called as many times as you issued the addFile() call: - * \code - * void PropertyMeshKernel::SaveDocFile (Base::Writer &writer) const + * The writer.isForceXML() is an indication to force you to write XML. Regardless of size and + * effectiveness. The second part informs the Base::writer through + * writer.addFile("MeshKernel.bms", this) that this object wants to write a file with the given + * name. The method addFile() returns a unique name that then is written in the XML stream. This + * allows your RestoreDocFile() method to identify and read the file again. Later your + * SaveDocFile() method is called as many times as you issued the addFile() call: \code void + * PropertyMeshKernel::SaveDocFile (Base::Writer &writer) const * { * _pcMesh->Write( writer ); * } * \endcode - * In this method you can simply stream your content to the file (Base::Writer inheriting from ostream). + * In this method you can simply stream your content to the file (Base::Writer inheriting from + * ostream). */ - virtual void SaveDocFile (Writer &/*writer*/) const; + virtual void SaveDocFile(Writer& /*writer*/) const; /** This method is used to restore large amounts of data from a file * In this method you simply stream in your SaveDocFile() saved data. * Again you have to apply for the call of this method in the Restore() call: @@ -140,14 +141,14 @@ public: * \endcode * @see Base::Reader,Base::XMLReader */ - virtual void RestoreDocFile(Reader &/*reader*/); + virtual void RestoreDocFile(Reader& /*reader*/); /// Encodes an attribute upon saving. static std::string encodeAttribute(const std::string&); - //dump the binary persistence data into into the stream + // dump the binary persistence data into into the stream void dumpToStream(std::ostream& stream, int compression); - //restore the binary persistence data from a stream. Must have the format used by dumpToStream + // restore the binary persistence data from a stream. Must have the format used by dumpToStream void restoreFromStream(std::istream& stream); private: @@ -156,10 +157,11 @@ private: * A subclass can set up some internals. The default * implementation does nothing. */ - virtual void restoreFinished() {} + virtual void restoreFinished() + {} }; -} //namespace Base +} // namespace Base -#endif // APP_PERSISTENCE_H +#endif // APP_PERSISTENCE_H diff --git a/src/Base/PersistencePy.xml b/src/Base/PersistencePy.xml index 7857ba0442..4638e43e01 100644 --- a/src/Base/PersistencePy.xml +++ b/src/Base/PersistencePy.xml @@ -1,18 +1,18 @@ - This is the Persistence class - Base.Persistence class. + Base.Persistence class. Class to dump and restore the content of an object. @@ -30,23 +30,23 @@ Class to dump and restore the content of an object. - dumpContent(Compression=3) -> bytearray + dumpContent(Compression=3) -> bytearray Dumps the content of the object, both the XML representation and the additional -data files required, into a byte representation. +data files required, into a byte representation. -Compression : int +Compression : int Set the data compression level in the range [0,9]. Set to 0 for no compression. - restoreContent(obj) -> None + restoreContent(obj) -> None Restore the content of the object from a byte representation as stored by `dumpContent`. -It could be restored from any Python object implementing the buffer protocol. +It could be restored from any Python object implementing the buffer protocol. -obj : buffer +obj : buffer Object with buffer protocol support. diff --git a/src/Base/PersistencePyImp.cpp b/src/Base/PersistencePyImp.cpp index ff87a264ed..4f5cbf962b 100644 --- a/src/Base/PersistencePyImp.cpp +++ b/src/Base/PersistencePyImp.cpp @@ -49,7 +49,7 @@ Py::String PersistencePy::getContent() const writer.setForceXML(true); getPersistencePtr()->Save(writer); - return {writer.getString()}; + return {writer.getString()}; } Py::Int PersistencePy::getMemSize() const @@ -57,31 +57,33 @@ Py::Int PersistencePy::getMemSize() const return Py::Int((long)getPersistencePtr()->getMemSize()); } -PyObject* PersistencePy::dumpContent(PyObject *args, PyObject *kwds) +PyObject* PersistencePy::dumpContent(PyObject* args, PyObject* kwds) { int compression = 3; - static const std::array kwds_def {"Compression", nullptr}; + static const std::array kwds_def {"Compression", nullptr}; PyErr_Clear(); if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|i", kwds_def, &compression)) { return nullptr; } - //setup the stream. the in flag is needed to make "read" work - std::stringstream stream(std::stringstream::out | std::stringstream::in | std::stringstream::binary); + // setup the stream. the in flag is needed to make "read" work + std::stringstream stream(std::stringstream::out | std::stringstream::in + | std::stringstream::binary); try { getPersistencePtr()->dumpToStream(stream, compression); } - catch(Base::NotImplementedError&) { - PyErr_SetString(PyExc_NotImplementedError, "Dumping content of this object type is not implemented"); + catch (Base::NotImplementedError&) { + PyErr_SetString(PyExc_NotImplementedError, + "Dumping content of this object type is not implemented"); return nullptr; } catch (...) { - PyErr_SetString(PyExc_IOError, "Unable to parse content into binary representation"); - return nullptr; + PyErr_SetString(PyExc_IOError, "Unable to parse content into binary representation"); + return nullptr; } - //build the byte array with correct size - if(!stream.seekp(0, stream.end)) { + // build the byte array with correct size + if (!stream.seekp(0, stream.end)) { PyErr_SetString(PyExc_IOError, "Unable to find end of stream"); return nullptr; } @@ -94,17 +96,17 @@ PyObject* PersistencePy::dumpContent(PyObject *args, PyObject *kwds) PyObject* ba = PyByteArray_FromStringAndSize(nullptr, offset); - //use the buffer protocol to access the underlying array and write into it + // use the buffer protocol to access the underlying array and write into it Py_buffer buf = Py_buffer(); PyObject_GetBuffer(ba, &buf, PyBUF_WRITABLE); try { - if(!stream.read((char*)buf.buf, offset)) { + if (!stream.read((char*)buf.buf, offset)) { PyErr_SetString(PyExc_IOError, "Error copying data into byte array"); return nullptr; } PyBuffer_Release(&buf); } - catch(...) { + catch (...) { PyBuffer_Release(&buf); PyErr_SetString(PyExc_IOError, "Error copying data into byte array"); return nullptr; @@ -113,28 +115,30 @@ PyObject* PersistencePy::dumpContent(PyObject *args, PyObject *kwds) return ba; } -PyObject* PersistencePy::restoreContent(PyObject *args) +PyObject* PersistencePy::restoreContent(PyObject* args) { PyObject* buffer = nullptr; - if( !PyArg_ParseTuple(args, "O", &buffer) ) + if (!PyArg_ParseTuple(args, "O", &buffer)) { return nullptr; + } - //check if it really is a buffer - if( !PyObject_CheckBuffer(buffer) ) { + // check if it really is a buffer + if (!PyObject_CheckBuffer(buffer)) { PyErr_SetString(PyExc_TypeError, "Must be a buffer object"); return nullptr; } Py_buffer buf; - if(PyObject_GetBuffer(buffer, &buf, PyBUF_SIMPLE) < 0) + if (PyObject_GetBuffer(buffer, &buf, PyBUF_SIMPLE) < 0) { return nullptr; + } - if(!PyBuffer_IsContiguous(&buf, 'C')) { + if (!PyBuffer_IsContiguous(&buf, 'C')) { PyErr_SetString(PyExc_TypeError, "Buffer must be contiguous"); return nullptr; } - //check if it really is a buffer + // check if it really is a buffer try { using Device = boost::iostreams::basic_array_source; boost::iostreams::stream stream((char*)buf.buf, buf.len); @@ -148,13 +152,12 @@ PyObject* PersistencePy::restoreContent(PyObject *args) Py_Return; } -PyObject *PersistencePy::getCustomAttributes(const char*) const +PyObject* PersistencePy::getCustomAttributes(const char*) const { return nullptr; } -int PersistencePy::setCustomAttributes(const char*,PyObject*) +int PersistencePy::setCustomAttributes(const char*, PyObject*) { return 0; } - diff --git a/src/Base/Placement.cpp b/src/Base/Placement.cpp index d2e3bcf729..6e335d495e 100644 --- a/src/Base/Placement.cpp +++ b/src/Base/Placement.cpp @@ -36,13 +36,12 @@ Placement::Placement(const Base::Matrix4D& matrix) fromMatrix(matrix); } -Placement::Placement(const Vector3d& Pos, const Rotation &Rot) +Placement::Placement(const Vector3d& Pos, const Rotation& Rot) : _pos(Pos) , _rot(Rot) -{ -} +{} -Placement::Placement(const Vector3d& Pos, const Rotation &Rot, const Vector3d& Cnt) +Placement::Placement(const Vector3d& Pos, const Rotation& Rot, const Vector3d& Cnt) : _rot(Rot) { Vector3d RotC = Cnt; @@ -54,7 +53,7 @@ Placement Placement::fromDualQuaternion(DualQuat qq) { Rotation rot(qq.x.re, qq.y.re, qq.z.re, qq.w.re); DualQuat mvq = 2 * qq.dual() * qq.real().conj(); - return {Vector3d(mvq.x.re,mvq.y.re, mvq.z.re), rot}; + return {Vector3d(mvq.x.re, mvq.y.re, mvq.z.re), rot}; } Base::Matrix4D Placement::toMatrix() const @@ -80,13 +79,13 @@ DualQuat Placement::toDualQuaternion() const DualQuat posqq(_pos.x, _pos.y, _pos.z, 0.0); DualQuat rotqq; _rot.getValue(rotqq.x.re, rotqq.y.re, rotqq.z.re, rotqq.w.re); - DualQuat ret (rotqq, 0.5 * posqq * rotqq); + DualQuat ret(rotqq, 0.5 * posqq * rotqq); return ret; } bool Placement::isIdentity() const { - Base::Vector3d nullvec(0,0,0); + Base::Vector3d nullvec(0, 0, 0); bool none = (this->_pos == nullvec) && (this->_rot.isIdentity()); return none; } @@ -98,14 +97,12 @@ bool Placement::isIdentity(double tol) const bool Placement::isSame(const Placement& p) const { - return this->_rot.isSame(p._rot) && - this->_pos.IsEqual(p._pos, 0); + return this->_rot.isSame(p._rot) && this->_pos.IsEqual(p._pos, 0); } bool Placement::isSame(const Placement& p, double tol) const { - return this->_rot.isSame(p._rot, tol) && - this->_pos.IsEqual(p._pos, tol); + return this->_rot.isSame(p._rot, tol) && this->_pos.IsEqual(p._pos, tol); } void Placement::invert() @@ -127,12 +124,12 @@ void Placement::move(const Vector3d& MovVec) _pos += MovVec; } -bool Placement::operator == (const Placement& that) const +bool Placement::operator==(const Placement& that) const { return (this->_pos == that._pos) && (this->_rot == that._rot); } -bool Placement::operator != (const Placement& that) const +bool Placement::operator!=(const Placement& that) const { return !(*this == that); } @@ -143,12 +140,12 @@ bool Placement::operator != (const Placement& that) const \sa multRight() */ -Placement & Placement::operator*=(const Placement & p) +Placement& Placement::operator*=(const Placement& p) { return multRight(p); } -Placement Placement::operator*(const Placement & p) const +Placement Placement::operator*(const Placement& p) const { Placement plm(*this); plm *= p; @@ -188,22 +185,22 @@ Placement& Placement::multLeft(const Base::Placement& p) return *this; } -void Placement::multVec(const Vector3d & src, Vector3d & dst) const +void Placement::multVec(const Vector3d& src, Vector3d& dst) const { this->_rot.multVec(src, dst); dst += this->_pos; } -void Placement::multVec(const Vector3f & src, Vector3f & dst) const +void Placement::multVec(const Vector3f& src, Vector3f& dst) const { this->_rot.multVec(src, dst); dst += Base::toVector(this->_pos); } -Placement Placement::slerp(const Placement & p0, const Placement & p1, double t) +Placement Placement::slerp(const Placement& p0, const Placement& p1, double t) { Rotation rot = Rotation::slerp(p0.getRotation(), p1.getRotation(), t); - Vector3d pos = p0.getPosition() * (1.0-t) + p1.getPosition() * t; + Vector3d pos = p0.getPosition() * (1.0 - t) + p1.getPosition() * t; return {pos, rot}; } diff --git a/src/Base/Placement.h b/src/Base/Placement.h index c4f835f8ef..39c11d470f 100644 --- a/src/Base/Placement.h +++ b/src/Base/Placement.h @@ -27,7 +27,8 @@ #include "Vector3D.h" -namespace Base { +namespace Base +{ class DualQuat; class Matrix4D; @@ -43,8 +44,8 @@ public: Placement(const Placement&) = default; Placement(Placement&&) = default; Placement(const Base::Matrix4D& matrix); - Placement(const Vector3d& Pos, const Rotation &Rot); - Placement(const Vector3d& Pos, const Rotation &Rot, const Vector3d& Cnt); + Placement(const Vector3d& Pos, const Rotation& Rot); + Placement(const Vector3d& Pos, const Rotation& Rot, const Vector3d& Cnt); /** specialty constructors */ //@{ @@ -52,15 +53,27 @@ public: //@} /// Destruction - ~Placement () = default; + ~Placement() = default; Matrix4D toMatrix() const; void fromMatrix(const Matrix4D& m); DualQuat toDualQuaternion() const; - const Vector3d& getPosition() const {return _pos;} - const Rotation& getRotation() const {return _rot;} - void setPosition(const Vector3d& Pos){_pos=Pos;} - void setRotation(const Rotation& Rot) {_rot = Rot;} + const Vector3d& getPosition() const + { + return _pos; + } + const Rotation& getRotation() const + { + return _rot; + } + void setPosition(const Vector3d& Pos) + { + _pos = Pos; + } + void setRotation(const Rotation& Rot) + { + _rot = Rot; + } bool isIdentity() const; bool isIdentity(double tol) const; @@ -73,32 +86,31 @@ public: /** Operators. */ //@{ - Placement & operator*=(const Placement & p); - Placement operator *(const Placement & p) const; - bool operator == (const Placement&) const; - bool operator != (const Placement&) const; - Placement& operator = (const Placement&) = default; - Placement& operator = (Placement&&) = default; + Placement& operator*=(const Placement& p); + Placement operator*(const Placement& p) const; + bool operator==(const Placement&) const; + bool operator!=(const Placement&) const; + Placement& operator=(const Placement&) = default; + Placement& operator=(Placement&&) = default; Placement pow(double t, bool shorten = true) const; Placement& multRight(const Base::Placement& p); Placement& multLeft(const Base::Placement& p); - void multVec(const Vector3d & src, Vector3d & dst) const; - void multVec(const Vector3f & src, Vector3f & dst) const; + void multVec(const Vector3d& src, Vector3d& dst) const; + void multVec(const Vector3f& src, Vector3f& dst) const; //@} - static Placement slerp(const Placement & p0, const Placement & p1, double t); - static Placement sclerp(const Placement & p0, const Placement & p1, double t, bool shorten = true); + static Placement slerp(const Placement& p0, const Placement& p1, double t); + static Placement + sclerp(const Placement& p0, const Placement& p1, double t, bool shorten = true); private: Vector3 _pos; - Base::Rotation _rot; + Base::Rotation _rot; }; -} // namespace Base - - -#endif // BASE_PLACEMENT_H +} // namespace Base +#endif // BASE_PLACEMENT_H diff --git a/src/Base/PlacementPy.xml b/src/Base/PlacementPy.xml index 9223b80386..0c8d6bd882 100644 --- a/src/Base/PlacementPy.xml +++ b/src/Base/PlacementPy.xml @@ -1,13 +1,13 @@ - - Base.Placement class. + Base.Placement class. A Placement defines an orientation (rotation) and a position (base) in 3D space. -It is used when no scaling or other distortion is needed. +It is used when no scaling or other distortion is needed. -The following constructors are supported: +The following constructors are supported: Placement() -Empty constructor. +Empty constructor. Placement(placement) Copy constructor. -placement : Base.Placement +placement : Base.Placement Placement(matrix) Define from a 4D matrix consisting of rotation and translation. -matrix : Base.Matrix +matrix : Base.Matrix Placement(base, rotation) Define from position and rotation. base : Base.Vector -rotation : Base.Rotation +rotation : Base.Rotation Placement(base, rotation, center) Define from position and rotation with center. base : Base.Vector rotation : Base.Rotation -center : Base.Vector +center : Base.Vector Placement(base, axis, angle) define position and rotation. @@ -53,46 +53,46 @@ angle : float - copy() -> Base.Placement + copy() -> Base.Placement Returns a copy of this placement. - move(vector) -> None + move(vector) -> None -Move the placement along a vector. +Move the placement along a vector. -vector : Base.Vector +vector : Base.Vector Vector by which to move the placement. - translate(vector) -> None + translate(vector) -> None -Alias to move(), to be compatible with TopoShape.translate(). +Alias to move(), to be compatible with TopoShape.translate(). -vector : Base.Vector +vector : Base.Vector Vector by which to move the placement. - rotate(center, axis, angle, comp) -> None + rotate(center, axis, angle, comp) -> None Rotate the current placement around center and axis with the given angle. This method is compatible with TopoShape.rotate() if the (optional) keyword argument comp is True (default=False). -center : Base.Vector, sequence of float +center : Base.Vector, sequence of float Rotation center. -axis : Base.Vector, sequence of float +axis : Base.Vector, sequence of float Rotation axis. -angle : float +angle : float Rotation angle in degrees. -comp : bool +comp : bool optional keyword only argument, if True (default=False), behave like TopoShape.rotate() (i.e. the resulting placements are interchangeable). @@ -100,101 +100,101 @@ behave like TopoShape.rotate() (i.e. the resulting placements are interchangeabl - multiply(placement) -> Base.Placement + multiply(placement) -> Base.Placement Right multiply this placement with another placement. -Also available as `*` operator. +Also available as `*` operator. -placement : Base.Placement +placement : Base.Placement Placement by which to multiply this placement. - multVec(vector) -> Base.Vector + multVec(vector) -> Base.Vector -Compute the transformed vector using the placement. +Compute the transformed vector using the placement. -vector : Base.Vector +vector : Base.Vector Vector to be transformed. - toMatrix() -> Base.Matrix + toMatrix() -> Base.Matrix Compute the matrix representation of the placement. - inverse() -> Base.Placement + inverse() -> Base.Placement Compute the inverse placement. - pow(t, shorten=True) -> Base.Placement + pow(t, shorten=True) -> Base.Placement Raise this placement to real power using ScLERP interpolation. -Also available as `**` operator. +Also available as `**` operator. -t : float +t : float Real power. -shorten : bool +shorten : bool If True, ensures rotation quaternion is net positive to make the path shorter. - sclerp(placement2, t, shorten=True) -> Base.Placement + sclerp(placement2, t, shorten=True) -> Base.Placement Screw Linear Interpolation (ScLERP) between this placement and `placement2`. Interpolation is a continuous motion along a helical path parametrized by `t` made of equal transforms if discretized. If quaternions of rotations of the two placements differ in sign, the interpolation -will take a long path. +will take a long path. placement2 : Base.Placement -t : float +t : float Parameter of helical path. t=0 returns this placement, t=1 returns `placement2`. t can also be outside of [0, 1] range for extrapolation. -shorten : bool +shorten : bool If True, the signs are harmonized before interpolation and the interpolation takes the shorter path. - slerp(placement2, t) -> Base.Placement + slerp(placement2, t) -> Base.Placement Spherical Linear Interpolation (SLERP) between this placement and `placement2`. This function performs independent interpolation of rotation and movement. Result of such interpolation might be not what application expects, thus this tool might be considered for simple cases or for interpolating between small intervals. -For more complex cases you better use the advanced sclerp() function. +For more complex cases you better use the advanced sclerp() function. placement2 : Base.Placement -t : float +t : float Parameter of the path. t=0 returns this placement, t=1 returns `placement2`. - isIdentity([tol=0.0]) -> bool + isIdentity([tol=0.0]) -> bool Returns True if the placement has no displacement and no rotation. Matrix representation is the 4D identity matrix. -tol : float +tol : float Tolerance used to check for identity. If tol is negative or zero, no tolerance is used. - isSame(Base.Placement, [tol=0.0]) -> bool + isSame(Base.Placement, [tol=0.0]) -> bool Checks whether this and the given placement are the same. The default tolerance is set to 0.0 diff --git a/src/Base/PlacementPyImp.cpp b/src/Base/PlacementPyImp.cpp index 9cf7aaaf9c..b2d34a6865 100644 --- a/src/Base/PlacementPyImp.cpp +++ b/src/Base/PlacementPyImp.cpp @@ -40,28 +40,29 @@ using namespace Base; // returns a string which represents the object e.g. when printed in python std::string PlacementPy::representation() const { - double yaw{}, pitch{}, roll{}; + double yaw {}, pitch {}, roll {}; PlacementPy::PointerType ptr = getPlacementPtr(); std::stringstream str; ptr->getRotation().getYawPitchRoll(yaw, pitch, roll); str << "Placement [Pos=("; - str << ptr->getPosition().x << ","<< ptr->getPosition().y << "," << ptr->getPosition().z; + str << ptr->getPosition().x << "," << ptr->getPosition().y << "," << ptr->getPosition().z; str << "), Yaw-Pitch-Roll=(" << yaw << "," << pitch << "," << roll << ")]"; return str.str(); } -PyObject *PlacementPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PlacementPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PlacementPy and the Twin object return new PlacementPy(new Placement); } +// clang-format off // constructor method int PlacementPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - PyObject* o{}; + PyObject* o {}; if (PyArg_ParseTuple(args, "")) { return 0; } @@ -81,61 +82,68 @@ int PlacementPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); if (PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &o)) { - Base::Placement *plm = static_cast(o)->getPlacementPtr(); + Base::Placement* plm = static_cast(o)->getPlacementPtr(); *(getPlacementPtr()) = *plm; return 0; } PyErr_Clear(); - PyObject* d{}; - double angle{}; - if (PyArg_ParseTuple(args, "O!O!d", &(Base::VectorPy::Type), &o, - &(Base::VectorPy::Type), &d, &angle)) { + PyObject* d {}; + double angle {}; + if (PyArg_ParseTuple(args, + "O!O!d", + &(Base::VectorPy::Type), &o, + &(Base::VectorPy::Type), &d, + &angle)) { // NOTE: The first parameter defines the translation, the second the rotation axis // and the last parameter defines the rotation angle in degree. - Base::Rotation rot(static_cast(d)->value(), angle/180.0*D_PI); - *getPlacementPtr() = Base::Placement(static_cast(o)->value(),rot); + Base::Rotation rot(static_cast(d)->value(), angle / 180.0 * D_PI); + *getPlacementPtr() = Base::Placement(static_cast(o)->value(), rot); return 0; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, - &(Base::RotationPy::Type), &d)) { - Base::Vector3d *pos = static_cast(o)->getVectorPtr(); + if (PyArg_ParseTuple(args, + "O!O!", + &(Base::VectorPy::Type), &o, + &(Base::RotationPy::Type), &d)) { + Base::Vector3d* pos = static_cast(o)->getVectorPtr(); getPlacementPtr()->setPosition(*pos); - Base::Rotation *rot = static_cast(d)->getRotationPtr(); + Base::Rotation* rot = static_cast(d)->getRotationPtr(); getPlacementPtr()->setRotation(*rot); return 0; } PyErr_Clear(); - PyObject* c{}; - if (PyArg_ParseTuple(args, "O!O!O!", &(Base::VectorPy::Type), &o, - &(Base::RotationPy::Type), &d, - &(Base::VectorPy::Type), &c)) { - Base::Vector3d *pos = static_cast(o)->getVectorPtr(); - Base::Rotation *rot = static_cast(d)->getRotationPtr(); - Base::Vector3d *cnt = static_cast(c)->getVectorPtr(); - Base::Placement p(*pos,*rot,*cnt); - getPlacementPtr()->operator = (p); + PyObject* c {}; + if (PyArg_ParseTuple(args, + "O!O!O!", + &(Base::VectorPy::Type), &o, + &(Base::RotationPy::Type), &d, + &(Base::VectorPy::Type), &c)) { + Base::Vector3d* pos = static_cast(o)->getVectorPtr(); + Base::Rotation* rot = static_cast(d)->getRotationPtr(); + Base::Vector3d* cnt = static_cast(c)->getVectorPtr(); + Base::Placement p(*pos, *rot, *cnt); + getPlacementPtr()->operator=(p); return 0; } PyErr_SetString(PyExc_TypeError, "empty parameter list, matrix or placement expected"); return -1; } +// clang-format on -PyObject* PlacementPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* PlacementPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(PlacementPy::Type)) && - PyObject_TypeCheck(w, &(PlacementPy::Type))) { + if (PyObject_TypeCheck(v, &(PlacementPy::Type)) + && PyObject_TypeCheck(w, &(PlacementPy::Type))) { Base::Placement p1 = *static_cast(v)->getPlacementPtr(); Base::Placement p2 = *static_cast(w)->getPlacementPtr(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for Placement"); + PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Placement"); return nullptr; } else if (op == Py_EQ) { @@ -156,46 +164,56 @@ PyObject* PlacementPy::richCompare(PyObject *v, PyObject *w, int op) } } -PyObject* PlacementPy::move(PyObject * args) +PyObject* PlacementPy::move(PyObject* args) { - PyObject *vec{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) + PyObject* vec {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) { return nullptr; + } getPlacementPtr()->move(static_cast(vec)->value()); Py_Return; } -PyObject* PlacementPy::translate(PyObject * args) +PyObject* PlacementPy::translate(PyObject* args) { return move(args); } -PyObject* PlacementPy::rotate(PyObject *args, PyObject *kwds) +// clang-format off +PyObject* PlacementPy::rotate(PyObject* args, PyObject* kwds) { - double angle{}; - static const std::array kwlist { "center", "axis", "angle", "comp", nullptr }; + double angle {}; + static const std::array kwlist {"center", "axis", "angle", "comp", nullptr}; Vector3d center; Vector3d axis; - PyObject* pyComp = Py_False; // NOLINT + PyObject* pyComp = Py_False; // NOLINT - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "(ddd)(ddd)d|O!", kwlist, ¢er.x, ¢er.y, ¢er.z, - &axis.x, &axis.y, &axis.z, &angle, &PyBool_Type, &pyComp)) { + if (!Base::Wrapped_ParseTupleAndKeywords(args, + kwds, + "(ddd)(ddd)d|O!", + kwlist, + ¢er.x, ¢er.y, ¢er.z, + &axis.x, &axis.y, &axis.z, + &angle, &PyBool_Type, &pyComp)) { return nullptr; } try { /* - * if comp is False, we retain the original behaviour that - contrary to the (old) documentation - generates - * Placements different from TopoShape.rotate() to ensure compatibility for existing code + * if comp is False, we retain the original behaviour that - contrary to the (old) + * documentation - generates Placements different from TopoShape.rotate() to ensure + * compatibility for existing code */ bool comp = Base::asBoolean(pyComp); if (!comp) { - getPlacementPtr()->multRight(Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); + getPlacementPtr()->multRight( + Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); } else { // multiply new Placement the same way TopoShape.rotate() does - getPlacementPtr()->multLeft(Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); + getPlacementPtr()->multLeft( + Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); } Py_Return; @@ -204,55 +222,62 @@ PyObject* PlacementPy::rotate(PyObject *args, PyObject *kwds) return nullptr; } } +// clang-format on -PyObject* PlacementPy::multiply(PyObject * args) +PyObject* PlacementPy::multiply(PyObject* args) { - PyObject *plm{}; - if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) + PyObject* plm {}; + if (!PyArg_ParseTuple(args, "O!", &(PlacementPy::Type), &plm)) { return nullptr; + } Placement mult = (*getPlacementPtr()) * (*static_cast(plm)->getPlacementPtr()); return new PlacementPy(new Placement(mult)); } -PyObject* PlacementPy::multVec(PyObject * args) +PyObject* PlacementPy::multVec(PyObject* args) { - PyObject *vec{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) + PyObject* vec {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) { return nullptr; + } Base::Vector3d pnt(static_cast(vec)->value()); getPlacementPtr()->multVec(pnt, pnt); return new VectorPy(new Vector3d(pnt)); } -PyObject* PlacementPy::copy(PyObject * args) +PyObject* PlacementPy::copy(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return new PlacementPy(new Placement(*getPlacementPtr())); } -PyObject* PlacementPy::toMatrix(PyObject * args) +PyObject* PlacementPy::toMatrix(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Matrix4D mat = getPlacementPtr()->toMatrix(); return new MatrixPy(new Matrix4D(mat)); } -PyObject* PlacementPy::inverse(PyObject * args) +PyObject* PlacementPy::inverse(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Placement p = getPlacementPtr()->inverse(); return new PlacementPy(new Placement(p)); } PyObject* PlacementPy::pow(PyObject* args) { - double t{}; + double t {}; PyObject* shorten = Py_True; - if (!PyArg_ParseTuple(args, "d|O!", &t, &(PyBool_Type), &shorten)) + if (!PyArg_ParseTuple(args, "d|O!", &t, &(PyBool_Type), &shorten)) { return nullptr; + } Base::Placement ret = getPlacementPtr()->pow(t, Base::asBoolean(shorten)); return new PlacementPy(new Placement(ret)); } @@ -260,53 +285,63 @@ PyObject* PlacementPy::pow(PyObject* args) PyObject* PlacementPy::sclerp(PyObject* args) { - PyObject* pyplm2{}; - double t{}; + PyObject* pyplm2 {}; + double t {}; PyObject* shorten = Py_True; - if (!PyArg_ParseTuple(args, "O!d|O!", &(PlacementPy::Type), &pyplm2, &t, &(PyBool_Type), &shorten)) + if (!PyArg_ParseTuple(args, + "O!d|O!", + &(PlacementPy::Type), + &pyplm2, + &t, + &(PyBool_Type), + &shorten)) { return nullptr; + } Base::Placement plm2 = static_cast(pyplm2)->value(); - Base::Placement ret = Base::Placement::sclerp(*getPlacementPtr(), plm2, t, Base::asBoolean(shorten)); + Base::Placement ret = + Base::Placement::sclerp(*getPlacementPtr(), plm2, t, Base::asBoolean(shorten)); return new PlacementPy(new Placement(ret)); } PyObject* PlacementPy::slerp(PyObject* args) { - PyObject* pyplm2{}; - double t{}; - if (!PyArg_ParseTuple(args, "O!d", &(PlacementPy::Type), &pyplm2, &t)) + PyObject* pyplm2 {}; + double t {}; + if (!PyArg_ParseTuple(args, "O!d", &(PlacementPy::Type), &pyplm2, &t)) { return nullptr; + } Base::Placement plm2 = static_cast(pyplm2)->value(); Base::Placement ret = Base::Placement::slerp(*getPlacementPtr(), plm2, t); return new PlacementPy(new Placement(ret)); } -PyObject* PlacementPy::isIdentity(PyObject *args) +PyObject* PlacementPy::isIdentity(PyObject* args) { double tol = 0.0; - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; - bool none = tol > 0 ? getPlacementPtr()->isIdentity(tol) - : getPlacementPtr()->isIdentity(); + } + bool none = tol > 0 ? getPlacementPtr()->isIdentity(tol) : getPlacementPtr()->isIdentity(); return Py_BuildValue("O", (none ? Py_True : Py_False)); } -PyObject* PlacementPy::isSame(PyObject *args) +PyObject* PlacementPy::isSame(PyObject* args) { - PyObject* plm{}; + PyObject* plm {}; double tol = 0.0; - if (!PyArg_ParseTuple(args, "O!|d", &PlacementPy::Type, &plm, &tol)) + if (!PyArg_ParseTuple(args, "O!|d", &PlacementPy::Type, &plm, &tol)) { return nullptr; + } - Base::Placement plm1 = * getPlacementPtr(); - Base::Placement plm2 = * static_cast(plm)->getPlacementPtr(); + Base::Placement plm1 = *getPlacementPtr(); + Base::Placement plm2 = *static_cast(plm)->getPlacementPtr(); bool same = tol > 0.0 ? plm1.isSame(plm2, tol) : plm1.isSame(plm2); return Py_BuildValue("O", (same ? Py_True : Py_False)); } Py::Object PlacementPy::getBase() const { - return Py::Vector(getPlacementPtr()->getPosition()); // NOLINT + return Py::Vector(getPlacementPtr()->getPosition()); // NOLINT } void PlacementPy::setBase(Py::Object arg) @@ -332,8 +367,7 @@ void PlacementPy::setRotation(Py::Object arg) getPlacementPtr()->setRotation(Base::Rotation(static_cast(Py::Float(tuple[0])), static_cast(Py::Float(tuple[1])), static_cast(Py::Float(tuple[2])), - static_cast(Py::Float(tuple[3])) - )); + static_cast(Py::Float(tuple[3])))); return; } @@ -348,8 +382,9 @@ Py::Object PlacementPy::getMatrix() const void PlacementPy::setMatrix(Py::Object arg) { Py::Matrix mat; - if (!mat.accepts(arg.ptr())) + if (!mat.accepts(arg.ptr())) { throw Py::TypeError("Expect type Matrix"); + } try { mat = arg; getPlacementPtr()->fromMatrix(mat); @@ -359,14 +394,14 @@ void PlacementPy::setMatrix(Py::Object arg) } } -PyObject *PlacementPy::getCustomAttributes(const char* attr) const +PyObject* PlacementPy::getCustomAttributes(const char* attr) const { // for backward compatibility if (strcmp(attr, "isNull") == 0) { - PyObject *w{}, *res{}; + PyObject *w {}, *res {}; w = PyUnicode_InternFromString("isIdentity"); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - res = PyObject_GenericGetAttr(const_cast(this), w); + res = PyObject_GenericGetAttr(const_cast(this), w); Py_XDECREF(w); return res; } @@ -378,30 +413,30 @@ int PlacementPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject* PlacementPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* PlacementPy::number_multiply_handler(PyObject* self, PyObject* other) { if (PyObject_TypeCheck(self, &(PlacementPy::Type))) { Base::Placement a = static_cast(self)->value(); if (PyObject_TypeCheck(other, &(VectorPy::Type))) { Vector3d res; - a.multVec(static_cast(other)->value(),res); + a.multVec(static_cast(other)->value(), res); return new VectorPy(res); } if (PyObject_TypeCheck(other, &(RotationPy::Type))) { - Placement b(Vector3d(),static_cast(other)->value()); - return new PlacementPy(a*b); + Placement b(Vector3d(), static_cast(other)->value()); + return new PlacementPy(a * b); } if (PyObject_TypeCheck(other, &(PlacementPy::Type))) { - const auto &b = static_cast(other)->value(); - return new PlacementPy(a*b); + const auto& b = static_cast(other)->value(); + return new PlacementPy(a * b); } if (PyObject_TypeCheck(other, &(MatrixPy::Type))) { - const auto &b = static_cast(other)->value(); - return new MatrixPy(a.toMatrix()*b); + const auto& b = static_cast(other)->value(); + return new MatrixPy(a.toMatrix() * b); } } @@ -409,19 +444,17 @@ PyObject* PlacementPy::number_multiply_handler(PyObject *self, PyObject *other) return nullptr; } -PyObject * PlacementPy::number_power_handler (PyObject* self, PyObject* other, PyObject* arg) +PyObject* PlacementPy::number_power_handler(PyObject* self, PyObject* other, PyObject* arg) { Py::Object pw(other); Py::Tuple tup(1); tup[0] = pw; - double pw_v{}; - if (!PyArg_ParseTuple(tup.ptr(), "d", &pw_v)){ + double pw_v {}; + if (!PyArg_ParseTuple(tup.ptr(), "d", &pw_v)) { return nullptr; } - if (!PyObject_TypeCheck(self, &(PlacementPy::Type)) - || arg != Py_None) - { + if (!PyObject_TypeCheck(self, &(PlacementPy::Type)) || arg != Py_None) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } @@ -430,104 +463,103 @@ PyObject * PlacementPy::number_power_handler (PyObject* self, PyObject* other, P return new PlacementPy(a.pow(pw_v)); } -PyObject* PlacementPy::number_add_handler(PyObject * /*self*/, PyObject * /*other*/) +PyObject* PlacementPy::number_add_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject* PlacementPy::number_subtract_handler(PyObject * /*self*/, PyObject * /*other*/) +PyObject* PlacementPy::number_subtract_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_divide_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_remainder_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_negative_handler (PyObject* /*self*/) +PyObject* PlacementPy::number_negative_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_positive_handler (PyObject* /*self*/) +PyObject* PlacementPy::number_positive_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_absolute_handler (PyObject* /*self*/) +PyObject* PlacementPy::number_absolute_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -int PlacementPy::number_nonzero_handler (PyObject* /*self*/) +int PlacementPy::number_nonzero_handler(PyObject* /*self*/) { return 1; } -PyObject * PlacementPy::number_invert_handler (PyObject* /*self*/) +PyObject* PlacementPy::number_invert_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_lshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_rshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_and_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_xor_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* PlacementPy::number_or_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_int_handler (PyObject * /*self*/) +PyObject* PlacementPy::number_int_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * PlacementPy::number_float_handler (PyObject * /*self*/) +PyObject* PlacementPy::number_float_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } - diff --git a/src/Base/PreCompiled.h b/src/Base/PreCompiled.h index 2bef608c20..f81b2e771b 100644 --- a/src/Base/PreCompiled.h +++ b/src/Base/PreCompiled.h @@ -39,7 +39,7 @@ #include #ifdef FC_OS_WIN32 #define _USE_MATH_DEFINES -#endif // FC_OS_WIN32 +#endif // FC_OS_WIN32 #include #include #include @@ -56,7 +56,7 @@ #include #endif -#if defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) +#if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) #include #include #include @@ -75,7 +75,7 @@ #include #include -//streams +// streams #include #include #include @@ -136,7 +136,6 @@ #include -#endif //_PreComp_ - -#endif // BASE_PRECOMPILED_H +#endif //_PreComp_ +#endif // BASE_PRECOMPILED_H diff --git a/src/Base/Precision.h b/src/Base/Precision.h index 6e38a9a039..a65ff5f7fc 100644 --- a/src/Base/Precision.h +++ b/src/Base/Precision.h @@ -26,31 +26,42 @@ #include -namespace Base { +namespace Base +{ // The methods are copied from OCC's Precision class -class Precision { +class Precision +{ public: /*! * \brief Angular - * Returns the recommended precision value when checking the equality of two angles (given in radians). - * \return + * Returns the recommended precision value when checking the equality of two angles (given in + * radians). \return */ - static double Angular() { return 1.e-12; } + static double Angular() + { + return 1.e-12; + } /*! * \brief Confusion - * Returns the recommended precision value when checking coincidence of two points in real space. - * \return + * Returns the recommended precision value when checking coincidence of two points in real + * space. \return */ - static double Confusion() { return 1.e-7; } + static double Confusion() + { + return 1.e-7; + } /*! * \brief SquareConfusion * Returns square of \ref Confusion. * \return */ - static double SquareConfusion() { return Confusion() * Confusion(); } + static double SquareConfusion() + { + return Confusion() * Confusion(); + } /*! * \brief Intersection @@ -58,7 +69,10 @@ public: * used by intersection algorithms to decide that a solution is reached. * \return */ - static double Intersection() { return Confusion() * 0.01; } + static double Intersection() + { + return Confusion() * 0.01; + } /*! * \brief Approximation @@ -66,7 +80,10 @@ public: * by approximation algorithms. * \return */ - static double Approximation() { return Confusion() * 10.0; } + static double Approximation() + { + return Confusion() * 10.0; + } /*! * \brief Parametric @@ -75,7 +92,10 @@ public: * \param T * \return */ - static double Parametric (const double P, const double T) { return P / T; } + static double Parametric(const double P, const double T) + { + return P / T; + } /*! * \brief PConfusion @@ -83,21 +103,30 @@ public: * \param T * \return */ - static double PConfusion (const double T) { return Parametric (Confusion(), T); } + static double PConfusion(const double T) + { + return Parametric(Confusion(), T); + } /*! * \brief PConfusion * Used to test distances in parametric space on a default curve. * \return */ - static double PConfusion() { return Parametric (Confusion()); } + static double PConfusion() + { + return Parametric(Confusion()); + } /*! * \brief SquarePConfusion * Returns square of \ref PConfusion. * \return */ - static double SquarePConfusion() { return PConfusion() * PConfusion(); } + static double SquarePConfusion() + { + return PConfusion() * PConfusion(); + } /*! * \brief PIntersection @@ -106,15 +135,20 @@ public: * \param T * \return */ - static double PIntersection (const double T) { return Parametric(Intersection(),T); } + static double PIntersection(const double T) + { + return Parametric(Intersection(), T); + } /*! * \brief PApproximation - * Returns a precision value in parametric space, which may be used by approximation algorithms. - * \param T - * \return + * Returns a precision value in parametric space, which may be used by approximation + * algorithms. \param T \return */ - static double PApproximation (const double T) { return Parametric(Approximation(),T); } + static double PApproximation(const double T) + { + return Parametric(Approximation(), T); + } /*! * \brief Parametric @@ -122,21 +156,30 @@ public: * \param P * \return */ - static double Parametric (const double P) { return Parametric (P, 100.0); } + static double Parametric(const double P) + { + return Parametric(P, 100.0); + } /*! * \brief PIntersection * Used for Intersections in parametric space on a default curve. * \return */ - static double PIntersection() { return Parametric (Intersection()); } + static double PIntersection() + { + return Parametric(Intersection()); + } /*! * \brief PApproximation * Used for Approximations in parametric space on a default curve. * \return */ - static double PApproximation() { return Parametric (Approximation()); } + static double PApproximation() + { + return Parametric(Approximation()); + } /*! * \brief IsInfinite @@ -144,7 +187,10 @@ public: * \param R * \return */ - static double IsInfinite (const double R) { return std::fabs (R) >= (0.5 * Precision::Infinite()); } + static double IsInfinite(const double R) + { + return std::fabs(R) >= (0.5 * Precision::Infinite()); + } /*! * \brief IsPositiveInfinite @@ -152,7 +198,10 @@ public: * \param R * \return */ - static double IsPositiveInfinite (const double R) { return R >= (0.5 * Precision::Infinite()); } + static double IsPositiveInfinite(const double R) + { + return R >= (0.5 * Precision::Infinite()); + } /*! * \brief IsNegativeInfinite @@ -160,16 +209,22 @@ public: * \param R * \return */ - static bool IsNegativeInfinite (const double R) { return R <= -(0.5 * Precision::Infinite()); } + static bool IsNegativeInfinite(const double R) + { + return R <= -(0.5 * Precision::Infinite()); + } /*! * \brief Infinite - * Returns a big number that can be considered as infinite. Use -Infinite() for a negative big number. - * \return + * Returns a big number that can be considered as infinite. Use -Infinite() for a negative + * big number. \return */ - static double Infinite() { return 2.e+100; } + static double Infinite() + { + return 2.e+100; + } }; -} +} // namespace Base -#endif // BASE_PRECISION_H +#endif // BASE_PRECISION_H diff --git a/src/Base/PrecisionPyImp.cpp b/src/Base/PrecisionPyImp.cpp index 2c1f045a2d..f69c102775 100644 --- a/src/Base/PrecisionPyImp.cpp +++ b/src/Base/PrecisionPyImp.cpp @@ -36,7 +36,7 @@ std::string PrecisionPy::representation() const return {""}; } -PyObject* PrecisionPy::angular(PyObject *args) +PyObject* PrecisionPy::angular(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -46,7 +46,7 @@ PyObject* PrecisionPy::angular(PyObject *args) return Py::new_reference_to(v); } -PyObject* PrecisionPy::confusion(PyObject *args) +PyObject* PrecisionPy::confusion(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -56,7 +56,7 @@ PyObject* PrecisionPy::confusion(PyObject *args) return Py::new_reference_to(v); } -PyObject* PrecisionPy::squareConfusion(PyObject *args) +PyObject* PrecisionPy::squareConfusion(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -66,7 +66,7 @@ PyObject* PrecisionPy::squareConfusion(PyObject *args) return Py::new_reference_to(v); } -PyObject* PrecisionPy::intersection(PyObject *args) +PyObject* PrecisionPy::intersection(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -76,7 +76,7 @@ PyObject* PrecisionPy::intersection(PyObject *args) return Py::new_reference_to(v); } -PyObject* PrecisionPy::approximation(PyObject *args) +PyObject* PrecisionPy::approximation(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -86,16 +86,16 @@ PyObject* PrecisionPy::approximation(PyObject *args) return Py::new_reference_to(v); } -PyObject* PrecisionPy::parametric(PyObject *args) +PyObject* PrecisionPy::parametric(PyObject* args) { - double p{}; + double p {}; if (PyArg_ParseTuple(args, "d", &p)) { Py::Float v(Precision::Parametric(p)); return Py::new_reference_to(v); } PyErr_Clear(); - double t{}; + double t {}; if (PyArg_ParseTuple(args, "dd", &p, &t)) { Py::Float v(Precision::Parametric(p, t)); return Py::new_reference_to(v); @@ -105,9 +105,9 @@ PyObject* PrecisionPy::parametric(PyObject *args) return nullptr; } -PyObject* PrecisionPy::isInfinite(PyObject *args) +PyObject* PrecisionPy::isInfinite(PyObject* args) { - double v{}; + double v {}; if (!PyArg_ParseTuple(args, "d", &v)) { return nullptr; } @@ -116,9 +116,9 @@ PyObject* PrecisionPy::isInfinite(PyObject *args) return Py::new_reference_to(b); } -PyObject* PrecisionPy::isPositiveInfinite(PyObject *args) +PyObject* PrecisionPy::isPositiveInfinite(PyObject* args) { - double v{}; + double v {}; if (!PyArg_ParseTuple(args, "d", &v)) { return nullptr; } @@ -127,9 +127,9 @@ PyObject* PrecisionPy::isPositiveInfinite(PyObject *args) return Py::new_reference_to(b); } -PyObject* PrecisionPy::isNegativeInfinite(PyObject *args) +PyObject* PrecisionPy::isNegativeInfinite(PyObject* args) { - double v{}; + double v {}; if (!PyArg_ParseTuple(args, "d", &v)) { return nullptr; } @@ -138,7 +138,7 @@ PyObject* PrecisionPy::isNegativeInfinite(PyObject *args) return Py::new_reference_to(b); } -PyObject* PrecisionPy::infinite(PyObject *args) +PyObject* PrecisionPy::infinite(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -148,7 +148,7 @@ PyObject* PrecisionPy::infinite(PyObject *args) return Py::new_reference_to(v); } -PyObject *PrecisionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PrecisionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Base/ProgressIndicatorPy.cpp b/src/Base/ProgressIndicatorPy.cpp index bea13ceeed..65346ca330 100644 --- a/src/Base/ProgressIndicatorPy.cpp +++ b/src/Base/ProgressIndicatorPy.cpp @@ -38,9 +38,9 @@ void ProgressIndicatorPy::init_type() behaviors().supportSetattr(); behaviors().set_tp_new(PyMake); - add_varargs_method("start",&ProgressIndicatorPy::start,"start(string,int)"); - add_varargs_method("next",&ProgressIndicatorPy::next,"next()"); - add_varargs_method("stop",&ProgressIndicatorPy::stop,"stop()"); + add_varargs_method("start", &ProgressIndicatorPy::start, "start(string,int)"); + add_varargs_method("next", &ProgressIndicatorPy::next, "next()"); + add_varargs_method("stop", &ProgressIndicatorPy::stop, "stop()"); } Py::PythonType& ProgressIndicatorPy::behaviors() @@ -58,7 +58,7 @@ bool ProgressIndicatorPy::check(PyObject* p) return Py::PythonExtension::check(p); } -PyObject *ProgressIndicatorPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* ProgressIndicatorPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { return new ProgressIndicatorPy(); } @@ -70,26 +70,28 @@ ProgressIndicatorPy::~ProgressIndicatorPy() = default; Py::Object ProgressIndicatorPy::repr() { std::string s = "Base.ProgressIndicator"; - return Py::String(s); // NOLINT + return Py::String(s); // NOLINT } Py::Object ProgressIndicatorPy::start(const Py::Tuple& args) { char* text = nullptr; unsigned int steps = 0; - if (!PyArg_ParseTuple(args.ptr(), "sI",&text,&steps)) + if (!PyArg_ParseTuple(args.ptr(), "sI", &text, &steps)) { throw Py::Exception(); + } if (!_seq.get()) { - _seq = std::make_unique(text,steps); + _seq = std::make_unique(text, steps); } return Py::None(); } Py::Object ProgressIndicatorPy::next(const Py::Tuple& args) { - int b=0; - if (!PyArg_ParseTuple(args.ptr(), "|i",&b)) + int b = 0; + if (!PyArg_ParseTuple(args.ptr(), "|i", &b)) { throw Py::Exception(); + } if (_seq.get()) { try { _seq->next(b ? true : false); @@ -104,8 +106,9 @@ Py::Object ProgressIndicatorPy::next(const Py::Tuple& args) Py::Object ProgressIndicatorPy::stop(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } _seq.reset(); return Py::None(); } diff --git a/src/Base/ProgressIndicatorPy.h b/src/Base/ProgressIndicatorPy.h index faed778ad1..1b14ee8431 100644 --- a/src/Base/ProgressIndicatorPy.h +++ b/src/Base/ProgressIndicatorPy.h @@ -31,10 +31,10 @@ namespace Base { // NOLINTNEXTLINE -class BaseExport ProgressIndicatorPy : public Py::PythonExtension +class BaseExport ProgressIndicatorPy: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods static Py::PythonType& behaviors(); static PyTypeObject* type_object(); static bool check(PyObject* p); @@ -49,12 +49,12 @@ public: Py::Object stop(const Py::Tuple&); private: - static PyObject *PyMake(struct _typeobject *, PyObject *, PyObject *); + static PyObject* PyMake(struct _typeobject*, PyObject*, PyObject*); private: std::unique_ptr _seq; }; -} // namespace Base +} // namespace Base -#endif // BASE_PROGRESSINDICATORPY_H +#endif // BASE_PROGRESSINDICATORPY_H diff --git a/src/Base/PyExport.h b/src/Base/PyExport.h index 180cc8d56e..ddaf7a6ab5 100644 --- a/src/Base/PyExport.h +++ b/src/Base/PyExport.h @@ -32,11 +32,11 @@ #define BASE_PYEXPORT_H // (re-)defined in pyconfig.h -#if defined (_POSIX_C_SOURCE) -# undef _POSIX_C_SOURCE +#if defined(_POSIX_C_SOURCE) +#undef _POSIX_C_SOURCE #endif -#if defined (_XOPEN_SOURCE) -# undef _XOPEN_SOURCE +#if defined(_XOPEN_SOURCE) +#undef _XOPEN_SOURCE #endif #include @@ -68,34 +68,35 @@ class PyObjectBase; * because at construction time the reference counter is already set to 1. If the Python * interpreter stores this object pointer into a local variable and destroys this variable * then the reference counter gets decremented (to 0) and the object gets destroyed automatically. - * In case we didn't make this specification and increment the Python object from outside once again then - * the reference counter would be set to 2 and there would be no chance to destroy the object again. + * In case we didn't make this specification and increment the Python object from outside once + * again then the reference counter would be set to 2 and there would be no chance to destroy the + * object again. * * The other case is that we have a member variable in our C++ class that holds the Python object - * then we either can create this Python in the constructor or create it the first time when GetPyObject() - * gets called. In the destructor then we must decrement the Python object to avoid a memory leak while - * GetPyObject() then increments the Python object every time it gets called. + * then we either can create this Python in the constructor or create it the first time when + * GetPyObject() gets called. In the destructor then we must decrement the Python object to avoid a + * memory leak while GetPyObject() then increments the Python object every time it gets called. * - * @remark One big consequence of this specification is that the programmer must know whether the Python interpreter - * gets the Python object or not. If the interpreter gets the object then it decrements the counter later on when - * the internal variable is freed. In case the interpreter doesn't get this object then the programmer must do the - * decrement on their own. + * @remark One big consequence of this specification is that the programmer must know whether the + * Python interpreter gets the Python object or not. If the interpreter gets the object then it + * decrements the counter later on when the internal variable is freed. In case the interpreter + * doesn't get this object then the programmer must do the decrement on their own. * - * @note To not to undermine this specification the programmer must make sure to get the Python object always via - * GetPyObject(). + * @note To not to undermine this specification the programmer must make sure to get the Python + * object always via GetPyObject(). * * @see PyHandle * @ */ -//class BaseExport PyHandler +// class BaseExport PyHandler //{ -//public: +// public: // void IncRef(void); // void DecRef(void); -// virtual ~PyHandler(); +// virtual ~PyHandler(); // virtual PyObjectBase *GetPyObject(void)=0; // -//}; +// }; /** Python Object handle class @@ -109,8 +110,8 @@ class PyObjectBase; * references on it! * @see PyObjectBase */ -template -class PyHandle +template +class PyHandle // NOLINT { public: //************************************************************************** @@ -121,17 +122,21 @@ public: * instead using a overwritten new operator in the * HandledType class! But is not easy to enforce! */ - PyHandle(HandledType *ToHandle=0L) - :_pHandles(ToHandle) { - if (_pHandles) + PyHandle(HandledType* ToHandle = 0L) + : _pHandles(ToHandle) + { + if (_pHandles) { _pHandles->IncRef(); + } } /// Copy constructor - PyHandle(const PyHandle &ToHandle) - :_pHandles(ToHandle._pHandles) { - if (_pHandles) + PyHandle(const PyHandle& ToHandle) + : _pHandles(ToHandle._pHandles) + { + if (_pHandles) { _pHandles->IncRef(); + } } /** destructor @@ -139,97 +144,113 @@ public: * if was the last one, the referenced object to * destruct! */ - ~PyHandle() { - if (_pHandles) + ~PyHandle() + { + if (_pHandles) { _pHandles->DecRef(); + } } //************************************************************************** // operator implementation // assign operator from a pointer - PyHandle &operator=(/*const*/ HandledType* other) { - if (_pHandles) + PyHandle& operator=(/*const*/ HandledType* other) + { + if (_pHandles) { _pHandles->DecRef(); + } // FIXME: Should be without "->_pHandles", shouldn't it? (Werner) - _pHandles = other;//_pHandles = other->_pHandles; - if (_pHandles) + _pHandles = other; //_pHandles = other->_pHandles; + if (_pHandles) { _pHandles->IncRef(); + } return *this; } // assign operator from a handle - PyHandle &operator=(const PyHandle &other) { - if (_pHandles) + PyHandle& operator=(const PyHandle& other) + { + if (_pHandles) { _pHandles->DecRef(); + } _pHandles = other._pHandles; - if (_pHandles) + if (_pHandles) { _pHandles->IncRef(); + } return *this; } /// dereference operators - HandledType &operator*() { + HandledType& operator*() + { return *_pHandles; } /// dereference operators - HandledType *operator->() { + HandledType* operator->() + { return _pHandles; } /// dereference operators - const HandledType &operator*() const { + const HandledType& operator*() const + { return _pHandles; } /// dereference operators - const HandledType *operator->() const { + const HandledType* operator->() const + { return _pHandles; } /** lower operator * needed for sorting in maps and sets */ - bool operator<(const PyHandle &other) const { - //return _pHandles<&other; - // FIXME: Shouldn't we compare both pointers?. (Werner) - return _pHandles& other) const + { + // return _pHandles<&other; + // FIXME: Shouldn't we compare both pointers?. (Werner) + return _pHandles < other._pHandles; } /// equal operator - bool operator==(const PyHandle &other) const { - //return _pHandles==&other; - // FIXME: Shouldn't we compare both pointers?. (Werner) - return _pHandles==other._pHandles; + bool operator==(const PyHandle& other) const + { + // return _pHandles==&other; + // FIXME: Shouldn't we compare both pointers?. (Werner) + return _pHandles == other._pHandles; } /// returns the type as PyObject - PyObject* getPyObject() const { + PyObject* getPyObject() const + { // return (PyObject*) _pHandles; // FIXME: Shouldn't we return the pointer's object?. (Werner) - return const_cast(_pHandles)->getPyObject(); + return const_cast(_pHandles)->getPyObject(); // NOLINT } //************************************************************************** // checking on the state /// Test if it handles something - bool IsValid() const { - return _pHandles!=0; + bool IsValid() const + { + return _pHandles != 0; } /// Test if it not handles something - bool IsNull() const { - return _pHandles==0; + bool IsNull() const + { + return _pHandles == 0; } private: /// the pointer on the handled object - HandledType *_pHandles; - + HandledType* _pHandles; }; -} // namespace Base +} // namespace Base -#endif // BASE_PYEXPORT_H +#endif // BASE_PYEXPORT_H diff --git a/src/Base/PyObjectBase.cpp b/src/Base/PyObjectBase.cpp index 4e0438f82b..3d2e0d3f61 100644 --- a/src/Base/PyObjectBase.cpp +++ b/src/Base/PyObjectBase.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "PyObjectBase.h" @@ -36,6 +36,7 @@ using namespace Base; +// clang-format off PyObject* Base::PyExc_FC_GeneralError = nullptr; PyObject* Base::PyExc_FC_FreeCADAbort = nullptr; PyObject* Base::PyExc_FC_XMLBaseException = nullptr; @@ -48,13 +49,13 @@ PyObject* Base::PyExc_FC_ExpressionError = nullptr; PyObject* Base::PyExc_FC_ParserError = nullptr; PyObject* Base::PyExc_FC_CADKernelError = nullptr; -typedef struct { +typedef struct { //NOLINT PyObject_HEAD PyObject* baseobject; PyObject* weakreflist; /* List of weak references */ } PyBaseProxy; -// Constructor +// NOLINTNEXTLINE PyObjectBase::PyObjectBase(void* voidp, PyTypeObject *T) : _pcTwinPointer(voidp) { @@ -78,6 +79,7 @@ PyObjectBase::~PyObjectBase() #ifdef FC_LOGPYOBJECTS Base::Console().Log("PyO-: %s (%p)\n",Py_TYPE(this)->tp_name, this); #endif + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) if (baseProxy && reinterpret_cast(baseProxy)->baseobject == this) Py_DECREF(baseProxy); Py_XDECREF(attrDict); @@ -105,6 +107,7 @@ static void PyBaseProxy_dealloc(PyObject* self) { /* Clear weakrefs first before calling any destructors */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) if (reinterpret_cast(self)->weakreflist) PyObject_ClearWeakRefs(self); Py_TYPE(self)->tp_free(self); @@ -164,7 +167,7 @@ static PyTypeObject PyBaseProxyType = { 0, /*tp_version_tag */ nullptr /*tp_finalize */ #if PY_VERSION_HEX >= 0x03090000 - ,0 /*tp_vectorcall */ + ,0 //NOLINT /*tp_vectorcall */ #elif PY_VERSION_HEX >= 0x03080000 ,0 /*tp_vectorcall */ /* bpo-37250: kept for backwards compatibility in CPython 3.8 only */ @@ -229,7 +232,7 @@ PyTypeObject PyObjectBase::Type = { 0, /*tp_version_tag */ nullptr /*tp_finalize */ #if PY_VERSION_HEX >= 0x03090000 - ,0 /*tp_vectorcall */ + ,0 //NOLINT /*tp_vectorcall */ #elif PY_VERSION_HEX >= 0x03080000 ,0 /*tp_vectorcall */ /* bpo-37250: kept for backwards compatibility in CPython 3.8 only */ @@ -254,6 +257,7 @@ PyObject* createWeakRef(PyObjectBase* ptr) if (!proxy) { proxy = PyType_GenericAlloc(&PyBaseProxyType, 0); ptr->baseProxy = proxy; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) reinterpret_cast(proxy)->baseobject = ptr; } @@ -266,6 +270,7 @@ PyObjectBase* getFromWeakRef(PyObject* ref) if (ref) { PyObject* proxy = PyWeakref_GetObject(ref); if (proxy && PyObject_TypeCheck(proxy, &PyBaseProxyType)) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return static_cast(reinterpret_cast(proxy)->baseobject); } } @@ -333,6 +338,7 @@ PyObject* PyObjectBase::__getattro(PyObject * obj, PyObject *attro) // something is wrong with the Python types. For example, a C++ class // that adds an extension uses the same Python type as a wrapper than // another C++ class without this extension. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) PyCFunctionObject* cfunc = reinterpret_cast(value); if (!cfunc->m_self) { Py_DECREF(cfunc); @@ -391,6 +397,7 @@ PyObject *PyObjectBase::_getattr(const char *attr) // Note: We must return the type object here, // so that our own types feel as really Python objects Py_INCREF(Py_TYPE(this)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return reinterpret_cast(Py_TYPE(this)); } else if (streq(attr, "__members__")) { @@ -565,3 +572,4 @@ void PyObjectBase::clearAttributes() PyDict_Clear(attrDict); } } +// clang-format on diff --git a/src/Base/PyObjectBase.h b/src/Base/PyObjectBase.h index 35c670d841..1a024c09a4 100644 --- a/src/Base/PyObjectBase.h +++ b/src/Base/PyObjectBase.h @@ -23,6 +23,7 @@ #ifndef BASE_PYOBJECTBASE_H #define BASE_PYOBJECTBASE_H +// clang-format off // Std. configurations // (re-)defined in pyconfig.h @@ -553,5 +554,6 @@ inline void PyTypeCheck(PyObject** ptr, int (*method)(PyObject*), const char* ms } // namespace Base +// clang-format on -#endif // BASE_PYOBJECTBASE_H +#endif // BASE_PYOBJECTBASE_H diff --git a/src/Base/PyTools.c b/src/Base/PyTools.c index fb6fca4fcc..4a90a3becd 100644 --- a/src/Base/PyTools.c +++ b/src/Base/PyTools.c @@ -1,9 +1,10 @@ +// clang-format off /* PPEMBED, VERSION 2.0 AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE Copyright 1996-2000, by Mark Lutz, and O'Reilly and Associates. -Permission to use, copy, modify, and distribute this software +Permission to use, copy, modify, and distribute this software for any purpose and without fee is hereby granted. This software is provided on an as is basis, without warranties of any kind. */ @@ -22,8 +23,8 @@ is provided on an as is basis, without warranties of any kind. //NOLINTBEGIN /***************************************************************************** - * RUN EMBEDDED OBJECT METHODS, ACCESS OBJECT ATTRIBUTES - * handles attribute fetch, debugging, input/output conversions; + * RUN EMBEDDED OBJECT METHODS, ACCESS OBJECT ATTRIBUTES + * handles attribute fetch, debugging, input/output conversions; * there is no module to reload here: assumes a known object; *****************************************************************************/ @@ -37,7 +38,7 @@ PP_Run_Method(PyObject *pobject, const char *method, va_start(argslist, argfmt); Py_Initialize(); /* init if first time */ - pmeth = PyObject_GetAttrString(pobject, method); + pmeth = PyObject_GetAttrString(pobject, method); if (pmeth == NULL) { /* get callable object */ va_end(argslist); return -1; /* bound method? has self */ @@ -50,9 +51,9 @@ PP_Run_Method(PyObject *pobject, const char *method, Py_DECREF(pmeth); return -1; } - if (PP_DEBUG) /* debug it too? */ - presult = PP_Debug_Function(pmeth, pargs); - else + if (PP_DEBUG) /* debug it too? */ + presult = PP_Debug_Function(pmeth, pargs); + else #if PY_VERSION_HEX < 0x03090000 presult = PyEval_CallObject(pmeth, pargs); /* run interpreter */ #else @@ -64,18 +65,18 @@ PP_Run_Method(PyObject *pobject, const char *method, return PP_Convert_Result(presult, resfmt, cresult); /* to C format */ } - + int PP_Get_Member(PyObject *pobject, const char *attrname, const char *resfmt, void *cresult) /* convert to c/c++ */ { PyObject *pmemb = NULL; /* "pobject.attrname" */ - Py_Initialize(); + Py_Initialize(); pmemb = PyObject_GetAttrString(pobject, attrname); /* incref'd */ return PP_Convert_Result(pmemb, resfmt, cresult); /* to C form, decrefs */ } - + int PP_Set_Member(PyObject *pobject, const char *attrname, @@ -91,15 +92,15 @@ PP_Set_Member(PyObject *pobject, const char *attrname, if (pval == NULL) return -1; result = PyObject_SetAttrString(pobject, attrname, pval); /* setattr */ - Py_DECREF(pval); + Py_DECREF(pval); return result; } /***************************************************************************** - * RUN EMBEDDED MODULE FUNCTIONS - * handles module (re)import, debugging, input/output conversions; - * note: also useful for calling classes (and C type constructors) at the + * RUN EMBEDDED MODULE FUNCTIONS + * handles module (re)import, debugging, input/output conversions; + * note: also useful for calling classes (and C type constructors) at the * top-level of a module to make Python instances: use class-name (or type * constructor function name) and 'O' result convert-code to get raw object; * use argfmt="()" for no args, cresult='NULL' for no result (procedure); @@ -151,9 +152,9 @@ PP_Debug_Function(PyObject *func, PyObject *args) /* expand tuple at front */ // it seems that some versions of python want just 2 arguments; in that // case, remove trailing 1 - oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args))); - oops |= PyTuple_SetItem(args, 0, func); - if (oops) + oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args))); + oops |= PyTuple_SetItem(args, 0, func); + if (oops) return NULL; /* "args = (funcobj,) + (arg,..)" */ res = PP_Run_Function( /* "pdb.runcall(funcobj, arg,..)" */ @@ -174,7 +175,7 @@ PP_Run_Known_Callable(PyObject *object, /* func|class|method */ va_list argslist; va_start(argslist, argfmt); /* "return object(args)" */ - Py_Initialize(); + Py_Initialize(); args = Py_VaBuildValue(argfmt, argslist); /* convert args to python */ va_end(argslist); if (args == NULL) /* args incref'd */ @@ -195,14 +196,14 @@ PP_Run_Known_Callable(PyObject *object, /* func|class|method */ /***************************************************************************** * PYTHON EXCEPTION INFORMATION ACCESS * fetch Python-related error info (type, value); - * after an API call returns an exception indicator, call + * after an API call returns an exception indicator, call * PP_Fetch_Error_Text, then get text from the 3 char[]'s; - * note: calling PyErr_Fetch() clears/erases the current - * exception in the Python system, as does PyErr_Print(), + * note: calling PyErr_Fetch() clears/erases the current + * exception in the Python system, as does PyErr_Print(), * so you should call one of these, one time, per exception: * caveats: not thread-specific since saves data in globals, - * and only exports traceback object (the exception type and - * data are converted to text strings and discarded); the + * and only exports traceback object (the exception type and + * data are converted to text strings and discarded); the * PyErr_Print() built-in also does a bit more on syntax errors, * and sends its text to sys.stderr: in principle, we could * assign stderr to a StringIO object and call PyErr_Print, but @@ -251,7 +252,7 @@ void PP_Fetch_Error_Text() { PP_last_error_type[0] = '\0'; } - + Py_XDECREF(pystring); pystring = NULL; @@ -262,7 +263,7 @@ void PP_Fetch_Error_Text() // PyDict_GetItemString returns a borrowed reference // so we must make sure not to decrement the reference PyObject* value = PyDict_GetItemString(errdata,"swhat"); - + if (value!=NULL) { strncpy(PP_last_error_info, PyUnicode_AsUTF8(value), MAX); PP_last_error_info[MAX-1] = '\0'; @@ -278,12 +279,12 @@ void PP_Fetch_Error_Text() strncpy(PP_last_error_info, PyUnicode_AsUTF8(pystring), MAX); /*Py->C*/ PP_last_error_info[MAX-1] = '\0'; } - else + else strcpy(PP_last_error_info, ""); - + Py_XDECREF(pystring); - /* convert traceback to string */ + /* convert traceback to string */ /* print text to a StringIO.StringIO() internal file object, then */ /* fetch by calling object's .getvalue() method (see lib manual); */ @@ -294,13 +295,13 @@ void PP_Fetch_Error_Text() (PyTraceBack_Print(errtraceback, pystring) == 0) && (PP_Run_Method(pystring, "getvalue", "s", &tempstr, "()") == 0) ) { - strncpy(PP_last_error_trace, tempstr, MAX); + strncpy(PP_last_error_trace, tempstr, MAX); PP_last_error_trace[MAX-1] = '\0'; free(tempstr); /* it's a strdup */ } else { PyFrameObject* frame = PyEval_GetFrame(); - if(!frame) + if(!frame) return; int line = PyFrame_GetLineNumber(frame); #if PY_VERSION_HEX < 0x030b0000 @@ -327,7 +328,7 @@ void PP_Fetch_Error_Text() PP_last_exception_type = 0; Py_XDECREF(errobj); Py_XDECREF(errdata); /* this function owns all 3 objects */ - Py_XDECREF(PP_last_traceback); /* they've been NULL'd out in Python */ + Py_XDECREF(PP_last_traceback); /* they've been NULL'd out in Python */ Py_XDECREF(PP_PyDict_Object); PP_last_traceback = errtraceback; /* save/export raw traceback object */ PP_PyDict_Object = pydict; @@ -337,9 +338,9 @@ void PP_Fetch_Error_Text() /***************************************************************************** * GET/SET MODULE-LEVEL (GLOBAL) PYTHON VARIABLES BY NAME * handles module (re)loading, input/output conversions; - * useful for passing data to/from codestrings (no args or return + * useful for passing data to/from codestrings (no args or return * val)--load module, set inputs, run codestring, get outputs; - * subtle thing: Python "s" output conversion code sets a C char* to + * subtle thing: Python "s" output conversion code sets a C char* to * the text in the middle of a Python string object, which may be * returned to the heap if decref'd--this api copies the text to a new * char array (with strdup) that the caller must free() when possible, @@ -390,7 +391,7 @@ PP_Get_Global(const char *modname, const char *varname, const char *resfmt, void int -PP_Set_Global(const char *modname, const char *varname, const char *valfmt, ... /* cval(s) */) +PP_Set_Global(const char *modname, const char *varname, const char *valfmt, ... /* cval(s) */) { int result = 0; PyObject *module = NULL, *val = NULL; /* "modname.varname = val" */ @@ -404,20 +405,20 @@ PP_Set_Global(const char *modname, const char *varname, const char *valfmt, ... } val = Py_VaBuildValue(valfmt, cvals); /* convert input to Python */ va_end(cvals); - if (val == NULL) + if (val == NULL) return -1; - result = PyObject_SetAttrString(module, varname, val); + result = PyObject_SetAttrString(module, varname, val); Py_DECREF(val); /* set global module var */ return result; /* decref val: var owns it */ } /* 0=success, varname set */ /***************************************************************************** - * MODULE INTERFACE + * MODULE INTERFACE * make/import/reload a python module by name * Note that Make_Dummy_Module could be implemented to keep a table - * of generated dictionaries to be used as namespaces, rather than - * using low level tools to create and mark real modules; this + * of generated dictionaries to be used as namespaces, rather than + * using low level tools to create and mark real modules; this * approach would require extra logic to manage and use the table; * see basic example of using dictionaries for string namespaces; *****************************************************************************/ @@ -443,10 +444,10 @@ PP_Make_Dummy_Module(const char *modname) /* namespace for strings, if no file Py_Initialize(); module = PyImport_AddModule(modname); /* fetch or make, no load */ if (module == NULL) /* module not incref'd */ - return -1; + return -1; else { /* module.__dict__ */ dict = PyModule_GetDict(module); /* ['__dummy__'] = None */ - PyDict_SetItemString(dict, "__dummy__", Py_None); + PyDict_SetItemString(dict, "__dummy__", Py_None); PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()); return 0; } @@ -456,15 +457,15 @@ PP_Make_Dummy_Module(const char *modname) /* namespace for strings, if no file PyObject * /* returns module object named modname */ PP_Load_Module(const char *modname) /* modname can be "package.module" form */ { /* reload just resets C extension mods */ - /* + /* * 4 cases: * - module "__main__" has no file, and not prebuilt: fetch or make * - dummy modules have no files: don't try to reload them * - reload=on and already loaded (on sys.modules): "reload()" before use - * - not loaded yet, or loaded but reload=off: "import" to fetch or load + * - not loaded yet, or loaded but reload=off: "import" to fetch or load */ - PyObject *module = NULL, *sysmods = NULL; + PyObject *module = NULL, *sysmods = NULL; modname = PP_Init(modname); /* default to __main__ */ if (strcmp(modname, "__main__") == 0) /* main: no file */ @@ -472,9 +473,9 @@ PP_Load_Module(const char *modname) /* modname can be "package.module" for sysmods = PyImport_GetModuleDict(); /* get sys.modules dict */ module = PyDict_GetItemString(sysmods, modname); /* mod in sys.modules? */ - + if (module != NULL && /* dummy: no file */ - PyModule_Check(module) && + PyModule_Check(module) && PyDict_GetItemString(PyModule_GetDict(module), "__dummy__")) { return module; /* not increfd */ } @@ -484,7 +485,7 @@ PP_Load_Module(const char *modname) /* modname can be "package.module" for Py_XDECREF(module); /* still on sys.modules */ return module; /* not increfd */ } - else { + else { module = PyImport_ImportModule(modname); /* fetch or load module */ Py_XDECREF(module); /* still on sys.modules */ return module; /* not increfd */ @@ -521,11 +522,11 @@ PP_Run_Command_Line(const char *prompt) } /***************************************************************************** - * RUN EMBEDDED CODE-STRINGS + * RUN EMBEDDED CODE-STRINGS * handles debugging, module (re)loading, namespaces, output conversions; * pbd.runeval returns a value: "eval(expr + '\n', globals, locals)"; * pdb.run is just a statement: "exec cmd + '\n' in globals, locals" - * New tools: precompiling strings to bytecode, running bytecode; + * New tools: precompiling strings to bytecode, running bytecode; *****************************************************************************/ @@ -547,9 +548,9 @@ PP_Run_Codestr(PPStringModes mode, const char *code, /* expr or stmt string */ return -1; parse_mode = (mode == PP_EXPRESSION ? Py_eval_input : Py_file_input); - if (PP_DEBUG) + if (PP_DEBUG) presult = PP_Debug_Codestr(mode, code, dict); /* run in pdb */ - else + else presult = PyRun_String(code, parse_mode, dict, dict); /* eval direct */ /* increfs res */ if (mode == PP_STATEMENT) { @@ -605,11 +606,11 @@ PP_Run_Bytecode(PyObject *codeobj, /* run compiled bytecode object */ /************************************************************************** * subtle things: * 1) pdb.run and pdb.runeval both accept either a string or a - * compiled code object, just because they call the built in exec and + * compiled code object, just because they call the built in exec and * eval(), which allow either form; further, eval() works on code * objects compiled as either expressions or statements, but returns - * None as the result of statements, so we don't need to distinguish - * between expressions and statements here again for bytecode (we + * None as the result of statements, so we don't need to distinguish + * between expressions and statements here again for bytecode (we * did when compiling); the equivalents in Python code: * >>> a = 1 * >>> s = compile('x = 1', '', 'exec') @@ -618,7 +619,7 @@ PP_Run_Bytecode(PyObject *codeobj, /* run compiled bytecode object */ * 2 * >>> print eval(s) * None - * on the other hand, we can't blindly use pdb.runeval when dealing + * on the other hand, we can't blindly use pdb.runeval when dealing * with uncompiled strings, because eval() fails on statement strings; * * 2) in 1.5, if you debug a string or bytecode object in a module's @@ -631,7 +632,7 @@ PP_Run_Bytecode(PyObject *codeobj, /* run compiled bytecode object */ **************************************************************************/ -static void fixPdbRetval(PyObject *moddict) +static void fixPdbRetval(PyObject *moddict) { if (PyDict_DelItemString(moddict, "__return__")) PyErr_Clear(); } @@ -646,7 +647,7 @@ PP_Debug_Codestr(PPStringModes mode, const char *codestring, PyObject *moddict) res = PP_Run_Function( /* "pdb.run(stmt, gdict, ldict)" */ "pdb", pdbname, /* "pdb.runeval(expr, gdict, ldict)" */ "O", &presult, - "(sOO)", codestring, moddict, moddict); + "(sOO)", codestring, moddict, moddict); return (res != 0) ? NULL : presult; /* return null or increfd object */ } @@ -660,8 +661,8 @@ PP_Debug_Bytecode(PyObject *codeobject, PyObject *moddict) res = PP_Run_Function( /* "pdb.runeval(codeobj, gdict, ldict)" */ "pdb", "runeval", /* accepts string|code, code=stmt|expr */ "O", &presult, - "(OOO)", codeobject, moddict, moddict); + "(OOO)", codeobject, moddict, moddict); return (res != 0) ? NULL : presult; /* null if error in run_function */ } // NOLINTEND - +// clang-format on diff --git a/src/Base/PyTools.h b/src/Base/PyTools.h index 13a7c0774c..3e63b08827 100644 --- a/src/Base/PyTools.h +++ b/src/Base/PyTools.h @@ -1,6 +1,7 @@ +// clang-format off /************************************************************************* * PPEMBED, VERSION 2.0 - * AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE + * AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE * * Wraps Python's run-time embedding API functions for easy use. * Most utilities assume the call is qualified by an enclosing module @@ -10,43 +11,43 @@ * * Python is automatically initialized when the first API call occurs. * Input/output conversions use the standard Python conversion format - * codes (described in the C API manual). Errors are flagged as either + * codes (described in the C API manual). Errors are flagged as either * a -1 int, or a NULL pointer result. Exported names use a PP_ prefix * to minimize clashes; names in the built-in Python API use Py prefixes - * instead (alas, there is no "import" equivalent in C, just "from*"). + * instead (alas, there is no "import" equivalent in C, just "from*"). * Also note that the varargs code here may not be portable to certain - * C compilers; to do it portably, see the text or file 'vararg.txt' + * C compilers; to do it portably, see the text or file 'vararg.txt' * here, or search for string STDARG in Python's source code files. * * New in this version/edition: names now have a PP_ prefix, files - * renamed, compiles to a single .a file, fixed pdb retval bug for - * strings, and char* results returned by the "s" convert code now - * point to new char arrays which the caller should free() when no - * longer needed (this was a potential bug in prior version). Also - * added new API interfaces for fetching exception info after errors, + * renamed, compiles to a single .a file, fixed pdb retval bug for + * strings, and char* results returned by the "s" convert code now + * point to new char arrays which the caller should free() when no + * longer needed (this was a potential bug in prior version). Also + * added new API interfaces for fetching exception info after errors, * precompiling code strings to byte code, and calling simple objects. * - * Also fully supports Python 1.5 module package imports: module names - * in this API can take the form "package.package.[...].module", where - * Python maps the package names to a nested directories path in your + * Also fully supports Python 1.5 module package imports: module names + * in this API can take the form "package.package.[...].module", where + * Python maps the package names to a nested directories path in your * file system hierarchy; package dirs all contain __init__.py files, * and the leftmost one is in a directory found on PYTHONPATH. This * API's dynamic reload feature also works for modules in packages; * Python stores the full path name in the sys.modules dictionary. * - * Caveats: there is no support for advanced things like threading or - * restricted execution mode here, but such things may be added with - * extra Python API calls external to this API (see the Python/C API - * manual for C-level threading calls; see modules rexec and bastion + * Caveats: there is no support for advanced things like threading or + * restricted execution mode here, but such things may be added with + * extra Python API calls external to this API (see the Python/C API + * manual for C-level threading calls; see modules rexec and bastion * in the library manual for restricted mode details). For threading, - * you may also be able to get by with C threads and distinct Python - * namespaces per Python code segments, or Python language threads + * you may also be able to get by with C threads and distinct Python + * namespaces per Python code segments, or Python language threads * started by Python code run from C (see the Python thread module). - * + * * Note that Python can only reload Python modules, not C extensions, - * but it's okay to leave the dynamic reload flag on even if you might + * but it's okay to leave the dynamic reload flag on even if you might * access dynamically-loaded C extension modules--in 1.5.2, Python - * simply resets C extension modules to their initial attribute state + * simply resets C extension modules to their initial attribute state * when reloaded, but doesn't actually reload the C extension file. *************************************************************************/ @@ -55,7 +56,7 @@ PPEMBED, VERSION 2.0 AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE Copyright 1996-2000, by Mark Lutz, and O'Reilly and Associates. -Permission to use, copy, modify, and distribute this software +Permission to use, copy, modify, and distribute this software for any purpose and without fee is hereby granted. This software is provided on an as is basis, without warranties of any kind. */ @@ -65,9 +66,9 @@ is provided on an as is basis, without warranties of any kind. #ifdef __cplusplus extern "C" { /* a C library, but callable from C++ */ -#endif +#endif -#include +#include //NOLINT // Python #if defined (_POSIX_C_SOURCE) # undef _POSIX_C_SOURCE @@ -80,7 +81,7 @@ extern "C" { /* a C library, but callable from C++ */ extern int PP_RELOAD; /* 1=reload py modules when attributes referenced */ extern int PP_DEBUG; /* 1=start debugger when string/function/member run */ -typedef enum { +typedef enum { //NOLINT PP_EXPRESSION, /* which kind of code-string */ PP_STATEMENT /* expressions and statements differ */ } PPStringModes; @@ -104,7 +105,7 @@ extern int PP_Run_Command_Line(const char *prompt); extern int PP_Convert_Result(PyObject *presult, const char *resFormat, void *resTarget); -extern int +extern int PP_Get_Global(const char *modname, const char *varname, const char *resfmt, void *cresult); extern int @@ -125,16 +126,16 @@ extern PyObject* const char *codestring, PyObject *moddict); extern PyObject * - PP_Compile_Codestr(PPStringModes mode, + PP_Compile_Codestr(PPStringModes mode, const char *codestr); /* precompile to bytecode */ extern int PP_Run_Bytecode(PyObject *codeobj, /* run a bytecode object */ - const char *modname, + const char *modname, const char *resfmt, void *restarget); extern PyObject * /* run bytecode under pdb */ - PP_Debug_Bytecode(PyObject *codeobject, PyObject *moddict); + PP_Debug_Bytecode(PyObject *codeobject, PyObject *moddict); /*******************************************************/ @@ -159,22 +160,22 @@ extern int /* ppembed-attributes.c: run object methods, access members */ /**************************************************************/ -extern int +extern int PP_Run_Method(PyObject *pobject, const char *method, /* uses Debug_Function */ const char *resfmt, void *cresult, /* output */ const char *argfmt, ... /* arg, arg... */ ); /* inputs */ -extern int +extern int PP_Get_Member(PyObject *pobject, const char *attrname, const char *resfmt, void *cresult); /* output */ -extern int +extern int PP_Set_Member(PyObject *pobject, const char *attrname, const char *valfmt, ... /* val, val... */ ); /* input */ /**********************************************************/ -/* ppembed-errors.c: get exception data after api error */ +/* ppembed-errors.c: get exception data after api error */ /**********************************************************/ extern void PP_Fetch_Error_Text(); /* fetch (and clear) exception */ @@ -193,3 +194,4 @@ extern PyObject *PP_last_exception_type; /* saved exception type */ #endif #endif /*PREEMBED_H*/ +// clang-format on diff --git a/src/Base/PyWrapParseTupleAndKeywords.h b/src/Base/PyWrapParseTupleAndKeywords.h index 741a3da235..db0d1acb8d 100644 --- a/src/Base/PyWrapParseTupleAndKeywords.h +++ b/src/Base/PyWrapParseTupleAndKeywords.h @@ -28,47 +28,45 @@ #include #include -namespace Base { +namespace Base +{ - /// A thin C++ wrapper around PyArg_ParseTupleAndKeywords providing const-correctness for the keywords argument - /// \arg args The Python args object - /// \arg kw The Python kw object - /// \arg format The format string describing the expected arguments - /// \arg keywords A std::array of keywords, terminated by a nullptr (required by CPython) - /// \arg (variadic) Pointers to the storage locations for the parameters - /// \returns boolean true on success, or false on failure - template - bool Wrapped_ParseTupleAndKeywords(PyObject *args, - PyObject *kw, - const char *format, - const std::array keywords, - ...) - { - static_assert(arraySize > 0, "keywords array must have at least a single nullptr in it"); - if (keywords.back()) { - PyErr_SetString(PyExc_ValueError, "Last element of keywords array is not null"); - return false; - } - - // NOTE: This code is from getargs.c in the Python source code (modified to use the public interface at - // PyArg_VaParseTupleAndKeywords and to return a bool). - - if ((args == nullptr || !PyTuple_Check(args)) || - (kw != nullptr && !PyDict_Check(kw)) || - format == nullptr) - { - PyErr_BadInternalCall(); - return false; - } - - va_list va; // NOLINT - va_start(va, keywords); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - int retval = PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast(keywords.data()), va); - va_end(va); - return retval != 0; // Convert to a true C++ boolean +/// A thin C++ wrapper around PyArg_ParseTupleAndKeywords providing const-correctness for the +/// keywords argument \arg args The Python args object \arg kw The Python kw object \arg format The +/// format string describing the expected arguments \arg keywords A std::array of keywords, +/// terminated by a nullptr (required by CPython) \arg (variadic) Pointers to the storage locations +/// for the parameters \returns boolean true on success, or false on failure +template +bool Wrapped_ParseTupleAndKeywords(PyObject* args, + PyObject* kw, + const char* format, + const std::array keywords, + ...) +{ + static_assert(arraySize > 0, "keywords array must have at least a single nullptr in it"); + if (keywords.back()) { + PyErr_SetString(PyExc_ValueError, "Last element of keywords array is not null"); + return false; } + // NOTE: This code is from getargs.c in the Python source code (modified to use the public + // interface at PyArg_VaParseTupleAndKeywords and to return a bool). + + if ((args == nullptr || !PyTuple_Check(args)) || (kw != nullptr && !PyDict_Check(kw)) + || format == nullptr) { + PyErr_BadInternalCall(); + return false; + } + + va_list va; // NOLINT + va_start(va, keywords); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + int retval = + PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast(keywords.data()), va); + va_end(va); + return retval != 0; // Convert to a true C++ boolean } -#endif //FREECAD_PYWRAPPARSETUPLEANDKEYWORDS_H +} // namespace Base + +#endif // FREECAD_PYWRAPPARSETUPLEANDKEYWORDS_H diff --git a/src/Base/PythonTypeExt.cpp b/src/Base/PythonTypeExt.cpp index 6054a9e764..d48d646d82 100644 --- a/src/Base/PythonTypeExt.cpp +++ b/src/Base/PythonTypeExt.cpp @@ -32,17 +32,19 @@ using namespace Base; PythonTypeExt::PythonTypeExt(Py::PythonType& type) : pytype(type) -{ -} +{} -Py::PythonType& PythonTypeExt::set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type)) +Py::PythonType& PythonTypeExt::set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, + PyObject* obj, + PyObject* type)) { pytype.type_object()->tp_descr_get = tp_descr_get; return pytype; } -Py::PythonType& PythonTypeExt::set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)) +Py::PythonType& +PythonTypeExt::set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)) { pytype.type_object()->tp_descr_set = tp_descr_set; diff --git a/src/Base/PythonTypeExt.h b/src/Base/PythonTypeExt.h index a1f49cec81..31eb76c87b 100644 --- a/src/Base/PythonTypeExt.h +++ b/src/Base/PythonTypeExt.h @@ -29,7 +29,7 @@ namespace Py { - class PythonType; +class PythonType; } using PyObject = struct _object; @@ -43,13 +43,15 @@ class BaseExport PythonTypeExt public: PythonTypeExt(Py::PythonType& type); - Py::PythonType& set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type)); - Py::PythonType& set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)); + Py::PythonType& + set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type)); + Py::PythonType& + set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)); private: Py::PythonType& pytype; }; -} // namespace Base +} // namespace Base -#endif // BASE_PYTHONTYPEEXT_H +#endif // BASE_PYTHONTYPEEXT_H diff --git a/src/Base/QtTools.cpp b/src/Base/QtTools.cpp index 3c6931be5d..0b37513953 100644 --- a/src/Base/QtTools.cpp +++ b/src/Base/QtTools.cpp @@ -26,10 +26,12 @@ #include "QtTools.h" -#if QT_VERSION < QT_VERSION_CHECK(5,14,0) -namespace Qt { - BaseExport QTextStream& endl(QTextStream& stream) { - return stream << QLatin1Char('\n') << flush; - } +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) +namespace Qt +{ +BaseExport QTextStream& endl(QTextStream& stream) +{ + return stream << QLatin1Char('\n') << flush; } +} // namespace Qt #endif diff --git a/src/Base/QtTools.h b/src/Base/QtTools.h index 7daf815b91..4d9cdb2497 100644 --- a/src/Base/QtTools.h +++ b/src/Base/QtTools.h @@ -30,26 +30,26 @@ // Suppress warning about 'SkipEmptyParts' not being used #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wunused-variable" -#elif defined (__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wunused-variable" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-variable" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" #endif #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) #include namespace Qt { - BaseExport QTextStream& endl(QTextStream& stream); - static auto SkipEmptyParts = QString::SkipEmptyParts; -} +BaseExport QTextStream& endl(QTextStream& stream); +static auto SkipEmptyParts = QString::SkipEmptyParts; +} // namespace Qt #endif #if defined(__clang__) -# pragma clang diagnostic pop -#elif defined (__GNUC__) -# pragma GCC diagnostic pop +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop #endif -#endif // BASE_QTTOOLS_H +#endif // BASE_QTTOOLS_H diff --git a/src/Base/Quantity.cpp b/src/Base/Quantity.cpp index 4a1cd38464..cb107f3b85 100644 --- a/src/Base/Quantity.cpp +++ b/src/Base/Quantity.cpp @@ -22,10 +22,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# ifdef FC_OS_WIN32 -# define _USE_MATH_DEFINES -# endif // FC_OS_WIN32 -# include +#ifdef FC_OS_WIN32 +#define _USE_MATH_DEFINES +#endif // FC_OS_WIN32 +#include #endif #include "Quantity.h" @@ -35,56 +35,53 @@ /** \defgroup Units Units system \ingroup BASE - \brief The quantities and units system enables FreeCAD to work transparently with many different units + \brief The quantities and units system enables FreeCAD to work transparently with many different + units */ // suppress annoying warnings from generated source files #ifdef _MSC_VER -# pragma warning(disable : 4003) -# pragma warning(disable : 4018) -# pragma warning(disable : 4065) -# pragma warning( disable : 4273 ) -# pragma warning(disable : 4335) // disable MAC file format warning on VC +#pragma warning(disable : 4003) +#pragma warning(disable : 4018) +#pragma warning(disable : 4065) +#pragma warning(disable : 4273) +#pragma warning(disable : 4335) // disable MAC file format warning on VC #endif using namespace Base; // ====== Static attributes ========================= // NOLINTNEXTLINE -int QuantityFormat::defaultDenominator = 8; // for 1/8" +int QuantityFormat::defaultDenominator = 8; // for 1/8" QuantityFormat::QuantityFormat() - : option(OmitGroupSeparator | RejectGroupSeparator) - , format(Fixed) - , precision(UnitsApi::getDecimals()) - , denominator(defaultDenominator) -{ -} + : option(OmitGroupSeparator | RejectGroupSeparator) + , format(Fixed) + , precision(UnitsApi::getDecimals()) + , denominator(defaultDenominator) +{} QuantityFormat::QuantityFormat(QuantityFormat::NumberFormat format, int decimals) - : option(OmitGroupSeparator | RejectGroupSeparator) - , format(format) - , precision(decimals < 0 ? UnitsApi::getDecimals() : decimals) - , denominator(defaultDenominator) -{ -} + : option(OmitGroupSeparator | RejectGroupSeparator) + , format(format) + , precision(decimals < 0 ? UnitsApi::getDecimals() : decimals) + , denominator(defaultDenominator) +{} // ---------------------------------------------------------------------------- Quantity::Quantity() - : myValue{0.0} -{ -} + : myValue {0.0} +{} Quantity::Quantity(double value, const Unit& unit) - : myValue{value} - , myUnit{unit} -{ -} + : myValue {value} + , myUnit {unit} +{} Quantity::Quantity(double value, const QString& unit) - : myValue{0.0} + : myValue {0.0} { if (unit.isEmpty()) { this->myValue = value; @@ -103,73 +100,77 @@ Quantity::Quantity(double value, const QString& unit) } } -double Quantity::getValueAs(const Quantity& other)const +double Quantity::getValueAs(const Quantity& other) const { return myValue / other.getValue(); } -bool Quantity::operator ==(const Quantity& that) const +bool Quantity::operator==(const Quantity& that) const { return (this->myValue == that.myValue) && (this->myUnit == that.myUnit); } -bool Quantity::operator !=(const Quantity& that) const +bool Quantity::operator!=(const Quantity& that) const { return !(*this == that); } -bool Quantity::operator <(const Quantity& that) const +bool Quantity::operator<(const Quantity& that) const { if (this->myUnit != that.myUnit) { - throw Base::UnitsMismatchError("Quantity::operator <(): quantities need to have same unit to compare"); + throw Base::UnitsMismatchError( + "Quantity::operator <(): quantities need to have same unit to compare"); } - return (this->myValue < that.myValue) ; + return (this->myValue < that.myValue); } -bool Quantity::operator >(const Quantity& that) const +bool Quantity::operator>(const Quantity& that) const { if (this->myUnit != that.myUnit) { - throw Base::UnitsMismatchError("Quantity::operator >(): quantities need to have same unit to compare"); + throw Base::UnitsMismatchError( + "Quantity::operator >(): quantities need to have same unit to compare"); } - return (this->myValue > that.myValue) ; + return (this->myValue > that.myValue); } -bool Quantity::operator <=(const Quantity& that) const +bool Quantity::operator<=(const Quantity& that) const { if (this->myUnit != that.myUnit) { - throw Base::UnitsMismatchError("Quantity::operator <=(): quantities need to have same unit to compare"); + throw Base::UnitsMismatchError( + "Quantity::operator <=(): quantities need to have same unit to compare"); } - return (this->myValue <= that.myValue) ; + return (this->myValue <= that.myValue); } -bool Quantity::operator >=(const Quantity& that) const +bool Quantity::operator>=(const Quantity& that) const { if (this->myUnit != that.myUnit) { - throw Base::UnitsMismatchError("Quantity::operator >=(): quantities need to have same unit to compare"); + throw Base::UnitsMismatchError( + "Quantity::operator >=(): quantities need to have same unit to compare"); } - return (this->myValue >= that.myValue) ; + return (this->myValue >= that.myValue); } -Quantity Quantity::operator *(const Quantity& other) const +Quantity Quantity::operator*(const Quantity& other) const { return Quantity(this->myValue * other.myValue, this->myUnit * other.myUnit); } -Quantity Quantity::operator *(double factor) const +Quantity Quantity::operator*(double factor) const { return Quantity(this->myValue * factor, this->myUnit); } -Quantity Quantity::operator /(const Quantity& other) const +Quantity Quantity::operator/(const Quantity& other) const { return Quantity(this->myValue / other.myValue, this->myUnit / other.myUnit); } -Quantity Quantity::operator /(double factor) const +Quantity Quantity::operator/(double factor) const { return Quantity(this->myValue / factor, this->myUnit); } @@ -180,21 +181,16 @@ Quantity Quantity::pow(const Quantity& other) const throw Base::UnitsMismatchError("Quantity::pow(): exponent must not have a unit"); } - return Quantity( - std::pow(this->myValue, other.myValue), - this->myUnit.pow(static_cast(other.myValue)) - ); + return Quantity(std::pow(this->myValue, other.myValue), + this->myUnit.pow(static_cast(other.myValue))); } Quantity Quantity::pow(double exp) const { - return Quantity( - std::pow(this->myValue, exp), - this->myUnit.pow(exp) - ); + return Quantity(std::pow(this->myValue, exp), this->myUnit.pow(exp)); } -Quantity Quantity::operator +(const Quantity& other) const +Quantity Quantity::operator+(const Quantity& other) const { if (this->myUnit != other.myUnit) { throw Base::UnitsMismatchError("Quantity::operator +(): Unit mismatch in plus operation"); @@ -203,7 +199,7 @@ Quantity Quantity::operator +(const Quantity& other) const return Quantity(this->myValue + other.myValue, this->myUnit); } -Quantity& Quantity::operator +=(const Quantity& other) +Quantity& Quantity::operator+=(const Quantity& other) { if (this->myUnit != other.myUnit) { throw Base::UnitsMismatchError("Quantity::operator +=(): Unit mismatch in plus operation"); @@ -214,16 +210,16 @@ Quantity& Quantity::operator +=(const Quantity& other) return *this; } -Quantity Quantity::operator -(const Quantity& other) const +Quantity Quantity::operator-(const Quantity& other) const { if (this->myUnit != other.myUnit) { throw Base::UnitsMismatchError("Quantity::operator -(): Unit mismatch in minus operation"); } - return Quantity(this->myValue - other.myValue,this->myUnit); + return Quantity(this->myValue - other.myValue, this->myUnit); } -Quantity& Quantity::operator -=(const Quantity& other) +Quantity& Quantity::operator-=(const Quantity& other) { if (this->myUnit != other.myUnit) { throw Base::UnitsMismatchError("Quantity::operator -=(): Unit mismatch in minus operation"); @@ -234,7 +230,7 @@ Quantity& Quantity::operator -=(const Quantity& other) return *this; } -Quantity Quantity::operator -() const +Quantity Quantity::operator-() const { return Quantity(-(this->myValue), this->myUnit); } @@ -244,7 +240,7 @@ QString Quantity::getUserString(double& factor, QString& unitString) const return Base::UnitsApi::schemaTranslate(*this, factor, unitString); } -QString Quantity::getUserString(UnitsSchema* schema, double &factor, QString &unitString) const +QString Quantity::getUserString(UnitsSchema* schema, double& factor, QString& unitString) const { return schema->schemaTranslate(*this, factor, unitString); } @@ -252,14 +248,11 @@ QString Quantity::getUserString(UnitsSchema* schema, double &factor, QString &un QString Quantity::getSafeUserString() const { auto retString = getUserString(); - if(Q_LIKELY(this->myValue != 0)) - { + if (Q_LIKELY(this->myValue != 0)) { auto feedbackQty = parse(retString); auto feedbackVal = feedbackQty.getValue(); if (feedbackVal == 0) { - retString = QStringLiteral("%1 %2") - .arg(this->myValue) - .arg(this->getUnit().getString()); + retString = QStringLiteral("%1 %2").arg(this->myValue).arg(this->getUnit().getString()); } } return retString; @@ -296,154 +289,160 @@ void Quantity::setInvalid() // === Predefined types ===================================================== -const Quantity Quantity::NanoMetre (1.0e-6 ,Unit(1)); -const Quantity Quantity::MicroMetre (1.0e-3 ,Unit(1)); -const Quantity Quantity::MilliMetre (1.0 ,Unit(1)); -const Quantity Quantity::CentiMetre (10.0 ,Unit(1)); -const Quantity Quantity::DeciMetre (100.0 ,Unit(1)); -const Quantity Quantity::Metre (1.0e3 ,Unit(1)); -const Quantity Quantity::KiloMetre (1.0e6 ,Unit(1)); +const Quantity Quantity::NanoMetre(1.0e-6, Unit(1)); +const Quantity Quantity::MicroMetre(1.0e-3, Unit(1)); +const Quantity Quantity::MilliMetre(1.0, Unit(1)); +const Quantity Quantity::CentiMetre(10.0, Unit(1)); +const Quantity Quantity::DeciMetre(100.0, Unit(1)); +const Quantity Quantity::Metre(1.0e3, Unit(1)); +const Quantity Quantity::KiloMetre(1.0e6, Unit(1)); -const Quantity Quantity::MilliLiter (1000.0 ,Unit(3)); -const Quantity Quantity::Liter (1.0e6 ,Unit(3)); +const Quantity Quantity::MilliLiter(1000.0, Unit(3)); +const Quantity Quantity::Liter(1.0e6, Unit(3)); -const Quantity Quantity::Hertz (1.0 ,Unit(0,0,-1)); -const Quantity Quantity::KiloHertz (1.0e3 ,Unit(0,0,-1)); -const Quantity Quantity::MegaHertz (1.0e6 ,Unit(0,0,-1)); -const Quantity Quantity::GigaHertz (1.0e9 ,Unit(0,0,-1)); -const Quantity Quantity::TeraHertz (1.0e12 ,Unit(0,0,-1)); +const Quantity Quantity::Hertz(1.0, Unit(0, 0, -1)); +const Quantity Quantity::KiloHertz(1.0e3, Unit(0, 0, -1)); +const Quantity Quantity::MegaHertz(1.0e6, Unit(0, 0, -1)); +const Quantity Quantity::GigaHertz(1.0e9, Unit(0, 0, -1)); +const Quantity Quantity::TeraHertz(1.0e12, Unit(0, 0, -1)); -const Quantity Quantity::MicroGram (1.0e-9 ,Unit(0,1)); -const Quantity Quantity::MilliGram (1.0e-6 ,Unit(0,1)); -const Quantity Quantity::Gram (1.0e-3 ,Unit(0,1)); -const Quantity Quantity::KiloGram (1.0 ,Unit(0,1)); -const Quantity Quantity::Ton (1.0e3 ,Unit(0,1)); +const Quantity Quantity::MicroGram(1.0e-9, Unit(0, 1)); +const Quantity Quantity::MilliGram(1.0e-6, Unit(0, 1)); +const Quantity Quantity::Gram(1.0e-3, Unit(0, 1)); +const Quantity Quantity::KiloGram(1.0, Unit(0, 1)); +const Quantity Quantity::Ton(1.0e3, Unit(0, 1)); -const Quantity Quantity::Second (1.0 ,Unit(0,0,1)); -const Quantity Quantity::Minute (60.0 ,Unit(0,0,1)); -const Quantity Quantity::Hour (3600.0 ,Unit(0,0,1)); +const Quantity Quantity::Second(1.0, Unit(0, 0, 1)); +const Quantity Quantity::Minute(60.0, Unit(0, 0, 1)); +const Quantity Quantity::Hour(3600.0, Unit(0, 0, 1)); -const Quantity Quantity::Ampere (1.0 ,Unit(0,0,0,1)); -const Quantity Quantity::MilliAmpere (0.001 ,Unit(0,0,0,1)); -const Quantity Quantity::KiloAmpere (1000.0 ,Unit(0,0,0,1)); -const Quantity Quantity::MegaAmpere (1.0e6 ,Unit(0,0,0,1)); +const Quantity Quantity::Ampere(1.0, Unit(0, 0, 0, 1)); +const Quantity Quantity::MilliAmpere(0.001, Unit(0, 0, 0, 1)); +const Quantity Quantity::KiloAmpere(1000.0, Unit(0, 0, 0, 1)); +const Quantity Quantity::MegaAmpere(1.0e6, Unit(0, 0, 0, 1)); -const Quantity Quantity::Kelvin (1.0 ,Unit(0,0,0,0,1)); -const Quantity Quantity::MilliKelvin (0.001 ,Unit(0,0,0,0,1)); -const Quantity Quantity::MicroKelvin (0.000001 ,Unit(0,0,0,0,1)); +const Quantity Quantity::Kelvin(1.0, Unit(0, 0, 0, 0, 1)); +const Quantity Quantity::MilliKelvin(0.001, Unit(0, 0, 0, 0, 1)); +const Quantity Quantity::MicroKelvin(0.000001, Unit(0, 0, 0, 0, 1)); -const Quantity Quantity::MilliMole (0.001 ,Unit(0,0,0,0,0,1)); -const Quantity Quantity::Mole (1.0 ,Unit(0,0,0,0,0,1)); +const Quantity Quantity::MilliMole(0.001, Unit(0, 0, 0, 0, 0, 1)); +const Quantity Quantity::Mole(1.0, Unit(0, 0, 0, 0, 0, 1)); -const Quantity Quantity::Candela (1.0 ,Unit(0,0,0,0,0,0,1)); +const Quantity Quantity::Candela(1.0, Unit(0, 0, 0, 0, 0, 0, 1)); -const Quantity Quantity::Inch (25.4 ,Unit(1)); -const Quantity Quantity::Foot (304.8 ,Unit(1)); -const Quantity Quantity::Thou (0.0254 ,Unit(1)); -const Quantity Quantity::Yard (914.4 ,Unit(1)); -const Quantity Quantity::Mile (1609344.0 ,Unit(1)); +const Quantity Quantity::Inch(25.4, Unit(1)); +const Quantity Quantity::Foot(304.8, Unit(1)); +const Quantity Quantity::Thou(0.0254, Unit(1)); +const Quantity Quantity::Yard(914.4, Unit(1)); +const Quantity Quantity::Mile(1609344.0, Unit(1)); -const Quantity Quantity::MilePerHour (447.04 ,Unit(1,0,-1)); -const Quantity Quantity::SquareFoot (92903.04 ,Unit(2)); -const Quantity Quantity::CubicFoot (28316846.592 ,Unit(3)); +const Quantity Quantity::MilePerHour(447.04, Unit(1, 0, -1)); +const Quantity Quantity::SquareFoot(92903.04, Unit(2)); +const Quantity Quantity::CubicFoot(28316846.592, Unit(3)); -const Quantity Quantity::Pound (0.45359237 ,Unit(0,1)); -const Quantity Quantity::Ounce (0.0283495231 ,Unit(0,1)); -const Quantity Quantity::Stone (6.35029318 ,Unit(0,1)); -const Quantity Quantity::Hundredweights (50.80234544 ,Unit(0,1)); +const Quantity Quantity::Pound(0.45359237, Unit(0, 1)); +const Quantity Quantity::Ounce(0.0283495231, Unit(0, 1)); +const Quantity Quantity::Stone(6.35029318, Unit(0, 1)); +const Quantity Quantity::Hundredweights(50.80234544, Unit(0, 1)); -const Quantity Quantity::PoundForce (4448.22 ,Unit(1,1,-2)); // lbf are ~= 4.44822 Newton +const Quantity Quantity::PoundForce(4448.22, Unit(1, 1, -2)); // lbf are ~= 4.44822 Newton -const Quantity Quantity::Newton (1000.0 ,Unit(1,1,-2)); // Newton (kg*m/s^2) -const Quantity Quantity::MilliNewton (1.0 ,Unit(1,1,-2)); -const Quantity Quantity::KiloNewton (1e+6 ,Unit(1,1,-2)); -const Quantity Quantity::MegaNewton (1e+9 ,Unit(1,1,-2)); +const Quantity Quantity::Newton(1000.0, Unit(1, 1, -2)); // Newton (kg*m/s^2) +const Quantity Quantity::MilliNewton(1.0, Unit(1, 1, -2)); +const Quantity Quantity::KiloNewton(1e+6, Unit(1, 1, -2)); +const Quantity Quantity::MegaNewton(1e+9, Unit(1, 1, -2)); -const Quantity Quantity::NewtonPerMeter (1.00 ,Unit(0,1,-2)); //Newton per meter (N/m or kg/s^2) -const Quantity Quantity::MilliNewtonPerMeter (1e-3 ,Unit(0,1,-2)); -const Quantity Quantity::KiloNewtonPerMeter (1e3 ,Unit(0,1,-2)); -const Quantity Quantity::MegaNewtonPerMeter (1e6 ,Unit(0,1,-2)); +const Quantity Quantity::NewtonPerMeter(1.00, Unit(0, 1, -2)); // Newton per meter (N/m or kg/s^2) +const Quantity Quantity::MilliNewtonPerMeter(1e-3, Unit(0, 1, -2)); +const Quantity Quantity::KiloNewtonPerMeter(1e3, Unit(0, 1, -2)); +const Quantity Quantity::MegaNewtonPerMeter(1e6, Unit(0, 1, -2)); -const Quantity Quantity::Pascal (0.001 ,Unit(-1,1,-2)); // Pascal (kg/m/s^2 or N/m^2) -const Quantity Quantity::KiloPascal (1.00 ,Unit(-1,1,-2)); -const Quantity Quantity::MegaPascal (1000.0 ,Unit(-1,1,-2)); -const Quantity Quantity::GigaPascal (1e+6 ,Unit(-1,1,-2)); +const Quantity Quantity::Pascal(0.001, Unit(-1, 1, -2)); // Pascal (kg/m/s^2 or N/m^2) +const Quantity Quantity::KiloPascal(1.00, Unit(-1, 1, -2)); +const Quantity Quantity::MegaPascal(1000.0, Unit(-1, 1, -2)); +const Quantity Quantity::GigaPascal(1e+6, Unit(-1, 1, -2)); -const Quantity Quantity::MilliBar (0.1 ,Unit(-1,1,-2)); -const Quantity Quantity::Bar (100.0 ,Unit(-1,1,-2)); // 1 bar = 100 kPa +const Quantity Quantity::MilliBar(0.1, Unit(-1, 1, -2)); +const Quantity Quantity::Bar(100.0, Unit(-1, 1, -2)); // 1 bar = 100 kPa -const Quantity Quantity::Torr (101.325/760.0 ,Unit(-1,1,-2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) -const Quantity Quantity::mTorr (0.101325/760.0,Unit(-1,1,-2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) -const Quantity Quantity::yTorr (0.000101325/760.0 ,Unit(-1,1,-2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) +const Quantity + Quantity::Torr(101.325 / 760.0, + Unit(-1, 1, -2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) +const Quantity + Quantity::mTorr(0.101325 / 760.0, + Unit(-1, 1, -2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) +const Quantity + Quantity::yTorr(0.000101325 / 760.0, + Unit(-1, 1, -2)); // Torr is a defined fraction of Pascal (kg/m/s^2 or N/m^2) -const Quantity Quantity::PSI (6.894744825494,Unit(-1,1,-2)); // pounds/in^2 -const Quantity Quantity::KSI (6894.744825494,Unit(-1,1,-2)); // 1000 x pounds/in^2 -const Quantity Quantity::MPSI (6894744.825494,Unit(-1,1,-2)); // 1000 ksi +const Quantity Quantity::PSI(6.894744825494, Unit(-1, 1, -2)); // pounds/in^2 +const Quantity Quantity::KSI(6894.744825494, Unit(-1, 1, -2)); // 1000 x pounds/in^2 +const Quantity Quantity::MPSI(6894744.825494, Unit(-1, 1, -2)); // 1000 ksi -const Quantity Quantity::Watt (1e+6 ,Unit(2,1,-3)); // Watt (kg*m^2/s^3) -const Quantity Quantity::MilliWatt (1e+3 ,Unit(2,1,-3)); -const Quantity Quantity::KiloWatt (1e+9 ,Unit(2,1,-3)); -const Quantity Quantity::VoltAmpere (1e+6 ,Unit(2,1,-3)); // VoltAmpere (kg*m^2/s^3) +const Quantity Quantity::Watt(1e+6, Unit(2, 1, -3)); // Watt (kg*m^2/s^3) +const Quantity Quantity::MilliWatt(1e+3, Unit(2, 1, -3)); +const Quantity Quantity::KiloWatt(1e+9, Unit(2, 1, -3)); +const Quantity Quantity::VoltAmpere(1e+6, Unit(2, 1, -3)); // VoltAmpere (kg*m^2/s^3) -const Quantity Quantity::Volt (1e+6 ,Unit(2,1,-3,-1)); // Volt (kg*m^2/A/s^3) -const Quantity Quantity::MilliVolt (1e+3 ,Unit(2,1,-3,-1)); -const Quantity Quantity::KiloVolt (1e+9 ,Unit(2,1,-3,-1)); +const Quantity Quantity::Volt(1e+6, Unit(2, 1, -3, -1)); // Volt (kg*m^2/A/s^3) +const Quantity Quantity::MilliVolt(1e+3, Unit(2, 1, -3, -1)); +const Quantity Quantity::KiloVolt(1e+9, Unit(2, 1, -3, -1)); -const Quantity Quantity::MegaSiemens (1.0 ,Unit(-2,-1,3,2)); -const Quantity Quantity::KiloSiemens (1e-3 ,Unit(-2,-1,3,2)); -const Quantity Quantity::Siemens (1e-6 ,Unit(-2,-1,3,2)); // Siemens (A^2*s^3/kg/m^2) -const Quantity Quantity::MilliSiemens (1e-9 ,Unit(-2,-1,3,2)); -const Quantity Quantity::MicroSiemens (1e-12 ,Unit(-2,-1,3,2)); +const Quantity Quantity::MegaSiemens(1.0, Unit(-2, -1, 3, 2)); +const Quantity Quantity::KiloSiemens(1e-3, Unit(-2, -1, 3, 2)); +const Quantity Quantity::Siemens(1e-6, Unit(-2, -1, 3, 2)); // Siemens (A^2*s^3/kg/m^2) +const Quantity Quantity::MilliSiemens(1e-9, Unit(-2, -1, 3, 2)); +const Quantity Quantity::MicroSiemens(1e-12, Unit(-2, -1, 3, 2)); -const Quantity Quantity::Ohm (1e+6 ,Unit(2,1,-3,-2)); // Ohm (kg*m^2/A^2/s^3) -const Quantity Quantity::KiloOhm (1e+9 ,Unit(2,1,-3,-2)); -const Quantity Quantity::MegaOhm (1e+12 ,Unit(2,1,-3,-2)); +const Quantity Quantity::Ohm(1e+6, Unit(2, 1, -3, -2)); // Ohm (kg*m^2/A^2/s^3) +const Quantity Quantity::KiloOhm(1e+9, Unit(2, 1, -3, -2)); +const Quantity Quantity::MegaOhm(1e+12, Unit(2, 1, -3, -2)); -const Quantity Quantity::Coulomb (1.0 ,Unit(0,0,1,1)); // Coulomb (A*s) +const Quantity Quantity::Coulomb(1.0, Unit(0, 0, 1, 1)); // Coulomb (A*s) -const Quantity Quantity::Tesla (1.0 ,Unit(0,1,-2,-1)); // Tesla (kg/s^2/A) -const Quantity Quantity::Gauss (1e-4 ,Unit(0,1,-2,-1)); // 1 G = 1e-4 T +const Quantity Quantity::Tesla(1.0, Unit(0, 1, -2, -1)); // Tesla (kg/s^2/A) +const Quantity Quantity::Gauss(1e-4, Unit(0, 1, -2, -1)); // 1 G = 1e-4 T -const Quantity Quantity::Weber (1e6 ,Unit(2,1,-2,-1)); // Weber (kg*m^2/s^2/A) +const Quantity Quantity::Weber(1e6, Unit(2, 1, -2, -1)); // Weber (kg*m^2/s^2/A) // disable Oersted because people need to input e.g. a field strength of // 1 ampere per meter -> 1 A/m and not get the recalculation to Oersted -//const Quantity Quantity::Oersted(0.07957747, Unit(-1, 0, 0, 1));// Oersted (A/m) +// const Quantity Quantity::Oersted(0.07957747, Unit(-1, 0, 0, 1));// Oersted (A/m) -const Quantity Quantity::PicoFarad (1e-18 ,Unit(-2,-1,4,2)); -const Quantity Quantity::NanoFarad (1e-15 ,Unit(-2,-1,4,2)); -const Quantity Quantity::MicroFarad (1e-12 ,Unit(-2,-1,4,2)); -const Quantity Quantity::MilliFarad (1e-9 ,Unit(-2,-1,4,2)); -const Quantity Quantity::Farad (1e-6 ,Unit(-2,-1,4,2)); // Farad (s^4*A^2/m^2/kg) +const Quantity Quantity::PicoFarad(1e-18, Unit(-2, -1, 4, 2)); +const Quantity Quantity::NanoFarad(1e-15, Unit(-2, -1, 4, 2)); +const Quantity Quantity::MicroFarad(1e-12, Unit(-2, -1, 4, 2)); +const Quantity Quantity::MilliFarad(1e-9, Unit(-2, -1, 4, 2)); +const Quantity Quantity::Farad(1e-6, Unit(-2, -1, 4, 2)); // Farad (s^4*A^2/m^2/kg) -const Quantity Quantity::NanoHenry (1e-3 ,Unit(2,1,-2,-2)); -const Quantity Quantity::MicroHenry (1.0 ,Unit(2,1,-2,-2)); -const Quantity Quantity::MilliHenry (1e+3 ,Unit(2,1,-2,-2)); -const Quantity Quantity::Henry (1e+6 ,Unit(2,1,-2,-2)); // Henry (kg*m^2/s^2/A^2) +const Quantity Quantity::NanoHenry(1e-3, Unit(2, 1, -2, -2)); +const Quantity Quantity::MicroHenry(1.0, Unit(2, 1, -2, -2)); +const Quantity Quantity::MilliHenry(1e+3, Unit(2, 1, -2, -2)); +const Quantity Quantity::Henry(1e+6, Unit(2, 1, -2, -2)); // Henry (kg*m^2/s^2/A^2) -const Quantity Quantity::Joule (1e+6 ,Unit(2,1,-2)); // Joule (kg*m^2/s^2) -const Quantity Quantity::MilliJoule (1e+3 ,Unit(2,1,-2)); -const Quantity Quantity::KiloJoule (1e+9 ,Unit(2,1,-2)); -const Quantity Quantity::NewtonMeter (1e+6 ,Unit(2,1,-2)); // Joule (kg*m^2/s^2) -const Quantity Quantity::VoltAmpereSecond (1e+6 ,Unit(2,1,-2)); // Joule (kg*m^2/s^2) -const Quantity Quantity::WattSecond (1e+6 ,Unit(2,1,-2)); // Joule (kg*m^2/s^2) -const Quantity Quantity::KiloWattHour (3.6e+12 ,Unit(2,1,-2)); // 1 kWh = 3.6e6 J -const Quantity Quantity::ElectronVolt (1.602176634e-13 ,Unit(2,1,-2)); // 1 eV = 1.602176634e-19 J -const Quantity Quantity::KiloElectronVolt (1.602176634e-10 ,Unit(2,1,-2)); -const Quantity Quantity::MegaElectronVolt (1.602176634e-7 ,Unit(2,1,-2)); -const Quantity Quantity::Calorie (4.1868e+6 ,Unit(2,1,-2)); // 1 cal = 4.1868 J -const Quantity Quantity::KiloCalorie (4.1868e+9 ,Unit(2,1,-2)); - -const Quantity Quantity::KMH (277.778 ,Unit(1,0,-1)); // km/h -const Quantity Quantity::MPH (447.04 ,Unit(1,0,-1)); // Mile/h - -const Quantity Quantity::AngMinute (1.0/60.0 ,Unit(0,0,0,0,0,0,0,1)); // angular minute -const Quantity Quantity::AngSecond (1.0/3600.0 ,Unit(0,0,0,0,0,0,0,1)); // angular second -const Quantity Quantity::Degree (1.0 ,Unit(0,0,0,0,0,0,0,1)); // degree (internal standard angle) -const Quantity Quantity::Radian (180/M_PI ,Unit(0,0,0,0,0,0,0,1)); // radian -const Quantity Quantity::Gon (360.0/400.0 ,Unit(0,0,0,0,0,0,0,1)); // gon +const Quantity Quantity::Joule(1e+6, Unit(2, 1, -2)); // Joule (kg*m^2/s^2) +const Quantity Quantity::MilliJoule(1e+3, Unit(2, 1, -2)); +const Quantity Quantity::KiloJoule(1e+9, Unit(2, 1, -2)); +const Quantity Quantity::NewtonMeter(1e+6, Unit(2, 1, -2)); // Joule (kg*m^2/s^2) +const Quantity Quantity::VoltAmpereSecond(1e+6, Unit(2, 1, -2)); // Joule (kg*m^2/s^2) +const Quantity Quantity::WattSecond(1e+6, Unit(2, 1, -2)); // Joule (kg*m^2/s^2) +const Quantity Quantity::KiloWattHour(3.6e+12, Unit(2, 1, -2)); // 1 kWh = 3.6e6 J +const Quantity Quantity::ElectronVolt(1.602176634e-13, Unit(2, 1, -2)); // 1 eV = 1.602176634e-19 J +const Quantity Quantity::KiloElectronVolt(1.602176634e-10, Unit(2, 1, -2)); +const Quantity Quantity::MegaElectronVolt(1.602176634e-7, Unit(2, 1, -2)); +const Quantity Quantity::Calorie(4.1868e+6, Unit(2, 1, -2)); // 1 cal = 4.1868 J +const Quantity Quantity::KiloCalorie(4.1868e+9, Unit(2, 1, -2)); +const Quantity Quantity::KMH(277.778, Unit(1, 0, -1)); // km/h +const Quantity Quantity::MPH(447.04, Unit(1, 0, -1)); // Mile/h +const Quantity Quantity::AngMinute(1.0 / 60.0, Unit(0, 0, 0, 0, 0, 0, 0, 1)); // angular minute +const Quantity Quantity::AngSecond(1.0 / 3600.0, Unit(0, 0, 0, 0, 0, 0, 0, 1)); // angular second +const Quantity + Quantity::Degree(1.0, + Unit(0, 0, 0, 0, 0, 0, 0, 1)); // degree (internal standard angle) +const Quantity Quantity::Radian(180 / M_PI, Unit(0, 0, 0, 0, 0, 0, 0, 1)); // radian +const Quantity Quantity::Gon(360.0 / 400.0, Unit(0, 0, 0, 0, 0, 0, 0, 1)); // gon // === Parser & Scanner stuff =============================================== @@ -457,24 +456,26 @@ Quantity QuantResult; // NOLINTBEGIN double num_change(char* yytext, char dez_delim, char grp_delim) { - double ret_val{}; + double ret_val {}; const int num = 40; - std::array temp{}; + std::array temp {}; int iter = 0; for (char* ch = yytext; *ch != '\0'; ch++) { // skip group delimiter - if (*ch == grp_delim) + if (*ch == grp_delim) { continue; + } // check for a dez delimiter other then dot if (*ch == dez_delim && dez_delim != '.') { - temp[iter++] = '.'; + temp[iter++] = '.'; } else { temp[iter++] = *ch; } // check buffer overflow - if (iter >= num) + if (iter >= num) { return 0.0; + } } temp[iter] = '\0'; @@ -485,32 +486,33 @@ double num_change(char* yytext, char dez_delim, char grp_delim) // NOLINTEND #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wmissing-noreturn" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-noreturn" #endif // error func -void Quantity_yyerror(char *errorinfo) +void Quantity_yyerror(char* errorinfo) { throw Base::ParserError(errorinfo); } #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wsign-compare" -# pragma clang diagnostic ignored "-Wunneeded-internal-declaration" -#elif defined (__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wsign-compare" -# pragma GCC diagnostic ignored "-Wfree-nonheap-object" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wunneeded-internal-declaration" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wfree-nonheap-object" #endif -namespace QuantityParser { +namespace QuantityParser +{ // NOLINTNEXTLINE #define YYINITDEPTH 20 @@ -526,25 +528,26 @@ int QuantityLexer(); // Scanner, defined in QuantityParser.l // NOLINTNEXTLINE #include "QuantityLexer.c" -#endif // DOXYGEN_SHOULD_SKIP_THIS -} +#endif // DOXYGEN_SHOULD_SKIP_THIS +} // namespace QuantityParser #if defined(__clang__) -# pragma clang diagnostic pop -#elif defined (__GNUC__) -# pragma GCC diagnostic pop +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop #endif -Quantity Quantity::parse(const QString &string) +Quantity Quantity::parse(const QString& string) { // parse from buffer - QuantityParser::YY_BUFFER_STATE my_string_buffer = QuantityParser::yy_scan_string (string.toUtf8().data()); + QuantityParser::YY_BUFFER_STATE my_string_buffer = + QuantityParser::yy_scan_string(string.toUtf8().data()); // set the global return variables QuantResult = Quantity(DOUBLE_MIN); // run the parser - QuantityParser::yyparse (); + QuantityParser::yyparse(); // free the scan buffer - QuantityParser::yy_delete_buffer (my_string_buffer); + QuantityParser::yy_delete_buffer(my_string_buffer); return QuantResult; } diff --git a/src/Base/Quantity.h b/src/Base/Quantity.h index 2be7a69998..f61dfcbd82 100644 --- a/src/Base/Quantity.h +++ b/src/Base/Quantity.h @@ -28,24 +28,28 @@ #include // NOLINTBEGIN -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ +#ifndef DOUBLE_MAX +#define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ #endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ +#ifndef DOUBLE_MIN +#define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ #endif // NOLINTEND -namespace Base { +namespace Base +{ class UnitsSchema; -struct BaseExport QuantityFormat { - enum NumberOption { +struct BaseExport QuantityFormat +{ + enum NumberOption + { None = 0x00, OmitGroupSeparator = 0x01, RejectGroupSeparator = 0x02 }; - enum NumberFormat { + enum NumberFormat + { Default = 0, Fixed = 1, Scientific = 2 @@ -60,51 +64,57 @@ struct BaseExport QuantityFormat { // Default denominator of minimum fractional inch. Only used in certain // schemas. // NOLINTNEXTLINE - static int defaultDenominator; // i.e 8 for 1/8" + static int defaultDenominator; // i.e 8 for 1/8" - static inline int getDefaultDenominator() { + static inline int getDefaultDenominator() + { return defaultDenominator; } - static inline void setDefaultDenominator(int denom) { + static inline void setDefaultDenominator(int denom) + { defaultDenominator = denom; } - inline int getDenominator() const { + inline int getDenominator() const + { return denominator; } - inline void setDenominator(int denom) { + inline void setDenominator(int denom) + { denominator = denom; } QuantityFormat(); - explicit QuantityFormat(NumberFormat format, int decimals=-1); - inline char toFormat() const { + explicit QuantityFormat(NumberFormat format, int decimals = -1); + inline char toFormat() const + { switch (format) { - case Fixed: - return 'f'; - case Scientific: - return 'e'; - default: - return 'g'; + case Fixed: + return 'f'; + case Scientific: + return 'e'; + default: + return 'g'; } } - static inline NumberFormat toFormat(char ch, bool* ok = nullptr) { + static inline NumberFormat toFormat(char ch, bool* ok = nullptr) + { if (ok) { *ok = true; } switch (ch) { - case 'f': - return Fixed; - case 'e': - return Scientific; - case 'g': - return Default; - default: - if (ok) { - *ok = false; - } - return Default; + case 'f': + return Fixed; + case 'e': + return Scientific; + case 'g': + return Default; + default: + if (ok) { + *ok = false; + } + return Default; } } }; @@ -119,74 +129,89 @@ public: Quantity(); Quantity(const Quantity&) = default; Quantity(Quantity&&) = default; - explicit Quantity(double value, const Unit& unit=Unit()); + explicit Quantity(double value, const Unit& unit = Unit()); explicit Quantity(double value, const QString& unit); /// Destruction - ~Quantity () = default; + ~Quantity() = default; /** Operators. */ //@{ - Quantity operator *(const Quantity &other) const; - Quantity operator *(double factor) const; - Quantity operator +(const Quantity &other) const; - Quantity& operator +=(const Quantity &other); - Quantity operator -(const Quantity &other) const; - Quantity& operator -=(const Quantity &other); - Quantity operator -() const; - Quantity operator /(const Quantity &other) const; - Quantity operator /(double factor) const; - bool operator ==(const Quantity&) const; - bool operator !=(const Quantity&) const; - bool operator < (const Quantity&) const; - bool operator > (const Quantity&) const; - bool operator <= (const Quantity&) const; - bool operator >= (const Quantity&) const; - Quantity& operator =(const Quantity&) = default; - Quantity& operator =(Quantity&&) = default; - Quantity pow(const Quantity&)const; - Quantity pow(double)const; + Quantity operator*(const Quantity& other) const; + Quantity operator*(double factor) const; + Quantity operator+(const Quantity& other) const; + Quantity& operator+=(const Quantity& other); + Quantity operator-(const Quantity& other) const; + Quantity& operator-=(const Quantity& other); + Quantity operator-() const; + Quantity operator/(const Quantity& other) const; + Quantity operator/(double factor) const; + bool operator==(const Quantity&) const; + bool operator!=(const Quantity&) const; + bool operator<(const Quantity&) const; + bool operator>(const Quantity&) const; + bool operator<=(const Quantity&) const; + bool operator>=(const Quantity&) const; + Quantity& operator=(const Quantity&) = default; + Quantity& operator=(Quantity&&) = default; + Quantity pow(const Quantity&) const; + Quantity pow(double) const; //@} - const QuantityFormat& getFormat() const { + const QuantityFormat& getFormat() const + { return myFormat; } - void setFormat(const QuantityFormat& fmt) { + void setFormat(const QuantityFormat& fmt) + { myFormat = fmt; } /// transfer to user preferred unit/potence - QString getUserString(double &factor, QString &unitString) const; - QString getUserString() const { // to satisfy GCC - double dummy1{}; - QString dummy2{}; + QString getUserString(double& factor, QString& unitString) const; + QString getUserString() const + { // to satisfy GCC + double dummy1 {}; + QString dummy2 {}; return getUserString(dummy1, dummy2); } - QString getUserString(UnitsSchema* schema, double &factor, QString &unitString) const; + QString getUserString(UnitsSchema* schema, double& factor, QString& unitString) const; QString getSafeUserString() const; - static Quantity parse(const QString &string); + static Quantity parse(const QString& string); /// returns the unit of the quantity - const Unit & getUnit() const{return myUnit;} + const Unit& getUnit() const + { + return myUnit; + } /// set the unit of the quantity - void setUnit(const Unit &un){myUnit = un;} + void setUnit(const Unit& un) + { + myUnit = un; + } /// get the Value of the quantity - double getValue() const{return myValue;} + double getValue() const + { + return myValue; + } /// set the value of the quantity - void setValue(double val){myValue = val;} + void setValue(double val) + { + myValue = val; + } /** get the Value in a special unit given as quantity. - * One can use one of the predifeined quantity units in this class - */ - double getValueAs(const Quantity &)const; + * One can use one of the predifeined quantity units in this class + */ + double getValueAs(const Quantity&) const; /// true if it has a number without a unit - bool isDimensionless()const; + bool isDimensionless() const; /// true if it has a specific unit or no dimension. - bool isDimensionlessOrUnit(const Unit& unit)const; + bool isDimensionlessOrUnit(const Unit& unit) const; /// true if it has a number and a valid unit - bool isQuantity()const; + bool isQuantity() const; /// true if it has a number with or without a unit - bool isValid()const; + bool isValid() const; /// sets the quantity invalid void setInvalid(); @@ -303,7 +328,7 @@ public: static const Quantity Weber; - //static const Quantity Oersted; + // static const Quantity Oersted; static const Quantity Farad; static const Quantity MilliFarad; @@ -340,12 +365,12 @@ public: //@} -protected: - double myValue; - Unit myUnit; +private: + double myValue; + Unit myUnit; QuantityFormat myFormat; }; -} // namespace Base +} // namespace Base -#endif // BASE_Quantity_H +#endif // BASE_Quantity_H diff --git a/src/Base/QuantityLexer.c b/src/Base/QuantityLexer.c index 5e29fc28ec..9a08a69a3c 100644 --- a/src/Base/QuantityLexer.c +++ b/src/Base/QuantityLexer.c @@ -1,3 +1,4 @@ +// clang-format off #line 1 "QuantityLexer.c" #line 3 "QuantityLexer.c" @@ -34,7 +35,7 @@ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, - * if you want the limit (max/min) macros for int types. + * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 @@ -51,7 +52,7 @@ typedef uint32_t flex_uint32_t; typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; -typedef unsigned char flex_uint8_t; +typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; @@ -162,10 +163,10 @@ extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 - + #define YY_LESS_LINENO(n) #define YY_LINENO_REWIND_TO(ptr) - + /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ @@ -678,7 +679,7 @@ char *yytext; */ #include #endif - + #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif @@ -727,7 +728,7 @@ extern int yywrap ( void ); #endif #ifndef YY_NO_UNPUT - + #endif #ifndef yytext_ptr @@ -854,7 +855,7 @@ YY_DECL yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; - + if ( !(yy_init) ) { (yy_init) = 1; @@ -1994,7 +1995,7 @@ static int yy_get_next_buffer (void) { yy_state_type yy_current_state; char *yy_cp; - + yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) @@ -2058,7 +2059,7 @@ static int yy_get_next_buffer (void) { int c; - + *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) @@ -2125,12 +2126,12 @@ static int yy_get_next_buffer (void) /** Immediately switch to a different input stream. * @param input_file A readable stream. - * + * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { - + if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = @@ -2143,11 +2144,11 @@ static int yy_get_next_buffer (void) /** Switch to a different input buffer. * @param new_buffer The new input buffer. - * + * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { - + /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); @@ -2187,13 +2188,13 @@ static void yy_load_buffer_state (void) /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. - * + * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; - + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); @@ -2216,11 +2217,11 @@ static void yy_load_buffer_state (void) /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() - * + * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { - + if ( ! b ) return; @@ -2241,7 +2242,7 @@ static void yy_load_buffer_state (void) { int oerrno = errno; - + yy_flush_buffer( b ); b->yy_input_file = file; @@ -2257,13 +2258,13 @@ static void yy_load_buffer_state (void) } b->yy_is_interactive = 0; - + errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. - * + * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { @@ -2292,7 +2293,7 @@ static void yy_load_buffer_state (void) * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. - * + * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { @@ -2322,7 +2323,7 @@ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. - * + * */ void yypop_buffer_state (void) { @@ -2346,7 +2347,7 @@ void yypop_buffer_state (void) static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; - + if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this @@ -2389,13 +2390,13 @@ static void yyensure_buffer_stack (void) /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer - * + * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; - + if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) @@ -2424,14 +2425,14 @@ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan - * + * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (const char * yystr ) { - + return yy_scan_bytes( yystr, (int) strlen(yystr) ); } @@ -2439,7 +2440,7 @@ YY_BUFFER_STATE yy_scan_string (const char * yystr ) * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. - * + * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) @@ -2448,7 +2449,7 @@ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) char *buf; yy_size_t n; int i; - + /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t) (_yybytes_len + 2); buf = (char *) yyalloc( n ); @@ -2502,16 +2503,16 @@ static void yynoreturn yy_fatal_error (const char* msg ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. - * + * */ int yyget_lineno (void) { - + return yylineno; } /** Get the input stream. - * + * */ FILE *yyget_in (void) { @@ -2519,7 +2520,7 @@ FILE *yyget_in (void) } /** Get the output stream. - * + * */ FILE *yyget_out (void) { @@ -2527,7 +2528,7 @@ FILE *yyget_out (void) } /** Get the length of the current token. - * + * */ int yyget_leng (void) { @@ -2535,7 +2536,7 @@ int yyget_leng (void) } /** Get the current token. - * + * */ char *yyget_text (void) @@ -2545,18 +2546,18 @@ char *yyget_text (void) /** Set the current line number. * @param _line_number line number - * + * */ void yyset_lineno (int _line_number ) { - + yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. - * + * * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str ) @@ -2610,7 +2611,7 @@ static int yy_init_globals (void) /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { - + /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer( YY_CURRENT_BUFFER ); @@ -2636,7 +2637,7 @@ int yylex_destroy (void) #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n ) { - + int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; @@ -2661,7 +2662,7 @@ void *yyalloc (yy_size_t size ) void *yyrealloc (void * ptr, yy_size_t size ) { - + /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter @@ -2680,3 +2681,4 @@ void yyfree (void * ptr ) #define YYTABLES_NAME "yytables" #line 249 "QuantityParser.l" +// clang-format on diff --git a/src/Base/QuantityParser.c b/src/Base/QuantityParser.c index 02d15502ab..bb8ae3915b 100644 --- a/src/Base/QuantityParser.c +++ b/src/Base/QuantityParser.c @@ -1,3 +1,4 @@ +// clang-format off /* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison implementation for Yacc-like parsers in C @@ -1745,3 +1746,4 @@ yyreturn: } #line 77 "QuantityParser.y" /* yacc.c:1906 */ +// clang-format on diff --git a/src/Base/QuantityParser.h b/src/Base/QuantityParser.h index 0475775fd9..7143ebc41e 100644 --- a/src/Base/QuantityParser.h +++ b/src/Base/QuantityParser.h @@ -1,3 +1,4 @@ +// clang-format off /* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison interface for Yacc-like parsers in C @@ -81,3 +82,4 @@ extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_QUANTITYPARSER_H_INCLUDED */ +// clang-format on diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index 01a12b14ef..e7b9c24fe0 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -35,14 +35,15 @@ std::string QuantityPy::representation() const { std::stringstream ret; - double val= getQuantityPtr()->getValue(); + double val = getQuantityPtr()->getValue(); Unit unit = getQuantityPtr()->getUnit(); // Use Python's implementation to repr() a float Py::Float flt(val); ret << static_cast(flt.repr()); - if (!unit.isEmpty()) + if (!unit.isEmpty()) { ret << " " << unit.getString().toUtf8().constData(); + } return ret.str(); } @@ -50,23 +51,25 @@ std::string QuantityPy::representation() const PyObject* QuantityPy::toStr(PyObject* args) { int prec = getQuantityPtr()->getFormat().precision; - if (!PyArg_ParseTuple(args,"|i", &prec)) + if (!PyArg_ParseTuple(args, "|i", &prec)) { return nullptr; + } - double val= getQuantityPtr()->getValue(); + double val = getQuantityPtr()->getValue(); Unit unit = getQuantityPtr()->getUnit(); std::stringstream ret; ret.precision(prec); ret.setf(std::ios::fixed, std::ios::floatfield); ret << val; - if (!unit.isEmpty()) + if (!unit.isEmpty()) { ret << " " << unit.getString().toUtf8().constData(); + } return Py_BuildValue("s", ret.str().c_str()); } -PyObject *QuantityPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* QuantityPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of QuantityPy and the Twin object return new QuantityPy(new Quantity); @@ -75,60 +78,61 @@ PyObject *QuantityPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // P // constructor method int QuantityPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - Quantity *self = getQuantityPtr(); + Quantity* self = getQuantityPtr(); - PyErr_Clear(); // set by PyArg_ParseTuple() - PyObject *object{}; - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + PyObject* object {}; + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { *self = *(static_cast(object)->getQuantityPtr()); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() + PyErr_Clear(); // set by PyArg_ParseTuple() double f = DOUBLE_MAX; - if (PyArg_ParseTuple(args,"dO!",&f,&(Base::UnitPy::Type), &object)) { - *self = Quantity(f,*(static_cast(object)->getUnitPtr())); + if (PyArg_ParseTuple(args, "dO!", &f, &(Base::UnitPy::Type), &object)) { + *self = Quantity(f, *(static_cast(object)->getUnitPtr())); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"dO!",&f,&(Base::QuantityPy::Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "dO!", &f, &(Base::QuantityPy::Type), &object)) { PyErr_SetString(PyExc_TypeError, "Second argument must be a Unit not a Quantity"); return -1; } - int i1=0; - int i2=0; - int i3=0; - int i4=0; - int i5=0; - int i6=0; - int i7=0; - int i8=0; - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args, "|diiiiiiii", &f,&i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) { + int i1 = 0; + int i2 = 0; + int i3 = 0; + int i4 = 0; + int i5 = 0; + int i6 = 0; + int i7 = 0; + int i8 = 0; + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "|diiiiiiii", &f, &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8)) { if (f < DOUBLE_MAX) { - *self = Quantity(f,Unit{static_cast(i1), - static_cast(i2), - static_cast(i3), - static_cast(i4), - static_cast(i5), - static_cast(i6), - static_cast(i7), - static_cast(i8)}); + *self = Quantity(f, + Unit {static_cast(i1), + static_cast(i2), + static_cast(i3), + static_cast(i4), + static_cast(i5), + static_cast(i6), + static_cast(i7), + static_cast(i8)}); } return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - char* string{}; - if (PyArg_ParseTuple(args,"et", "utf-8", &string)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + char* string {}; + if (PyArg_ParseTuple(args, "et", "utf-8", &string)) { QString qstr = QString::fromUtf8(string); PyMem_Free(string); try { *self = Quantity::parse(qstr); } - catch(const Base::ParserError& e) { + catch (const Base::ParserError& e) { PyErr_SetString(PyExc_ValueError, e.what()); return -1; } @@ -136,14 +140,14 @@ int QuantityPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"det", &f, "utf-8", &string)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "det", &f, "utf-8", &string)) { QString unit = QString::fromUtf8(string); PyMem_Free(string); try { *self = Quantity(f, unit); } - catch(const Base::ParserError& e) { + catch (const Base::ParserError& e) { PyErr_SetString(PyExc_ValueError, e.what()); return -1; } @@ -158,45 +162,45 @@ int QuantityPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyObject* QuantityPy::getUserPreferred(PyObject* /*args*/) { QString uus; - double factor{}; + double factor {}; Py::Tuple res(3); - QString uss = getQuantityPtr()->getUserString(factor,uus); + QString uss = getQuantityPtr()->getUserString(factor, uus); - res[0] = Py::String(uss.toUtf8(),"utf-8"); + res[0] = Py::String(uss.toUtf8(), "utf-8"); res[1] = Py::Float(factor); - res[2] = Py::String(uus.toUtf8(),"utf-8"); + res[2] = Py::String(uus.toUtf8(), "utf-8"); return Py::new_reference_to(res); } -PyObject* QuantityPy::getValueAs(PyObject *args) +PyObject* QuantityPy::getValueAs(PyObject* args) { Quantity quant; quant.setInvalid(); // first try Quantity if (!quant.isValid()) { - PyObject *object{}; - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { - quant = * static_cast(object)->getQuantityPtr(); + PyObject* object {}; + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { + quant = *static_cast(object)->getQuantityPtr(); } } if (!quant.isValid()) { - PyObject *object{}; + PyObject* object {}; PyErr_Clear(); - if (PyArg_ParseTuple(args,"O!",&(Base::UnitPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::UnitPy::Type), &object)) { quant.setUnit(*static_cast(object)->getUnitPtr()); quant.setValue(1.0); } } if (!quant.isValid()) { - PyObject *object{}; - double value{}; + PyObject* object {}; + double value {}; PyErr_Clear(); - if (PyArg_ParseTuple(args,"dO!",&value, &(Base::UnitPy::Type), &object)) { + if (PyArg_ParseTuple(args, "dO!", &value, &(Base::UnitPy::Type), &object)) { quant.setUnit(*static_cast(object)->getUnitPtr()); quant.setValue(value); } @@ -204,33 +208,34 @@ PyObject* QuantityPy::getValueAs(PyObject *args) if (!quant.isValid()) { double f = DOUBLE_MAX; - int i1=0; - int i2=0; - int i3=0; - int i4=0; - int i5=0; - int i6=0; - int i7=0; - int i8=0; + int i1 = 0; + int i2 = 0; + int i3 = 0; + int i4 = 0; + int i5 = 0; + int i6 = 0; + int i7 = 0; + int i8 = 0; PyErr_Clear(); - if (PyArg_ParseTuple(args, "d|iiiiiiii", &f,&i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) { + if (PyArg_ParseTuple(args, "d|iiiiiiii", &f, &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8)) { if (f < DOUBLE_MAX) { - quant = Quantity(f,Unit{static_cast(i1), - static_cast(i2), - static_cast(i3), - static_cast(i4), - static_cast(i5), - static_cast(i6), - static_cast(i7), - static_cast(i8)}); + quant = Quantity(f, + Unit {static_cast(i1), + static_cast(i2), + static_cast(i3), + static_cast(i4), + static_cast(i5), + static_cast(i6), + static_cast(i7), + static_cast(i8)}); } } } if (!quant.isValid()) { PyErr_Clear(); - char* string{}; - if (PyArg_ParseTuple(args,"et", "utf-8", &string)) { + char* string {}; + if (PyArg_ParseTuple(args, "et", "utf-8", &string)) { QString qstr = QString::fromUtf8(string); PyMem_Free(string); quant = Quantity::parse(qstr); @@ -251,9 +256,9 @@ PyObject* QuantityPy::getValueAs(PyObject *args) return new QuantityPy(new Quantity(quant)); } -PyObject * QuantityPy::__round__ (PyObject *args) +PyObject* QuantityPy::__round__(PyObject* args) { - double val= getQuantityPtr()->getValue(); + double val = getQuantityPtr()->getValue(); Unit unit = getQuantityPtr()->getUnit(); Py::Float flt(val); Py::Callable func(flt.getAttr("__round__")); @@ -262,7 +267,7 @@ PyObject * QuantityPy::__round__ (PyObject *args) return new QuantityPy(new Quantity(rnd, unit)); } -PyObject * QuantityPy::number_float_handler (PyObject *self) +PyObject* QuantityPy::number_float_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "Arg must be Quantity"); @@ -273,7 +278,7 @@ PyObject * QuantityPy::number_float_handler (PyObject *self) return PyFloat_FromDouble(q->getValue()); } -PyObject * QuantityPy::number_int_handler (PyObject *self) +PyObject* QuantityPy::number_int_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "Arg must be Quantity"); @@ -284,139 +289,167 @@ PyObject * QuantityPy::number_int_handler (PyObject *self) return PyLong_FromLong(long(q->getValue())); } -PyObject * QuantityPy::number_negative_handler (PyObject *self) +PyObject* QuantityPy::number_negative_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "Arg must be Quantity"); return nullptr; } - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); double b = -1; return new QuantityPy(new Quantity(*a * b)); } -PyObject * QuantityPy::number_positive_handler (PyObject *self) +PyObject* QuantityPy::number_positive_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "Arg must be Quantity"); return nullptr; } - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); return new QuantityPy(new Quantity(*a)); } -PyObject * QuantityPy::number_absolute_handler (PyObject *self) +PyObject* QuantityPy::number_absolute_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "Arg must be Quantity"); return nullptr; } - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); return new QuantityPy(new Quantity(fabs(a->getValue()), a->getUnit())); } -static Quantity &pyToQuantity(Quantity &q, PyObject *pyobj) { - if (PyObject_TypeCheck(pyobj, &Base::QuantityPy::Type)) +static Quantity& pyToQuantity(Quantity& q, PyObject* pyobj) +{ + if (PyObject_TypeCheck(pyobj, &Base::QuantityPy::Type)) { q = *static_cast(pyobj)->getQuantityPtr(); - else if (PyFloat_Check(pyobj)) + } + else if (PyFloat_Check(pyobj)) { q = Quantity(PyFloat_AsDouble(pyobj)); - else if (PyLong_Check(pyobj)) + } + else if (PyLong_Check(pyobj)) { q = Quantity(PyLong_AsLong(pyobj)); + } else { - PyErr_Format(PyExc_TypeError,"Cannot convert %s to Quantity",Py_TYPE(pyobj)->tp_name); + PyErr_Format(PyExc_TypeError, "Cannot convert %s to Quantity", Py_TYPE(pyobj)->tp_name); throw Py::Exception(); } return q; } -PyObject* QuantityPy::number_add_handler(PyObject *self, PyObject *other) +PyObject* QuantityPy::number_add_handler(PyObject* self, PyObject* other) { - Quantity *pa=nullptr, *pb=nullptr; - Quantity a,b; - PY_TRY { - if (PyObject_TypeCheck(self, &(QuantityPy::Type))) + Quantity *pa = nullptr, *pb = nullptr; + Quantity a, b; + PY_TRY + { + if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { pa = static_cast(self)->getQuantityPtr(); - else - pa = &pyToQuantity(a,self); + } + else { + pa = &pyToQuantity(a, self); + } - if (PyObject_TypeCheck(other, &(QuantityPy::Type))) + if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { pb = static_cast(other)->getQuantityPtr(); - else - pb = &pyToQuantity(b,other); - return new QuantityPy(new Quantity(*pa + *pb) ); - } PY_CATCH + } + else { + pb = &pyToQuantity(b, other); + } + return new QuantityPy(new Quantity(*pa + *pb)); + } + PY_CATCH } -PyObject* QuantityPy::number_subtract_handler(PyObject *self, PyObject *other) +PyObject* QuantityPy::number_subtract_handler(PyObject* self, PyObject* other) { - Quantity *pa=nullptr, *pb=nullptr; - Quantity a,b; - PY_TRY { - if (PyObject_TypeCheck(self, &(QuantityPy::Type))) + Quantity *pa = nullptr, *pb = nullptr; + Quantity a, b; + PY_TRY + { + if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { pa = static_cast(self)->getQuantityPtr(); - else - pa = &pyToQuantity(a,self); + } + else { + pa = &pyToQuantity(a, self); + } - if (PyObject_TypeCheck(other, &(QuantityPy::Type))) + if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { pb = static_cast(other)->getQuantityPtr(); - else - pb = &pyToQuantity(b,other); - return new QuantityPy(new Quantity(*pa - *pb) ); - } PY_CATCH + } + else { + pb = &pyToQuantity(b, other); + } + return new QuantityPy(new Quantity(*pa - *pb)); + } + PY_CATCH } -PyObject* QuantityPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* QuantityPy::number_multiply_handler(PyObject* self, PyObject* other) { - Quantity *pa=nullptr, *pb=nullptr; - Quantity a,b; - PY_TRY { - if (PyObject_TypeCheck(self, &(QuantityPy::Type))) + Quantity *pa = nullptr, *pb = nullptr; + Quantity a, b; + PY_TRY + { + if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { pa = static_cast(self)->getQuantityPtr(); - else - pa = &pyToQuantity(a,self); + } + else { + pa = &pyToQuantity(a, self); + } - if (PyObject_TypeCheck(other, &(QuantityPy::Type))) + if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { pb = static_cast(other)->getQuantityPtr(); - else - pb = &pyToQuantity(b,other); - return new QuantityPy(new Quantity(*pa * *pb) ); - } PY_CATCH + } + else { + pb = &pyToQuantity(b, other); + } + return new QuantityPy(new Quantity(*pa * *pb)); + } + PY_CATCH } -PyObject * QuantityPy::number_divide_handler (PyObject *self, PyObject *other) +PyObject* QuantityPy::number_divide_handler(PyObject* self, PyObject* other) { - Quantity *pa=nullptr, *pb=nullptr; - Quantity a,b; - PY_TRY { - if (PyObject_TypeCheck(self, &(QuantityPy::Type))) + Quantity *pa = nullptr, *pb = nullptr; + Quantity a, b; + PY_TRY + { + if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { pa = static_cast(self)->getQuantityPtr(); - else - pa = &pyToQuantity(a,self); + } + else { + pa = &pyToQuantity(a, self); + } - if (PyObject_TypeCheck(other, &(QuantityPy::Type))) + if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { pb = static_cast(other)->getQuantityPtr(); - else - pb = &pyToQuantity(b,other); - return new QuantityPy(new Quantity(*pa / *pb) ); - } PY_CATCH + } + else { + pb = &pyToQuantity(b, other); + } + return new QuantityPy(new Quantity(*pa / *pb)); + } + PY_CATCH } -PyObject * QuantityPy::number_remainder_handler (PyObject *self, PyObject *other) +PyObject* QuantityPy::number_remainder_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Quantity"); return nullptr; } - double d1{}, d2{}; - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + double d1 {}, d2 {}; + Base::Quantity* a = static_cast(self)->getQuantityPtr(); d1 = a->getValue(); if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { - Base::Quantity *b = static_cast(other)->getQuantityPtr(); + Base::Quantity* b = static_cast(other)->getQuantityPtr(); d2 = b->getValue(); } else if (PyFloat_Check(other)) { @@ -435,42 +468,44 @@ PyObject * QuantityPy::number_remainder_handler (PyObject *self, PyObject *other PyObject* r = PyNumber_Remainder(p1, p2); Py_DECREF(p1); Py_DECREF(p2); - if (!r) + if (!r) { return nullptr; + } double q = PyFloat_AsDouble(r); Py_DECREF(r); - return new QuantityPy(new Quantity(q,a->getUnit())); + return new QuantityPy(new Quantity(q, a->getUnit())); } -PyObject * QuantityPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) { - //PyNumber_Divmod(); + // PyNumber_Divmod(); PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * QuantityPy::number_power_handler (PyObject *self, PyObject *other, PyObject * /*modulo*/) +PyObject* QuantityPy::number_power_handler(PyObject* self, PyObject* other, PyObject* /*modulo*/) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Quantity"); return nullptr; } - PY_TRY { + PY_TRY + { if (PyObject_TypeCheck(other, &(QuantityPy::Type))) { - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); - Base::Quantity *b = static_cast(other)->getQuantityPtr(); - Base::Quantity q(a->pow(*b)); // to prevent memory leak in case of exception + Base::Quantity* a = static_cast(self)->getQuantityPtr(); + Base::Quantity* b = static_cast(other)->getQuantityPtr(); + Base::Quantity q(a->pow(*b)); // to prevent memory leak in case of exception return new QuantityPy(new Quantity(q)); } else if (PyFloat_Check(other)) { - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); double b = PyFloat_AsDouble(other); - return new QuantityPy(new Quantity(a->pow(b)) ); + return new QuantityPy(new Quantity(a->pow(b))); } else if (PyLong_Check(other)) { - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); double b = (double)PyLong_AsLong(other); return new QuantityPy(new Quantity(a->pow(b))); } @@ -478,27 +513,27 @@ PyObject * QuantityPy::number_power_handler (PyObject *self, PyObject *other, Py PyErr_SetString(PyExc_TypeError, "Expected quantity or number"); return nullptr; } - }PY_CATCH + } + PY_CATCH } -int QuantityPy::number_nonzero_handler (PyObject *self) +int QuantityPy::number_nonzero_handler(PyObject* self) { if (!PyObject_TypeCheck(self, &(QuantityPy::Type))) { return 1; } - Base::Quantity *a = static_cast(self) ->getQuantityPtr(); + Base::Quantity* a = static_cast(self)->getQuantityPtr(); return a->getValue() != 0.0; } -PyObject* QuantityPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* QuantityPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(QuantityPy::Type)) && - PyObject_TypeCheck(w, &(QuantityPy::Type))) { - const Quantity * u1 = static_cast(v)->getQuantityPtr(); - const Quantity * u2 = static_cast(w)->getQuantityPtr(); + if (PyObject_TypeCheck(v, &(QuantityPy::Type)) && PyObject_TypeCheck(w, &(QuantityPy::Type))) { + const Quantity* u1 = static_cast(v)->getQuantityPtr(); + const Quantity* u2 = static_cast(w)->getQuantityPtr(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op == Py_NE) { res = (!(*u1 == *u2)) ? Py_True : Py_False; Py_INCREF(res); @@ -510,12 +545,12 @@ PyObject* QuantityPy::richCompare(PyObject *v, PyObject *w, int op) return res; } else if (op == Py_LE) { - res = (*u1 < *u2)||(*u1 == *u2) ? Py_True : Py_False; + res = (*u1 < *u2) || (*u1 == *u2) ? Py_True : Py_False; Py_INCREF(res); return res; } else if (op == Py_GT) { - res = (!(*u1 < *u2))&&(!(*u1 == *u2)) ? Py_True : Py_False; + res = (!(*u1 < *u2)) && (!(*u1 == *u2)) ? Py_True : Py_False; Py_INCREF(res); return res; } @@ -534,7 +569,7 @@ PyObject* QuantityPy::richCompare(PyObject *v, PyObject *w, int op) // Try to get floating numbers double u1 = PyFloat_AsDouble(v); double u2 = PyFloat_AsDouble(w); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op == Py_NE) { res = (u1 != u2) ? Py_True : Py_False; Py_INCREF(res); @@ -590,15 +625,16 @@ Py::Object QuantityPy::getUnit() const void QuantityPy::setUnit(Py::Object arg) { Py::Type UnitType(Base::getTypeAsObject(&Base::UnitPy::Type)); - if(!arg.isType(UnitType)) + if (!arg.isType(UnitType)) { throw Py::AttributeError("Not yet implemented"); + } getQuantityPtr()->setUnit(*static_cast((*arg))->getUnitPtr()); } Py::String QuantityPy::getUserString() const { - return {getQuantityPtr()->getUserString().toUtf8(),"utf-8"}; + return {getQuantityPtr()->getUserString().toUtf8(), "utf-8"}; } Py::Dict QuantityPy::getFormat() const @@ -606,18 +642,18 @@ Py::Dict QuantityPy::getFormat() const QuantityFormat fmt = getQuantityPtr()->getFormat(); Py::Dict dict; - dict.setItem("Precision", Py::Int (fmt.precision)); + dict.setItem("Precision", Py::Int(fmt.precision)); dict.setItem("NumberFormat", Py::Char(fmt.toFormat())); dict.setItem("Denominator", Py::Int(fmt.denominator)); return dict; } -void QuantityPy::setFormat(Py::Dict arg) +void QuantityPy::setFormat(Py::Dict arg) { QuantityFormat fmt = getQuantityPtr()->getFormat(); if (arg.hasKey("Precision")) { - Py::Int prec(arg.getItem("Precision")); + Py::Int prec(arg.getItem("Precision")); fmt.precision = static_cast(prec); } @@ -625,39 +661,44 @@ void QuantityPy::setFormat(Py::Dict arg) Py::Object item = arg.getItem("NumberFormat"); if (item.isNumeric()) { int format = static_cast(Py::Int(item)); - if (format < 0 || format > QuantityFormat::Scientific) + if (format < 0 || format > QuantityFormat::Scientific) { throw Py::ValueError("Invalid format value"); + } fmt.format = static_cast(format); } else { Py::Char form(item); std::string fmtstr = static_cast(Py::String(form)); - if (fmtstr.size() != 1) + if (fmtstr.size() != 1) { throw Py::ValueError("Invalid format character"); + } bool ok = false; fmt.format = Base::QuantityFormat::toFormat(fmtstr[0], &ok); - if (!ok) + if (!ok) { throw Py::ValueError("Invalid format character"); + } } } if (arg.hasKey("Denominator")) { - Py::Int denom(arg.getItem("Denominator")); + Py::Int denom(arg.getItem("Denominator")); int fracInch = static_cast(denom); // check that the value is positive and a power of 2 - if (fracInch <= 0) + if (fracInch <= 0) { throw Py::ValueError("Denominator must be higher than zero"); + } // bitwise check - if (fracInch & (fracInch - 1)) + if (fracInch & (fracInch - 1)) { throw Py::ValueError("Denominator must be a power of two"); + } fmt.denominator = fracInch; } getQuantityPtr()->setFormat(fmt); } -PyObject *QuantityPy::getCustomAttributes(const char* attr) const +PyObject* QuantityPy::getCustomAttributes(const char* attr) const { QuantityPy* py = nullptr; if (strcmp(attr, "Torr") == 0) { @@ -691,39 +732,38 @@ int QuantityPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject * QuantityPy::number_invert_handler (PyObject* /*self*/) +PyObject* QuantityPy::number_invert_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_TypeError, "bad operand type for unary ~"); return nullptr; } -PyObject * QuantityPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_lshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_TypeError, "unsupported operand type(s) for <<"); return nullptr; } -PyObject * QuantityPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_rshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_TypeError, "unsupported operand type(s) for >>"); return nullptr; } -PyObject * QuantityPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_and_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_TypeError, "unsupported operand type(s) for &"); return nullptr; } -PyObject * QuantityPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_xor_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_TypeError, "unsupported operand type(s) for ^"); return nullptr; } -PyObject * QuantityPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* QuantityPy::number_or_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_TypeError, "unsupported operand type(s) for |"); return nullptr; } - diff --git a/src/Base/Reader.cpp b/src/Base/Reader.cpp index c33e5d091c..d3036492a8 100644 --- a/src/Base/Reader.cpp +++ b/src/Base/Reader.cpp @@ -25,7 +25,7 @@ #ifndef _PreComp_ #include -# include +#include #endif #include @@ -57,7 +57,7 @@ using namespace std; // --------------------------------------------------------------------------- Base::XMLReader::XMLReader(const char* FileName, std::istream& str) - : _File(FileName) + : _File(FileName) { #ifdef _MSC_VER str.imbue(std::locale::empty()); @@ -66,7 +66,7 @@ Base::XMLReader::XMLReader(const char* FileName, std::istream& str) #endif // create the parser - parser = XMLReaderFactory::createXMLReader(); + parser = XMLReaderFactory::createXMLReader(); // NOLINT parser->setContentHandler(this); parser->setLexicalHandler(this); @@ -78,14 +78,12 @@ Base::XMLReader::XMLReader(const char* FileName, std::istream& str) } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); - cerr << "Exception message is: \n" - << message << "\n"; + cerr << "Exception message is: \n" << message << "\n"; XMLString::release(&message); } catch (const SAXParseException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); - cerr << "Exception message is: \n" - << message << "\n"; + cerr << "Exception message is: \n" << message << "\n"; XMLString::release(&message); } #ifndef FC_DEBUG @@ -131,7 +129,7 @@ unsigned long Base::XMLReader::getAttributeAsUnsigned(const char* AttrName) cons AttrMapType::const_iterator pos = AttrMap.find(AttrName); if (pos != AttrMap.end()) { - return strtoul(pos->second.c_str(),nullptr,10); + return strtoul(pos->second.c_str(), nullptr, 10); } else { // wrong name, use hasAttribute if not sure! @@ -141,7 +139,7 @@ unsigned long Base::XMLReader::getAttributeAsUnsigned(const char* AttrName) cons } } -double Base::XMLReader::getAttributeAsFloat (const char* AttrName) const +double Base::XMLReader::getAttributeAsFloat(const char* AttrName) const { AttrMapType::const_iterator pos = AttrMap.find(AttrName); @@ -156,7 +154,7 @@ double Base::XMLReader::getAttributeAsFloat (const char* AttrName) const } } -const char* Base::XMLReader::getAttribute (const char* AttrName) const +const char* Base::XMLReader::getAttribute(const char* AttrName) const { AttrMapType::const_iterator pos = AttrMap.find(AttrName); @@ -171,7 +169,7 @@ const char* Base::XMLReader::getAttribute (const char* AttrName) const } } -bool Base::XMLReader::hasAttribute (const char* AttrName) const +bool Base::XMLReader::hasAttribute(const char* AttrName) const { return AttrMap.find(AttrName) != AttrMap.end(); } @@ -205,11 +203,14 @@ bool Base::XMLReader::read() void Base::XMLReader::readElement(const char* ElementName) { - bool ok{}; + bool ok {}; int currentLevel = Level; std::string currentName = LocalName; do { - ok = read(); if (!ok) break; + ok = read(); + if (!ok) { + break; + } if (ReadType == EndElement && currentName == LocalName && currentLevel >= Level) { // we have reached the end of the element when calling this method // thus we must stop reading on. @@ -219,32 +220,37 @@ void Base::XMLReader::readElement(const char* ElementName) // the end of the document has been reached but we still try to continue on reading throw Base::XMLParseException("End of document reached"); } - } while ((ReadType != StartElement && ReadType != StartEndElement) || - (ElementName && LocalName != ElementName)); + } while ((ReadType != StartElement && ReadType != StartEndElement) + || (ElementName && LocalName != ElementName)); } bool Base::XMLReader::readNextElement() { - bool ok{}; + bool ok {}; while (true) { ok = read(); - if (!ok) + if (!ok) { break; - if (ReadType == StartElement) + } + if (ReadType == StartElement) { break; - if (ReadType == StartEndElement) + } + if (ReadType == StartEndElement) { break; - if (ReadType == EndElement) + } + if (ReadType == EndElement) { break; - if (ReadType == EndDocument) + } + if (ReadType == EndDocument) { break; + } }; - return (ReadType == StartElement || - ReadType == StartEndElement); + return (ReadType == StartElement || ReadType == StartEndElement); } -int Base::XMLReader::level() const { +int Base::XMLReader::level() const +{ return Level; } @@ -266,11 +272,8 @@ bool Base::XMLReader::isEndOfDocument() const void Base::XMLReader::readEndElement(const char* ElementName, int level) { // if we are already at the end of the current element - if (ReadType == EndElement - && ElementName - && LocalName == ElementName - && (level<0 || level==Level)) - { + if (ReadType == EndElement && ElementName && LocalName == ElementName + && (level < 0 || level == Level)) { return; } else if (ReadType == EndDocument) { @@ -278,15 +281,17 @@ void Base::XMLReader::readEndElement(const char* ElementName, int level) throw Base::XMLParseException("End of document reached"); } - bool ok{}; + bool ok {}; do { - ok = read(); if (!ok) break; - if (ReadType == EndDocument) + ok = read(); + if (!ok) { break; + } + if (ReadType == EndDocument) { + break; + } } while (ReadType != EndElement - || (ElementName - && (LocalName != ElementName - || (level>=0 && level!=Level)))); + || (ElementName && (LocalName != ElementName || (level >= 0 && level != Level)))); } void Base::XMLReader::readCharacters(const char* filename, CharStreamFormat format) @@ -377,8 +382,9 @@ std::istream& Base::XMLReader::beginCharStream(CharStreamFormat format) CharStream = std::make_unique(); auto* filteringStream = dynamic_cast(CharStream.get()); - if(format == CharStreamFormat::Base64Encoded) { - filteringStream->push(base64_decoder(Base::base64DefaultBufferSize, Base64ErrorHandling::silent)); + if (format == CharStreamFormat::Base64Encoded) { + filteringStream->push( + base64_decoder(Base::base64DefaultBufferSize, Base64ErrorHandling::silent)); } filteringStream->push(boost::ref(*this)); return *CharStream; @@ -388,19 +394,23 @@ void Base::XMLReader::readBinFile(const char* filename) { Base::FileInfo fi(filename); Base::ofstream to(fi, std::ios::out | std::ios::binary); - if (!to) + if (!to) { throw Base::FileException("XMLReader::readBinFile() Could not open file!"); + } - bool ok{}; + bool ok {}; do { - ok = read(); if (!ok) break; + ok = read(); + if (!ok) { + break; + } } while (ReadType != EndCDATA); to << Base::base64_decode(Characters); to.close(); } -void Base::XMLReader::readFiles(zipios::ZipInputStream &zipstream) const +void Base::XMLReader::readFiles(zipios::ZipInputStream& zipstream) const { // It's possible that not all objects inside the document could be created, e.g. if a module // is missing that would know these object types. So, there may be data files inside the zip @@ -423,26 +433,29 @@ void Base::XMLReader::readFiles(zipios::ZipInputStream &zipstream) const Base::SequencerLauncher seq("Importing project files...", FileList.size()); while (entry->isValid() && it != FileList.end()) { std::vector::const_iterator jt = it; - // Check if the current entry is registered, otherwise check the next registered files as soon as - // both file names match - while (jt != FileList.end() && entry->getName() != jt->FileName) + // Check if the current entry is registered, otherwise check the next registered files as + // soon as both file names match + while (jt != FileList.end() && entry->getName() != jt->FileName) { ++jt; + } // If this condition is true both file names match and we can read-in the data, otherwise // no file name for the current entry in the zip was registered. if (jt != FileList.end()) { try { Base::Reader reader(zipstream, jt->FileName, FileVersion); jt->Object->RestoreDocFile(reader); - if (reader.getLocalReader()) + if (reader.getLocalReader()) { reader.getLocalReader()->readFiles(zipstream); + } } - catch(...) { + catch (...) { // For any exception we just continue with the next file. // It doesn't matter if the last reader has read more or // less data than the file size would allow. // All what we need to do is to notify the user about the // failure. - Base::Console().Error("Reading failed from embedded file: %s\n", entry->toString().c_str()); + Base::Console().Error("Reading failed from embedded file: %s\n", + entry->toString().c_str()); } // Go to the next registered file name it = jt + 1; @@ -461,14 +474,14 @@ void Base::XMLReader::readFiles(zipios::ZipInputStream &zipstream) const } } -const char *Base::XMLReader::addFile(const char* Name, Base::Persistence *Object) +const char* Base::XMLReader::addFile(const char* Name, Base::Persistence* Object) { FileEntry temp; temp.FileName = Name; temp.Object = Object; FileList.push_back(temp); - FileNames.push_back( temp.FileName ); + FileNames.push_back(temp.FileName); return Name; } @@ -478,12 +491,13 @@ const std::vector& Base::XMLReader::getFilenames() const return FileNames; } -bool Base::XMLReader::isRegistered(Base::Persistence *Object) const +bool Base::XMLReader::isRegistered(Base::Persistence* Object) const { if (Object) { - for (const auto & it : FileList) { - if (it.Object == Object) + for (const auto& it : FileList) { + if (it.Object == Object) { return true; + } } } @@ -491,8 +505,7 @@ bool Base::XMLReader::isRegistered(Base::Persistence *Object) const } void Base::XMLReader::addName(const char*, const char*) -{ -} +{} const char* Base::XMLReader::getName(const char* name) const { @@ -517,9 +530,12 @@ void Base::XMLReader::endDocument() ReadType = EndDocument; } -void Base::XMLReader::startElement(const XMLCh* const /*uri*/, const XMLCh* const localname, const XMLCh* const /*qname*/, const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) +void Base::XMLReader::startElement(const XMLCh* const /*uri*/, + const XMLCh* const localname, + const XMLCh* const /*qname*/, + const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) { - Level++; // new scope + Level++; // new scope LocalName = StrX(localname).c_str(); // saving attributes of the current scope, delete all previously stored ones @@ -531,45 +547,49 @@ void Base::XMLReader::startElement(const XMLCh* const /*uri*/, const XMLCh* cons ReadType = StartElement; } -void Base::XMLReader::endElement (const XMLCh* const /*uri*/, const XMLCh *const localname, const XMLCh *const /*qname*/) +void Base::XMLReader::endElement(const XMLCh* const /*uri*/, + const XMLCh* const localname, + const XMLCh* const /*qname*/) { - Level--; // end of scope + Level--; // end of scope LocalName = StrX(localname).c_str(); - if (ReadType == StartElement) + if (ReadType == StartElement) { ReadType = StartEndElement; - else + } + else { ReadType = EndElement; + } } -void Base::XMLReader::startCDATA () +void Base::XMLReader::startCDATA() { ReadType = StartCDATA; } -void Base::XMLReader::endCDATA () +void Base::XMLReader::endCDATA() { ReadType = EndCDATA; } -void Base::XMLReader::characters(const XMLCh* const chars, const XMLSize_t length) +void Base::XMLReader::characters(const XMLCh* const chars, const XMLSize_t length) { Characters = StrX(chars).c_str(); ReadType = Chars; CharacterCount += length; } -void Base::XMLReader::ignorableWhitespace( const XMLCh* const /*chars*/, const XMLSize_t /*length*/) +void Base::XMLReader::ignorableWhitespace(const XMLCh* const /*chars*/, const XMLSize_t /*length*/) { - //fSpaceCount += length; + // fSpaceCount += length; } void Base::XMLReader::resetDocument() { - //fAttrCount = 0; - //fCharacterCount = 0; - //fElementCount = 0; - //fSpaceCount = 0; + // fAttrCount = 0; + // fCharacterCount = 0; + // fElementCount = 0; + // fSpaceCount = 0; } @@ -580,9 +600,8 @@ void Base::XMLReader::error(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseExcepti { // print some details to error output and throw an // exception to abort the parsing - cerr << "Error at file " << StrX(e.getSystemId()) - << ", line " << e.getLineNumber() - << ", char " << e.getColumnNumber() << endl; + cerr << "Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " + << e.getColumnNumber() << endl; throw e; } @@ -590,8 +609,7 @@ void Base::XMLReader::fatalError(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseEx { // print some details to error output and throw an // exception to abort the parsing - cerr << "Fatal Error at file " << StrX(e.getSystemId()) - << ", line " << e.getLineNumber() + cerr << "Fatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << endl; throw e; } @@ -600,15 +618,13 @@ void Base::XMLReader::warning(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseExcep { // print some details to error output and throw an // exception to abort the parsing - cerr << "Warning at file " << StrX(e.getSystemId()) - << ", line " << e.getLineNumber() - << ", char " << e.getColumnNumber() << endl; - throw e; + cerr << "Warning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() + << ", char " << e.getColumnNumber() << endl; + throw e; } void Base::XMLReader::resetErrors() -{ -} +{} bool Base::XMLReader::testStatus(ReaderStatus pos) const { @@ -648,10 +664,13 @@ void Base::XMLReader::clearPartialRestoreObject() // ---------------------------------------------------------- +// NOLINTNEXTLINE Base::Reader::Reader(std::istream& str, const std::string& name, int version) - : std::istream(str.rdbuf()), _str(str), _name(name), fileVersion(version) -{ -} + : std::istream(str.rdbuf()) + , _str(str) + , _name(name) + , fileVersion(version) +{} std::string Base::Reader::getFileName() const { @@ -675,5 +694,5 @@ void Base::Reader::initLocalReader(std::shared_ptr reader) std::shared_ptr Base::Reader::getLocalReader() const { - return(this->localreader); + return (this->localreader); } diff --git a/src/Base/Reader.h b/src/Base/Reader.h index 2f8ed00b93..bab60fa008 100644 --- a/src/Base/Reader.h +++ b/src/Base/Reader.h @@ -38,13 +38,14 @@ #include "FileInfo.h" -namespace zipios { +namespace zipios +{ class ZipInputStream; } XERCES_CPP_NAMESPACE_BEGIN - class DefaultHandler; - class SAX2XMLReader; +class DefaultHandler; +class SAX2XMLReader; XERCES_CPP_NAMESPACE_END namespace Base @@ -88,9 +89,9 @@ void PropertyContainer::Save (short indent,std::ostream &str) std::map::iterator it; for(it = Map.begin(); it != Map.end(); ++it) { - str << ind(indent+1) << "first << "\" type=\"" << it->second->getTypeId().getName() << "\">" ; - it->second->Save(indent+2,str); - str << "" << endl; + str << ind(indent+1) << "first << "\" type=\"" << +it->second->getTypeId().getName() << "\">" ; it->second->Save(indent+2,str); str << "" << +endl; } str << ind(indent) << "" << endl; } @@ -116,14 +117,17 @@ void PropertyContainer::Restore(Base::Reader &reader) * \see Base::Persistence * \author Juergen Riegel */ -class BaseExport XMLReader : public XERCES_CPP_NAMESPACE_QUALIFIER DefaultHandler +class BaseExport XMLReader: public XERCES_CPP_NAMESPACE_QUALIFIER DefaultHandler { public: - enum ReaderStatus { - PartialRestore = 0, // This bit indicates that a partial restore took place somewhere in this Document - PartialRestoreInDocumentObject = 1, // This bit is local to the DocumentObject being read indicating a partial restore therein - PartialRestoreInProperty = 2, // Local to the Property - PartialRestoreInObject = 3 // Local to the object partially restored itself + enum ReaderStatus + { + PartialRestore = + 0, // This bit indicates that a partial restore took place somewhere in this Document + PartialRestoreInDocumentObject = 1, // This bit is local to the DocumentObject being read + // indicating a partial restore therein + PartialRestoreInProperty = 2, // Local to the Property + PartialRestoreInObject = 3 // Local to the object partially restored itself }; /// open the file and read the first element XMLReader(const char* FileName, std::istream&); @@ -136,9 +140,18 @@ public: std::streamsize read(char_type* s, std::streamsize n); //@} - bool isValid() const { return _valid; } - bool isVerbose() const { return _verbose; } - void setVerbose(bool on) { _verbose = on; } + bool isValid() const + { + return _valid; + } + bool isVerbose() const + { + return _verbose; + } + void setVerbose(bool on) + { + _verbose = on; + } /** @name Parser handling */ //@{ @@ -156,8 +169,9 @@ public: /// return true if the end of the document is reached, false otherwise bool isEndOfDocument() const; - /// read until a start element is found (\) or start-end element (\) (with special name if given) - void readElement (const char* ElementName=nullptr); + /// read until a start element is found (\) or start-end element (\) (with + /// special name if given) + void readElement(const char* ElementName = nullptr); /// Read in the next element. Return true if it succeeded and false otherwise bool readNextElement(); @@ -176,7 +190,7 @@ public: * child element may have the same name as its parent, otherwise, using \c * ElementName is enough. */ - void readEndElement(const char* ElementName=nullptr, int level=-1); + void readEndElement(const char* ElementName = nullptr, int level = -1); /// read until characters are found void readCharacters(const char* filename, CharStreamFormat format = CharStreamFormat::Raw); @@ -186,11 +200,11 @@ public: * auto destroyed when you call with readElement() or readEndElement(), or * you can end it explicitly with endCharStream(). */ - std::istream &beginCharStream(CharStreamFormat format = CharStreamFormat::Raw); + std::istream& beginCharStream(CharStreamFormat format = CharStreamFormat::Raw); /// Manually end the current character stream void endCharStream(); /// Obtain the current character stream - std::istream &charStream(); + std::istream& charStream(); //@} /// read binary file @@ -215,23 +229,23 @@ public: /** @name additional file reading */ //@{ /// add a read request of a persistent object - const char *addFile(const char* Name, Base::Persistence *Object); + const char* addFile(const char* Name, Base::Persistence* Object); /// process the requested file writes - void readFiles(zipios::ZipInputStream &zipstream) const; + void readFiles(zipios::ZipInputStream& zipstream) const; /// get all registered file names const std::vector& getFilenames() const; - bool isRegistered(Base::Persistence *Object) const; + bool isRegistered(Base::Persistence* Object) const; virtual void addName(const char*, const char*); virtual const char* getName(const char*) const; virtual bool doNameMapping() const; //@} /// Schema Version of the document - int DocumentSchema{0}; + int DocumentSchema {0}; /// Version of FreeCAD that wrote this document std::string ProgramVersion; /// Version of the file format - int FileVersion{0}; + int FileVersion {0}; /// sets simultaneously the global and local PartialRestore bits void setPartialRestore(bool on); @@ -256,16 +270,21 @@ protected: //@{ void startDocument() override; void endDocument() override; - void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) override; - void endElement (const XMLCh* const uri, const XMLCh *const localname, const XMLCh *const qname) override; - void characters (const XMLCh* const chars, const XMLSize_t length) override; + void startElement(const XMLCh* const uri, + const XMLCh* const localname, + const XMLCh* const qname, + const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) override; + void endElement(const XMLCh* const uri, + const XMLCh* const localname, + const XMLCh* const qname) override; + void characters(const XMLCh* const chars, const XMLSize_t length) override; void ignorableWhitespace(const XMLCh* const chars, const XMLSize_t length) override; //@} /** @name Lexical handler */ //@{ - void startCDATA () override; - void endCDATA () override; + void startCDATA() override; + void endCDATA() override; //@} /** @name Document handler */ @@ -286,16 +305,17 @@ protected: //@} private: - int Level{0}; + int Level {0}; std::string LocalName; std::string Characters; - unsigned int CharacterCount{0}; - std::streamsize CharacterOffset{-1}; + unsigned int CharacterCount {0}; + std::streamsize CharacterOffset {-1}; - std::map AttrMap; - using AttrMapType = std::map; + std::map AttrMap; + using AttrMapType = std::map; - enum { + enum + { None = 0, Chars, StartDocument, @@ -305,18 +325,19 @@ private: EndElement, StartCDATA, EndCDATA - } ReadType{None}; + } ReadType {None}; FileInfo _File; XERCES_CPP_NAMESPACE_QUALIFIER SAX2XMLReader* parser; XERCES_CPP_NAMESPACE_QUALIFIER XMLPScanToken token; - bool _valid{false}; - bool _verbose{true}; + bool _valid {false}; + bool _verbose {true}; - struct FileEntry { + struct FileEntry + { std::string FileName; - Base::Persistence *Object; + Base::Persistence* Object; }; std::vector FileList; std::vector FileNames; @@ -326,7 +347,7 @@ private: std::unique_ptr CharStream; }; -class BaseExport Reader : public std::istream +class BaseExport Reader: public std::istream { public: Reader(std::istream&, const std::string&, int version); @@ -343,7 +364,7 @@ private: std::shared_ptr localreader; }; -} +} // namespace Base #endif diff --git a/src/Base/Rotation.cpp b/src/Base/Rotation.cpp index e7a6d40890..b8f7516efc 100644 --- a/src/Base/Rotation.cpp +++ b/src/Base/Rotation.cpp @@ -35,11 +35,10 @@ using namespace Base; Rotation::Rotation() - : quat{0.0,0.0,0.0,1.0} - , _axis{0.0,0.0,1.0} - , _angle{0.0} -{ -} + : quat {0.0, 0.0, 0.0, 1.0} + , _axis {0.0, 0.0, 1.0} + , _angle {0.0} +{} /** Construct a rotation by rotation axis and angle */ Rotation::Rotation(const Vector3d& axis, const double fAngle) @@ -76,7 +75,7 @@ Rotation::Rotation(const double q0, const double q1, const double q2, const doub this->setValue(q0, q1, q2, q3); } -Rotation::Rotation(const Vector3d & rotateFrom, const Vector3d & rotateTo) +Rotation::Rotation(const Vector3d& rotateFrom, const Vector3d& rotateTo) : Rotation() { this->setValue(rotateFrom, rotateTo); @@ -93,10 +92,10 @@ Rotation::Rotation(const Rotation& rot) this->_axis[0] = rot._axis[0]; this->_axis[1] = rot._axis[1]; this->_axis[2] = rot._axis[2]; - this->_angle = rot._angle; + this->_angle = rot._angle; } -void Rotation::operator = (const Rotation& rot) +void Rotation::operator=(const Rotation& rot) { this->quat[0] = rot.quat[0]; this->quat[1] = rot.quat[1]; @@ -106,15 +105,15 @@ void Rotation::operator = (const Rotation& rot) this->_axis[0] = rot._axis[0]; this->_axis[1] = rot._axis[1]; this->_axis[2] = rot._axis[2]; - this->_angle = rot._angle; + this->_angle = rot._angle; } -const double * Rotation::getValue() const +const double* Rotation::getValue() const { return &this->quat[0]; } -void Rotation::getValue(double & q0, double & q1, double & q2, double & q3) const +void Rotation::getValue(double& q0, double& q1, double& q2, double& q3) const { q0 = this->quat[0]; q1 = this->quat[1]; @@ -132,7 +131,9 @@ void Rotation::evaluateVector() double scale = sin(rfAngle / 2.0); // Get a normalized vector double l = this->_axis.Length(); - if (l < Base::Vector3d::epsilon()) l = 1; + if (l < Base::Vector3d::epsilon()) { + l = 1; + } this->_axis.x = this->quat[0] * l / scale; this->_axis.y = this->quat[1] * l / scale; this->_axis.z = this->quat[2] * l / scale; @@ -155,7 +156,7 @@ void Rotation::setValue(const double q0, const double q1, const double q2, const this->evaluateVector(); } -void Rotation::getValue(Vector3d & axis, double & rfAngle) const +void Rotation::getValue(Vector3d& axis, double& rfAngle) const { rfAngle = _angle; axis.x = _axis.x; @@ -164,7 +165,7 @@ void Rotation::getValue(Vector3d & axis, double & rfAngle) const axis.Normalize(); } -void Rotation::getRawValue(Vector3d & axis, double & rfAngle) const +void Rotation::getRawValue(Vector3d& axis, double& rfAngle) const { rfAngle = _angle; axis.x = _axis.x; @@ -175,32 +176,30 @@ void Rotation::getRawValue(Vector3d & axis, double & rfAngle) const /** * Returns this rotation in form of a matrix. */ -void Rotation::getValue(Matrix4D & matrix) const +void Rotation::getValue(Matrix4D& matrix) const { // Taken from // - const double l = sqrt(this->quat[0] * this->quat[0] + - this->quat[1] * this->quat[1] + - this->quat[2] * this->quat[2] + - this->quat[3] * this->quat[3]); + const double l = sqrt(this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] + + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]); const double x = this->quat[0] / l; const double y = this->quat[1] / l; const double z = this->quat[2] / l; const double w = this->quat[3] / l; - matrix[0][0] = 1.0-2.0*(y*y+z*z); - matrix[0][1] = 2.0*(x*y-z*w); - matrix[0][2] = 2.0*(x*z+y*w); + matrix[0][0] = 1.0 - 2.0 * (y * y + z * z); + matrix[0][1] = 2.0 * (x * y - z * w); + matrix[0][2] = 2.0 * (x * z + y * w); matrix[0][3] = 0.0; - matrix[1][0] = 2.0*(x*y+z*w); - matrix[1][1] = 1.0-2.0*(x*x+z*z); - matrix[1][2] = 2.0*(y*z-x*w); + matrix[1][0] = 2.0 * (x * y + z * w); + matrix[1][1] = 1.0 - 2.0 * (x * x + z * z); + matrix[1][2] = 2.0 * (y * z - x * w); matrix[1][3] = 0.0; - matrix[2][0] = 2.0*(x*z-y*w); - matrix[2][1] = 2.0*(y*z+x*w); - matrix[2][2] = 1.0-2.0*(x*x+y*y); + matrix[2][0] = 2.0 * (x * z - y * w); + matrix[2][1] = 2.0 * (y * z + x * w); + matrix[2][2] = 1.0 - 2.0 * (x * x + y * y); matrix[2][3] = 0.0; matrix[3][0] = 0.0; @@ -219,14 +218,14 @@ void Rotation::setValue(const double q[4]) this->evaluateVector(); } -void Rotation::setValue(const Matrix4D & m) +void Rotation::setValue(const Matrix4D& m) { // Get the rotation part matrix Matrix4D mc = m.decompose()[2]; // Extract quaternion double trace = (mc[0][0] + mc[1][1] + mc[2][2]); if (trace > 0.0) { - double s = sqrt(1.0+trace); + double s = sqrt(1.0 + trace); this->quat[3] = 0.5 * s; s = 0.5 / s; this->quat[0] = ((mc[2][1] - mc[1][2]) * s); @@ -238,11 +237,15 @@ void Rotation::setValue(const Matrix4D & m) // // Get the max. element of the trace unsigned short i = 0; - if (mc[1][1] > mc[0][0]) i = 1; - if (mc[2][2] > mc[i][i]) i = 2; + if (mc[1][1] > mc[0][0]) { + i = 1; + } + if (mc[2][2] > mc[i][i]) { + i = 2; + } - unsigned short j = (i+1)%3; - unsigned short k = (i+2)%3; + unsigned short j = (i + 1) % 3; + unsigned short k = (i + 2) % 3; double s = sqrt((mc[i][i] - (mc[j][j] + mc[k][k])) + 1.0); this->quat[i] = s * 0.5; @@ -255,14 +258,14 @@ void Rotation::setValue(const Matrix4D & m) this->evaluateVector(); } -void Rotation::setValue(const Vector3d & axis, const double fAngle) +void Rotation::setValue(const Vector3d& axis, const double fAngle) { // Taken from // // normalization of the angle to be in [0, 2pi[ _angle = fAngle; - double theAngle = fAngle - floor(fAngle / (2.0 * D_PI))*(2.0 * D_PI); - this->quat[3] = cos(theAngle/2.0); + double theAngle = fAngle - floor(fAngle / (2.0 * D_PI)) * (2.0 * D_PI); + this->quat[3] = cos(theAngle / 2.0); Vector3d norm = axis; norm.Normalize(); @@ -276,23 +279,26 @@ void Rotation::setValue(const Vector3d & axis, const double fAngle) norm.Normalize(); } - double scale = sin(theAngle/2.0); + double scale = sin(theAngle / 2.0); this->quat[0] = norm.x * scale; this->quat[1] = norm.y * scale; this->quat[2] = norm.z * scale; } -void Rotation::setValue(const Vector3d & rotateFrom, const Vector3d & rotateTo) +void Rotation::setValue(const Vector3d& rotateFrom, const Vector3d& rotateTo) { - Vector3d u(rotateFrom); u.Normalize(); - Vector3d v(rotateTo); v.Normalize(); + Vector3d u(rotateFrom); + u.Normalize(); + Vector3d v(rotateTo); + v.Normalize(); - // The vector from x to is the rotation axis because it's the normal of the plane defined by (0,u,v) + // The vector from x to is the rotation axis because it's the normal of the plane defined by + // (0,u,v) const double dot = u * v; Vector3d w = u % v; const double wlen = w.Length(); - if (wlen == 0.0) { // Parallel vectors + if (wlen == 0.0) { // Parallel vectors // Check if they are pointing in the same direction. if (dot > 0.0) { this->setValue(0.0, 0.0, 0.0, 1.0); @@ -300,14 +306,16 @@ void Rotation::setValue(const Vector3d & rotateFrom, const Vector3d & rotateTo) else { // We can use any axis perpendicular to u (and v) Vector3d t = u % Vector3d(1.0, 0.0, 0.0); - if (t.Length() < Base::Vector3d::epsilon()) + if (t.Length() < Base::Vector3d::epsilon()) { t = u % Vector3d(0.0, 1.0, 0.0); + } this->setValue(t.x, t.y, t.z, 0.0); } } - else { // Vectors are not parallel + else { // Vectors are not parallel // Note: A quaternion is not well-defined by specifying a point and its transformed point. - // Every quaternion with a rotation axis having the same angle to the vectors of both points is okay. + // Every quaternion with a rotation axis having the same angle to the vectors of both points + // is okay. double angle = acos(dot); this->setValue(w, angle); } @@ -315,10 +323,8 @@ void Rotation::setValue(const Vector3d & rotateFrom, const Vector3d & rotateTo) void Rotation::normalize() { - double len = sqrt(this->quat[0]*this->quat[0]+ - this->quat[1]*this->quat[1]+ - this->quat[2]*this->quat[2]+ - this->quat[3]*this->quat[3]); + double len = sqrt(this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] + + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]); if (len > 0.0) { this->quat[0] /= len; this->quat[1] /= len; @@ -327,7 +333,7 @@ void Rotation::normalize() } } -Rotation & Rotation::invert() +Rotation& Rotation::invert() { this->quat[0] = -this->quat[0]; this->quat[1] = -this->quat[1]; @@ -346,7 +352,7 @@ Rotation Rotation::inverse() const rot.quat[0] = -this->quat[0]; rot.quat[1] = -this->quat[1]; rot.quat[2] = -this->quat[2]; - rot.quat[3] = this->quat[3]; + rot.quat[3] = this->quat[3]; rot._axis[0] = -this->_axis[0]; rot._axis[1] = -this->_axis[1]; @@ -361,12 +367,12 @@ Rotation Rotation::inverse() const \sa multRight() */ -Rotation & Rotation::operator*=(const Rotation & q) +Rotation& Rotation::operator*=(const Rotation& q) { return multRight(q); } -Rotation Rotation::operator*(const Rotation & q) const +Rotation Rotation::operator*(const Rotation& q) const { Rotation quat(*this); quat *= q; @@ -382,15 +388,15 @@ Rotation Rotation::operator*(const Rotation & q) const Rotation& Rotation::multRight(const Base::Rotation& q) { // Taken from - double x0{}, y0{}, z0{}, w0{}; + double x0 {}, y0 {}, z0 {}, w0 {}; this->getValue(x0, y0, z0, w0); - double x1{}, y1{}, z1{}, w1{}; + double x1 {}, y1 {}, z1 {}, w1 {}; q.getValue(x1, y1, z1, w1); - this->setValue(w0*x1 + x0*w1 + y0*z1 - z0*y1, - w0*y1 - x0*z1 + y0*w1 + z0*x1, - w0*z1 + x0*y1 - y0*x1 + z0*w1, - w0*w1 - x0*x1 - y0*y1 - z0*z1); + this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, + w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, + w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, + w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1); return *this; } @@ -403,45 +409,42 @@ Rotation& Rotation::multRight(const Base::Rotation& q) Rotation& Rotation::multLeft(const Base::Rotation& q) { // Taken from - double x0{}, y0{}, z0{}, w0{}; + double x0 {}, y0 {}, z0 {}, w0 {}; q.getValue(x0, y0, z0, w0); - double x1{}, y1{}, z1{}, w1{}; + double x1 {}, y1 {}, z1 {}, w1 {}; this->getValue(x1, y1, z1, w1); - this->setValue(w0*x1 + x0*w1 + y0*z1 - z0*y1, - w0*y1 - x0*z1 + y0*w1 + z0*x1, - w0*z1 + x0*y1 - y0*x1 + z0*w1, - w0*w1 - x0*x1 - y0*y1 - z0*z1); + this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, + w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, + w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, + w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1); return *this; } -bool Rotation::operator==(const Rotation & q) const +bool Rotation::operator==(const Rotation& q) const { - if ((this->quat[0] == q.quat[0] && - this->quat[1] == q.quat[1] && - this->quat[2] == q.quat[2] && - this->quat[3] == q.quat[3]) || - (this->quat[0] == -q.quat[0] && - this->quat[1] == -q.quat[1] && - this->quat[2] == -q.quat[2] && - this->quat[3] == -q.quat[3])) + if ((this->quat[0] == q.quat[0] && this->quat[1] == q.quat[1] && this->quat[2] == q.quat[2] + && this->quat[3] == q.quat[3]) + || (this->quat[0] == -q.quat[0] && this->quat[1] == -q.quat[1] + && this->quat[2] == -q.quat[2] && this->quat[3] == -q.quat[3])) { return true; + } return false; } -bool Rotation::operator!=(const Rotation & q) const +bool Rotation::operator!=(const Rotation& q) const { return !(*this == q); } -Vector3d Rotation::multVec(const Vector3d & src) const +Vector3d Rotation::multVec(const Vector3d& src) const { Vector3d dst; - multVec(src,dst); + multVec(src, dst); return dst; } -void Rotation::multVec(const Vector3d & src, Vector3d & dst) const +void Rotation::multVec(const Vector3d& src, Vector3d& dst) const { double x = this->quat[0]; double y = this->quat[1]; @@ -452,46 +455,54 @@ void Rotation::multVec(const Vector3d & src, Vector3d & dst) const double z2 = z * z; double w2 = w * w; - double dx = (x2+w2-y2-z2)*src.x + 2.0*(x*y-z*w)*src.y + 2.0*(x*z+y*w)*src.z; - double dy = 2.0*(x*y+z*w)*src.x + (w2-x2+y2-z2)*src.y + 2.0*(y*z-x*w)*src.z; - double dz = 2.0*(x*z-y*w)*src.x + 2.0*(x*w+y*z)*src.y + (w2-x2-y2+z2)*src.z; + double dx = + (x2 + w2 - y2 - z2) * src.x + 2.0 * (x * y - z * w) * src.y + 2.0 * (x * z + y * w) * src.z; + double dy = + 2.0 * (x * y + z * w) * src.x + (w2 - x2 + y2 - z2) * src.y + 2.0 * (y * z - x * w) * src.z; + double dz = + 2.0 * (x * z - y * w) * src.x + 2.0 * (x * w + y * z) * src.y + (w2 - x2 - y2 + z2) * src.z; dst.x = dx; dst.y = dy; dst.z = dz; } -void Rotation::multVec(const Vector3f & src, Vector3f & dst) const +void Rotation::multVec(const Vector3f& src, Vector3f& dst) const { Base::Vector3d srcd = Base::toVector(src); multVec(srcd, srcd); dst = Base::toVector(srcd); } -Vector3f Rotation::multVec(const Vector3f & src) const +Vector3f Rotation::multVec(const Vector3f& src) const { Vector3f dst; - multVec(src,dst); + multVec(src, dst); return dst; } void Rotation::scaleAngle(const double scaleFactor) { Vector3d axis; - double fAngle{}; + double fAngle {}; this->getValue(axis, fAngle); this->setValue(axis, fAngle * scaleFactor); } -Rotation Rotation::slerp(const Rotation & q0, const Rotation & q1, double t) +Rotation Rotation::slerp(const Rotation& q0, const Rotation& q1, double t) { // Taken from - if (t<0.0) t=0.0; - else if (t>1.0) t=1.0; + if (t < 0.0) { + t = 0.0; + } + else if (t > 1.0) { + t = 1.0; + } double scale0 = 1.0 - t; double scale1 = t; - double dot = q0.quat[0]*q1.quat[0]+q0.quat[1]*q1.quat[1]+q0.quat[2]*q1.quat[2]+q0.quat[3]*q1.quat[3]; - bool neg=false; + double dot = q0.quat[0] * q1.quat[0] + q0.quat[1] * q1.quat[1] + q0.quat[2] * q1.quat[2] + + q0.quat[3] * q1.quat[3]; + bool neg = false; if (dot < 0.0) { dot = -dot; neg = true; @@ -507,8 +518,9 @@ Rotation Rotation::slerp(const Rotation & q0, const Rotation & q1, double t) } } - if (neg) + if (neg) { scale1 = -scale1; + } double x = scale0 * q0.quat[0] + scale1 * q1.quat[0]; double y = scale0 * q0.quat[1] + scale1 * q1.quat[1]; @@ -522,142 +534,158 @@ Rotation Rotation::identity() return {0.0, 0.0, 0.0, 1.0}; } -Rotation Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder) +Rotation +Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder) { const double tol = Precision::Confusion(); - enum dirIndex { + enum dirIndex + { X, Y, Z }; - //convert priorityOrder string into a sequence of ints. - if (strlen(priorityOrder)!=3) + // convert priorityOrder string into a sequence of ints. + if (strlen(priorityOrder) != 3) { THROWM(ValueError, "makeRotationByAxes: length of priorityOrder is not 3"); + } int order[3]; - for (int i = 0; i < 3; ++i){ + for (int i = 0; i < 3; ++i) { order[i] = priorityOrder[i] - 'X'; - if (order[i] < 0 || order[i] > 2) - THROWM(ValueError, "makeRotationByAxes: characters in priorityOrder must be uppercase X, Y, or Z. Some other character encountered.") + if (order[i] < 0 || order[i] > 2) { + THROWM(ValueError, + "makeRotationByAxes: characters in priorityOrder must be uppercase X, Y, or Z. " + "Some other character encountered.") + } } - //ensure every axis is listed in priority list - if( order[0] == order[1] || - order[1] == order[2] || - order[2] == order[0]) - THROWM(ValueError,"makeRotationByAxes: not all axes are listed in priorityOrder"); + // ensure every axis is listed in priority list + if (order[0] == order[1] || order[1] == order[2] || order[2] == order[0]) { + THROWM(ValueError, "makeRotationByAxes: not all axes are listed in priorityOrder"); + } - //group up dirs into an array, to access them by indexes stored in @order. + // group up dirs into an array, to access them by indexes stored in @order. std::vector dirs = {&xdir, &ydir, &zdir}; - auto dropPriority = [&order](int index){ - int tmp{}; - if (index == 0){ + auto dropPriority = [&order](int index) { + int tmp {}; + if (index == 0) { tmp = order[0]; order[0] = order[1]; order[1] = order[2]; order[2] = tmp; - } else if (index == 1) { + } + else if (index == 1) { tmp = order[1]; order[1] = order[2]; order[2] = tmp; - } //else if index == 2 do nothing + } // else if index == 2 do nothing }; - //pick up the strict direction + // pick up the strict direction Vector3d mainDir; - for (int i = 0; i < 3; ++i){ + for (int i = 0; i < 3; ++i) { mainDir = *(dirs[size_t(order[0])]); - if (mainDir.Length() > tol) + if (mainDir.Length() > tol) { break; - else + } + else { dropPriority(0); - if (i == 2) + } + if (i == 2) { THROWM(ValueError, "makeRotationByAxes: all directions supplied are zero"); + } } mainDir.Normalize(); - //pick up the 2nd priority direction, "hint" direction. + // pick up the 2nd priority direction, "hint" direction. Vector3d hintDir; - for (int i = 0; i < 2; ++i){ + for (int i = 0; i < 2; ++i) { hintDir = *(dirs[size_t(order[1])]); - if ((hintDir.Cross(mainDir)).Length() > tol) + if ((hintDir.Cross(mainDir)).Length() > tol) { break; - else + } + else { dropPriority(1); - if (i == 1) - hintDir = Vector3d(); //no vector can be used as hint direction. Zero it out, to indicate that a guess is needed. + } + if (i == 1) { + hintDir = Vector3d(); // no vector can be used as hint direction. Zero it out, to + // indicate that a guess is needed. + } } - if (hintDir.Length() == 0.0){ - switch (order[0]){ - case X: { //xdir is main - //align zdir to OZ - order[1] = Z; - order[2] = Y; - hintDir = Vector3d(0,0,1); - if ((hintDir.Cross(mainDir)).Length() <= tol){ - //aligning to OZ is impossible, align to ydir to OY. Why so? I don't know, just feels right =) - hintDir = Vector3d(0,1,0); - order[1] = Y; - order[2] = Z; - } - } break; - case Y: { //ydir is main - //align zdir to OZ - order[1] = Z; - order[2] = X; - hintDir = mainDir.z > -tol ? Vector3d(0,0,1) : Vector3d(0,0,-1); - if ((hintDir.Cross(mainDir)).Length() <= tol){ - //aligning zdir to OZ is impossible, align xdir to OX then. - hintDir = Vector3d(1,0,0); - order[1] = X; - order[2] = Z; - } - } break; - case Z: { //zdir is main - //align ydir to OZ - order[1] = Y; - order[2] = X; - hintDir = Vector3d(0,0,1); - if ((hintDir.Cross(mainDir)).Length() <= tol){ - //aligning ydir to OZ is impossible, align xdir to OX then. - hintDir = Vector3d(1,0,0); - order[1] = X; + if (hintDir.Length() == 0.0) { + switch (order[0]) { + case X: { // xdir is main + // align zdir to OZ + order[1] = Z; order[2] = Y; - } - } break; - }//switch ordet[0] + hintDir = Vector3d(0, 0, 1); + if ((hintDir.Cross(mainDir)).Length() <= tol) { + // aligning to OZ is impossible, align to ydir to OY. Why so? I don't know, just + // feels right =) + hintDir = Vector3d(0, 1, 0); + order[1] = Y; + order[2] = Z; + } + } break; + case Y: { // ydir is main + // align zdir to OZ + order[1] = Z; + order[2] = X; + hintDir = mainDir.z > -tol ? Vector3d(0, 0, 1) : Vector3d(0, 0, -1); + if ((hintDir.Cross(mainDir)).Length() <= tol) { + // aligning zdir to OZ is impossible, align xdir to OX then. + hintDir = Vector3d(1, 0, 0); + order[1] = X; + order[2] = Z; + } + } break; + case Z: { // zdir is main + // align ydir to OZ + order[1] = Y; + order[2] = X; + hintDir = Vector3d(0, 0, 1); + if ((hintDir.Cross(mainDir)).Length() <= tol) { + // aligning ydir to OZ is impossible, align xdir to OX then. + hintDir = Vector3d(1, 0, 0); + order[1] = X; + order[2] = Y; + } + } break; + } // switch ordet[0] } - //ensure every axis is listed in priority list + // ensure every axis is listed in priority list assert(order[0] != order[1]); assert(order[1] != order[2]); assert(order[2] != order[0]); hintDir.Normalize(); - //make hintDir perpendicular to mainDir. For that, we cross-product the two to obtain the third axis direction, and then recover back the hint axis by doing another cross product. + // make hintDir perpendicular to mainDir. For that, we cross-product the two to obtain the third + // axis direction, and then recover back the hint axis by doing another cross product. Vector3d lastDir = mainDir.Cross(hintDir); lastDir.Normalize(); hintDir = lastDir.Cross(mainDir); - hintDir.Normalize(); //redundant? + hintDir.Normalize(); // redundant? Vector3d finaldirs[3]; finaldirs[order[0]] = mainDir; finaldirs[order[1]] = hintDir; finaldirs[order[2]] = lastDir; - //fix handedness - if (finaldirs[X].Cross(finaldirs[Y]) * finaldirs[Z] < 0.0) - //handedness is wrong. Switch the direction of the least important axis + // fix handedness + if (finaldirs[X].Cross(finaldirs[Y]) * finaldirs[Z] < 0.0) { + // handedness is wrong. Switch the direction of the least important axis finaldirs[order[2]] = finaldirs[order[2]] * (-1.0); + } - //build the rotation, by constructing a matrix first. + // build the rotation, by constructing a matrix first. Matrix4D m; m.setToUnity(); - for (int i = 0; i < 3; ++i){ - //matrix indexing: [row][col] + for (int i = 0; i < 3; ++i) { + // matrix indexing: [row][col] m[0][i] = finaldirs[i].x; m[1][i] = finaldirs[i].y; m[2][i] = finaldirs[i].z; @@ -670,75 +698,71 @@ void Rotation::setYawPitchRoll(double y, double p, double r) { // The Euler angles (yaw,pitch,roll) are in XY'Z''-notation // convert to radians - y = (y/180.0)*D_PI; - p = (p/180.0)*D_PI; - r = (r/180.0)*D_PI; + y = (y / 180.0) * D_PI; + p = (p / 180.0) * D_PI; + r = (r / 180.0) * D_PI; - double c1 = cos(y/2.0); - double s1 = sin(y/2.0); - double c2 = cos(p/2.0); - double s2 = sin(p/2.0); - double c3 = cos(r/2.0); - double s3 = sin(r/2.0); + double c1 = cos(y / 2.0); + double s1 = sin(y / 2.0); + double c2 = cos(p / 2.0); + double s2 = sin(p / 2.0); + double c3 = cos(r / 2.0); + double s3 = sin(r / 2.0); - this->setValue ( - c1*c2*s3 - s1*s2*c3, - c1*s2*c3 + s1*c2*s3, - s1*c2*c3 - c1*s2*s3, - c1*c2*c3 + s1*s2*s3 - ); + this->setValue(c1 * c2 * s3 - s1 * s2 * c3, + c1 * s2 * c3 + s1 * c2 * s3, + s1 * c2 * c3 - c1 * s2 * s3, + c1 * c2 * c3 + s1 * s2 * s3); } void Rotation::getYawPitchRoll(double& y, double& p, double& r) const { - double q00 = quat[0]*quat[0]; - double q11 = quat[1]*quat[1]; - double q22 = quat[2]*quat[2]; - double q33 = quat[3]*quat[3]; - double q01 = quat[0]*quat[1]; - double q02 = quat[0]*quat[2]; - double q03 = quat[0]*quat[3]; - double q12 = quat[1]*quat[2]; - double q13 = quat[1]*quat[3]; - double q23 = quat[2]*quat[3]; - double qd2 = 2.0*(q13-q02); + double q00 = quat[0] * quat[0]; + double q11 = quat[1] * quat[1]; + double q22 = quat[2] * quat[2]; + double q33 = quat[3] * quat[3]; + double q01 = quat[0] * quat[1]; + double q02 = quat[0] * quat[2]; + double q03 = quat[0] * quat[3]; + double q12 = quat[1] * quat[2]; + double q13 = quat[1] * quat[3]; + double q23 = quat[2] * quat[3]; + double qd2 = 2.0 * (q13 - q02); // handle gimbal lock - if (fabs(qd2-1.0) <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" + if (fabs(qd2 - 1.0) <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" // north pole y = 0.0; - p = D_PI/2.0; - r = 2.0 * atan2(quat[0],quat[3]); + p = D_PI / 2.0; + r = 2.0 * atan2(quat[0], quat[3]); } - else if (fabs(qd2+1.0) <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" + else if (fabs(qd2 + 1.0) + <= 16 * DBL_EPSILON) { // Tolerance copied from OCC "gp_Quaternion.cxx" // south pole y = 0.0; - p = -D_PI/2.0; - r = 2.0 * atan2(quat[0],quat[3]); + p = -D_PI / 2.0; + r = 2.0 * atan2(quat[0], quat[3]); } else { - y = atan2(2.0*(q01+q23),(q00+q33)-(q11+q22)); - p = qd2 > 1.0 ? D_PI/2.0 : (qd2 < -1.0 ? -D_PI/2.0 : asin (qd2)); - r = atan2(2.0*(q12+q03),(q22+q33)-(q00+q11)); + y = atan2(2.0 * (q01 + q23), (q00 + q33) - (q11 + q22)); + p = qd2 > 1.0 ? D_PI / 2.0 : (qd2 < -1.0 ? -D_PI / 2.0 : asin(qd2)); + r = atan2(2.0 * (q12 + q03), (q22 + q33) - (q00 + q11)); } // convert to degree - y = (y/D_PI)*180; - p = (p/D_PI)*180; - r = (r/D_PI)*180; + y = (y / D_PI) * 180; + p = (p / D_PI) * 180; + r = (r / D_PI) * 180; } bool Rotation::isSame(const Rotation& q) const { - if ((this->quat[0] == q.quat[0] && - this->quat[1] == q.quat[1] && - this->quat[2] == q.quat[2] && - this->quat[3] == q.quat[3]) || - (this->quat[0] == -q.quat[0] && - this->quat[1] == -q.quat[1] && - this->quat[2] == -q.quat[2] && - this->quat[3] == -q.quat[3])) + if ((this->quat[0] == q.quat[0] && this->quat[1] == q.quat[1] && this->quat[2] == q.quat[2] + && this->quat[3] == q.quat[3]) + || (this->quat[0] == -q.quat[0] && this->quat[1] == -q.quat[1] + && this->quat[2] == -q.quat[2] && this->quat[3] == -q.quat[3])) { return true; + } return false; } @@ -753,17 +777,15 @@ bool Rotation::isSame(const Rotation& q, double tol) const // Is it safe to assume that? // Because a quaternion (x1,x2,x3,x4) is equal to (-x1,-x2,-x3,-x4) we use the // absolute value of the scalar product - double dot = q.quat[0]*quat[0]+q.quat[1]*quat[1]+q.quat[2]*quat[2]+q.quat[3]*quat[3]; - return fabs(dot) >= 1.0 - tol/2; + double dot = + q.quat[0] * quat[0] + q.quat[1] * quat[1] + q.quat[2] * quat[2] + q.quat[3] * quat[3]; + return fabs(dot) >= 1.0 - tol / 2; } bool Rotation::isIdentity() const { - return ((this->quat[0] == 0.0 && - this->quat[1] == 0.0 && - this->quat[2] == 0.0) && - (this->quat[3] == 1.0 || - this->quat[3] == -1.0)); + return ((this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0) + && (this->quat[3] == 1.0 || this->quat[3] == -1.0)); } bool Rotation::isIdentity(double tol) const @@ -773,20 +795,19 @@ bool Rotation::isIdentity(double tol) const bool Rotation::isNull() const { - return (this->quat[0] == 0.0 && - this->quat[1] == 0.0 && - this->quat[2] == 0.0 && - this->quat[3] == 0.0); + return (this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0 + && this->quat[3] == 0.0); } //======================================================================= // The following code is borrowed from OCCT gp/gp_Quaternion.cxx -namespace { // anonymous namespace +namespace +{ // anonymous namespace //======================================================================= -//function : translateEulerSequence -//purpose : -// Code supporting conversion between quaternion and generalized +// function : translateEulerSequence +// purpose : +// Code supporting conversion between quaternion and generalized // Euler angles (sequence of three rotations) is based on // algorithm by Ken Shoemake, published in Graphics Gems IV, p. 222-22 // http://tog.acm.org/resources/GraphicsGems/gemsiv/euler_angle/EulerAngles.c @@ -794,85 +815,109 @@ namespace { // anonymous namespace struct EulerSequence_Parameters { - int i; // first rotation axis - int j; // next axis of rotation - int k; // third axis - bool isOdd; // true if order of two first rotation axes is odd permutation, e.g. XZ - bool isTwoAxes; // true if third rotation is about the same axis as first - bool isExtrinsic; // true if rotations are made around fixed axes + int i; // first rotation axis + int j; // next axis of rotation + int k; // third axis + bool isOdd; // true if order of two first rotation axes is odd permutation, e.g. XZ + bool isTwoAxes; // true if third rotation is about the same axis as first + bool isExtrinsic; // true if rotations are made around fixed axes - EulerSequence_Parameters (int theAx1, - bool theisOdd, - bool theisTwoAxes, - bool theisExtrinsic) - : i(theAx1), - j(1 + (theAx1 + (theisOdd ? 1 : 0)) % 3), - k(1 + (theAx1 + (theisOdd ? 0 : 1)) % 3), - isOdd(theisOdd), - isTwoAxes(theisTwoAxes), - isExtrinsic(theisExtrinsic) - {} + EulerSequence_Parameters(int theAx1, bool theisOdd, bool theisTwoAxes, bool theisExtrinsic) + : i(theAx1) + , j(1 + (theAx1 + (theisOdd ? 1 : 0)) % 3) + , k(1 + (theAx1 + (theisOdd ? 0 : 1)) % 3) + , isOdd(theisOdd) + , isTwoAxes(theisTwoAxes) + , isExtrinsic(theisExtrinsic) + {} }; -EulerSequence_Parameters translateEulerSequence (const Rotation::EulerSequence theSeq) +EulerSequence_Parameters translateEulerSequence(const Rotation::EulerSequence theSeq) { const bool F = false; const bool T = true; - switch (theSeq) - { - case Rotation::Extrinsic_XYZ: return {1, F, F, T}; - case Rotation::Extrinsic_XZY: return {1, T, F, T}; - case Rotation::Extrinsic_YZX: return {2, F, F, T}; - case Rotation::Extrinsic_YXZ: return {2, T, F, T}; - case Rotation::Extrinsic_ZXY: return {3, F, F, T}; - case Rotation::Extrinsic_ZYX: return {3, T, F, T}; + switch (theSeq) { + case Rotation::Extrinsic_XYZ: + return {1, F, F, T}; + case Rotation::Extrinsic_XZY: + return {1, T, F, T}; + case Rotation::Extrinsic_YZX: + return {2, F, F, T}; + case Rotation::Extrinsic_YXZ: + return {2, T, F, T}; + case Rotation::Extrinsic_ZXY: + return {3, F, F, T}; + case Rotation::Extrinsic_ZYX: + return {3, T, F, T}; - // Conversion of intrinsic angles is made by the same code as for extrinsic, - // using equivalence rule: intrinsic rotation is equivalent to extrinsic - // rotation by the same angles but with inverted order of elemental rotations. - // Swapping of angles (Alpha <-> Gamma) is done inside conversion procedure; - // sequence of axes is inverted by setting appropriate parameters here. - // Note that proper Euler angles (last block below) are symmetric for sequence of axes. - case Rotation::Intrinsic_XYZ: return {3, T, F, F}; - case Rotation::Intrinsic_XZY: return {2, F, F, F}; - case Rotation::Intrinsic_YZX: return {1, T, F, F}; - case Rotation::Intrinsic_YXZ: return {3, F, F, F}; - case Rotation::Intrinsic_ZXY: return {2, T, F, F}; - case Rotation::Intrinsic_ZYX: return {1, F, F, F}; + // Conversion of intrinsic angles is made by the same code as for extrinsic, + // using equivalence rule: intrinsic rotation is equivalent to extrinsic + // rotation by the same angles but with inverted order of elemental rotations. + // Swapping of angles (Alpha <-> Gamma) is done inside conversion procedure; + // sequence of axes is inverted by setting appropriate parameters here. + // Note that proper Euler angles (last block below) are symmetric for sequence of axes. + case Rotation::Intrinsic_XYZ: + return {3, T, F, F}; + case Rotation::Intrinsic_XZY: + return {2, F, F, F}; + case Rotation::Intrinsic_YZX: + return {1, T, F, F}; + case Rotation::Intrinsic_YXZ: + return {3, F, F, F}; + case Rotation::Intrinsic_ZXY: + return {2, T, F, F}; + case Rotation::Intrinsic_ZYX: + return {1, F, F, F}; - case Rotation::Extrinsic_XYX: return {1, F, T, T}; - case Rotation::Extrinsic_XZX: return {1, T, T, T}; - case Rotation::Extrinsic_YZY: return {2, F, T, T}; - case Rotation::Extrinsic_YXY: return {2, T, T, T}; - case Rotation::Extrinsic_ZXZ: return {3, F, T, T}; - case Rotation::Extrinsic_ZYZ: return {3, T, T, T}; + case Rotation::Extrinsic_XYX: + return {1, F, T, T}; + case Rotation::Extrinsic_XZX: + return {1, T, T, T}; + case Rotation::Extrinsic_YZY: + return {2, F, T, T}; + case Rotation::Extrinsic_YXY: + return {2, T, T, T}; + case Rotation::Extrinsic_ZXZ: + return {3, F, T, T}; + case Rotation::Extrinsic_ZYZ: + return {3, T, T, T}; - case Rotation::Intrinsic_XYX: return {1, F, T, F}; - case Rotation::Intrinsic_XZX: return {1, T, T, F}; - case Rotation::Intrinsic_YZY: return {2, F, T, F}; - case Rotation::Intrinsic_YXY: return {2, T, T, F}; - case Rotation::Intrinsic_ZXZ: return {3, F, T, F}; - case Rotation::Intrinsic_ZYZ: return {3, T, T, F}; + case Rotation::Intrinsic_XYX: + return {1, F, T, F}; + case Rotation::Intrinsic_XZX: + return {1, T, T, F}; + case Rotation::Intrinsic_YZY: + return {2, F, T, F}; + case Rotation::Intrinsic_YXY: + return {2, T, T, F}; + case Rotation::Intrinsic_ZXZ: + return {3, F, T, F}; + case Rotation::Intrinsic_ZYZ: + return {3, T, T, F}; - default: - case Rotation::EulerAngles : return {3, F, T, F}; // = Intrinsic_ZXZ - case Rotation::YawPitchRoll: return {1, F, F, F}; // = Intrinsic_ZYX + default: + case Rotation::EulerAngles: + return {3, F, T, F}; // = Intrinsic_ZXZ + case Rotation::YawPitchRoll: + return {1, F, F, F}; // = Intrinsic_ZYX }; } -class Mat : public Base::Matrix4D +class Mat: public Base::Matrix4D { public: - double operator()(int i, int j) const { - return this->operator[](i-1)[j-1]; + double operator()(int i, int j) const + { + return this->operator[](i - 1)[j - 1]; } - double & operator()(int i, int j) { - return this->operator[](i-1)[j-1]; + double& operator()(int i, int j) + { + return this->operator[](i - 1)[j - 1]; } }; -const char *EulerSequenceNames[] = { +const char* EulerSequenceNames[] = { //! Classic Euler angles, alias to Intrinsic_ZXZ "Euler", @@ -910,21 +955,23 @@ const char *EulerSequenceNames[] = { "IZYZ", }; -} // anonymous namespace +} // anonymous namespace -const char * Rotation::eulerSequenceName(EulerSequence seq) +const char* Rotation::eulerSequenceName(EulerSequence seq) { - if (seq == Invalid || seq >= EulerSequenceLast) + if (seq == Invalid || seq >= EulerSequenceLast) { return nullptr; - return EulerSequenceNames[seq-1]; + } + return EulerSequenceNames[seq - 1]; } -Rotation::EulerSequence Rotation::eulerSequenceFromName(const char *name) +Rotation::EulerSequence Rotation::eulerSequenceFromName(const char* name) { if (name) { - for (unsigned i=0; i(i+1); + for (unsigned i = 0; i < sizeof(EulerSequenceNames) / sizeof(EulerSequenceNames[0]); ++i) { + if (boost::iequals(name, EulerSequenceNames[i])) { + return static_cast(i + 1); + } } } return Invalid; @@ -935,53 +982,55 @@ void Rotation::setEulerAngles(EulerSequence theOrder, double theBeta, double theGamma) { - if (theOrder == Invalid || theOrder >= EulerSequenceLast) + if (theOrder == Invalid || theOrder >= EulerSequenceLast) { throw Base::ValueError("invalid euler sequence"); + } - EulerSequence_Parameters o = translateEulerSequence (theOrder); + EulerSequence_Parameters o = translateEulerSequence(theOrder); - theAlpha *= D_PI/180.0; - theBeta *= D_PI/180.0; - theGamma *= D_PI/180.0; + theAlpha *= D_PI / 180.0; + theBeta *= D_PI / 180.0; + theGamma *= D_PI / 180.0; double a = theAlpha, b = theBeta, c = theGamma; - if ( ! o.isExtrinsic ) + if (!o.isExtrinsic) { std::swap(a, c); + } - if ( o.isOdd ) + if (o.isOdd) { b = -b; + } - double ti = 0.5 * a; - double tj = 0.5 * b; + double ti = 0.5 * a; + double tj = 0.5 * b; double th = 0.5 * c; - double ci = cos (ti); - double cj = cos (tj); - double ch = cos (th); - double si = sin (ti); - double sj = sin (tj); - double sh = sin (th); - double cc = ci * ch; - double cs = ci * sh; - double sc = si * ch; + double ci = cos(ti); + double cj = cos(tj); + double ch = cos(th); + double si = sin(ti); + double sj = sin(tj); + double sh = sin(th); + double cc = ci * ch; + double cs = ci * sh; + double sc = si * ch; double ss = si * sh; - double values[4]; // w, x, y, z - if ( o.isTwoAxes ) - { + double values[4]; // w, x, y, z + if (o.isTwoAxes) { values[o.i] = cj * (cs + sc); values[o.j] = sj * (cc + ss); values[o.k] = sj * (cs - sc); - values[0] = cj * (cc - ss); - } - else - { + values[0] = cj * (cc - ss); + } + else { values[o.i] = cj * sc - sj * cs; values[o.j] = cj * ss + sj * cc; values[o.k] = cj * cs - sj * sc; - values[0] = cj * cc + sj * ss; + values[0] = cj * cc + sj * ss; } - if ( o.isOdd ) + if (o.isOdd) { values[o.j] = -values[o.j]; + } quat[0] = values[1]; quat[1] = values[2]; @@ -997,51 +1046,43 @@ void Rotation::getEulerAngles(EulerSequence theOrder, Mat M; getValue(M); - EulerSequence_Parameters o = translateEulerSequence (theOrder); - if ( o.isTwoAxes ) - { - double sy = sqrt (M(o.i, o.j) * M(o.i, o.j) + M(o.i, o.k) * M(o.i, o.k)); - if (sy > 16 * DBL_EPSILON) - { - theAlpha = atan2 (M(o.i, o.j), M(o.i, o.k)); - theGamma = atan2 (M(o.j, o.i), -M(o.k, o.i)); - } - else - { - theAlpha = atan2 (-M(o.j, o.k), M(o.j, o.j)); + EulerSequence_Parameters o = translateEulerSequence(theOrder); + if (o.isTwoAxes) { + double sy = sqrt(M(o.i, o.j) * M(o.i, o.j) + M(o.i, o.k) * M(o.i, o.k)); + if (sy > 16 * DBL_EPSILON) { + theAlpha = atan2(M(o.i, o.j), M(o.i, o.k)); + theGamma = atan2(M(o.j, o.i), -M(o.k, o.i)); + } + else { + theAlpha = atan2(-M(o.j, o.k), M(o.j, o.j)); theGamma = 0.; } - theBeta = atan2 (sy, M(o.i, o.i)); - } - else - { - double cy = sqrt (M(o.i, o.i) * M(o.i, o.i) + M(o.j, o.i) * M(o.j, o.i)); - if (cy > 16 * DBL_EPSILON) - { - theAlpha = atan2 (M(o.k, o.j), M(o.k, o.k)); - theGamma = atan2 (M(o.j, o.i), M(o.i, o.i)); - } - else - { - theAlpha = atan2 (-M(o.j, o.k), M(o.j, o.j)); - theGamma = 0.; - } - theBeta = atan2 (-M(o.k, o.i), cy); + theBeta = atan2(sy, M(o.i, o.i)); } - if ( o.isOdd ) - { + else { + double cy = sqrt(M(o.i, o.i) * M(o.i, o.i) + M(o.j, o.i) * M(o.j, o.i)); + if (cy > 16 * DBL_EPSILON) { + theAlpha = atan2(M(o.k, o.j), M(o.k, o.k)); + theGamma = atan2(M(o.j, o.i), M(o.i, o.i)); + } + else { + theAlpha = atan2(-M(o.j, o.k), M(o.j, o.j)); + theGamma = 0.; + } + theBeta = atan2(-M(o.k, o.i), cy); + } + if (o.isOdd) { theAlpha = -theAlpha; - theBeta = -theBeta; + theBeta = -theBeta; theGamma = -theGamma; } - if ( ! o.isExtrinsic ) - { - double aFirst = theAlpha; + if (!o.isExtrinsic) { + double aFirst = theAlpha; theAlpha = theGamma; theGamma = aFirst; } - theAlpha *= 180.0/D_PI; - theBeta *= 180.0/D_PI; - theGamma *= 180.0/D_PI; + theAlpha *= 180.0 / D_PI; + theBeta *= 180.0 / D_PI; + theGamma *= 180.0 / D_PI; } diff --git a/src/Base/Rotation.h b/src/Base/Rotation.h index 55b05ab41d..edcdfec0db 100644 --- a/src/Base/Rotation.h +++ b/src/Base/Rotation.h @@ -29,7 +29,8 @@ #include #endif -namespace Base { +namespace Base +{ // forward declarations class Matrix4D; @@ -50,18 +51,18 @@ public: /** Methods to get or set rotations. */ //@{ - const double * getValue() const; - void getValue(double & q0, double & q1, double & q2, double & q3) const; + const double* getValue() const; + void getValue(double& q0, double& q1, double& q2, double& q3) const; void setValue(const double q0, const double q1, const double q2, const double q3); /// If not a null quaternion then \a axis will be normalized - void getValue(Vector3d & axis, double & rfAngle) const; + void getValue(Vector3d& axis, double& rfAngle) const; /// Does the same as the method above unless normalizing the axis. - void getRawValue(Vector3d & axis, double & rfAngle) const; - void getValue(Matrix4D & matrix) const; + void getRawValue(Vector3d& axis, double& rfAngle) const; + void getValue(Matrix4D& matrix) const; void setValue(const double q[4]); void setValue(const Matrix4D& matrix); - void setValue(const Vector3d & axis, const double fAngle); - void setValue(const Vector3d & rotateFrom, const Vector3d & rotateTo); + void setValue(const Vector3d& axis, const double fAngle); + void setValue(const Vector3d& rotateFrom, const Vector3d& rotateTo); /// Euler angles in yaw,pitch,roll notation void setYawPitchRoll(double y, double p, double r); /// Euler angles in yaw,pitch,roll notation @@ -109,9 +110,9 @@ public: EulerSequenceLast, }; - static const char *eulerSequenceName(EulerSequence seq); - static EulerSequence eulerSequenceFromName(const char *name); - void getEulerAngles(EulerSequence seq, double &alpha, double &beta, double &gamma) const; + static const char* eulerSequenceName(EulerSequence seq); + static EulerSequence eulerSequenceFromName(const char* name); + void getEulerAngles(EulerSequence seq, double& alpha, double& beta, double& gamma) const; void setEulerAngles(EulerSequence seq, double alpha, double beta, double gamma); bool isIdentity() const; bool isIdentity(double tol) const; @@ -122,32 +123,38 @@ public: /** Invert rotations. */ //@{ - Rotation & invert(); + Rotation& invert(); Rotation inverse() const; //@} /** Operators. */ //@{ - Rotation & operator*=(const Rotation & q); - Rotation operator *(const Rotation & q) const; - bool operator==(const Rotation & q) const; - bool operator!=(const Rotation & q) const; - double & operator [] (unsigned short usIndex){return quat[usIndex];} - const double & operator [] (unsigned short usIndex) const{return quat[usIndex];} - void operator = (const Rotation&); + Rotation& operator*=(const Rotation& q); + Rotation operator*(const Rotation& q) const; + bool operator==(const Rotation& q) const; + bool operator!=(const Rotation& q) const; + double& operator[](unsigned short usIndex) + { + return quat[usIndex]; + } + const double& operator[](unsigned short usIndex) const + { + return quat[usIndex]; + } + void operator=(const Rotation&); Rotation& multRight(const Base::Rotation& q); Rotation& multLeft(const Base::Rotation& q); - void multVec(const Vector3d & src, Vector3d & dst) const; - Vector3d multVec(const Vector3d & src) const; - void multVec(const Vector3f & src, Vector3f & dst) const; - Vector3f multVec(const Vector3f & src) const; + void multVec(const Vector3d& src, Vector3d& dst) const; + Vector3d multVec(const Vector3d& src) const; + void multVec(const Vector3f& src, Vector3f& dst) const; + Vector3f multVec(const Vector3f& src) const; void scaleAngle(const double scaleFactor); //@} /** Specialty constructors */ - static Rotation slerp(const Rotation & rot0, const Rotation & rot1, double t); + static Rotation slerp(const Rotation& rot0, const Rotation& rot1, double t); static Rotation identity(); /** @@ -164,16 +171,19 @@ public: * * If only one vector provided is nonzero, the other two directions are picked automatically. */ - static Rotation makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder = "ZXY"); + static Rotation makeRotationByAxes(Vector3d xdir, + Vector3d ydir, + Vector3d zdir, + const char* priorityOrder = "ZXY"); private: void normalize(); - void evaluateVector (); + void evaluateVector(); double quat[4]; - Vector3d _axis; // the axis kept not to lose direction when angle is 0 - double _angle; // this angle to keep the angle chosen by the user + Vector3d _axis; // the axis kept not to lose direction when angle is 0 + double _angle; // this angle to keep the angle chosen by the user }; -} +} // namespace Base -#endif // BASE_ROTATION_H +#endif // BASE_ROTATION_H diff --git a/src/Base/RotationPyImp.cpp b/src/Base/RotationPyImp.cpp index 1af310e4c9..80c6eb180b 100644 --- a/src/Base/RotationPyImp.cpp +++ b/src/Base/RotationPyImp.cpp @@ -45,48 +45,61 @@ std::string RotationPy::representation() const Py::Float q3(ptr->getValue()[3]); std::stringstream str; str << "Rotation ("; - str << static_cast(q0.repr()) << ", " - << static_cast(q1.repr()) << ", " - << static_cast(q2.repr()) << ", " + str << static_cast(q0.repr()) << ", " << static_cast(q1.repr()) + << ", " << static_cast(q2.repr()) << ", " << static_cast(q3.repr()); str << ")"; return str.str(); } -PyObject *RotationPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* RotationPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of RotationPy and the Twin object return new RotationPy(new Rotation); } +// clang-format off // constructor method int RotationPy::PyInit(PyObject* args, PyObject* kwds) { - PyObject* o{}; + PyObject* o {}; if (PyArg_ParseTuple(args, "")) { return 0; } PyErr_Clear(); if (PyArg_ParseTuple(args, "O!", &(Base::RotationPy::Type), &o)) { - Base::Rotation *rot = static_cast(o)->getRotationPtr(); + Base::Rotation* rot = static_cast(o)->getRotationPtr(); getRotationPtr()->setValue(rot->getValue()); return 0; } PyErr_Clear(); - double angle{}; - static const std::array kw_deg {"Axis", "Degree", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", kw_deg, &(Base::VectorPy::Type), &o, &angle)) { + double angle {}; + static const std::array kw_deg {"Axis", "Degree", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, + kwds, + "O!d", + kw_deg, + &(Base::VectorPy::Type), + &o, + &angle)) { // NOTE: The last parameter defines the rotation angle in degree. - getRotationPtr()->setValue(static_cast(o)->value(), Base::toRadians(angle)); + getRotationPtr()->setValue(static_cast(o)->value(), + Base::toRadians(angle)); return 0; } PyErr_Clear(); - static const std::array kw_rad {"Axis", "Radian", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", kw_rad, &(Base::VectorPy::Type), &o, &angle)) { + static const std::array kw_rad {"Axis", "Radian", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, + kwds, + "O!d", + kw_rad, + &(Base::VectorPy::Type), + &o, + &angle)) { getRotationPtr()->setValue(static_cast(o)->value(), angle); return 0; } @@ -104,28 +117,29 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) } PyErr_Clear(); - double q0{}, q1{}, q2{}, q3{}; + double q0 {}, q1 {}, q2 {}, q3 {}; if (PyArg_ParseTuple(args, "dddd", &q0, &q1, &q2, &q3)) { getRotationPtr()->setValue(q0, q1, q2, q3); return 0; } PyErr_Clear(); - double y{}, p{}, r{}; + double y {}, p {}, r {}; if (PyArg_ParseTuple(args, "ddd", &y, &p, &r)) { getRotationPtr()->setYawPitchRoll(y, p, r); return 0; } PyErr_Clear(); - const char *seq{}; - double a{}, b{}, c{}; + const char* seq {}; + double a {}, b {}, c {}; if (PyArg_ParseTuple(args, "sddd", &seq, &a, &b, &c)) { - PY_TRY { - getRotationPtr()->setEulerAngles( - Rotation::eulerSequenceFromName(seq), a, b, c); + PY_TRY + { + getRotationPtr()->setEulerAngles(Rotation::eulerSequenceFromName(seq), a, b, c); return 0; - } _PY_CATCH(return -1) + } + _PY_CATCH(return -1) } double a11 = 1.0, a12 = 0.0, a13 = 0.0, a14 = 0.0; @@ -135,12 +149,12 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) // try read a 4x4 matrix PyErr_Clear(); - if (PyArg_ParseTuple(args, "dddddddddddddddd", - &a11, &a12, &a13, &a14, - &a21, &a22, &a23, &a24, - &a31, &a32, &a33, &a34, - &a41, &a42, &a43, &a44)) - { + if (PyArg_ParseTuple(args, + "dddddddddddddddd", + &a11, &a12, &a13, &a14, + &a21, &a22, &a23, &a24, + &a31, &a32, &a33, &a34, + &a41, &a42, &a43, &a44)) { try { Matrix4D mtx(a11, a12, a13, a14, a21, a22, a23, a24, @@ -158,10 +172,9 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) // try read a 3x3 matrix PyErr_Clear(); if (PyArg_ParseTuple(args, "ddddddddd", - &a11, &a12, &a13, - &a21, &a22, &a23, - &a31, &a32, &a33)) - { + &a11, &a12, &a13, + &a21, &a22, &a23, + &a31, &a32, &a33)) { try { Matrix4D mtx(a11, a12, a13, a14, a21, a22, a23, a24, @@ -177,9 +190,11 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) } PyErr_Clear(); - PyObject *v1{}, *v2{}; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &v1, - &(Base::VectorPy::Type), &v2)) { + PyObject *v1 {}, *v2 {}; + if (PyArg_ParseTuple(args, + "O!O!", + &(Base::VectorPy::Type), &v1, + &(Base::VectorPy::Type), &v2)) { Py::Vector from(v1, false); Py::Vector to(v2, false); getRotationPtr()->setValue(from.toVector(), to.toVector()); @@ -187,57 +202,63 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) } PyErr_Clear(); - PyObject *v3{}; - const char *priority = nullptr; - if (PyArg_ParseTuple(args, "O!O!O!|s", &(Base::VectorPy::Type), &v1, - &(Base::VectorPy::Type), &v2, - &(Base::VectorPy::Type), &v3, - &priority)) { + PyObject* v3 {}; + const char* priority = nullptr; + if (PyArg_ParseTuple(args, + "O!O!O!|s", + &(Base::VectorPy::Type), &v1, + &(Base::VectorPy::Type), &v2, + &(Base::VectorPy::Type), &v3, + &priority)) { Py::Vector xdir(v1, false); Py::Vector ydir(v2, false); Py::Vector zdir(v3, false); - if (!priority) + if (!priority) { priority = "ZXY"; + } try { - *getRotationPtr() = (Rotation::makeRotationByAxes(xdir.toVector(), ydir.toVector(), zdir.toVector(), priority)); - } catch(Base::Exception &e) { + *getRotationPtr() = (Rotation::makeRotationByAxes(xdir.toVector(), + ydir.toVector(), + zdir.toVector(), + priority)); + } + catch (Base::Exception& e) { std::string str; str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - PyErr_SetString(Base::PyExc_FC_GeneralError,str.c_str()); + PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); return -1; } return 0; } - PyErr_SetString(PyExc_TypeError, "Rotation constructor accepts:\n" - "-- empty parameter list\n" - "-- Rotation object" - "-- four floats (a quaternion)\n" - "-- three floats (yaw, pitch, roll)" - "-- Vector (rotation axis) and float (rotation angle)\n" - "-- two Vectors (two axes)\n" - "-- Matrix object\n" - "-- 16 floats (4x4 matrix)\n" - "-- 9 floats (3x3 matrix)\n" - "-- 3 vectors + optional string" - ); + PyErr_SetString(PyExc_TypeError, + "Rotation constructor accepts:\n" + "-- empty parameter list\n" + "-- Rotation object" + "-- four floats (a quaternion)\n" + "-- three floats (yaw, pitch, roll)" + "-- Vector (rotation axis) and float (rotation angle)\n" + "-- two Vectors (two axes)\n" + "-- Matrix object\n" + "-- 16 floats (4x4 matrix)\n" + "-- 9 floats (3x3 matrix)\n" + "-- 3 vectors + optional string"); return -1; } +// clang-format on -PyObject* RotationPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* RotationPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(RotationPy::Type)) && - PyObject_TypeCheck(w, &(RotationPy::Type))) { + if (PyObject_TypeCheck(v, &(RotationPy::Type)) && PyObject_TypeCheck(w, &(RotationPy::Type))) { Base::Rotation r1 = *static_cast(v)->getRotationPtr(); Base::Rotation r2 = *static_cast(w)->getRotationPtr(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for Rotation"); + PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Rotation"); return nullptr; } else if (op == Py_EQ) { @@ -258,68 +279,75 @@ PyObject* RotationPy::richCompare(PyObject *v, PyObject *w, int op) } } -PyObject* RotationPy::invert(PyObject * args) +PyObject* RotationPy::invert(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } this->getRotationPtr()->invert(); Py_Return; } -PyObject* RotationPy::inverted(PyObject * args) +PyObject* RotationPy::inverted(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Rotation mult = this->getRotationPtr()->inverse(); return new RotationPy(new Rotation(mult)); } -PyObject* RotationPy::multiply(PyObject * args) +PyObject* RotationPy::multiply(PyObject* args) { - PyObject *rot{}; - if (!PyArg_ParseTuple(args, "O!", &(RotationPy::Type), &rot)) + PyObject* rot {}; + if (!PyArg_ParseTuple(args, "O!", &(RotationPy::Type), &rot)) { return nullptr; + } Rotation mult = (*getRotationPtr()) * (*static_cast(rot)->getRotationPtr()); return new RotationPy(new Rotation(mult)); } -PyObject* RotationPy::multVec(PyObject * args) +PyObject* RotationPy::multVec(PyObject* args) { - PyObject *obj{}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } Base::Vector3d vec(static_cast(obj)->value()); getRotationPtr()->multVec(vec, vec); return new VectorPy(new Vector3d(vec)); } -PyObject* RotationPy::slerp(PyObject * args) +PyObject* RotationPy::slerp(PyObject* args) { - PyObject *rot{}; - double t{}; - if (!PyArg_ParseTuple(args, "O!d", &(RotationPy::Type), &rot, &t)) + PyObject* rot {}; + double t {}; + if (!PyArg_ParseTuple(args, "O!d", &(RotationPy::Type), &rot, &t)) { return nullptr; - Rotation *rot0 = this->getRotationPtr(); - Rotation *rot1 = static_cast(rot)->getRotationPtr(); + } + Rotation* rot0 = this->getRotationPtr(); + Rotation* rot1 = static_cast(rot)->getRotationPtr(); Rotation sl = Rotation::slerp(*rot0, *rot1, t); return new RotationPy(new Rotation(sl)); } -PyObject* RotationPy::setYawPitchRoll(PyObject * args) +PyObject* RotationPy::setYawPitchRoll(PyObject* args) { - double A{},B{},C{}; - if (!PyArg_ParseTuple(args, "ddd", &A, &B, &C)) + double A {}, B {}, C {}; + if (!PyArg_ParseTuple(args, "ddd", &A, &B, &C)) { return nullptr; - this->getRotationPtr()->setYawPitchRoll(A,B,C); + } + this->getRotationPtr()->setYawPitchRoll(A, B, C); Py_Return; } -PyObject* RotationPy::getYawPitchRoll(PyObject * args) +PyObject* RotationPy::getYawPitchRoll(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); + } + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(A)); @@ -328,16 +356,16 @@ PyObject* RotationPy::getYawPitchRoll(PyObject * args) return Py::new_reference_to(tuple); } -PyObject* RotationPy::setEulerAngles(PyObject * args) +PyObject* RotationPy::setEulerAngles(PyObject* args) { - const char *seq{}; - double A{},B{},C{}; - if (!PyArg_ParseTuple(args, "sddd", &seq, &A, &B, &C)) + const char* seq {}; + double A {}, B {}, C {}; + if (!PyArg_ParseTuple(args, "sddd", &seq, &A, &B, &C)) { return nullptr; + } try { - getRotationPtr()->setEulerAngles( - Rotation::eulerSequenceFromName(seq), A, B, C); + getRotationPtr()->setEulerAngles(Rotation::eulerSequenceFromName(seq), A, B, C); Py_Return; } catch (const Base::Exception& e) { @@ -346,75 +374,80 @@ PyObject* RotationPy::setEulerAngles(PyObject * args) } } -PyObject* RotationPy::toEulerAngles(PyObject * args) +PyObject* RotationPy::toEulerAngles(PyObject* args) { - const char *seq = nullptr; - if (!PyArg_ParseTuple(args, "|s", &seq)) + const char* seq = nullptr; + if (!PyArg_ParseTuple(args, "|s", &seq)) { return nullptr; + } if (!seq) { Py::List res; - for (int i=1; igetRotationPtr()->getEulerAngles( - Rotation::eulerSequenceFromName(seq),A,B,C); + PY_TRY + { + double A {}, B {}, C {}; + this->getRotationPtr()->getEulerAngles(Rotation::eulerSequenceFromName(seq), A, B, C); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(A)); tuple.setItem(1, Py::Float(B)); tuple.setItem(2, Py::Float(C)); return Py::new_reference_to(tuple); - } PY_CATCH - + } + PY_CATCH } -PyObject* RotationPy::toMatrix(PyObject * args) +PyObject* RotationPy::toMatrix(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Matrix4D mat; getRotationPtr()->getValue(mat); return new MatrixPy(new Matrix4D(mat)); } -PyObject* RotationPy::isSame(PyObject *args) +PyObject* RotationPy::isSame(PyObject* args) { - PyObject *rot{}; + PyObject* rot {}; double tol = 0.0; - if (!PyArg_ParseTuple(args, "O!|d", &(RotationPy::Type), &rot, &tol)) + if (!PyArg_ParseTuple(args, "O!|d", &(RotationPy::Type), &rot, &tol)) { return nullptr; - Base::Rotation rot1 = * getRotationPtr(); - Base::Rotation rot2 = * static_cast(rot)->getRotationPtr(); + } + Base::Rotation rot1 = *getRotationPtr(); + Base::Rotation rot2 = *static_cast(rot)->getRotationPtr(); bool same = tol > 0.0 ? rot1.isSame(rot2, tol) : rot1.isSame(rot2); return Py_BuildValue("O", (same ? Py_True : Py_False)); } -PyObject* RotationPy::isIdentity(PyObject *args) +PyObject* RotationPy::isIdentity(PyObject* args) { double tol = 0.0; - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; - bool null = tol > 0.0 ? getRotationPtr()->isIdentity(tol) - : getRotationPtr()->isIdentity(); + } + bool null = tol > 0.0 ? getRotationPtr()->isIdentity(tol) : getRotationPtr()->isIdentity(); return Py_BuildValue("O", (null ? Py_True : Py_False)); } -PyObject* RotationPy::isNull(PyObject *args) +PyObject* RotationPy::isNull(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool null = getRotationPtr()->isNull(); return Py_BuildValue("O", (null ? Py_True : Py_False)); } Py::Tuple RotationPy::getQ() const { - double q0{}, q1{}, q2{}, q3{}; - this->getRotationPtr()->getValue(q0,q1,q2,q3); + double q0 {}, q1 {}, q2 {}, q3 {}; + this->getRotationPtr()->getValue(q0, q1, q2, q3); Py::Tuple tuple(4); tuple.setItem(0, Py::Float(q0)); @@ -430,26 +463,29 @@ void RotationPy::setQ(Py::Tuple arg) double q1 = static_cast(Py::Float(arg.getItem(1))); double q2 = static_cast(Py::Float(arg.getItem(2))); double q3 = static_cast(Py::Float(arg.getItem(3))); - this->getRotationPtr()->setValue(q0,q1,q2,q3); + this->getRotationPtr()->setValue(q0, q1, q2, q3); } Py::Object RotationPy::getRawAxis() const { - Base::Vector3d axis; double angle{}; + Base::Vector3d axis; + double angle {}; this->getRotationPtr()->getRawValue(axis, angle); - return Py::Vector(axis); // NOLINT + return Py::Vector(axis); // NOLINT } Py::Object RotationPy::getAxis() const { - Base::Vector3d axis; double angle{}; + Base::Vector3d axis; + double angle {}; this->getRotationPtr()->getValue(axis, angle); - return Py::Vector(axis); // NOLINT + return Py::Vector(axis); // NOLINT } void RotationPy::setAxis(Py::Object arg) { - Base::Vector3d axis; double angle{}; + Base::Vector3d axis; + double angle {}; this->getRotationPtr()->getValue(axis, angle); axis = Py::Vector(arg).toVector(); this->getRotationPtr()->setValue(axis, angle); @@ -457,20 +493,22 @@ void RotationPy::setAxis(Py::Object arg) Py::Float RotationPy::getAngle() const { - Base::Vector3d axis; double angle{}; + Base::Vector3d axis; + double angle {}; this->getRotationPtr()->getValue(axis, angle); return Py::Float(angle); } void RotationPy::setAngle(Py::Float arg) { - Base::Vector3d axis; double angle{}; + Base::Vector3d axis; + double angle {}; this->getRotationPtr()->getRawValue(axis, angle); angle = static_cast(arg); this->getRotationPtr()->setValue(axis, angle); } -PyObject *RotationPy::getCustomAttributes(const char* attr) const +PyObject* RotationPy::getCustomAttributes(const char* attr) const { if (strcmp(attr, "Matrix") == 0) { Matrix4D mat; @@ -478,18 +516,18 @@ PyObject *RotationPy::getCustomAttributes(const char* attr) const return new MatrixPy(mat); } else if (strcmp(attr, "Yaw") == 0) { - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(A); } else if (strcmp(attr, "Pitch") == 0) { - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(B); } else if (strcmp(attr, "Roll") == 0) { - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(C); } else if (strcmp(attr, "toEuler") == 0) { @@ -518,11 +556,10 @@ int RotationPy::setCustomAttributes(const char* attr, PyObject* obj) if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { PyObject* vec1 = PySequence_GetItem(obj, 0); PyObject* vec2 = PySequence_GetItem(obj, 1); - if (PyObject_TypeCheck(vec1, &(VectorPy::Type)) && - PyObject_TypeCheck(vec2, &(VectorPy::Type))) { - this->getRotationPtr()->setValue( - *static_cast(vec1)->getVectorPtr(), - *static_cast(vec2)->getVectorPtr()); + if (PyObject_TypeCheck(vec1, &(VectorPy::Type)) + && PyObject_TypeCheck(vec2, &(VectorPy::Type))) { + this->getRotationPtr()->setValue(*static_cast(vec1)->getVectorPtr(), + *static_cast(vec2)->getVectorPtr()); return 1; } } @@ -530,59 +567,59 @@ int RotationPy::setCustomAttributes(const char* attr, PyObject* obj) else if (strcmp(attr, "Yaw") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); - this->getRotationPtr()->setYawPitchRoll(V,B,C); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); + this->getRotationPtr()->setYawPitchRoll(V, B, C); return 1; } } else if (strcmp(attr, "Pitch") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); - this->getRotationPtr()->setYawPitchRoll(A,V,C); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); + this->getRotationPtr()->setYawPitchRoll(A, V, C); return 1; } } else if (strcmp(attr, "Roll") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A{},B{},C{}; - this->getRotationPtr()->getYawPitchRoll(A,B,C); - this->getRotationPtr()->setYawPitchRoll(A,B,V); + double A {}, B {}, C {}; + this->getRotationPtr()->getYawPitchRoll(A, B, C); + this->getRotationPtr()->setYawPitchRoll(A, B, V); return 1; } } return 0; } -PyObject* RotationPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* RotationPy::number_multiply_handler(PyObject* self, PyObject* other) { if (PyObject_TypeCheck(self, &(RotationPy::Type))) { auto a = static_cast(self)->value(); if (PyObject_TypeCheck(other, &(VectorPy::Type))) { Vector3d res; - a.multVec(static_cast(other)->value(),res); + a.multVec(static_cast(other)->value(), res); return new VectorPy(res); } if (PyObject_TypeCheck(other, &(PlacementPy::Type))) { - const auto &b = static_cast(other)->value(); - return new PlacementPy(Placement(Vector3d(),a)*b); + const auto& b = static_cast(other)->value(); + return new PlacementPy(Placement(Vector3d(), a) * b); } if (PyObject_TypeCheck(other, &(RotationPy::Type))) { - const auto &b = static_cast(other)->value(); - return new RotationPy(a*b); + const auto& b = static_cast(other)->value(); + return new RotationPy(a * b); } if (PyObject_TypeCheck(other, &(MatrixPy::Type))) { - const auto &b = static_cast(other)->value(); + const auto& b = static_cast(other)->value(); Matrix4D mat; a.getValue(mat); - return new MatrixPy(mat*b); + return new MatrixPy(mat * b); } } @@ -590,12 +627,9 @@ PyObject* RotationPy::number_multiply_handler(PyObject *self, PyObject *other) return nullptr; } -PyObject * RotationPy::number_power_handler (PyObject* self, PyObject* other, PyObject* arg) +PyObject* RotationPy::number_power_handler(PyObject* self, PyObject* other, PyObject* arg) { - if (!PyObject_TypeCheck(self, &(RotationPy::Type)) || - !PyLong_Check(other) || - arg != Py_None) - { + if (!PyObject_TypeCheck(self, &(RotationPy::Type)) || !PyLong_Check(other) || arg != Py_None) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } @@ -604,7 +638,7 @@ PyObject * RotationPy::number_power_handler (PyObject* self, PyObject* other, Py long b = Py::Int(other); Vector3d axis; - double rfAngle{}; + double rfAngle {}; a.getRawValue(axis, rfAngle); rfAngle *= b; @@ -613,104 +647,103 @@ PyObject * RotationPy::number_power_handler (PyObject* self, PyObject* other, Py return new RotationPy(a); } -PyObject* RotationPy::number_add_handler(PyObject * /*self*/, PyObject * /*other*/) +PyObject* RotationPy::number_add_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject* RotationPy::number_subtract_handler(PyObject * /*self*/, PyObject * /*other*/) +PyObject* RotationPy::number_subtract_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_divide_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_remainder_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_negative_handler (PyObject* /*self*/) +PyObject* RotationPy::number_negative_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_positive_handler (PyObject* /*self*/) +PyObject* RotationPy::number_positive_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_absolute_handler (PyObject* /*self*/) +PyObject* RotationPy::number_absolute_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -int RotationPy::number_nonzero_handler (PyObject* /*self*/) +int RotationPy::number_nonzero_handler(PyObject* /*self*/) { return 1; } -PyObject * RotationPy::number_invert_handler (PyObject* /*self*/) +PyObject* RotationPy::number_invert_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_lshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_rshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_and_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_xor_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* RotationPy::number_or_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_int_handler (PyObject * /*self*/) +PyObject* RotationPy::number_int_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * RotationPy::number_float_handler (PyObject * /*self*/) +PyObject* RotationPy::number_float_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } - diff --git a/src/Base/Sequencer.cpp b/src/Base/Sequencer.cpp index b9b29020d0..15d140324f 100644 --- a/src/Base/Sequencer.cpp +++ b/src/Base/Sequencer.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "Sequencer.h" @@ -33,41 +33,43 @@ using namespace Base; -namespace Base { - struct SequencerP { - // members - static std::vector _instances; /**< A vector of all created instances */ - static SequencerLauncher* _topLauncher; /**< The outermost launcher */ - static QRecursiveMutex mutex; /**< A mutex-locker for the launcher */ - /** Sets a global sequencer object. - * Access to the last registered object is performed by @see Sequencer(). - */ - static void appendInstance (SequencerBase* s) - { - _instances.push_back(s); - } - static void removeInstance (SequencerBase* s) - { - std::vector::iterator it; - it = std::find(_instances.begin(), _instances.end(), s); - _instances.erase(it); - } - static SequencerBase& getInstance () - { - return *_instances.back(); - } - }; - - /** - * The _instances member just stores the pointer of the - * all instantiated SequencerBase objects. +namespace Base +{ +struct SequencerP +{ + // members + static std::vector _instances; /**< A vector of all created instances */ + static SequencerLauncher* _topLauncher; /**< The outermost launcher */ + static QRecursiveMutex mutex; /**< A mutex-locker for the launcher */ + /** Sets a global sequencer object. + * Access to the last registered object is performed by @see Sequencer(). */ - std::vector SequencerP::_instances; - SequencerLauncher* SequencerP::_topLauncher = nullptr; - QRecursiveMutex SequencerP::mutex; -} + static void appendInstance(SequencerBase* s) + { + _instances.push_back(s); + } + static void removeInstance(SequencerBase* s) + { + std::vector::iterator it; + it = std::find(_instances.begin(), _instances.end(), s); + _instances.erase(it); + } + static SequencerBase& getInstance() + { + return *_instances.back(); + } +}; -SequencerBase& SequencerBase::Instance () +/** + * The _instances member just stores the pointer of the + * all instantiated SequencerBase objects. + */ +std::vector SequencerP::_instances; +SequencerLauncher* SequencerP::_topLauncher = nullptr; +QRecursiveMutex SequencerP::mutex; +} // namespace Base + +SequencerBase& SequencerBase::Instance() { // not initialized? if (SequencerP::_instances.size() == 0) { @@ -99,8 +101,9 @@ bool SequencerBase::start(const char* pszStr, size_t steps) setText(pszStr); // reimplemented in sub-classes - if (!this->_bLocked) + if (!this->_bLocked) { startStep(); + } return true; } @@ -111,8 +114,7 @@ size_t SequencerBase::numberOfSteps() const } void SequencerBase::startStep() -{ -} +{} bool SequencerBase::next(bool canAbort) { @@ -125,20 +127,19 @@ bool SequencerBase::next(bool canAbort) this->_nLastPercentage = perc; // if not locked - if (!this->_bLocked) + if (!this->_bLocked) { nextStep(canAbort); + } } return this->nProgress < this->nTotalSteps; } -void SequencerBase::nextStep( bool ) -{ -} +void SequencerBase::nextStep(bool) +{} void SequencerBase::setProgress(size_t) -{ -} +{} bool SequencerBase::stop() { @@ -147,12 +148,10 @@ bool SequencerBase::stop() } void SequencerBase::pause() -{ -} +{} void SequencerBase::resume() -{ -} +{} bool SequencerBase::isBlocking() const { @@ -206,26 +205,25 @@ void SequencerBase::resetData() } void SequencerBase::setText(const char*) -{ -} +{} // --------------------------------------------------------- using Base::ConsoleSequencer; -void ConsoleSequencer::setText (const char* pszTxt) +void ConsoleSequencer::setText(const char* pszTxt) { printf("%s...\n", pszTxt); } void ConsoleSequencer::startStep() -{ -} +{} -void ConsoleSequencer::nextStep( bool ) +void ConsoleSequencer::nextStep(bool) { - if (this->nTotalSteps != 0) + if (this->nTotalSteps != 0) { printf("\t\t\t\t\t\t(%d %%)\t\r", progressInPercent()); + } } void ConsoleSequencer::resetData() @@ -249,14 +247,15 @@ SequencerLauncher::SequencerLauncher(const char* pszStr, size_t steps) SequencerLauncher::~SequencerLauncher() { QMutexLocker locker(&SequencerP::mutex); - if (SequencerP::_topLauncher == this) + if (SequencerP::_topLauncher == this) { SequencerBase::Instance().stop(); + } if (SequencerP::_topLauncher == this) { SequencerP::_topLauncher = nullptr; } } -void SequencerLauncher::setText (const char* pszTxt) +void SequencerLauncher::setText(const char* pszTxt) { QMutexLocker locker(&SequencerP::mutex); SequencerBase::Instance().setText(pszTxt); @@ -265,8 +264,9 @@ void SequencerLauncher::setText (const char* pszTxt) bool SequencerLauncher::next(bool canAbort) { QMutexLocker locker(&SequencerP::mutex); - if (SequencerP::_topLauncher != this) - return true; // ignore + if (SequencerP::_topLauncher != this) { + return true; // ignore + } return SequencerBase::Instance().next(canAbort); } diff --git a/src/Base/Sequencer.h b/src/Base/Sequencer.h index cd7d202e10..72e39d98b7 100644 --- a/src/Base/Sequencer.h +++ b/src/Base/Sequencer.h @@ -148,7 +148,8 @@ public: bool wasCanceled() const; /// Check if the operation is aborted by user - virtual void checkAbort() {} + virtual void checkAbort() + {} protected: /** @@ -211,7 +212,7 @@ protected: * Sets a text what the pending operation is doing. The default implementation * does nothing. */ - virtual void setText (const char* pszTxt); + virtual void setText(const char* pszTxt); /** * This method can be reimplemented in sub-classes to give the user a feedback * when a new sequence starts. The default implementation does nothing. @@ -236,21 +237,21 @@ protected: virtual void resetData(); protected: - //NOLINTBEGIN - size_t nProgress{0}; /**< Stores the current amount of progress.*/ - size_t nTotalSteps{0}; /**< Stores the total number of steps */ - //NOLINTEND + // NOLINTBEGIN + size_t nProgress {0}; /**< Stores the current amount of progress.*/ + size_t nTotalSteps {0}; /**< Stores the total number of steps */ + // NOLINTEND private: - bool _bLocked{false}; /**< Lock/unlock sequencer. */ - bool _bCanceled{false}; /**< Is set to true if the last pending operation was canceled */ - int _nLastPercentage{-1}; /**< Progress in percent. */ + bool _bLocked {false}; /**< Lock/unlock sequencer. */ + bool _bCanceled {false}; /**< Is set to true if the last pending operation was canceled */ + int _nLastPercentage {-1}; /**< Progress in percent. */ }; /** This special sequencer might be useful if you want to suppress any indication * of the progress to the user. */ -class BaseExport EmptySequencer : public Base::SequencerBase +class BaseExport EmptySequencer: public Base::SequencerBase { public: /** construction */ @@ -260,11 +261,11 @@ public: /** * \brief This class writes the progress to the console window. */ -class BaseExport ConsoleSequencer : public SequencerBase +class BaseExport ConsoleSequencer: public SequencerBase { public: /** construction */ - ConsoleSequencer () = default; + ConsoleSequencer() = default; protected: /** Starts the sequencer */ @@ -274,21 +275,21 @@ protected: private: /** Puts text to the console window */ - void setText (const char* pszTxt) override; + void setText(const char* pszTxt) override; /** Resets the sequencer */ void resetData() override; }; /** The SequencerLauncher class is provided for convenience. It allows you to run an instance of the - * sequencer by instantiating an object of this class -- most suitable on the stack. So this mechanism - * can be used for try-catch-blocks to destroy the object automatically if the C++ exception mechanism - * cleans up the stack. + * sequencer by instantiating an object of this class -- most suitable on the stack. So this + * mechanism can be used for try-catch-blocks to destroy the object automatically if the C++ + * exception mechanism cleans up the stack. * - * This class has been introduced to simplify the use with the sequencer. In the FreeCAD Gui layer there - * is a subclass of SequencerBase called ProgressBar that grabs the keyboard and filters most of the incoming - * events. If the programmer uses the API of SequencerBase directly to start an instance without due diligence - * with exceptions then a not handled exception could block the whole application -- the user has to kill the - * application then. + * This class has been introduced to simplify the use with the sequencer. In the FreeCAD Gui layer + * there is a subclass of SequencerBase called ProgressBar that grabs the keyboard and filters most + * of the incoming events. If the programmer uses the API of SequencerBase directly to start an + * instance without due diligence with exceptions then a not handled exception could block the whole + * application -- the user has to kill the application then. * * Below is an example of a not correctly used sequencer. * @@ -304,7 +305,8 @@ private: * runOperation(); * } catch(...) { * // the programmer forgot to stop the sequencer here - * // Under circumstances the sequencer never gets stopped so the keyboard never gets ungrabbed and + * // Under circumstances the sequencer never gets stopped so the keyboard never gets + * ungrabbed and * // all Gui events still gets filtered. * } * } @@ -367,7 +369,7 @@ public: SequencerLauncher(const char* pszStr, size_t steps); ~SequencerLauncher(); size_t numberOfSteps() const; - void setText (const char* pszTxt); + void setText(const char* pszTxt); bool next(bool canAbort = false); void setProgress(size_t); bool wasCanceled() const; @@ -377,11 +379,11 @@ public: }; /** Access to the only SequencerBase instance */ -inline SequencerBase& Sequencer () +inline SequencerBase& Sequencer() { return SequencerBase::Instance(); } -} // namespace Base +} // namespace Base -#endif // BASE_SEQUENCER_H +#endif // BASE_SEQUENCER_H diff --git a/src/Base/SmartPtrPy.cpp b/src/Base/SmartPtrPy.cpp index 1a6bdf8604..a0ac89435e 100644 --- a/src/Base/SmartPtrPy.cpp +++ b/src/Base/SmartPtrPy.cpp @@ -29,97 +29,98 @@ #include -namespace Py { - void SmartPtr::set(PyObject *pyob, bool owned) - { - release(); - p = pyob; - if( !owned ) - { - Py::_XINCREF( p ); - } - } - - void SmartPtr::release() - { - Py::_XDECREF( p ); - p = nullptr; - } - - SmartPtr::SmartPtr() - : p( Py::_None() ) - { - Py::_XINCREF( p ); - } - - SmartPtr::SmartPtr( PyObject *pyob, bool owned) - : p( pyob ) - { - if( !owned ) - { - Py::_XINCREF( p ); - } - } - - SmartPtr::SmartPtr( const SmartPtr &ob ) - : p( ob.p ) - { - Py::_XINCREF( p ); - } - - SmartPtr &SmartPtr::operator=( const SmartPtr &rhs ) - { - set( rhs.ptr() ); - return *this; - } - - SmartPtr &SmartPtr::operator=( const Object &rhs ) - { - set( rhs.ptr() ); - return *this; - } - - SmartPtr &SmartPtr::operator=( PyObject *rhsp ) - { - if( ptr() != rhsp ) - set( rhsp ); - - return *this; - } - - SmartPtr::~SmartPtr() - { - release(); - } - - PyObject *SmartPtr::operator*() const - { - return p; - } - - PyObject *SmartPtr::ptr() const - { - return p; - } - - bool SmartPtr::is( PyObject *pother ) const - { // identity test - return p == pother; - } - - bool SmartPtr::is( const SmartPtr &other ) const - { // identity test - return p == other.p; - } - - bool SmartPtr::isNull() const - { - return p == nullptr; - } - - BaseExport PyObject* new_reference_to(const SmartPtr& g) { - PyObject* p = g.ptr(); +namespace Py +{ +void SmartPtr::set(PyObject* pyob, bool owned) +{ + release(); + p = pyob; + if (!owned) { Py::_XINCREF(p); - return p; } } + +void SmartPtr::release() +{ + Py::_XDECREF(p); + p = nullptr; +} + +SmartPtr::SmartPtr() + : p(Py::_None()) +{ + Py::_XINCREF(p); +} + +SmartPtr::SmartPtr(PyObject* pyob, bool owned) + : p(pyob) +{ + if (!owned) { + Py::_XINCREF(p); + } +} + +SmartPtr::SmartPtr(const SmartPtr& ob) + : p(ob.p) +{ + Py::_XINCREF(p); +} + +SmartPtr& SmartPtr::operator=(const SmartPtr& rhs) +{ + set(rhs.ptr()); + return *this; +} + +SmartPtr& SmartPtr::operator=(const Object& rhs) +{ + set(rhs.ptr()); + return *this; +} + +SmartPtr& SmartPtr::operator=(PyObject* rhsp) +{ + if (ptr() != rhsp) { + set(rhsp); + } + + return *this; +} + +SmartPtr::~SmartPtr() +{ + release(); +} + +PyObject* SmartPtr::operator*() const +{ + return p; +} + +PyObject* SmartPtr::ptr() const +{ + return p; +} + +bool SmartPtr::is(PyObject* pother) const +{ // identity test + return p == pother; +} + +bool SmartPtr::is(const SmartPtr& other) const +{ // identity test + return p == other.p; +} + +bool SmartPtr::isNull() const +{ + return p == nullptr; +} + +BaseExport PyObject* new_reference_to(const SmartPtr& g) +{ + PyObject* p = g.ptr(); + Py::_XINCREF(p); + return p; +} +} // namespace Py diff --git a/src/Base/SmartPtrPy.h b/src/Base/SmartPtrPy.h index 867f990145..f549d007a6 100644 --- a/src/Base/SmartPtrPy.h +++ b/src/Base/SmartPtrPy.h @@ -29,7 +29,8 @@ // forward declarations using PyObject = struct _object; -namespace Py { +namespace Py +{ class Object; /** @@ -40,50 +41,50 @@ class Object; * * \author Werner Mayer */ -class BaseExport SmartPtr +class BaseExport SmartPtr // NOLINT { private: - PyObject *p; + PyObject* p; protected: - void set(PyObject *pyob, bool owned = false); + void set(PyObject* pyob, bool owned = false); void release(); public: SmartPtr(); // Constructor acquires new ownership of pointer unless explicitly told not to. - explicit SmartPtr(PyObject *pyob, bool owned = false); + explicit SmartPtr(PyObject* pyob, bool owned = false); // Copy constructor acquires new ownership of pointer - SmartPtr(const SmartPtr &ob); + SmartPtr(const SmartPtr& ob); // Assignment acquires new ownership of pointer - SmartPtr &operator=( const SmartPtr &rhs ); - SmartPtr &operator=( const Object &rhs ); + SmartPtr& operator=(const SmartPtr& rhs); + SmartPtr& operator=(const Object& rhs); - SmartPtr &operator=(PyObject *rhsp); + SmartPtr& operator=(PyObject* rhsp); // Destructor virtual ~SmartPtr(); // Loaning the pointer to others, retain ownership - PyObject *operator*() const; + PyObject* operator*() const; // Would like to call this pointer() but messes up STL in SeqBase - PyObject *ptr() const; + PyObject* ptr() const; // // Queries // - bool is(PyObject *pother) const; - bool is(const SmartPtr &other) const; + bool is(PyObject* pother) const; + bool is(const SmartPtr& other) const; bool isNull() const; }; BaseExport PyObject* new_reference_to(const SmartPtr&); -} +} // namespace Py -#endif // PY_SMARTPTRPY_H +#endif // PY_SMARTPTRPY_H diff --git a/src/Base/StackWalker.cpp b/src/Base/StackWalker.cpp index dcf5998af6..c3c4a7159c 100644 --- a/src/Base/StackWalker.cpp +++ b/src/Base/StackWalker.cpp @@ -1,5 +1,6 @@ +// clang-format off /********************************************************************** - * + * * StackWalker.cpp * http://stackwalker.codeplex.com/ * @@ -9,14 +10,14 @@ * http://www.codeproject.com/threads/StackWalker.asp * 2005-07-28 v2 - Changed the params of the constructor and ShowCallstack * (to simplify the usage) - * 2005-08-01 v3 - Changed to use 'CONTEXT_FULL' instead of CONTEXT_ALL + * 2005-08-01 v3 - Changed to use 'CONTEXT_FULL' instead of CONTEXT_ALL * (should also be enough) * - Changed to compile correctly with the PSDK of VC7.0 * (GetFileVersionInfoSizeA and GetFileVersionInfoA is wrongly defined: * it uses LPSTR instead of LPCSTR as first parameter) * - Added declarations to support VC5/6 without using 'dbghelp.h' - * - Added a 'pUserData' member to the ShowCallstack function and the - * PReadProcessMemoryRoutine declaration (to pass some user-defined data, + * - Added a 'pUserData' member to the ShowCallstack function and the + * PReadProcessMemoryRoutine declaration (to pass some user-defined data, * which can be used in the readMemoryFunction-callback) * 2005-08-02 v4 - OnSymInit now also outputs the OS-Version by default * - Added example for doing an exception-callstack-walking in main.cpp @@ -56,26 +57,26 @@ * Copyright (c) 2005-2013, Jochen Kalmbach * All rights reserved. * - * Redistribution and use in source and binary forms, with or without modification, + * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Jochen Kalmbach nor the names of its contributors may be - * used to endorse or promote products derived from this software without - * specific prior written permission. - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of Jochen Kalmbach nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ @@ -102,7 +103,7 @@ // Some missing defines (for VC5/6): #ifndef INVALID_FILE_ATTRIBUTES #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) -#endif +#endif static void MyStrCpy(char* szDest, size_t nMaxDestSize, const char* szSrc) @@ -263,7 +264,7 @@ public: m_szSymPath = _strdup(szSymPath); if (!this->pSI(m_hProcess, m_szSymPath, FALSE)) this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0); - + DWORD symOptions = this->pSGO(); // SymGetOptions symOptions |= SYMOPT_LOAD_LINES; symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS; @@ -378,11 +379,11 @@ typedef struct IMAGEHLP_MODULE64_V2 { tSSO pSSO; // StackWalk64() - typedef BOOL (__stdcall *tSW)( - DWORD MachineType, + typedef BOOL (__stdcall *tSW)( + DWORD MachineType, HANDLE hProcess, - HANDLE hThread, - LPSTACKFRAME64 StackFrame, + HANDLE hThread, + LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, @@ -869,7 +870,7 @@ BOOL StackWalker::LoadModules() // The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction // This has to be done due to a problem with the "hProcess"-parameter in x64... -// Because this class is in no case multi-threading-enabled (because of the limitations +// Because this class is in no case multi-threading-enabled (because of the limitations // of dbghelp.dll) it is "safe" to use a static-variable static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL; static LPVOID s_readMemoryFunction_UserData = NULL; @@ -1079,7 +1080,7 @@ BOOL StackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadPro et = firstEntry; bLastEntryCalled = false; this->OnCallstackEntry(et, csEntry); - + if (s.AddrReturn.Offset == 0) { bLastEntryCalled = true; @@ -1192,3 +1193,4 @@ void StackWalker::OnOutput(LPCSTR buffer) { OutputDebugStringA(buffer); } +// clang-format on diff --git a/src/Base/StackWalker.h b/src/Base/StackWalker.h index bb54bf7d9f..e8d6df0699 100644 --- a/src/Base/StackWalker.h +++ b/src/Base/StackWalker.h @@ -1,5 +1,6 @@ +// clang-format off /********************************************************************** - * + * * StackWalker.h * * @@ -9,26 +10,26 @@ * Copyright (c) 2005-2009, Jochen Kalmbach * All rights reserved. * - * Redistribution and use in source and binary forms, with or without modification, + * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Jochen Kalmbach nor the names of its contributors may be - * used to endorse or promote products derived from this software without - * specific prior written permission. - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of Jochen Kalmbach nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * **********************************************************************/ @@ -46,42 +47,42 @@ class BaseExport StackWalker public: typedef enum StackWalkOptions { - // No addition info will be retrieved + // No addition info will be retrieved // (only the address is available) RetrieveNone = 0, - + // Try to get the symbol-name RetrieveSymbol = 1, - + // Try to get the line for this symbol RetrieveLine = 2, - + // Try to retrieve the module-infos RetrieveModuleInfo = 4, - + // Also retrieve the version for the DLL/EXE RetrieveFileVersion = 8, - + // Contains all the above RetrieveVerbose = 0xF, - + // Generate a "good" symbol-search-path SymBuildPath = 0x10, - + // Also use the public Microsoft-Symbol-Server SymUseSymSrv = 0x20, - + // Contains all the above "Sym"-options SymAll = 0x30, - + // Contains all options (default) OptionsAll = 0x3F } StackWalkOptions; StackWalker( int options = OptionsAll, // 'int' is by design, to combine the enum-flags - LPCSTR szSymPath = NULL, - DWORD dwProcessId = GetCurrentProcessId(), + LPCSTR szSymPath = NULL, + DWORD dwProcessId = GetCurrentProcessId(), HANDLE hProcess = GetCurrentProcess() ); StackWalker(DWORD dwProcessId, HANDLE hProcess); @@ -99,8 +100,8 @@ public: BOOL LoadModules(); BOOL ShowCallstack( - HANDLE hThread = GetCurrentThread(), - const CONTEXT *context = NULL, + HANDLE hThread = GetCurrentThread(), + const CONTEXT *context = NULL, PReadProcessMemoryRoutine readMemoryFunction = NULL, LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback ); @@ -150,16 +151,16 @@ protected: // The "ugly" assembler-implementation is needed for systems before XP -// If you have a new PSDK and you only compile for XP and later, then you can use +// If you have a new PSDK and you only compile for XP and later, then you can use // the "RtlCaptureContext" -// Currently there is no define which determines the PSDK-Version... -// So we just use the compiler-version (and assumes that the PSDK is +// Currently there is no define which determines the PSDK-Version... +// So we just use the compiler-version (and assumes that the PSDK is // the one which was installed by the VS-IDE) #if defined(_M_IX86) #ifdef CURRENT_THREAD_VIA_EXCEPTION -// TODO: The following is not a "good" implementation, +// TODO: The following is not a "good" implementation, // because the callstack is only valid in the "__except" block... #define GET_CURRENT_CONTEXT(c, contextFlags) \ do { \ @@ -196,3 +197,4 @@ protected: RtlCaptureContext(&c); \ } while(0); #endif +// clang-format on diff --git a/src/Base/Stream.cpp b/src/Base/Stream.cpp index d23aa7439a..d32ff3df51 100644 --- a/src/Base/Stream.cpp +++ b/src/Base/Stream.cpp @@ -24,12 +24,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #ifdef __GNUC__ -# include +#include #endif #endif @@ -54,169 +54,202 @@ void Stream::setByteOrder(ByteOrder bo) _swap = (bo == BigEndian); } -OutputStream::OutputStream(std::ostream &rout) : _out(rout) -{ -} +OutputStream::OutputStream(std::ostream& rout) + : _out(rout) +{} OutputStream::~OutputStream() = default; -OutputStream& OutputStream::operator << (bool b) +OutputStream& OutputStream::operator<<(bool b) { _out.write((const char*)&b, sizeof(bool)); return *this; } -OutputStream& OutputStream::operator << (int8_t ch) +OutputStream& OutputStream::operator<<(int8_t ch) { _out.write((const char*)&ch, sizeof(int8_t)); return *this; } -OutputStream& OutputStream::operator << (uint8_t uch) +OutputStream& OutputStream::operator<<(uint8_t uch) { _out.write((const char*)&uch, sizeof(uint8_t)); return *this; } -OutputStream& OutputStream::operator << (int16_t s) +OutputStream& OutputStream::operator<<(int16_t s) { - if (isSwapped()) SwapEndian(s); + if (isSwapped()) { + SwapEndian(s); + } _out.write((const char*)&s, sizeof(int16_t)); return *this; } -OutputStream& OutputStream::operator << (uint16_t us) +OutputStream& OutputStream::operator<<(uint16_t us) { - if (isSwapped()) SwapEndian(us); + if (isSwapped()) { + SwapEndian(us); + } _out.write((const char*)&us, sizeof(uint16_t)); return *this; } -OutputStream& OutputStream::operator << (int32_t i) +OutputStream& OutputStream::operator<<(int32_t i) { - if (isSwapped()) SwapEndian(i); + if (isSwapped()) { + SwapEndian(i); + } _out.write((const char*)&i, sizeof(int32_t)); return *this; } -OutputStream& OutputStream::operator << (uint32_t ui) +OutputStream& OutputStream::operator<<(uint32_t ui) { - if (isSwapped()) SwapEndian(ui); + if (isSwapped()) { + SwapEndian(ui); + } _out.write((const char*)&ui, sizeof(uint32_t)); return *this; } -OutputStream& OutputStream::operator << (int64_t l) +OutputStream& OutputStream::operator<<(int64_t l) { - if (isSwapped()) SwapEndian(l); + if (isSwapped()) { + SwapEndian(l); + } _out.write((const char*)&l, sizeof(int64_t)); return *this; } -OutputStream& OutputStream::operator << (uint64_t ul) +OutputStream& OutputStream::operator<<(uint64_t ul) { - if (isSwapped()) SwapEndian(ul); + if (isSwapped()) { + SwapEndian(ul); + } _out.write((const char*)&ul, sizeof(uint64_t)); return *this; } -OutputStream& OutputStream::operator << (float f) +OutputStream& OutputStream::operator<<(float f) { - if (isSwapped()) SwapEndian(f); + if (isSwapped()) { + SwapEndian(f); + } _out.write((const char*)&f, sizeof(float)); return *this; } -OutputStream& OutputStream::operator << (double d) +OutputStream& OutputStream::operator<<(double d) { - if (isSwapped()) SwapEndian(d); + if (isSwapped()) { + SwapEndian(d); + } _out.write((const char*)&d, sizeof(double)); return *this; } -InputStream::InputStream(std::istream &rin) : _in(rin) -{ -} +InputStream::InputStream(std::istream& rin) + : _in(rin) +{} InputStream::~InputStream() = default; -InputStream& InputStream::operator >> (bool& b) +InputStream& InputStream::operator>>(bool& b) { _in.read((char*)&b, sizeof(bool)); return *this; } -InputStream& InputStream::operator >> (int8_t& ch) +InputStream& InputStream::operator>>(int8_t& ch) { _in.read((char*)&ch, sizeof(int8_t)); return *this; } -InputStream& InputStream::operator >> (uint8_t& uch) +InputStream& InputStream::operator>>(uint8_t& uch) { _in.read((char*)&uch, sizeof(uint8_t)); return *this; } -InputStream& InputStream::operator >> (int16_t& s) +InputStream& InputStream::operator>>(int16_t& s) { _in.read((char*)&s, sizeof(int16_t)); - if (isSwapped()) SwapEndian(s); + if (isSwapped()) { + SwapEndian(s); + } return *this; } -InputStream& InputStream::operator >> (uint16_t& us) +InputStream& InputStream::operator>>(uint16_t& us) { _in.read((char*)&us, sizeof(uint16_t)); - if (isSwapped()) SwapEndian(us); + if (isSwapped()) { + SwapEndian(us); + } return *this; } -InputStream& InputStream::operator >> (int32_t& i) +InputStream& InputStream::operator>>(int32_t& i) { _in.read((char*)&i, sizeof(int32_t)); - if (isSwapped()) SwapEndian(i); + if (isSwapped()) { + SwapEndian(i); + } return *this; } -InputStream& InputStream::operator >> (uint32_t& ui) +InputStream& InputStream::operator>>(uint32_t& ui) { _in.read((char*)&ui, sizeof(uint32_t)); - if (isSwapped()) SwapEndian(ui); + if (isSwapped()) { + SwapEndian(ui); + } return *this; } -InputStream& InputStream::operator >> (int64_t& l) +InputStream& InputStream::operator>>(int64_t& l) { _in.read((char*)&l, sizeof(int64_t)); - if (isSwapped()) SwapEndian(l); + if (isSwapped()) { + SwapEndian(l); + } return *this; } -InputStream& InputStream::operator >> (uint64_t& ul) +InputStream& InputStream::operator>>(uint64_t& ul) { _in.read((char*)&ul, sizeof(uint64_t)); - if (isSwapped()) SwapEndian(ul); + if (isSwapped()) { + SwapEndian(ul); + } return *this; } -InputStream& InputStream::operator >> (float& f) +InputStream& InputStream::operator>>(float& f) { _in.read((char*)&f, sizeof(float)); - if (isSwapped()) SwapEndian(f); + if (isSwapped()) { + SwapEndian(f); + } return *this; } -InputStream& InputStream::operator >> (double& d) +InputStream& InputStream::operator>>(double& d) { _in.read((char*)&d, sizeof(double)); - if (isSwapped()) SwapEndian(d); + if (isSwapped()) { + SwapEndian(d); + } return *this; } // ---------------------------------------------------------------------- -ByteArrayOStreambuf::ByteArrayOStreambuf(QByteArray& ba) : _buffer(new QBuffer(&ba)) +ByteArrayOStreambuf::ByteArrayOStreambuf(QByteArray& ba) + : _buffer(new QBuffer(&ba)) { _buffer->open(QIODevice::WriteOnly); } @@ -227,27 +260,25 @@ ByteArrayOStreambuf::~ByteArrayOStreambuf() delete _buffer; } -std::streambuf::int_type -ByteArrayOStreambuf::overflow(std::streambuf::int_type c) +std::streambuf::int_type ByteArrayOStreambuf::overflow(std::streambuf::int_type c) { if (c != EOF) { char z = static_cast(c); - if (_buffer->write (&z, 1) != 1) { + if (_buffer->write(&z, 1) != 1) { return EOF; } } return c; } -std::streamsize ByteArrayOStreambuf::xsputn (const char* s, std::streamsize num) +std::streamsize ByteArrayOStreambuf::xsputn(const char* s, std::streamsize num) { - return _buffer->write(s,num); + return _buffer->write(s, num); } -std::streambuf::pos_type -ByteArrayOStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayOStreambuf::seekoff(std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = _buffer->pos(); @@ -266,16 +297,16 @@ ByteArrayOStreambuf::seekoff(std::streambuf::off_type off, } if (endpos != curpos) { - if (!_buffer->seek(endpos)) + if (!_buffer->seek(endpos)) { endpos = -1; + } } return {endpos}; } -std::streambuf::pos_type -ByteArrayOStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayOStreambuf::seekpos(std::streambuf::pos_type pos, + std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -287,31 +318,33 @@ ByteArrayIStreambuf::ByteArrayIStreambuf(const QByteArray& data) , _beg(0) , _end(data.size()) , _cur(0) -{ -} +{} ByteArrayIStreambuf::~ByteArrayIStreambuf() = default; ByteArrayIStreambuf::int_type ByteArrayIStreambuf::underflow() { - if (_cur == _end) + if (_cur == _end) { return traits_type::eof(); + } return static_cast(_buffer[_cur]) & 0x000000ff; } ByteArrayIStreambuf::int_type ByteArrayIStreambuf::uflow() { - if (_cur == _end) + if (_cur == _end) { return traits_type::eof(); + } return static_cast(_buffer[_cur++]) & 0x000000ff; } ByteArrayIStreambuf::int_type ByteArrayIStreambuf::pbackfail(int_type ch) { - if (_cur == _beg || (ch != traits_type::eof() && ch != _buffer[_cur-1])) + if (_cur == _beg || (ch != traits_type::eof() && ch != _buffer[_cur - 1])) { return traits_type::eof(); + } return static_cast(_buffer[--_cur]) & 0x000000ff; } @@ -321,66 +354,67 @@ std::streamsize ByteArrayIStreambuf::showmanyc() return _end - _cur; } -std::streambuf::pos_type -ByteArrayIStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/ ) +std::streambuf::pos_type ByteArrayIStreambuf::seekoff(std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode /*mode*/) { - int p_pos=-1; - if (way == std::ios_base::beg) + int p_pos = -1; + if (way == std::ios_base::beg) { p_pos = _beg; - else if (way == std::ios_base::end) + } + else if (way == std::ios_base::end) { p_pos = _end; - else if (way == std::ios_base::cur) + } + else if (way == std::ios_base::cur) { p_pos = _cur; + } - if (p_pos > _end) + if (p_pos > _end) { return traits_type::eof(); + } - if (((p_pos + off) > _end) || ((p_pos + off) < _beg)) + if (((p_pos + off) > _end) || ((p_pos + off) < _beg)) { return traits_type::eof(); + } - _cur = p_pos+ off; + _cur = p_pos + off; - return ((p_pos+off) - _beg); + return ((p_pos + off) - _beg); } -std::streambuf::pos_type -ByteArrayIStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayIStreambuf::seekpos(std::streambuf::pos_type pos, + std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } // ---------------------------------------------------------------------- -IODeviceOStreambuf::IODeviceOStreambuf(QIODevice* dev) : device(dev) -{ -} +IODeviceOStreambuf::IODeviceOStreambuf(QIODevice* dev) + : device(dev) +{} IODeviceOStreambuf::~IODeviceOStreambuf() = default; -std::streambuf::int_type -IODeviceOStreambuf::overflow(std::streambuf::int_type c) +std::streambuf::int_type IODeviceOStreambuf::overflow(std::streambuf::int_type c) { if (c != EOF) { char z = static_cast(c); - if (device->write (&z, 1) != 1) { + if (device->write(&z, 1) != 1) { return EOF; } } return c; } -std::streamsize IODeviceOStreambuf::xsputn (const char* s, std::streamsize num) +std::streamsize IODeviceOStreambuf::xsputn(const char* s, std::streamsize num) { - return device->write(s,num); + return device->write(s, num); } -std::streambuf::pos_type -IODeviceOStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceOStreambuf::seekoff(std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = device->pos(); @@ -399,36 +433,36 @@ IODeviceOStreambuf::seekoff(std::streambuf::off_type off, } if (endpos != curpos) { - if (!device->seek(endpos)) + if (!device->seek(endpos)) { endpos = -1; + } } return {endpos}; } -std::streambuf::pos_type -IODeviceOStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceOStreambuf::seekpos(std::streambuf::pos_type pos, + std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } // ---------------------------------------------------------------------- -IODeviceIStreambuf::IODeviceIStreambuf(QIODevice* dev) : device(dev) +IODeviceIStreambuf::IODeviceIStreambuf(QIODevice* dev) + : device(dev) { - setg (buffer+pbSize, // beginning of putback area - buffer+pbSize, // read position - buffer+pbSize); // end position + setg(buffer + pbSize, // beginning of putback area + buffer + pbSize, // read position + buffer + pbSize); // end position } IODeviceIStreambuf::~IODeviceIStreambuf() = default; -std::streambuf::int_type -IODeviceIStreambuf::underflow() +std::streambuf::int_type IODeviceIStreambuf::underflow() { #ifndef _MSC_VER -using std::memcpy; + using std::memcpy; #endif // is read position before end of buffer? @@ -440,7 +474,7 @@ using std::memcpy; * - use number of characters read * - but at most size of putback area */ - int numPutback{}; + int numPutback {}; numPutback = gptr() - eback(); if (numPutback > pbSize) { numPutback = pbSize; @@ -449,30 +483,28 @@ using std::memcpy; /* copy up to pbSize characters previously read into * the putback area */ - memcpy (buffer+(pbSize-numPutback), gptr()-numPutback, - numPutback); + memcpy(buffer + (pbSize - numPutback), gptr() - numPutback, numPutback); // read at most bufSize new characters - int num{}; - num = device->read(buffer+pbSize, bufSize); + int num {}; + num = device->read(buffer + pbSize, bufSize); if (num <= 0) { // ERROR or EOF return EOF; } // reset buffer pointers - setg (buffer+(pbSize-numPutback), // beginning of putback area - buffer+pbSize, // read position - buffer+pbSize+num); // end of buffer + setg(buffer + (pbSize - numPutback), // beginning of putback area + buffer + pbSize, // read position + buffer + pbSize + num); // end of buffer // return next character return *gptr(); } -std::streambuf::pos_type -IODeviceIStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceIStreambuf::seekoff(std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = device->pos(); @@ -491,16 +523,16 @@ IODeviceIStreambuf::seekoff(std::streambuf::off_type off, } if (endpos != curpos) { - if (!device->seek(endpos)) + if (!device->seek(endpos)) { endpos = -1; + } } return {endpos}; } -std::streambuf::pos_type -IODeviceIStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceIStreambuf::seekpos(std::streambuf::pos_type pos, + std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -517,10 +549,10 @@ PyStreambuf::PyStreambuf(PyObject* o, std::size_t buf_size, std::size_t put_back , buffer(std::max(buf_size, put_back) + put_back) { Py_INCREF(inp); - char *end = &buffer.front() + buffer.size(); + char* end = &buffer.front() + buffer.size(); setg(end, end, end); #ifdef PYSTREAM_BUFFERED - char *base = &buffer.front(); + char* base = &buffer.front(); setp(base, base + buffer.size()); #endif } @@ -537,15 +569,15 @@ PyStreambuf::int_type PyStreambuf::underflow() return traits_type::to_int_type(*gptr()); } - char *base = &buffer.front(); - char *start = base; + char* base = &buffer.front(); + char* start = base; - if (eback() == base) { // true when this isn't the first fill + if (eback() == base) { // true when this isn't the first fill std::memmove(base, egptr() - put_back, put_back); start += put_back; } - std::size_t n{}; + std::size_t n {}; Py::Tuple arg(1); long len = static_cast(buffer.size() - (start - base)); arg.setItem(0, Py::Long(len)); @@ -581,8 +613,7 @@ PyStreambuf::int_type PyStreambuf::underflow() return traits_type::to_int_type(*gptr()); } -PyStreambuf::int_type -PyStreambuf::overflow(PyStreambuf::int_type ch) +PyStreambuf::int_type PyStreambuf::overflow(PyStreambuf::int_type ch) { #ifdef PYSTREAM_BUFFERED sync(); @@ -596,8 +627,9 @@ PyStreambuf::overflow(PyStreambuf::int_type ch) #else if (ch != EOF) { char z = ch; - if (!writeStr(&z, 1)) + if (!writeStr(&z, 1)) { return traits_type::eof(); + } } return ch; @@ -656,45 +688,47 @@ bool PyStreambuf::writeStr(const char* str, std::streamsize num) return true; } else { - throw; // re-throw + throw; // re-throw } } } } - catch(Py::Exception& e) { + catch (Py::Exception& e) { e.clear(); } return false; } -std::streamsize PyStreambuf::xsputn (const char* s, std::streamsize num) +std::streamsize PyStreambuf::xsputn(const char* s, std::streamsize num) { #ifdef PYSTREAM_BUFFERED return std::streambuf::xsputn(s, num); #else - if (!writeStr(s, num)) + if (!writeStr(s, num)) { return 0; + } return num; #endif } -PyStreambuf::pos_type -PyStreambuf::seekoff(PyStreambuf::off_type offset, PyStreambuf::seekdir dir, PyStreambuf::openmode /*mode*/) +PyStreambuf::pos_type PyStreambuf::seekoff(PyStreambuf::off_type offset, + PyStreambuf::seekdir dir, + PyStreambuf::openmode /*mode*/) { int whence = 0; switch (dir) { - case std::ios_base::beg: - whence = 0; - break; - case std::ios_base::cur: - whence = 1; - break; - case std::ios_base::end: - whence = 2; - break; - default: - return {off_type(-1)}; + case std::ios_base::beg: + whence = 0; + break; + case std::ios_base::cur: + whence = 1; + break; + case std::ios_base::end: + whence = 2; + break; + default: + return {off_type(-1)}; } try { @@ -711,14 +745,13 @@ PyStreambuf::seekoff(PyStreambuf::off_type offset, PyStreambuf::seekdir dir, PyS long cur_pos = static_cast(pos); return static_cast(cur_pos); } - catch(Py::Exception& e) { + catch (Py::Exception& e) { e.clear(); return {off_type(-1)}; } } -PyStreambuf::pos_type -PyStreambuf::seekpos(PyStreambuf::pos_type offset, PyStreambuf::openmode mode) +PyStreambuf::pos_type PyStreambuf::seekpos(PyStreambuf::pos_type offset, PyStreambuf::openmode mode) { return seekoff(offset, std::ios::beg, mode); } @@ -729,32 +762,35 @@ Streambuf::Streambuf(const std::string& data) { _beg = data.begin(); _end = data.end(); - _cur = _beg; //NOLINT + _cur = _beg; // NOLINT } Streambuf::~Streambuf() = default; Streambuf::int_type Streambuf::underflow() { - if (_cur == _end) + if (_cur == _end) { return traits_type::eof(); + } return static_cast(*_cur) & 0x000000ff; } Streambuf::int_type Streambuf::uflow() { - if (_cur == _end) + if (_cur == _end) { return traits_type::eof(); + } return static_cast(*_cur++) & 0x000000ff; } -Streambuf::int_type Streambuf::pbackfail( int_type ch ) +Streambuf::int_type Streambuf::pbackfail(int_type ch) { /* coverity[negative_returns] _cur is an iterator */ - if (_cur == _beg || (ch != traits_type::eof() && ch != _cur[-1])) + if (_cur == _beg || (ch != traits_type::eof() && ch != _cur[-1])) { return traits_type::eof(); + } return static_cast(*--_cur) & 0x000000ff; } @@ -764,33 +800,36 @@ std::streamsize Streambuf::showmanyc() return _end - _cur; } -std::streambuf::pos_type -Streambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/ ) +std::streambuf::pos_type Streambuf::seekoff(std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode /*mode*/) { std::string::const_iterator p_pos; - if (way == std::ios_base::beg) + if (way == std::ios_base::beg) { p_pos = _beg; - else if (way == std::ios_base::end) + } + else if (way == std::ios_base::end) { p_pos = _end; - else if (way == std::ios_base::cur) + } + else if (way == std::ios_base::cur) { p_pos = _cur; + } - if (p_pos > _end) + if (p_pos > _end) { return traits_type::eof(); + } - if (((p_pos + off) > _end) || ((p_pos + off) < _beg)) + if (((p_pos + off) > _end) || ((p_pos + off) < _beg)) { return traits_type::eof(); + } - _cur = p_pos+ off; + _cur = p_pos + off; - return ((p_pos+off) - _beg); + return ((p_pos + off) - _beg); } -std::streambuf::pos_type -Streambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type Streambuf::seekpos(std::streambuf::pos_type pos, + std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } diff --git a/src/Base/Stream.h b/src/Base/Stream.h index 10097b0757..e7664211a3 100644 --- a/src/Base/Stream.h +++ b/src/Base/Stream.h @@ -25,7 +25,7 @@ #define BASE_STREAM_H #ifdef __GNUC__ -# include +#include #endif #include @@ -40,12 +40,17 @@ class QIODevice; class QBuffer; using PyObject = struct _object; -namespace Base { +namespace Base +{ class BaseExport Stream { public: - enum ByteOrder { BigEndian, LittleEndian }; + enum ByteOrder + { + BigEndian, + LittleEndian + }; ByteOrder byteOrder() const; void setByteOrder(ByteOrder); @@ -58,38 +63,41 @@ protected: Stream& operator=(const Stream&) = default; Stream& operator=(Stream&&) = default; - bool isSwapped() const { return _swap; }; + bool isSwapped() const + { + return _swap; + }; private: - bool _swap{false}; + bool _swap {false}; }; /** * The OutputStream class provides writing of binary data to an ostream. * @author Werner Mayer */ -class BaseExport OutputStream : public Stream +class BaseExport OutputStream: public Stream { public: - OutputStream(std::ostream &rout); + OutputStream(std::ostream& rout); ~OutputStream() override; - OutputStream& operator << (bool b); - OutputStream& operator << (int8_t ch); - OutputStream& operator << (uint8_t uch); - OutputStream& operator << (int16_t s); - OutputStream& operator << (uint16_t us); - OutputStream& operator << (int32_t i); - OutputStream& operator << (uint32_t ui); - OutputStream& operator << (int64_t l); - OutputStream& operator << (uint64_t ul); - OutputStream& operator << (float f); - OutputStream& operator << (double d); + OutputStream& operator<<(bool b); + OutputStream& operator<<(int8_t ch); + OutputStream& operator<<(uint8_t uch); + OutputStream& operator<<(int16_t s); + OutputStream& operator<<(uint16_t us); + OutputStream& operator<<(int32_t i); + OutputStream& operator<<(uint32_t ui); + OutputStream& operator<<(int64_t l); + OutputStream& operator<<(uint64_t ul); + OutputStream& operator<<(float f); + OutputStream& operator<<(double d); - OutputStream (const OutputStream&) = delete; - OutputStream (OutputStream&&) = delete; - void operator = (const OutputStream&) = delete; - void operator = (OutputStream&&) = delete; + OutputStream(const OutputStream&) = delete; + OutputStream(OutputStream&&) = delete; + void operator=(const OutputStream&) = delete; + void operator=(OutputStream&&) = delete; private: std::ostream& _out; @@ -99,23 +107,23 @@ private: * The InputStream class provides reading of binary data from an istream. * @author Werner Mayer */ -class BaseExport InputStream : public Stream +class BaseExport InputStream: public Stream { public: - InputStream(std::istream &rin); + InputStream(std::istream& rin); ~InputStream() override; - InputStream& operator >> (bool& b); - InputStream& operator >> (int8_t& ch); - InputStream& operator >> (uint8_t& uch); - InputStream& operator >> (int16_t& s); - InputStream& operator >> (uint16_t& us); - InputStream& operator >> (int32_t& i); - InputStream& operator >> (uint32_t& ui); - InputStream& operator >> (int64_t& l); - InputStream& operator >> (uint64_t& ul); - InputStream& operator >> (float& f); - InputStream& operator >> (double& d); + InputStream& operator>>(bool& b); + InputStream& operator>>(int8_t& ch); + InputStream& operator>>(uint8_t& uch); + InputStream& operator>>(int16_t& s); + InputStream& operator>>(uint16_t& us); + InputStream& operator>>(int32_t& i); + InputStream& operator>>(uint32_t& ui); + InputStream& operator>>(int64_t& l); + InputStream& operator>>(uint64_t& ul); + InputStream& operator>>(float& f); + InputStream& operator>>(double& d); operator bool() const { @@ -123,10 +131,10 @@ public: return !_in.eof(); } - InputStream (const InputStream&) = delete; - InputStream (InputStream&&) = delete; - void operator = (const InputStream&) = delete; - void operator = (InputStream&&) = delete; + InputStream(const InputStream&) = delete; + InputStream(InputStream&&) = delete; + void operator=(const InputStream&) = delete; + void operator=(InputStream&&) = delete; private: std::istream& _in; @@ -139,7 +147,7 @@ private: * This class can only be used for writing but not for reading purposes. * @author Werner Mayer */ -class BaseExport ByteArrayOStreambuf : public std::streambuf +class BaseExport ByteArrayOStreambuf: public std::streambuf { public: explicit ByteArrayOStreambuf(QByteArray& ba); @@ -147,14 +155,12 @@ public: protected: int_type overflow(std::streambuf::int_type v) override; - std::streamsize xsputn (const char* s, std::streamsize num) override; + std::streamsize xsputn(const char* s, std::streamsize num) override; pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out) override; pos_type seekpos(std::streambuf::pos_type sp, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::openmode which = std::ios::in | std::ios::out) override; public: ByteArrayOStreambuf(const ByteArrayOStreambuf&) = delete; @@ -171,7 +177,7 @@ private: * This class can only be used for reading but not for writing purposes. * @author Werner Mayer */ -class BaseExport ByteArrayIStreambuf : public std::streambuf +class BaseExport ByteArrayIStreambuf: public std::streambuf { public: explicit ByteArrayIStreambuf(const QByteArray& buf); @@ -183,12 +189,11 @@ protected: int_type pbackfail(int_type ch) override; std::streamsize showmanyc() override; pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out) override; pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::openmode which = std::ios::in | std::ios::out) override; + public: ByteArrayIStreambuf(const ByteArrayIStreambuf&) = delete; ByteArrayIStreambuf(ByteArrayIStreambuf&&) = delete; @@ -205,7 +210,7 @@ private: * This class can only be used for writing but not reading purposes. * @author Werner Mayer */ -class BaseExport IODeviceOStreambuf : public std::streambuf +class BaseExport IODeviceOStreambuf: public std::streambuf { public: IODeviceOStreambuf(QIODevice* dev); @@ -213,14 +218,13 @@ public: protected: int_type overflow(std::streambuf::int_type v) override; - std::streamsize xsputn (const char* s, std::streamsize num) override; + std::streamsize xsputn(const char* s, std::streamsize num) override; pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out) override; pos_type seekpos(std::streambuf::pos_type sp, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::openmode which = std::ios::in | std::ios::out) override; + public: IODeviceOStreambuf(const IODeviceOStreambuf&) = delete; IODeviceOStreambuf(IODeviceOStreambuf&&) = delete; @@ -236,7 +240,7 @@ private: * This class can only be used for readihg but not writing purposes. * @author Werner Mayer */ -class BaseExport IODeviceIStreambuf : public std::streambuf +class BaseExport IODeviceIStreambuf: public std::streambuf { public: IODeviceIStreambuf(QIODevice* dev); @@ -245,12 +249,11 @@ public: protected: int_type underflow() override; pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out) override; pos_type seekpos(std::streambuf::pos_type sp, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::openmode which = std::ios::in | std::ios::out) override; + public: IODeviceIStreambuf(const IODeviceIStreambuf&) = delete; IODeviceIStreambuf(IODeviceIStreambuf&&) = delete; @@ -263,21 +266,22 @@ private: * - at most, pbSize characters in putback area plus * - at most, bufSize characters in ordinary read buffer */ - static const int pbSize = 4; // size of putback area - static const int bufSize = 1024; // size of the data buffer - char buffer[bufSize+pbSize]{}; // data buffer + static const int pbSize = 4; // size of putback area + static const int bufSize = 1024; // size of the data buffer + char buffer[bufSize + pbSize] {}; // data buffer }; -class BaseExport PyStreambuf : public std::streambuf +class BaseExport PyStreambuf: public std::streambuf { using int_type = std::streambuf::int_type; using pos_type = std::streambuf::pos_type; using off_type = std::streambuf::off_type; - using seekdir = std::ios::seekdir; + using seekdir = std::ios::seekdir; using openmode = std::ios::openmode; public: - enum Type { + enum Type + { StringIO, BytesIO, Unknown @@ -285,14 +289,15 @@ public: PyStreambuf(PyObject* o, std::size_t buf_size = 256, std::size_t put_back = 8); ~PyStreambuf() override; - void setType(Type t) { + void setType(Type t) + { type = t; } protected: int_type underflow() override; int_type overflow(int_type c = EOF) override; - std::streamsize xsputn (const char* s, std::streamsize num) override; + std::streamsize xsputn(const char* s, std::streamsize num) override; int sync() override; pos_type seekoff(off_type offset, seekdir dir, openmode) override; pos_type seekpos(pos_type offset, openmode mode) override; @@ -309,12 +314,12 @@ public: private: PyObject* inp; - Type type{Unknown}; + Type type {Unknown}; const std::size_t put_back; std::vector buffer; }; -class BaseExport Streambuf : public std::streambuf +class BaseExport Streambuf: public std::streambuf { public: explicit Streambuf(const std::string& data); @@ -326,12 +331,10 @@ protected: int_type pbackfail(int_type ch) override; std::streamsize showmanyc() override; pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out) override; pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = - std::ios::in | std::ios::out) override; + std::ios_base::openmode which = std::ios::in | std::ios::out) override; public: Streambuf(const Streambuf&) = delete; @@ -355,22 +358,22 @@ class FileInfo; * while on Linux platforms the file name is UTF-8 encoded. * @author Werner Mayer */ -class ofstream : public std::ofstream +class ofstream: public std::ofstream { public: ofstream() = default; ofstream(const ofstream&) = delete; ofstream(ofstream&&) = delete; - ofstream(const FileInfo& fi, ios_base::openmode mode = - std::ios::out | std::ios::trunc) + ofstream(const FileInfo& fi, ios_base::openmode mode = std::ios::out | std::ios::trunc) #ifdef _MSC_VER - : std::ofstream(fi.toStdWString().c_str(), mode) {} + : std::ofstream(fi.toStdWString().c_str(), mode) {} #else - : std::ofstream(fi.filePath().c_str(), mode) {} + : std::ofstream(fi.filePath().c_str(), mode) + {} #endif - ~ofstream() override = default; - void open(const FileInfo& fi, ios_base::openmode mode = - std::ios::out | std::ios::trunc) { + ~ofstream() override = default; + void open(const FileInfo& fi, ios_base::openmode mode = std::ios::out | std::ios::trunc) + { #ifdef _MSC_VER std::ofstream::open(fi.toStdWString().c_str(), mode); #else @@ -378,8 +381,8 @@ public: #endif } - ofstream& operator = (const ofstream&) = delete; - ofstream& operator = (ofstream&&) = delete; + ofstream& operator=(const ofstream&) = delete; + ofstream& operator=(ofstream&&) = delete; }; /** @@ -388,22 +391,22 @@ public: * while on Linux platforms the file name is UTF-8 encoded. * @author Werner Mayer */ -class ifstream : public std::ifstream +class ifstream: public std::ifstream { public: ifstream() = default; ifstream(const ifstream&) = delete; ifstream(ifstream&&) = delete; - ifstream(const FileInfo& fi, ios_base::openmode mode = - std::ios::in) + ifstream(const FileInfo& fi, ios_base::openmode mode = std::ios::in) #ifdef _MSC_VER - : std::ifstream(fi.toStdWString().c_str(), mode) {} + : std::ifstream(fi.toStdWString().c_str(), mode) {} #else - : std::ifstream(fi.filePath().c_str(), mode) {} + : std::ifstream(fi.filePath().c_str(), mode) + {} #endif - ~ifstream() override = default; - void open(const FileInfo& fi, ios_base::openmode mode = - std::ios::in) { + ~ifstream() override = default; + void open(const FileInfo& fi, ios_base::openmode mode = std::ios::in) + { #ifdef _MSC_VER std::ifstream::open(fi.toStdWString().c_str(), mode); #else @@ -411,10 +414,10 @@ public: #endif } - ifstream& operator = (const ifstream&) = delete; - ifstream& operator = (ifstream&&) = delete; + ifstream& operator=(const ifstream&) = delete; + ifstream& operator=(ifstream&&) = delete; }; -} // namespace Base +} // namespace Base -#endif // BASE_STREAM_H +#endif // BASE_STREAM_H diff --git a/src/Base/Swap.cpp b/src/Base/Swap.cpp index 159793936a..26cdb337bb 100644 --- a/src/Base/Swap.cpp +++ b/src/Base/Swap.cpp @@ -25,78 +25,80 @@ #include "Swap.h" -unsigned short Base::SwapOrder () +unsigned short Base::SwapOrder() { - unsigned short usDummy = 1; - return *((char*) &usDummy) == 1 ? LOW_ENDIAN : HIGH_ENDIAN; + unsigned short usDummy = 1; + return *((char*)&usDummy) == 1 ? LOW_ENDIAN : HIGH_ENDIAN; } -void Base::SwapVar (char&) +void Base::SwapVar(char&) +{} + +void Base::SwapVar(unsigned char&) +{} + +void Base::SwapVar(short& s) { + short sTmp = s; + int i = 0; + + for (i = 0; i < (int)sizeof(short); i++) { + *(((char*)&sTmp) + i) = *(((char*)&s) + sizeof(short) - i - 1); + } + s = sTmp; } -void Base::SwapVar (unsigned char&) +void Base::SwapVar(unsigned short& s) { + short sTmp = s; + int i = 0; + + for (i = 0; i < (int)sizeof(short); i++) { + *(((char*)&sTmp) + i) = *(((char*)&s) + sizeof(short) - i - 1); + } + s = sTmp; } -void Base::SwapVar (short& s) +void Base::SwapVar(long& l) { - short sTmp = s; - int i = 0; + long lTmp = l; + int i = 0; - for (i = 0; i < (int)sizeof (short); i++) - *(((char*) &sTmp) + i) = *(((char*) &s) + sizeof (short) - i - 1); - s = sTmp; + for (i = 0; i < (int)sizeof(long); i++) { + *(((char*)&lTmp) + i) = *(((char*)&l) + sizeof(long) - i - 1); + } + l = lTmp; } -void Base::SwapVar (unsigned short& s) +void Base::SwapVar(unsigned long& l) { - short sTmp = s; - int i = 0; + long lTmp = l; + int i = 0; - for (i = 0; i < (int)sizeof (short); i++) - *(((char*) &sTmp) + i) = *(((char*) &s) + sizeof (short) - i - 1); - s = sTmp; + for (i = 0; i < (int)sizeof(long); i++) { + *(((char*)&lTmp) + i) = *(((char*)&l) + sizeof(long) - i - 1); + } + l = lTmp; } -void Base::SwapVar (long& l) +void Base::SwapVar(float& f) { - long lTmp = l; - int i = 0; + float fTmp = f; + int i = 0; - for (i = 0; i < (int)sizeof (long); i++) - *(((char*) &lTmp) + i) = *(((char*) &l) + sizeof (long) - i - 1); - l = lTmp; + for (i = 0; i < (int)sizeof(float); i++) { + *(((char*)&fTmp) + i) = *(((char*)&f) + sizeof(float) - i - 1); + } + f = fTmp; } -void Base::SwapVar (unsigned long& l) +void Base::SwapVar(double& d) { - long lTmp = l; - int i = 0; + double dTmp = d; + int i = 0; - for (i = 0; i < (int)sizeof (long); i++) - *(((char*) &lTmp) + i) = *(((char*) &l) + sizeof (long) - i - 1); - l = lTmp; + for (i = 0; i < (int)sizeof(double); i++) { + *(((char*)&dTmp) + i) = *(((char*)&d) + sizeof(double) - i - 1); + } + d = dTmp; } - -void Base::SwapVar (float& f) -{ - float fTmp = f; - int i = 0; - - for (i = 0; i < (int)sizeof (float); i++) - *(((char*) &fTmp) + i) = *(((char*) &f) + sizeof (float) - i - 1); - f = fTmp; -} - -void Base::SwapVar (double& d) -{ - double dTmp = d; - int i = 0; - - for (i = 0; i < (int)sizeof (double); i++) - *(((char*) &dTmp) + i) = *(((char*) &d) + sizeof (double) - i - 1); - d = dTmp; -} - - diff --git a/src/Base/Swap.h b/src/Base/Swap.h index c04a6911c1..3dc27884d6 100644 --- a/src/Base/Swap.h +++ b/src/Base/Swap.h @@ -24,11 +24,12 @@ #ifndef BASE_SWAP_H #define BASE_SWAP_H -#define LOW_ENDIAN (unsigned short) 0x4949 -#define HIGH_ENDIAN (unsigned short) 0x4D4D +#define LOW_ENDIAN (unsigned short)0x4949 +#define HIGH_ENDIAN (unsigned short)0x4D4D -namespace Base { +namespace Base +{ /** * \brief Definition of functions that allow swapping of data types @@ -36,29 +37,30 @@ namespace Base { */ /** Returns machine type (low endian, high endian) */ -unsigned short SwapOrder (); +unsigned short SwapOrder(); -void SwapVar (char&); -void SwapVar (unsigned char&); -void SwapVar (short&); -void SwapVar (unsigned short&); -void SwapVar (long&); -void SwapVar (unsigned long&); -void SwapVar (float&); -void SwapVar (double&); +void SwapVar(char&); +void SwapVar(unsigned char&); +void SwapVar(short&); +void SwapVar(unsigned short&); +void SwapVar(long&); +void SwapVar(unsigned long&); +void SwapVar(float&); +void SwapVar(double&); -template +template void SwapEndian(T& v) { - T tmp = v; - int i = 0; + T tmp = v; + int i = 0; - for (i = 0; i < (int)sizeof (T); i++) - *(((char*) &tmp) + i) = *(((char*) &v) + sizeof (T) - i - 1); - v = tmp; + for (i = 0; i < (int)sizeof(T); i++) { + *(((char*)&tmp) + i) = *(((char*)&v) + sizeof(T) - i - 1); + } + v = tmp; } -} // namespace Base +} // namespace Base -#endif // BASE_SWAP_H +#endif // BASE_SWAP_H diff --git a/src/Base/TimeInfo.cpp b/src/Base/TimeInfo.cpp index 9ea9c49f0a..8b14da8bd2 100644 --- a/src/Base/TimeInfo.cpp +++ b/src/Base/TimeInfo.cpp @@ -24,11 +24,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# if defined(FC_OS_LINUX) || defined(__MINGW32__) -# include -# endif +#include +#include +#if defined(FC_OS_LINUX) || defined(__MINGW32__) +#include +#endif #endif #include "TimeInfo.h" @@ -58,7 +58,7 @@ TimeInfo::~TimeInfo() = default; void TimeInfo::setCurrent() { -#if defined (FC_OS_BSD) || defined(FC_OS_LINUX) || defined(__MINGW32__) +#if defined(FC_OS_BSD) || defined(FC_OS_LINUX) || defined(__MINGW32__) struct timeval t; gettimeofday(&t, nullptr); timebuffer.time = t.tv_sec; @@ -66,29 +66,31 @@ void TimeInfo::setCurrent() #elif defined(FC_OS_WIN32) _ftime(&timebuffer); #else - ftime(&timebuffer); // deprecated + ftime(&timebuffer); // deprecated #endif } -void TimeInfo::setTime_t (int64_t seconds) +void TimeInfo::setTime_t(int64_t seconds) { timebuffer.time = seconds; } std::string TimeInfo::currentDateTimeString() { - return QDateTime::currentDateTime().toTimeSpec(Qt::OffsetFromUTC) - .toString(Qt::ISODate).toStdString(); + return QDateTime::currentDateTime() + .toTimeSpec(Qt::OffsetFromUTC) + .toString(Qt::ISODate) + .toStdString(); } -std::string TimeInfo::diffTime(const TimeInfo &timeStart,const TimeInfo &timeEnd ) +std::string TimeInfo::diffTime(const TimeInfo& timeStart, const TimeInfo& timeEnd) { - std::stringstream str; - str << diffTimeF(timeStart,timeEnd); - return str.str(); + std::stringstream str; + str << diffTimeF(timeStart, timeEnd); + return str.str(); } -float TimeInfo::diffTimeF(const TimeInfo &timeStart,const TimeInfo &timeEnd ) +float TimeInfo::diffTimeF(const TimeInfo& timeStart, const TimeInfo& timeEnd) { int64_t ds = int64_t(timeEnd.getSeconds() - timeStart.getSeconds()); int dms = int(timeEnd.getMiliseconds()) - int(timeStart.getMiliseconds()); diff --git a/src/Base/TimeInfo.h b/src/Base/TimeInfo.h index 73799ffdc9..084dddd2f2 100644 --- a/src/Base/TimeInfo.h +++ b/src/Base/TimeInfo.h @@ -36,7 +36,7 @@ #include #ifdef __GNUC__ -# include +#include #endif #include @@ -65,28 +65,28 @@ public: /// sets the object to the actual system time void setCurrent(); - void setTime_t (int64_t seconds); + void setTime_t(int64_t seconds); int64_t getSeconds() const; - unsigned short getMiliseconds() const; + unsigned short getMiliseconds() const; - void operator = (const TimeInfo &time); - bool operator == (const TimeInfo &time) const; - bool operator != (const TimeInfo &time) const; + void operator=(const TimeInfo& time); + bool operator==(const TimeInfo& time) const; + bool operator!=(const TimeInfo& time) const; - bool operator < (const TimeInfo &time) const; - bool operator <= (const TimeInfo &time) const; - bool operator >= (const TimeInfo &time) const; - bool operator > (const TimeInfo &time) const; + bool operator<(const TimeInfo& time) const; + bool operator<=(const TimeInfo& time) const; + bool operator>=(const TimeInfo& time) const; + bool operator>(const TimeInfo& time) const; static std::string currentDateTimeString(); - static std::string diffTime(const TimeInfo &timeStart,const TimeInfo &timeEnd = TimeInfo()); - static float diffTimeF(const TimeInfo &timeStart,const TimeInfo &timeEnd = TimeInfo()); + static std::string diffTime(const TimeInfo& timeStart, const TimeInfo& timeEnd = TimeInfo()); + static float diffTimeF(const TimeInfo& timeStart, const TimeInfo& timeEnd = TimeInfo()); bool isNull() const; static TimeInfo null(); protected: -#if defined (_MSC_VER) +#if defined(_MSC_VER) struct _timeb timebuffer; #elif defined(__GNUC__) struct timeb timebuffer; @@ -94,72 +94,74 @@ protected: }; - inline int64_t TimeInfo::getSeconds() const - { - return timebuffer.time; - } - - inline unsigned short TimeInfo::getMiliseconds() const - { - return timebuffer.millitm; - } - -inline bool -TimeInfo::operator != (const TimeInfo &time) const +inline int64_t TimeInfo::getSeconds() const { - return (timebuffer.time != time.timebuffer.time || timebuffer.millitm != time.timebuffer.millitm); + return timebuffer.time; } -inline void -TimeInfo::operator = (const TimeInfo &time) +inline unsigned short TimeInfo::getMiliseconds() const +{ + return timebuffer.millitm; +} + +inline bool TimeInfo::operator!=(const TimeInfo& time) const +{ + return (timebuffer.time != time.timebuffer.time + || timebuffer.millitm != time.timebuffer.millitm); +} + +inline void TimeInfo::operator=(const TimeInfo& time) { timebuffer = time.timebuffer; } -inline bool -TimeInfo::operator == (const TimeInfo &time) const +inline bool TimeInfo::operator==(const TimeInfo& time) const { - return (timebuffer.time == time.timebuffer.time && timebuffer.millitm == time.timebuffer.millitm); + return (timebuffer.time == time.timebuffer.time + && timebuffer.millitm == time.timebuffer.millitm); } -inline bool -TimeInfo::operator < (const TimeInfo &time) const +inline bool TimeInfo::operator<(const TimeInfo& time) const { - if (timebuffer.time == time.timebuffer.time) + if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm < time.timebuffer.millitm; - else + } + else { return timebuffer.time < time.timebuffer.time; + } } -inline bool -TimeInfo::operator <= (const TimeInfo &time) const +inline bool TimeInfo::operator<=(const TimeInfo& time) const { - if (timebuffer.time == time.timebuffer.time) + if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm <= time.timebuffer.millitm; - else + } + else { return timebuffer.time <= time.timebuffer.time; + } } -inline bool -TimeInfo::operator >= (const TimeInfo &time) const +inline bool TimeInfo::operator>=(const TimeInfo& time) const { - if (timebuffer.time == time.timebuffer.time) + if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm >= time.timebuffer.millitm; - else + } + else { return timebuffer.time >= time.timebuffer.time; + } } -inline bool -TimeInfo::operator > (const TimeInfo &time) const +inline bool TimeInfo::operator>(const TimeInfo& time) const { - if (timebuffer.time == time.timebuffer.time) + if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm > time.timebuffer.millitm; - else + } + else { return timebuffer.time > time.timebuffer.time; + } } -} //namespace Base +} // namespace Base -#endif // BASE_TIMEINFO_H - +#endif // BASE_TIMEINFO_H diff --git a/src/Base/Tools.cpp b/src/Base/Tools.cpp index 8bcbe30f92..224c123ba9 100644 --- a/src/Base/Tools.cpp +++ b/src/Base/Tools.cpp @@ -23,39 +23,44 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #endif #include "PyExport.h" #include "Interpreter.h" #include "Tools.h" -namespace Base { +namespace Base +{ struct string_comp { // s1 and s2 must be numbers represented as string bool operator()(const std::string& s1, const std::string& s2) { - if (s1.size() < s2.size()) + if (s1.size() < s2.size()) { return true; - else if (s1.size() > s2.size()) + } + else if (s1.size() > s2.size()) { return false; - else + } + else { return s1 < s2; + } } static std::string increment(const std::string& s) { std::string n = s; - int addcarry=1; + int addcarry = 1; for (std::string::reverse_iterator it = n.rbegin(); it != n.rend(); ++it) { - if (addcarry == 0) + if (addcarry == 0) { break; + } int d = *it - 48; d = d + addcarry; - *it = ((d%10) + 48); + *it = ((d % 10) + 48); addcarry = d / 10; } if (addcarry > 0) { @@ -73,8 +78,8 @@ class unique_name { public: unique_name(const std::string& name, const std::vector& names, int padding) - : base_name{name} - , padding{padding} + : base_name {name} + , padding {padding} { removeDigitsFromEnd(); findHighestSuffix(names); @@ -89,7 +94,7 @@ private: void removeDigitsFromEnd() { std::string::size_type pos = base_name.find_last_not_of("0123456789"); - if (pos != std::string::npos && (pos +1) < base_name.size()) { + if (pos != std::string::npos && (pos + 1) < base_name.size()) { num_suffix = base_name.substr(pos + 1); base_name.erase(pos + 1); } @@ -97,8 +102,8 @@ private: void findHighestSuffix(const std::vector& names) { - for (const auto & name : names) { - if (name.substr(0, base_name.length()) == base_name) { // same prefix + for (const auto& name : names) { + if (name.substr(0, base_name.length()) == base_name) { // same prefix std::string suffix(name.substr(base_name.length())); if (suffix.size() > 0) { std::string::size_type pos = suffix.find_first_not_of("0123456789"); @@ -128,9 +133,10 @@ private: int padding; }; -} +} // namespace Base -std::string Base::Tools::getUniqueName(const std::string& name, const std::vector& names, int pad) +std::string +Base::Tools::getUniqueName(const std::string& name, const std::vector& names, int pad) { if (names.empty()) { return name; @@ -154,18 +160,21 @@ std::string Base::Tools::addNumber(const std::string& name, unsigned int num, in std::string Base::Tools::getIdentifier(const std::string& name) { - if (name.empty()) + if (name.empty()) { return "_"; + } // check for first character whether it's a digit std::string CleanName = name; - if (!CleanName.empty() && CleanName[0] >= 48 && CleanName[0] <= 57) + if (!CleanName.empty() && CleanName[0] >= 48 && CleanName[0] <= 57) { CleanName[0] = '_'; + } // strip illegal chars - for (char & it : CleanName) { - if (!((it>=48 && it<=57) || // number - (it>=65 && it<=90) || // uppercase letter - (it>=97 && it<=122))) // lowercase letter - it = '_'; // it's neither number nor letter + for (char& it : CleanName) { + if (!((it >= 48 && it <= 57) || // number + (it >= 65 && it <= 90) || // uppercase letter + (it >= 97 && it <= 122))) { // lowercase letter + it = '_'; // it's neither number nor letter + } } return CleanName; @@ -174,29 +183,32 @@ std::string Base::Tools::getIdentifier(const std::string& name) std::wstring Base::Tools::widen(const std::string& str) { std::wostringstream wstm; - const std::ctype& ctfacet = std::use_facet< std::ctype >(wstm.getloc()); - for (char i : str) + const std::ctype& ctfacet = std::use_facet>(wstm.getloc()); + for (char i : str) { wstm << ctfacet.widen(i); + } return wstm.str(); } std::string Base::Tools::narrow(const std::wstring& str) { std::ostringstream stm; - const std::ctype& ctfacet = std::use_facet< std::ctype >(stm.getloc()); - for (wchar_t i : str) + const std::ctype& ctfacet = std::use_facet>(stm.getloc()); + for (wchar_t i : str) { stm << ctfacet.narrow(i, 0); + } return stm.str(); } -std::string Base::Tools::escapedUnicodeFromUtf8(const char *s) +std::string Base::Tools::escapedUnicodeFromUtf8(const char* s) { Base::PyGILStateLocker lock; std::string escapedstr; PyObject* unicode = PyUnicode_FromString(s); - if (!unicode) + if (!unicode) { return escapedstr; + } PyObject* escaped = PyUnicode_AsUnicodeEscapeString(unicode); if (escaped) { @@ -213,9 +225,11 @@ std::string Base::Tools::escapedUnicodeToUtf8(const std::string& s) Base::PyGILStateLocker lock; std::string string; - PyObject* unicode = PyUnicode_DecodeUnicodeEscape(s.c_str(), static_cast(s.size()), "strict"); - if (!unicode) + PyObject* unicode = + PyUnicode_DecodeUnicodeEscape(s.c_str(), static_cast(s.size()), "strict"); + if (!unicode) { return string; + } if (PyUnicode_Check(unicode)) { string = PyUnicode_AsUTF8(unicode); } @@ -229,14 +243,18 @@ QString Base::Tools::escapeEncodeString(const QString& s) const int len = s.length(); result.reserve(int(len * 1.1)); for (int i = 0; i < len; ++i) { - if (s.at(i) == QLatin1Char('\\')) + if (s.at(i) == QLatin1Char('\\')) { result += QLatin1String("\\\\"); - else if (s.at(i) == QLatin1Char('\"')) + } + else if (s.at(i) == QLatin1Char('\"')) { result += QLatin1String("\\\""); - else if (s.at(i) == QLatin1Char('\'')) + } + else if (s.at(i) == QLatin1Char('\'')) { result += QLatin1String("\\\'"); - else + } + else { result += s.at(i); + } } result.squeeze(); return result; @@ -247,14 +265,18 @@ std::string Base::Tools::escapeEncodeString(const std::string& s) std::string result; size_t len = s.size(); for (size_t i = 0; i < len; ++i) { - if (s.at(i) == '\\') + if (s.at(i) == '\\') { result += "\\\\"; - else if (s.at(i) == '\"') + } + else if (s.at(i) == '\"') { result += "\\\""; - else if (s.at(i) == '\'') + } + else if (s.at(i) == '\'') { result += "\\\'"; - else + } + else { result += s.at(i); + } } return result; } @@ -265,12 +287,15 @@ QString Base::Tools::escapeEncodeFilename(const QString& s) const int len = s.length(); result.reserve(int(len * 1.1)); for (int i = 0; i < len; ++i) { - if (s.at(i) == QLatin1Char('\"')) + if (s.at(i) == QLatin1Char('\"')) { result += QLatin1String("\\\""); - else if (s.at(i) == QLatin1Char('\'')) + } + else if (s.at(i) == QLatin1Char('\'')) { result += QLatin1String("\\\'"); - else + } + else { result += s.at(i); + } } result.squeeze(); return result; @@ -281,12 +306,15 @@ std::string Base::Tools::escapeEncodeFilename(const std::string& s) std::string result; size_t len = s.size(); for (size_t i = 0; i < len; ++i) { - if (s.at(i) == '\"') + if (s.at(i) == '\"') { result += "\\\""; - else if (s.at(i) == '\'') + } + else if (s.at(i) == '\'') { result += "\\\'"; - else + } + else { result += s.at(i); + } } return result; } @@ -305,8 +333,7 @@ std::string Base::Tools::quoted(const std::string& name) return str.str(); } -std::string Base::Tools::joinList(const std::vector& vec, - const std::string& sep) +std::string Base::Tools::joinList(const std::vector& vec, const std::string& sep) { std::stringstream str; for (const auto& it : vec) { @@ -324,9 +351,9 @@ struct StopWatch::Private QElapsedTimer t; }; -StopWatch::StopWatch() : d(new Private) -{ -} +StopWatch::StopWatch() + : d(new Private) +{} StopWatch::~StopWatch() { @@ -359,13 +386,17 @@ std::string StopWatch::toString(int ms) const int hour = total / 60; std::stringstream str; str << "Needed time: "; - if (hour > 0) + if (hour > 0) { str << hour << "h " << mins << "m " << secs << "s"; - else if (mins > 0) + } + else if (mins > 0) { str << mins << "m " << secs << "s"; - else if (secs > 0) + } + else if (secs > 0) { str << secs << "s"; - else + } + else { str << msec << "ms"; + } return str.str(); } diff --git a/src/Base/Tools.h b/src/Base/Tools.h index c4eb15ccf7..2f637db067 100644 --- a/src/Base/Tools.h +++ b/src/Base/Tools.h @@ -41,12 +41,17 @@ namespace Base { -template +template struct iotaGen { public: - T operator()() { return n++; } - iotaGen(T v) : n(v) {} + T operator()() + { + return n++; + } + iotaGen(T v) + : n(v) + {} private: T n; @@ -54,17 +59,18 @@ private: // ---------------------------------------------------------------------------- -template +template class manipulator { T i_; std::ostream& (*f_)(std::ostream&, T); public: - manipulator(std::ostream& (*f)(std::ostream&, T), T i) : i_(i), f_(f) - { - } - friend std::ostream& operator<<( std::ostream& os, manipulator m) + manipulator(std::ostream& (*f)(std::ostream&, T), T i) + : i_(i) + , f_(f) + {} + friend std::ostream& operator<<(std::ostream& os, manipulator m) { return m.f_(os, m.i_); } @@ -72,15 +78,17 @@ public: inline std::ostream& tabsN(std::ostream& os, int n) { - for (int i=0;i blanks(int n) // ---------------------------------------------------------------------------- template -inline T clamp (T num, T lower, T upper) +inline T clamp(T num, T lower, T upper) { - return std::max(std::min(upper,num),lower); + return std::max(std::min(upper, num), lower); } template -inline T sgn (T t) +inline T sgn(T t) { - if (t == 0) + if (t == 0) { return T(0); - else + } + else { return (t > 0) ? T(1) : T(-1); + } } #ifndef M_PI -#define M_PI 3.14159265358979323846 +#define M_PI 3.14159265358979323846 #endif template inline T toRadians(T d) { - return static_cast((d*M_PI)/180.0); + return static_cast((d * M_PI) / 180.0); } template inline T toDegrees(T r) { - return static_cast((r/M_PI)*180.0); + return static_cast((r / M_PI) * 180.0); } template @@ -154,28 +164,35 @@ private: // ---------------------------------------------------------------------------- -template -struct FlagToggler { +// NOLINTBEGIN +template +struct FlagToggler +{ - Flag &flag; + Flag& flag; bool toggled; - FlagToggler(Flag &_flag) - :flag(_flag),toggled(true) + FlagToggler(Flag& _flag) + : flag(_flag) + , toggled(true) { flag = !flag; } - FlagToggler(Flag &_flag, Flag check) - :flag(_flag),toggled(check==_flag) + FlagToggler(Flag& _flag, Flag check) + : flag(_flag) + , toggled(check == _flag) { - if (toggled) + if (toggled) { flag = !flag; + } } - ~FlagToggler() { - if (toggled) + ~FlagToggler() + { + if (toggled) { flag = !flag; + } } }; @@ -185,10 +202,18 @@ template class ObjectStatusLocker { public: - ObjectStatusLocker(Status s, Object* o, bool value = true) : status(s), obj(o) - { old_value = obj->testStatus(status); obj->setStatus(status, value); } + ObjectStatusLocker(Status s, Object* o, bool value = true) + : status(s) + , obj(o) + { + old_value = obj->testStatus(status); + obj->setStatus(status, value); + } ~ObjectStatusLocker() - { obj->setStatus(status, old_value); } + { + obj->setStatus(status, old_value); + } + private: Status status; Object* obj; @@ -200,10 +225,17 @@ private: class StateLocker { public: - StateLocker(bool& flag, bool value = true) : lock(flag) - { old_value = lock; lock = value; } + StateLocker(bool& flag, bool value = true) + : lock(flag) + { + old_value = lock; + lock = value; + } // NOLINT ~StateLocker() - { lock = old_value; } + { + lock = old_value; + } + private: bool& lock; bool old_value; @@ -216,39 +248,50 @@ class BitsetLocker { public: BitsetLocker(T& flags, std::size_t flag, bool value = true) - : flags(flags), flag(flag) - { oldValue = flags.test(flag); flags.set(flag,value); } + : flags(flags) + , flag(flag) + { + oldValue = flags.test(flag); + flags.set(flag, value); + } ~BitsetLocker() - { flags.set(flag,oldValue); } + { + flags.set(flag, oldValue); + } + private: - T &flags; + T& flags; std::size_t flag; bool oldValue; }; // ---------------------------------------------------------------------------- -class ConnectionBlocker { +class ConnectionBlocker +{ using Connection = boost::signals2::connection; using ConnectionBlock = boost::signals2::shared_connection_block; ConnectionBlock blocker; public: - ConnectionBlocker(Connection& c) : blocker(c) { - } + ConnectionBlocker(Connection& c) + : blocker(c) + {} ~ConnectionBlocker() = default; }; +// NOLINTEND // ---------------------------------------------------------------------------- struct BaseExport Tools { - static std::string getUniqueName(const std::string&, const std::vector&,int d=0); - static std::string addNumber(const std::string&, unsigned int, int d=0); + static std::string + getUniqueName(const std::string&, const std::vector&, int d = 0); + static std::string addNumber(const std::string&, unsigned int, int d = 0); static std::string getIdentifier(const std::string&); static std::wstring widen(const std::string& str); static std::string narrow(const std::wstring& str); - static std::string escapedUnicodeFromUtf8(const char *s); + static std::string escapedUnicodeFromUtf8(const char* s); static std::string escapedUnicodeToUtf8(const std::string& s); static QString escapeEncodeString(const QString& s); @@ -261,7 +304,8 @@ struct BaseExport Tools * @param s String to convert. * @return A std::string encoded as UTF-8. */ - static inline std::string toStdString(const QString& s) { + static inline std::string toStdString(const QString& s) + { QByteArray tmp = s.toUtf8(); return {tmp.constData(), static_cast(tmp.size())}; } @@ -271,7 +315,8 @@ struct BaseExport Tools * @param s std::string, expected to be UTF-8 encoded. * @return String represented as a QString. */ - static inline QString fromStdString(const std::string & s) { + static inline QString fromStdString(const std::string& s) + { return QString::fromUtf8(s.c_str(), static_cast(s.size())); } @@ -295,11 +340,10 @@ struct BaseExport Tools * @param sep * @return */ - static std::string joinList(const std::vector& vec, - const std::string& sep = ", "); + static std::string joinList(const std::vector& vec, const std::string& sep = ", "); }; -} // namespace Base +} // namespace Base -#endif // BASE_TOOLS_H +#endif // BASE_TOOLS_H diff --git a/src/Base/Tools2D.cpp b/src/Base/Tools2D.cpp index 6b61f526ce..cc68068170 100644 --- a/src/Base/Tools2D.cpp +++ b/src/Base/Tools2D.cpp @@ -24,8 +24,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "Tools2D.h" @@ -33,181 +33,187 @@ using namespace Base; -double Vector2d::GetAngle (const Vector2d &rclVect) const +double Vector2d::GetAngle(const Vector2d& rclVect) const { - double fDivid = 0.0, fNum = 0.0; + double fDivid = 0.0, fNum = 0.0; - fDivid = Length() * rclVect.Length(); + fDivid = Length() * rclVect.Length(); - if ((fDivid < -1e-10) || (fDivid > 1e-10)) - { - fNum = (*this * rclVect) / fDivid; - if (fNum < -1) - return D_PI; - else - if (fNum > 1) - return 0.0; - else - return acos(fNum); - } - else - return -FLOAT_MAX; // division by zero + if ((fDivid < -1e-10) || (fDivid > 1e-10)) { + fNum = (*this * rclVect) / fDivid; + if (fNum < -1) { + return D_PI; + } + else if (fNum > 1) { + return 0.0; + } + else { + return acos(fNum); + } + } + else { + return -FLOAT_MAX; // division by zero + } } -void Vector2d::ProjectToLine (const Vector2d &rclPt, const Vector2d &rclLine) +void Vector2d::ProjectToLine(const Vector2d& rclPt, const Vector2d& rclLine) { - double l = rclLine.Length(); - double t1 = (rclPt * rclLine) / l; - Vector2d clNormal = rclLine; - clNormal.Normalize(); - clNormal.Scale(t1); - *this = clNormal; + double l = rclLine.Length(); + double t1 = (rclPt * rclLine) / l; + Vector2d clNormal = rclLine; + clNormal.Normalize(); + clNormal.Scale(t1); + *this = clNormal; } /********************************************************/ /** BOUNDBOX2d ********************************************/ -bool BoundBox2d::Intersect(const Line2d &rclLine) const +bool BoundBox2d::Intersect(const Line2d& rclLine) const { - Line2d clThisLine; - Vector2d clVct; + Line2d clThisLine; + Vector2d clVct; - // first line - clThisLine.clV1.x = MinX; - clThisLine.clV1.y = MinY; - clThisLine.clV2.x = MaxX; - clThisLine.clV2.y = MinY; - if (clThisLine.IntersectAndContain (rclLine, clVct)) - return true; + // first line + clThisLine.clV1.x = MinX; + clThisLine.clV1.y = MinY; + clThisLine.clV2.x = MaxX; + clThisLine.clV2.y = MinY; + if (clThisLine.IntersectAndContain(rclLine, clVct)) { + return true; + } - // second line - clThisLine.clV1 = clThisLine.clV2; - clThisLine.clV2.x = MaxX; - clThisLine.clV2.y = MaxY; - if (clThisLine.IntersectAndContain (rclLine, clVct)) - return true; + // second line + clThisLine.clV1 = clThisLine.clV2; + clThisLine.clV2.x = MaxX; + clThisLine.clV2.y = MaxY; + if (clThisLine.IntersectAndContain(rclLine, clVct)) { + return true; + } - // third line - clThisLine.clV1 = clThisLine.clV2; - clThisLine.clV2.x = MinX; - clThisLine.clV2.y = MaxY; - if (clThisLine.IntersectAndContain (rclLine, clVct)) - return true; + // third line + clThisLine.clV1 = clThisLine.clV2; + clThisLine.clV2.x = MinX; + clThisLine.clV2.y = MaxY; + if (clThisLine.IntersectAndContain(rclLine, clVct)) { + return true; + } - // fourth line - clThisLine.clV1 = clThisLine.clV2; - clThisLine.clV2.x = MinX; - clThisLine.clV2.y = MinY; - if (clThisLine.IntersectAndContain (rclLine, clVct)) - return true; + // fourth line + clThisLine.clV1 = clThisLine.clV2; + clThisLine.clV2.x = MinX; + clThisLine.clV2.y = MinY; + if (clThisLine.IntersectAndContain(rclLine, clVct)) { + return true; + } - return false; + return false; } -bool BoundBox2d::Intersect(const BoundBox2d &rclBB) const +bool BoundBox2d::Intersect(const BoundBox2d& rclBB) const { - if (MinX < rclBB.MaxX && - rclBB.MinX < MaxX && - MinY < rclBB.MaxY && - rclBB.MinY < MaxY ) - return true; - else // no intersection - return false; + if (MinX < rclBB.MaxX && rclBB.MinX < MaxX && MinY < rclBB.MaxY && rclBB.MinY < MaxY) { + return true; + } + else { // no intersection + return false; + } } -bool BoundBox2d::Intersect(const Polygon2d &rclPoly) const +bool BoundBox2d::Intersect(const Polygon2d& rclPoly) const { - unsigned long i = 0; - Line2d clLine; + unsigned long i = 0; + Line2d clLine; - // points contained in boundbox - for (i = 0; i < rclPoly.GetCtVectors(); i++) - if (Contains (rclPoly[i])) - return true; /***** RETURN INTERSECTION *********/ - - // points contained in polygon - if (rclPoly.Contains (Vector2d (MinX, MinY)) || - rclPoly.Contains (Vector2d (MaxX, MinY)) || - rclPoly.Contains (Vector2d (MaxX, MaxY)) || - rclPoly.Contains (Vector2d (MinX, MaxY))) - return true; /***** RETURN INTERSECTION *********/ - - // test intersections of bound-lines - if (rclPoly.GetCtVectors() < 3) - return false; - for (i = 0; i < rclPoly.GetCtVectors(); i++) - { - if (i == rclPoly.GetCtVectors() - 1) - { - clLine.clV1 = rclPoly[i]; - clLine.clV2 = rclPoly[0]; + // points contained in boundbox + for (i = 0; i < rclPoly.GetCtVectors(); i++) { + if (Contains(rclPoly[i])) { + return true; /***** RETURN INTERSECTION *********/ + } } - else - { - clLine.clV1 = rclPoly[i]; - clLine.clV2 = rclPoly[i + 1]; + + // points contained in polygon + if (rclPoly.Contains(Vector2d(MinX, MinY)) || rclPoly.Contains(Vector2d(MaxX, MinY)) + || rclPoly.Contains(Vector2d(MaxX, MaxY)) || rclPoly.Contains(Vector2d(MinX, MaxY))) { + return true; /***** RETURN INTERSECTION *********/ } - if (Intersect(clLine)) - return true; /***** RETURN INTERSECTION *********/ - } - // no intersection - return false; + + // test intersections of bound-lines + if (rclPoly.GetCtVectors() < 3) { + return false; + } + for (i = 0; i < rclPoly.GetCtVectors(); i++) { + if (i == rclPoly.GetCtVectors() - 1) { + clLine.clV1 = rclPoly[i]; + clLine.clV2 = rclPoly[0]; + } + else { + clLine.clV1 = rclPoly[i]; + clLine.clV2 = rclPoly[i + 1]; + } + if (Intersect(clLine)) { + return true; /***** RETURN INTERSECTION *********/ + } + } + // no intersection + return false; } /********************************************************/ /** LINE2D **********************************************/ -BoundBox2d Line2d::CalcBoundBox () const +BoundBox2d Line2d::CalcBoundBox() const { - BoundBox2d clBB; - clBB.MinX = std::min (clV1.x, clV2.x); - clBB.MinY = std::min (clV1.y, clV2.y); - clBB.MaxX = std::max (clV1.x, clV2.x); - clBB.MaxY = std::max (clV1.y, clV2.y); - return clBB; + BoundBox2d clBB; + clBB.MinX = std::min(clV1.x, clV2.x); + clBB.MinY = std::min(clV1.y, clV2.y); + clBB.MaxX = std::max(clV1.x, clV2.x); + clBB.MaxY = std::max(clV1.y, clV2.y); + return clBB; } -bool Line2d::Intersect (const Line2d& rclLine, Vector2d &rclV) const +bool Line2d::Intersect(const Line2d& rclLine, Vector2d& rclV) const { - double m1 = 0.0, m2 = 0.0, b1 = 0.0, b2 = 0.0; + double m1 = 0.0, m2 = 0.0, b1 = 0.0, b2 = 0.0; - // calc coefficients - if (fabs (clV2.x - clV1.x) > 1e-10) - m1 = (clV2.y - clV1.y) / (clV2.x - clV1.x); - else - m1 = DOUBLE_MAX; - if (fabs (rclLine.clV2.x - rclLine.clV1.x) > 1e-10) - m2 = (rclLine.clV2.y - rclLine.clV1.y) / (rclLine.clV2.x - rclLine.clV1.x); - else - m2 = DOUBLE_MAX; - if (m1 == m2) /****** RETURN ERR (parallel lines) *************/ - return false; + // calc coefficients + if (fabs(clV2.x - clV1.x) > 1e-10) { + m1 = (clV2.y - clV1.y) / (clV2.x - clV1.x); + } + else { + m1 = DOUBLE_MAX; + } + if (fabs(rclLine.clV2.x - rclLine.clV1.x) > 1e-10) { + m2 = (rclLine.clV2.y - rclLine.clV1.y) / (rclLine.clV2.x - rclLine.clV1.x); + } + else { + m2 = DOUBLE_MAX; + } + if (m1 == m2) { /****** RETURN ERR (parallel lines) *************/ + return false; + } - b1 = clV1.y - m1 * clV1.x; - b2 = rclLine.clV1.y - m2 * rclLine.clV1.x; + b1 = clV1.y - m1 * clV1.x; + b2 = rclLine.clV1.y - m2 * rclLine.clV1.x; - // calc intersection - if (m1 == DOUBLE_MAX) - { - rclV.x = clV1.x; - rclV.y = m2 * rclV.x + b2; - } - else - if (m2 == DOUBLE_MAX) - { - rclV.x = rclLine.clV1.x; - rclV.y = m1 * rclV.x + b1; - } - else - { - rclV.x = (b2 - b1) / (m1 - m2); - rclV.y = m1 * rclV.x + b1; - } + // calc intersection + if (m1 == DOUBLE_MAX) { + rclV.x = clV1.x; + rclV.y = m2 * rclV.x + b2; + } + else if (m2 == DOUBLE_MAX) { + rclV.x = rclLine.clV1.x; + rclV.y = m1 * rclV.x + b1; + } + else { + rclV.x = (b2 - b1) / (m1 - m2); + rclV.y = m1 * rclV.x + b1; + } - return true; /*** RETURN true (intersection) **********/ + return true; /*** RETURN true (intersection) **********/ } -bool Line2d::Intersect (const Vector2d &rclV, double eps) const +bool Line2d::Intersect(const Vector2d& rclV, double eps) const { double dxc = rclV.x - clV1.x; double dyc = rclV.y - clV1.y; @@ -218,246 +224,257 @@ bool Line2d::Intersect (const Vector2d &rclV, double eps) const double cross = dxc * dyl - dyc * dxl; // is point on the infinite line? - if (fabs(cross) > eps) + if (fabs(cross) > eps) { return false; + } // point is on line but it is also between V1 and V2? double dot = dxc * dxl + dyc * dyl; double len = dxl * dxl + dyl * dyl; - if (dot < -eps || dot > len + eps) + if (dot < -eps || dot > len + eps) { return false; + } return true; } -Vector2d Line2d::FromPos (double fDistance) const +Vector2d Line2d::FromPos(double fDistance) const { - Vector2d clDir(clV2 - clV1); - clDir.Normalize(); - return {clV1.x + (clDir.x * fDistance), clV1.y + (clDir.y * fDistance)}; + Vector2d clDir(clV2 - clV1); + clDir.Normalize(); + return {clV1.x + (clDir.x * fDistance), clV1.y + (clDir.y * fDistance)}; } -bool Line2d::IntersectAndContain (const Line2d& rclLine, Vector2d &rclV) const +bool Line2d::IntersectAndContain(const Line2d& rclLine, Vector2d& rclV) const { - bool rc = Intersect (rclLine, rclV); - if (rc) - rc = Contains (rclV) && rclLine.Contains (rclV); - return rc; + bool rc = Intersect(rclLine, rclV); + if (rc) { + rc = Contains(rclV) && rclLine.Contains(rclV); + } + return rc; } /********************************************************/ /** POLYGON2d ********************************************/ -BoundBox2d Polygon2d::CalcBoundBox () const +BoundBox2d Polygon2d::CalcBoundBox() const { - unsigned long i = 0; - BoundBox2d clBB; - for (i = 0; i < _aclVct.size(); i++) - { - clBB.MinX = std::min (clBB.MinX, _aclVct[i].x); - clBB.MinY = std::min (clBB.MinY, _aclVct[i].y); - clBB.MaxX = std::max (clBB.MaxX, _aclVct[i].x); - clBB.MaxY = std::max (clBB.MaxY, _aclVct[i].y); - } - return clBB; + unsigned long i = 0; + BoundBox2d clBB; + for (i = 0; i < _aclVct.size(); i++) { + clBB.MinX = std::min(clBB.MinX, _aclVct[i].x); + clBB.MinY = std::min(clBB.MinY, _aclVct[i].y); + clBB.MaxX = std::max(clBB.MaxX, _aclVct[i].x); + clBB.MaxY = std::max(clBB.MaxY, _aclVct[i].y); + } + return clBB; } -static short _CalcTorsion (double *pfLine, double fX, double fY) +static short _CalcTorsion(double* pfLine, double fX, double fY) { - int sQuad[2], i = 0; // Changing this from short to int allows the compiler to inline this function - double fResX = 0.0; + int sQuad[2], + i = 0; // Changing this from short to int allows the compiler to inline this function + double fResX = 0.0; - // Classification of both polygon points into quadrants - for (i = 0; i < 2; i++) - { - if (pfLine[i * 2] <= fX) - sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 0 : 3; - else - sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 1 : 2; - } - - // Abort at line points within a quadrant - // Abort at non-intersecting line points - if (abs (sQuad[0] - sQuad[1]) <= 1) - return 0; - - // Both points to the left of ulX - if (abs (sQuad[0] - sQuad[1]) == 3) - return (sQuad[0] == 0) ? 1 : -1; - - // Remaining cases: Quadrant difference from 2 - // mathematical tests on intersection - fResX = pfLine[0] + (fY - pfLine[1]) / - ((pfLine[3] - pfLine[1]) / (pfLine[2] - pfLine[0])); - if (fResX < fX) - - // up/down or down/up - return (sQuad[0] <= 1) ? 1 : -1; - - // Remaining cases? - return 0; -} - -bool Polygon2d::Contains (const Vector2d &rclV) const -{ - // Using the number of turns method, determines - // whether a point is contained within a polygon. - // The sum of all turns indicates whether yes or no. - double pfTmp[4]; - unsigned long i = 0; - short sTorsion = 0; - - // Error check - if (GetCtVectors() < 3) - return false; - - // for all polygon lines - for (i = 0; i < GetCtVectors(); i++) - { - // Evidence of line structure - if (i == GetCtVectors() - 1) - { - // Close polygon automatically - pfTmp[0] = _aclVct[i].x; - pfTmp[1] = _aclVct[i].y; - pfTmp[2] = _aclVct[0].x; - pfTmp[3] = _aclVct[0].y; - } - else - { - // accept point i and i+1 - pfTmp[0] = _aclVct[i].x; - pfTmp[1] = _aclVct[i].y; - pfTmp[2] = _aclVct[i + 1].x; - pfTmp[3] = _aclVct[i + 1].y; - } - - // Carry out a cut test and calculate the turn counter - sTorsion += _CalcTorsion (pfTmp, rclV.x, rclV.y); - } - - // Evaluate turn counter - return sTorsion != 0; -} - -void Polygon2d::Intersect (const Polygon2d &rclPolygon, std::list &rclResultPolygonList) const -{ - // trim the passed polygon with the current one, the result is a list of polygons (subset of the passed polygon) - // your own (trim) polygon is closed - // - if ((rclPolygon.GetCtVectors() < 2) || (GetCtVectors() < 2)) - return; - - // position of first points (in or out of polygon) - bool bInner = Contains(rclPolygon[0]); - - Polygon2d clResultPolygon; - if (bInner) // add first point if inner trim-polygon - clResultPolygon.Add(rclPolygon[0]); - - // for each polygon segment - size_t ulPolyCt = rclPolygon.GetCtVectors(); - size_t ulTrimCt = GetCtVectors(); - for (size_t ulVec = 0; ulVec < (ulPolyCt-1); ulVec++) - { - Vector2d clPt0 = rclPolygon[ulVec]; - Vector2d clPt1 = rclPolygon[ulVec+1]; - Line2d clLine(clPt0, clPt1); - - // try to intersect with each line of the trim-polygon - std::set afIntersections; // set of intersections (sorted by line parameter) - Vector2d clTrimPt2; // second line point - for (size_t i = 0; i < ulTrimCt; i++) - { - clTrimPt2 = At((i + 1) % ulTrimCt); - Line2d clToTrimLine(At(i), clTrimPt2); - - Vector2d clV; - if (clLine.IntersectAndContain(clToTrimLine, clV)) - { - // save line parameter of intersection point - double fDist = (clV - clPt0).Length(); - afIntersections.insert(fDist); - } - } - - if (afIntersections.size() > 0) // intersections founded - { - for (double it : afIntersections) - { - // intersection point - Vector2d clPtIS = clLine.FromPos(it); - if (bInner) - { - clResultPolygon.Add(clPtIS); - rclResultPolygonList.push_back(clResultPolygon); - clResultPolygon.DeleteAll(); - bInner = false; + // Classification of both polygon points into quadrants + for (i = 0; i < 2; i++) { + if (pfLine[i * 2] <= fX) { + sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 0 : 3; } - else - { - clResultPolygon.Add(clPtIS); - bInner = true; + else { + sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 1 : 2; } - } - - if (bInner) // add line end point if inside - clResultPolygon.Add(clPt1); } - else - { // no intersections, add line (means second point of it) if inside trim-polygon - if (bInner) - clResultPolygon.Add(clPt1); - } - } - // add last segment - if (clResultPolygon.GetCtVectors() > 0) - rclResultPolygonList.push_back(clResultPolygon); + // Abort at line points within a quadrant + // Abort at non-intersecting line points + if (abs(sQuad[0] - sQuad[1]) <= 1) { + return 0; + } + + // Both points to the left of ulX + if (abs(sQuad[0] - sQuad[1]) == 3) { + return (sQuad[0] == 0) ? 1 : -1; + } + + // Remaining cases: Quadrant difference from 2 + // mathematical tests on intersection + fResX = pfLine[0] + (fY - pfLine[1]) / ((pfLine[3] - pfLine[1]) / (pfLine[2] - pfLine[0])); + if (fResX < fX) { + + // up/down or down/up + return (sQuad[0] <= 1) ? 1 : -1; + } + + // Remaining cases? + return 0; } -bool Polygon2d::Intersect (const Polygon2d &other) const { - if (other.GetCtVectors()<2 || GetCtVectors() < 2) +bool Polygon2d::Contains(const Vector2d& rclV) const +{ + // Using the number of turns method, determines + // whether a point is contained within a polygon. + // The sum of all turns indicates whether yes or no. + double pfTmp[4]; + unsigned long i = 0; + short sTorsion = 0; + + // Error check + if (GetCtVectors() < 3) { return false; - - for (auto &v : _aclVct) { - if (other.Contains(v)) - return true; } - if (Contains(other[0])) - return true; + // for all polygon lines + for (i = 0; i < GetCtVectors(); i++) { + // Evidence of line structure + if (i == GetCtVectors() - 1) { + // Close polygon automatically + pfTmp[0] = _aclVct[i].x; + pfTmp[1] = _aclVct[i].y; + pfTmp[2] = _aclVct[0].x; + pfTmp[3] = _aclVct[0].y; + } + else { + // accept point i and i+1 + pfTmp[0] = _aclVct[i].x; + pfTmp[1] = _aclVct[i].y; + pfTmp[2] = _aclVct[i + 1].x; + pfTmp[3] = _aclVct[i + 1].y; + } - for (size_t j=1; j& rclResultPolygonList) const +{ + // trim the passed polygon with the current one, the result is a list of polygons (subset of the + // passed polygon) your own (trim) polygon is closed + // + if ((rclPolygon.GetCtVectors() < 2) || (GetCtVectors() < 2)) { + return; + } + + // position of first points (in or out of polygon) + bool bInner = Contains(rclPolygon[0]); + + Polygon2d clResultPolygon; + if (bInner) { // add first point if inner trim-polygon + clResultPolygon.Add(rclPolygon[0]); + } + + // for each polygon segment + size_t ulPolyCt = rclPolygon.GetCtVectors(); + size_t ulTrimCt = GetCtVectors(); + for (size_t ulVec = 0; ulVec < (ulPolyCt - 1); ulVec++) { + Vector2d clPt0 = rclPolygon[ulVec]; + Vector2d clPt1 = rclPolygon[ulVec + 1]; + Line2d clLine(clPt0, clPt1); + + // try to intersect with each line of the trim-polygon + std::set afIntersections; // set of intersections (sorted by line parameter) + Vector2d clTrimPt2; // second line point + for (size_t i = 0; i < ulTrimCt; i++) { + clTrimPt2 = At((i + 1) % ulTrimCt); + Line2d clToTrimLine(At(i), clTrimPt2); + + Vector2d clV; + if (clLine.IntersectAndContain(clToTrimLine, clV)) { + // save line parameter of intersection point + double fDist = (clV - clPt0).Length(); + afIntersections.insert(fDist); + } + } + + if (afIntersections.size() > 0) // intersections founded + { + for (double it : afIntersections) { + // intersection point + Vector2d clPtIS = clLine.FromPos(it); + if (bInner) { + clResultPolygon.Add(clPtIS); + rclResultPolygonList.push_back(clResultPolygon); + clResultPolygon.DeleteAll(); + bInner = false; + } + else { + clResultPolygon.Add(clPtIS); + bInner = true; + } + } + + if (bInner) { // add line end point if inside + clResultPolygon.Add(clPt1); + } + } + else { // no intersections, add line (means second point of it) if inside trim-polygon + if (bInner) { + clResultPolygon.Add(clPt1); + } + } + } + + // add last segment + if (clResultPolygon.GetCtVectors() > 0) { + rclResultPolygonList.push_back(clResultPolygon); + } +} + +bool Polygon2d::Intersect(const Polygon2d& other) const +{ + if (other.GetCtVectors() < 2 || GetCtVectors() < 2) { + return false; + } + + for (auto& v : _aclVct) { + if (other.Contains(v)) { return true; + } + } + + if (Contains(other[0])) { + return true; + } + + for (size_t j = 1; j < other.GetCtVectors(); ++j) { + auto& v0 = other[j - 1]; + auto& v1 = other[j]; + + if (Contains(v1)) { + return true; + } Line2d line(v0, v1); - for (size_t i=0; i +#include #endif -namespace Base { +namespace Base +{ class Vector2d; class BoundBox2d; @@ -49,51 +50,51 @@ class Polygon2d; class BaseExport Vector2d { public: - double x, y; + double x, y; - inline Vector2d(); - inline Vector2d(float x, float y); - inline Vector2d(double x, double y); - inline Vector2d(const Vector2d&) = default; - inline Vector2d(Vector2d&&) = default; - ~Vector2d() = default; + inline Vector2d(); + inline Vector2d(float x, float y); + inline Vector2d(double x, double y); + inline Vector2d(const Vector2d&) = default; + inline Vector2d(Vector2d&&) = default; + ~Vector2d() = default; - // operators - inline Vector2d& operator= (const Vector2d&) = default; - inline Vector2d& operator= (Vector2d&&) = default; - inline bool operator== (const Vector2d &v) const; - inline Vector2d operator+ () const; - inline Vector2d operator+ (const Vector2d &v) const; - inline Vector2d& operator+= (const Vector2d &v); - inline Vector2d operator- () const; - inline Vector2d operator- (const Vector2d &v) const; - inline Vector2d& operator-= (const Vector2d &v); - inline Vector2d operator* (double c) const; - inline Vector2d& operator*= (double c); - inline double operator* (const Vector2d &v) const; - inline Vector2d operator/ (double c) const; - inline Vector2d& operator/= (double c); + // operators + inline Vector2d& operator=(const Vector2d&) = default; + inline Vector2d& operator=(Vector2d&&) = default; + inline bool operator==(const Vector2d& v) const; + inline Vector2d operator+() const; + inline Vector2d operator+(const Vector2d& v) const; + inline Vector2d& operator+=(const Vector2d& v); + inline Vector2d operator-() const; + inline Vector2d operator-(const Vector2d& v) const; + inline Vector2d& operator-=(const Vector2d& v); + inline Vector2d operator*(double c) const; + inline Vector2d& operator*=(double c); + inline double operator*(const Vector2d& v) const; + inline Vector2d operator/(double c) const; + inline Vector2d& operator/=(double c); - // methods - inline bool IsNull(double tolerance = 0.0) const; - inline double Length() const; - inline double Angle() const; - inline double Sqr() const; + // methods + inline bool IsNull(double tolerance = 0.0) const; + inline double Length() const; + inline double Angle() const; + inline double Sqr() const; - inline Vector2d& Set(double x, double y); - inline Vector2d& Negate(); - inline Vector2d& Scale(double factor); - inline Vector2d& Rotate(double angle); - inline Vector2d& Normalize(); + inline Vector2d& Set(double x, double y); + inline Vector2d& Negate(); + inline Vector2d& Scale(double factor); + inline Vector2d& Rotate(double angle); + inline Vector2d& Normalize(); - inline Vector2d Perpendicular(bool clockwise = false) const; - static inline Vector2d FromPolar(double r, double fi); + inline Vector2d Perpendicular(bool clockwise = false) const; + static inline Vector2d FromPolar(double r, double fi); - inline double Distance(const Vector2d &v) const; - inline bool IsEqual(const Vector2d &v, double tolerance = 0.0) const; + inline double Distance(const Vector2d& v) const; + inline bool IsEqual(const Vector2d& v, double tolerance = 0.0) const; - double GetAngle(const Vector2d &v) const; - void ProjectToLine(const Vector2d &point, const Vector2d &line); + double GetAngle(const Vector2d& v) const; + void ProjectToLine(const Vector2d& point, const Vector2d& line); }; /** BoundBox2d ********************************************/ @@ -104,34 +105,34 @@ public: class BaseExport BoundBox2d { public: - double MinX, MinY, MaxX, MaxY; + double MinX, MinY, MaxX, MaxY; - inline BoundBox2d (); - inline BoundBox2d (const BoundBox2d&) = default; - inline BoundBox2d (BoundBox2d&&) = default; - inline BoundBox2d (double fX1, double fY1, double fX2, double fY2); - ~BoundBox2d() = default; - inline bool IsValid (); - inline bool IsEqual(const BoundBox2d&, double tolerance) const; + inline BoundBox2d(); + inline BoundBox2d(const BoundBox2d&) = default; + inline BoundBox2d(BoundBox2d&&) = default; + inline BoundBox2d(double fX1, double fY1, double fX2, double fY2); + ~BoundBox2d() = default; + inline bool IsValid(); + inline bool IsEqual(const BoundBox2d&, double tolerance) const; - // operators - inline BoundBox2d& operator= (const BoundBox2d&) = default; - inline BoundBox2d& operator= (BoundBox2d&&) = default; - inline bool operator== (const BoundBox2d& rclBB) const; + // operators + inline BoundBox2d& operator=(const BoundBox2d&) = default; + inline BoundBox2d& operator=(BoundBox2d&&) = default; + inline bool operator==(const BoundBox2d& rclBB) const; - // methods - inline double Width() const; - inline double Height() const; - inline bool Contains(const Vector2d &v) const; - inline bool Contains(const Vector2d &v, double tolerance) const; - inline Vector2d GetCenter() const; + // methods + inline double Width() const; + inline double Height() const; + inline bool Contains(const Vector2d& v) const; + inline bool Contains(const Vector2d& v, double tolerance) const; + inline Vector2d GetCenter() const; - inline void SetVoid(); - inline void Add(const Vector2d &v); + inline void SetVoid(); + inline void Add(const Vector2d& v); - bool Intersect(const Line2d &rclLine) const; - bool Intersect(const BoundBox2d &rclBB) const; - bool Intersect(const Polygon2d &rclPoly) const; + bool Intersect(const Line2d& rclLine) const; + bool Intersect(const BoundBox2d& rclBB) const; + bool Intersect(const Polygon2d& rclPoly) const; }; /** Line2d ********************************************/ @@ -142,29 +143,29 @@ public: class BaseExport Line2d { public: - Vector2d clV1, clV2; + Vector2d clV1, clV2; - Line2d () = default; - ~Line2d () = default; - inline Line2d (const Line2d&) = default; - inline Line2d (Line2d&&) = default; - inline Line2d (const Vector2d &rclV1, const Vector2d &rclV2); + Line2d() = default; + ~Line2d() = default; + inline Line2d(const Line2d&) = default; + inline Line2d(Line2d&&) = default; + inline Line2d(const Vector2d& rclV1, const Vector2d& rclV2); - // methods - inline double Length () const; - BoundBox2d CalcBoundBox () const; + // methods + inline double Length() const; + BoundBox2d CalcBoundBox() const; - // operators - inline Line2d& operator= (const Line2d&) = default; - inline Line2d& operator= (Line2d&&) = default; - inline bool operator== (const Line2d& rclLine) const; + // operators + inline Line2d& operator=(const Line2d&) = default; + inline Line2d& operator=(Line2d&&) = default; + inline bool operator==(const Line2d& rclLine) const; - // misc - inline bool Contains (const Vector2d &rclV) const; - bool Intersect (const Line2d& rclLine, Vector2d &rclV) const; - bool Intersect (const Vector2d &rclV, double eps) const; - bool IntersectAndContain (const Line2d& rclLine, Vector2d &rclV) const; - Vector2d FromPos (double fDistance) const; + // misc + inline bool Contains(const Vector2d& rclV) const; + bool Intersect(const Line2d& rclLine, Vector2d& rclV) const; + bool Intersect(const Vector2d& rclV, double eps) const; + bool IntersectAndContain(const Line2d& rclLine, Vector2d& rclV) const; + Vector2d FromPos(double fDistance) const; }; /** Polygon2d ********************************************/ @@ -175,359 +176,353 @@ public: class BaseExport Polygon2d { public: - Polygon2d () = default; - inline Polygon2d (const Polygon2d&) = default; - inline Polygon2d (Polygon2d&&) = default; - ~Polygon2d () = default; + Polygon2d() = default; + inline Polygon2d(const Polygon2d&) = default; + inline Polygon2d(Polygon2d&&) = default; + ~Polygon2d() = default; - inline Polygon2d& operator = (const Polygon2d &rclP); - inline Polygon2d& operator = (Polygon2d &&rclP); + inline Polygon2d& operator=(const Polygon2d& rclP); + inline Polygon2d& operator=(Polygon2d&& rclP); - // admin-interface - inline size_t GetCtVectors () const; - inline bool Add (const Vector2d &rclVct); - inline const Vector2d& operator[] (size_t ulNdx) const; - inline const Vector2d& At (size_t ulNdx) const; - inline Vector2d& operator[] (size_t ulNdx); - inline Vector2d& At (size_t ulNdx); - inline bool Delete (size_t ulNdx); - inline void DeleteAll (); + // admin-interface + inline size_t GetCtVectors() const; + inline bool Add(const Vector2d& rclVct); + inline const Vector2d& operator[](size_t ulNdx) const; + inline const Vector2d& At(size_t ulNdx) const; + inline Vector2d& operator[](size_t ulNdx); + inline Vector2d& At(size_t ulNdx); + inline bool Delete(size_t ulNdx); + inline void DeleteAll(); - // misc - BoundBox2d CalcBoundBox () const; - bool Contains (const Vector2d &rclV) const; - void Intersect (const Polygon2d &rclPolygon, std::list &rclResultPolygonList) const; - bool Intersect (const Polygon2d &rclPolygon) const; - bool Intersect (const Vector2d &rclV, double eps) const; + // misc + BoundBox2d CalcBoundBox() const; + bool Contains(const Vector2d& rclV) const; + void Intersect(const Polygon2d& rclPolygon, std::list& rclResultPolygonList) const; + bool Intersect(const Polygon2d& rclPolygon) const; + bool Intersect(const Vector2d& rclV, double eps) const; private: - std::vector _aclVct; + std::vector _aclVct; }; /** INLINES ********************************************/ inline Vector2d::Vector2d() -: x(0.0), y(0.0) -{ -} + : x(0.0) + , y(0.0) +{} inline Vector2d::Vector2d(float x, float y) -: x(double(x)), y(double(y)) -{ -} + : x(double(x)) + , y(double(y)) +{} inline Vector2d::Vector2d(double x, double y) -: x(x), y(y) + : x(x) + , y(y) +{} + +inline bool Vector2d::operator==(const Vector2d& v) const { + return (x == v.x) && (y == v.y); } -inline bool Vector2d::operator== (const Vector2d &v) const +inline Vector2d Vector2d::operator+() const { - return (x == v.x) && (y == v.y); + return {x, y}; } -inline Vector2d Vector2d::operator+ () const +inline Vector2d Vector2d::operator+(const Vector2d& v) const { - return {x, y}; + return {x + v.x, y + v.y}; } -inline Vector2d Vector2d::operator+ (const Vector2d &v) const +inline Vector2d& Vector2d::operator+=(const Vector2d& v) { - return {x + v.x, y + v.y}; + x += v.x; + y += v.y; + return *this; } -inline Vector2d& Vector2d::operator+= (const Vector2d &v) +inline Vector2d Vector2d::operator-() const { - x += v.x; - y += v.y; - return *this; + return {-x, -y}; } -inline Vector2d Vector2d::operator- () const +inline Vector2d Vector2d::operator-(const Vector2d& v) const { - return {-x, -y}; + return {x - v.x, y - v.y}; } -inline Vector2d Vector2d::operator- (const Vector2d &v) const +inline Vector2d& Vector2d::operator-=(const Vector2d& v) { - return {x - v.x, y - v.y}; + x -= v.x; + y -= v.y; + return *this; } -inline Vector2d& Vector2d::operator-= (const Vector2d &v) +inline Vector2d Vector2d::operator*(double c) const { - x -= v.x; - y -= v.y; - return *this; + return {c * x, c * y}; } -inline Vector2d Vector2d::operator* (double c) const +inline Vector2d& Vector2d::operator*=(double c) { - return {c * x, c * y}; + x *= c; + y *= c; + return *this; } -inline Vector2d& Vector2d::operator*= (double c) +inline double Vector2d::operator*(const Vector2d& v) const { - x *= c; - y *= c; - return *this; + return x * v.x + y * v.y; } -inline double Vector2d::operator* (const Vector2d &v) const +inline Vector2d operator*(double c, const Vector2d& v) { - return x * v.x + y * v.y; + return {c * v.x, c * v.y}; } -inline Vector2d operator* (double c, const Vector2d &v) +inline Vector2d Vector2d::operator/(double c) const { - return {c * v.x, c * v.y}; + return {x / c, y / c}; } -inline Vector2d Vector2d::operator/ (double c) const +inline Vector2d& Vector2d::operator/=(double c) { - return {x / c, y / c}; -} - -inline Vector2d& Vector2d::operator/= (double c) -{ - x /= c; - y /= c; - return *this; + x /= c; + y /= c; + return *this; } inline bool Vector2d::IsNull(double tolerance) const { - return x * x + y * y <= tolerance * tolerance; + return x * x + y * y <= tolerance * tolerance; } inline double Vector2d::Length() const { - return sqrt(x * x + y * y); + return sqrt(x * x + y * y); } inline double Vector2d::Angle() const { - return atan2(y, x); + return atan2(y, x); } inline double Vector2d::Sqr() const { - return x * x + y * y; + return x * x + y * y; } inline Vector2d& Vector2d::Set(double x, double y) { - this->x = x; - this->y = y; - return *this; + this->x = x; + this->y = y; + return *this; } inline Vector2d& Vector2d::Negate() { - x = -x; - y = -y; - return *this; + x = -x; + y = -y; + return *this; } inline Vector2d& Vector2d::Scale(double factor) { - x *= factor; - y *= factor; - return *this; + x *= factor; + y *= factor; + return *this; } inline Vector2d& Vector2d::Rotate(double angle) { - auto tmp_x = x; - x = x * cos(angle) - y * sin(angle); - y = tmp_x * sin(angle) + y * cos(angle); - return *this; + auto tmp_x = x; + x = x * cos(angle) - y * sin(angle); + y = tmp_x * sin(angle) + y * cos(angle); + return *this; } inline Vector2d& Vector2d::Normalize() { - double length = Length(); - if (length > 0.0) - { - x /= length; - y /= length; - } + double length = Length(); + if (length > 0.0) { + x /= length; + y /= length; + } - return *this; + return *this; } inline Vector2d Vector2d::Perpendicular(bool clockwise) const { - return clockwise ? Vector2d(y, -x) : Vector2d(-y, x); + return clockwise ? Vector2d(y, -x) : Vector2d(-y, x); } inline Vector2d Vector2d::FromPolar(double r, double fi) { - return {r * cos(fi), r * sin(fi)}; + return {r * cos(fi), r * sin(fi)}; } inline double Vector2d::Distance(const Vector2d& v) const { - double dx = (x - v.x); - double dy = (y - v.y); + double dx = (x - v.x); + double dy = (y - v.y); - return sqrt(dx * dx + dy * dy); + return sqrt(dx * dx + dy * dy); } inline bool Vector2d::IsEqual(const Vector2d& v, double tolerance) const { - return Distance(v) <= tolerance; + return Distance(v) <= tolerance; } // ======================================== -inline Polygon2d& Polygon2d::operator = (const Polygon2d &rclP) = default; +inline Polygon2d& Polygon2d::operator=(const Polygon2d& rclP) = default; -inline Polygon2d& Polygon2d::operator = (Polygon2d &&rclP) = default; +inline Polygon2d& Polygon2d::operator=(Polygon2d&& rclP) = default; -inline void Polygon2d::DeleteAll () +inline void Polygon2d::DeleteAll() { - _aclVct.clear(); + _aclVct.clear(); } -inline size_t Polygon2d::GetCtVectors () const +inline size_t Polygon2d::GetCtVectors() const { - return _aclVct.size (); + return _aclVct.size(); } -inline bool Polygon2d::Add (const Vector2d &rclVct) +inline bool Polygon2d::Add(const Vector2d& rclVct) { - _aclVct.push_back (rclVct); - return true; -} - -inline bool Polygon2d::Delete (size_t ulNdx) -{ - if ( ulNdx < _aclVct.size() ) - { - std::vector::iterator it = _aclVct.begin(); - std::advance(it, ulNdx); - _aclVct.erase(it); + _aclVct.push_back(rclVct); return true; - } - - return false; } -inline const Vector2d& Polygon2d::operator[] (size_t ulNdx) const +inline bool Polygon2d::Delete(size_t ulNdx) { - return _aclVct[ulNdx]; + if (ulNdx < _aclVct.size()) { + std::vector::iterator it = _aclVct.begin(); + std::advance(it, ulNdx); + _aclVct.erase(it); + return true; + } + + return false; } -inline const Vector2d& Polygon2d::At (size_t ulNdx) const +inline const Vector2d& Polygon2d::operator[](size_t ulNdx) const { - return _aclVct.at(ulNdx); + return _aclVct[ulNdx]; } -inline Vector2d& Polygon2d::operator[] (size_t ulNdx) +inline const Vector2d& Polygon2d::At(size_t ulNdx) const { - return _aclVct[ulNdx]; + return _aclVct.at(ulNdx); } -inline Vector2d& Polygon2d::At (size_t ulNdx) +inline Vector2d& Polygon2d::operator[](size_t ulNdx) { - return _aclVct.at(ulNdx); + return _aclVct[ulNdx]; } - -inline Line2d::Line2d (const Vector2d &rclV1, const Vector2d &rclV2) - : clV1 (rclV1), clV2 (rclV2) +inline Vector2d& Polygon2d::At(size_t ulNdx) { + return _aclVct.at(ulNdx); } -inline double Line2d::Length () const + +inline Line2d::Line2d(const Vector2d& rclV1, const Vector2d& rclV2) + : clV1(rclV1) + , clV2(rclV2) +{} + +inline double Line2d::Length() const { - return (clV2 - clV1).Length (); + return (clV2 - clV1).Length(); } -inline bool Line2d::operator== (const Line2d& rclLine) const +inline bool Line2d::operator==(const Line2d& rclLine) const { - return (clV1 == rclLine.clV1) && (clV2 == rclLine.clV2); + return (clV1 == rclLine.clV1) && (clV2 == rclLine.clV2); } -inline bool Line2d::Contains (const Vector2d &rclV) const +inline bool Line2d::Contains(const Vector2d& rclV) const { - return CalcBoundBox ().Contains (rclV); + return CalcBoundBox().Contains(rclV); } -inline BoundBox2d::BoundBox2d () +inline BoundBox2d::BoundBox2d() { - MinX = MinY = DOUBLE_MAX; - MaxX = MaxY = - DOUBLE_MAX; + MinX = MinY = DOUBLE_MAX; + MaxX = MaxY = -DOUBLE_MAX; } -inline BoundBox2d::BoundBox2d (double fX1, double fY1, double fX2, double fY2) +inline BoundBox2d::BoundBox2d(double fX1, double fY1, double fX2, double fY2) : MinX(std::min(fX1, fX2)) , MinY(std::min(fY1, fY2)) , MaxX(std::max(fX1, fX2)) , MaxY(std::max(fY1, fY2)) -{ -} +{} -inline bool BoundBox2d::IsValid () +inline bool BoundBox2d::IsValid() { - return (MaxX >= MinX) && (MaxY >= MinY); + return (MaxX >= MinX) && (MaxY >= MinY); } inline bool BoundBox2d::IsEqual(const BoundBox2d& b, double tolerance) const { - return Vector2d(MinX, MinY).IsEqual(Vector2d(b.MinX, b.MinY), tolerance) && - Vector2d(MaxX, MaxY).IsEqual(Vector2d(b.MaxX, b.MaxY), tolerance); + return Vector2d(MinX, MinY).IsEqual(Vector2d(b.MinX, b.MinY), tolerance) + && Vector2d(MaxX, MaxY).IsEqual(Vector2d(b.MaxX, b.MaxY), tolerance); } -inline bool BoundBox2d::operator== (const BoundBox2d& rclBB) const +inline bool BoundBox2d::operator==(const BoundBox2d& rclBB) const { - return (MinX == rclBB.MinX) && - (MinY == rclBB.MinY) && - (MaxX == rclBB.MaxX) && - (MaxY == rclBB.MaxY); + return (MinX == rclBB.MinX) && (MinY == rclBB.MinY) && (MaxX == rclBB.MaxX) + && (MaxY == rclBB.MaxY); } inline double BoundBox2d::Width() const { - return MaxX - MinX; + return MaxX - MinX; } inline double BoundBox2d::Height() const { - return MaxY - MinY; + return MaxY - MinY; } -inline bool BoundBox2d::Contains(const Vector2d &v) const +inline bool BoundBox2d::Contains(const Vector2d& v) const { - return v.x >= MinX && v.x <= MaxX - && v.y >= MinY && v.y <= MaxY; + return v.x >= MinX && v.x <= MaxX && v.y >= MinY && v.y <= MaxY; } -inline bool BoundBox2d::Contains(const Vector2d &v, double tolerance) const +inline bool BoundBox2d::Contains(const Vector2d& v, double tolerance) const { - return v.x >= MinX - tolerance && v.x <= MaxX + tolerance - && v.y >= MinY - tolerance && v.y <= MaxY + tolerance; + return v.x >= MinX - tolerance && v.x <= MaxX + tolerance && v.y >= MinY - tolerance + && v.y <= MaxY + tolerance; } inline Vector2d BoundBox2d::GetCenter() const { - return {(MinX + MaxX) * 0.5, (MinY + MaxY) * 0.5}; + return {(MinX + MaxX) * 0.5, (MinY + MaxY) * 0.5}; } inline void BoundBox2d::SetVoid() { - MinX = MinY = DOUBLE_MAX; - MaxX = MaxY = -DOUBLE_MAX; + MinX = MinY = DOUBLE_MAX; + MaxX = MaxY = -DOUBLE_MAX; } -inline void BoundBox2d::Add(const Vector2d &v) +inline void BoundBox2d::Add(const Vector2d& v) { - MinX = std::min(MinX, v.x); - MinY = std::min(MinY, v.y); - MaxX = std::max(MaxX, v.x); - MaxY = std::max(MaxY, v.y); + MinX = std::min(MinX, v.x); + MinY = std::min(MinY, v.y); + MaxX = std::max(MaxX, v.x); + MaxY = std::max(MaxY, v.y); } -} // namespace Base +} // namespace Base -#endif // BASE_TOOLS2D_H +#endif // BASE_TOOLS2D_H diff --git a/src/Base/Tools3D.cpp b/src/Base/Tools3D.cpp index b58aedb454..eefc88f7be 100644 --- a/src/Base/Tools3D.cpp +++ b/src/Base/Tools3D.cpp @@ -24,8 +24,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "Tools3D.h" @@ -34,32 +34,31 @@ using namespace Base; -template +template Line3::Line3(const Vector3& p1, const Vector3& p2) - : p1(p1) - , p2(p2) -{ -} + : p1(p1) + , p2(p2) +{} -template -bool Line3::operator== (const Line3& line) const +template +bool Line3::operator==(const Line3& line) const { return (p1 == line.p1 && p2 == line.p2); } -template +template float_type Line3::Length() const { return Base::Distance(p1, p2); } -template +template float_type Line3::SqrLength() const { return Base::DistanceP2(p1, p2); } -template +template BoundBox3 Line3::CalcBoundBox() const { BoundBox3 box; @@ -68,40 +67,40 @@ BoundBox3 Line3::CalcBoundBox() const return box; } -template +template Vector3 Line3::GetBase() const { return p1; } -template +template Vector3 Line3::GetDirection() const { return p2 - p1; } -template +template void Line3::Transform(const Base::Matrix4D& mat) { mat.multVec(p1, p1); mat.multVec(p2, p2); } -template +template void Line3::Transform(const Base::Placement& plm) { plm.multVec(p1, p1); plm.multVec(p2, p2); } -template +template void Line3::Transform(const Base::Rotation& rot) { rot.multVec(p1, p1); rot.multVec(p2, p2); } -template +template Line3 Line3::Transformed(const Base::Matrix4D& mat) const { Line3 line(*this); @@ -109,7 +108,7 @@ Line3 Line3::Transformed(const Base::Matrix4D& mat) cons return line; } -template +template Line3 Line3::Transformed(const Base::Placement& plm) const { Line3 line(*this); @@ -117,7 +116,7 @@ Line3 Line3::Transformed(const Base::Placement& plm) con return line; } -template +template Line3 Line3::Transformed(const Base::Rotation& rot) const { Line3 line(*this); @@ -125,25 +124,26 @@ Line3 Line3::Transformed(const Base::Rotation& rot) cons return line; } -template +template bool Line3::Contains(const Vector3& pt) const { return Contains(pt, Vector3::epsilon()); } -template +template bool Line3::Contains(const Vector3& pt, float_type eps) const { Vector3 v1 = p1 - pt; Vector3 v2 = p2 - pt; Vector3 v3 = p2 - p1; float_type dot = v1.Dot(v2); - if (dot > eps) + if (dot > eps) { return false; + } return v3.Cross(v1).Length() < eps; } -template +template Vector3 Line3::FromPos(float_type distance) const { Vector3 dir(p2 - p1); @@ -153,43 +153,43 @@ Vector3 Line3::FromPos(float_type distance) const // ---------------------------------------------------------------------------- -template +template size_t Polygon3::GetSize() const { return points.size(); } -template -void Polygon3::Add (const Vector3& p) +template +void Polygon3::Add(const Vector3& p) { points.push_back(p); } -template -const Vector3& Polygon3::operator[] (size_t pos) const +template +const Vector3& Polygon3::operator[](size_t pos) const { return points[pos]; } -template -const Vector3& Polygon3::At (size_t pos) const +template +const Vector3& Polygon3::At(size_t pos) const { return points.at(pos); } -template -Vector3& Polygon3::operator[] (size_t pos) +template +Vector3& Polygon3::operator[](size_t pos) { return points[pos]; } -template -Vector3& Polygon3::At (size_t pos) +template +Vector3& Polygon3::At(size_t pos) { return points.at(pos); } -template +template bool Polygon3::Remove(size_t pos) { if (pos < points.size()) { @@ -202,43 +202,47 @@ bool Polygon3::Remove(size_t pos) return false; } -template +template void Polygon3::Clear() { points.clear(); } -template +template BoundBox3 Polygon3::CalcBoundBox() const { BoundBox3 box; - for (const auto& it : points) + for (const auto& it : points) { box.Add(it); + } return box; } -template +template void Polygon3::Transform(const Base::Matrix4D& mat) { - for (auto& it : points) + for (auto& it : points) { mat.multVec(it, it); + } } -template +template void Polygon3::Transform(const Base::Placement& plm) { - for (auto& it : points) + for (auto& it : points) { plm.multVec(it, it); + } } -template +template void Polygon3::Transform(const Base::Rotation& rot) { - for (auto& it : points) + for (auto& it : points) { rot.multVec(it, it); + } } -template +template Polygon3 Polygon3::Transformed(const Base::Matrix4D& mat) const { Polygon3 poly(*this); @@ -246,7 +250,7 @@ Polygon3 Polygon3::Transformed(const Base::Matrix4D& mat return poly; } -template +template Polygon3 Polygon3::Transformed(const Base::Placement& plm) const { Polygon3 poly(*this); @@ -254,7 +258,7 @@ Polygon3 Polygon3::Transformed(const Base::Placement& pl return poly; } -template +template Polygon3 Polygon3::Transformed(const Base::Rotation& rot) const { Polygon3 poly(*this); @@ -263,9 +267,10 @@ Polygon3 Polygon3::Transformed(const Base::Rotation& rot } // explicit template instantiation -namespace Base { +namespace Base +{ template class BaseExport Line3; template class BaseExport Line3; template class BaseExport Polygon3; template class BaseExport Polygon3; -} +} // namespace Base diff --git a/src/Base/Tools3D.h b/src/Base/Tools3D.h index 8bf7d14e95..13b8e1839b 100644 --- a/src/Base/Tools3D.h +++ b/src/Base/Tools3D.h @@ -38,7 +38,8 @@ #include #endif -namespace Base { +namespace Base +{ class Vector2d; class BoundBox2d; @@ -50,7 +51,7 @@ class Polygon2d; /** * 3D line class. */ -template +template class Line3 { public: @@ -63,13 +64,13 @@ public: Line3(const Vector3& p1, const Vector3& p2); // operators - Line3& operator= (const Line3& line) = default; - Line3& operator= (Line3&& line) = default; - bool operator== (const Line3& line) const; + Line3& operator=(const Line3& line) = default; + Line3& operator=(Line3&& line) = default; + bool operator==(const Line3& line) const; // methods - float_type Length () const; - float_type SqrLength () const; + float_type Length() const; + float_type SqrLength() const; BoundBox3 CalcBoundBox() const; Vector3 GetBase() const; Vector3 GetDirection() const; @@ -96,7 +97,7 @@ public: * \return */ bool Contains(const Vector3& p, float_type eps) const; - Vector3 FromPos (float_type distance) const; + Vector3 FromPos(float_type distance) const; }; /** Polygon3 ********************************************/ @@ -104,7 +105,7 @@ public: /** * 3D polygon class. */ -template +template class Polygon3 { public: @@ -113,15 +114,15 @@ public: Polygon3(const Polygon3& poly) = default; Polygon3(Polygon3&& poly) = default; - Polygon3& operator = (const Polygon3& poly) = default; - Polygon3& operator = (Polygon3&& poly) = default; + Polygon3& operator=(const Polygon3& poly) = default; + Polygon3& operator=(Polygon3&& poly) = default; size_t GetSize() const; - void Add (const Vector3& p); - const Vector3& operator[] (size_t pos) const; - const Vector3& At (size_t pos) const; - Vector3& operator[] (size_t pos); - Vector3& At (size_t pos); + void Add(const Vector3& p); + const Vector3& operator[](size_t pos) const; + const Vector3& At(size_t pos) const; + Vector3& operator[](size_t pos); + Vector3& At(size_t pos); bool Remove(size_t pos); void Clear(); @@ -144,6 +145,6 @@ using Line3d = Line3; using Polygon3f = Polygon3; using Polygon3d = Polygon3; -} // namespace Base +} // namespace Base -#endif // BASE_TOOLS3D_H +#endif // BASE_TOOLS3D_H diff --git a/src/Base/Translate.cpp b/src/Base/Translate.cpp index 771c24df88..f900c0685b 100644 --- a/src/Base/Translate.cpp +++ b/src/Base/Translate.cpp @@ -30,58 +30,65 @@ using namespace Base; Translate::Translate() - : Py::ExtensionModule("__Translate__") + : Py::ExtensionModule("__Translate__") { add_varargs_method("translate", - &Translate::translate, - "translate(context, sourcetext, disambiguation = None, n=-1)\n" - "-- Returns the translation text for sourceText, by querying\n" - "the installed translation files. The translation files are\n" - "searched from the most recently installed file back to the\n" - "first installed file."); + &Translate::translate, + "translate(context, sourcetext, disambiguation = None, n=-1)\n" + "-- Returns the translation text for sourceText, by querying\n" + "the installed translation files. The translation files are\n" + "searched from the most recently installed file back to the\n" + "first installed file."); add_varargs_method("QT_TRANSLATE_NOOP", - &Translate::translateNoop, - "QT_TRANSLATE_NOOP(context, sourcetext)\n" - "Marks the UTF-8 encoded string literal sourcetext for delayed translation in the given context.\n" - "The context is typically a class name and also needs to be specified as a string literal."); + &Translate::translateNoop, + "QT_TRANSLATE_NOOP(context, sourcetext)\n" + "Marks the UTF-8 encoded string literal sourcetext for delayed translation " + "in the given context.\n" + "The context is typically a class name and also needs to be specified as a " + "string literal."); add_varargs_method("QT_TRANSLATE_NOOP3", - &Translate::translateNoop3, - "QT_TRANSLATE_NOOP3(context, sourcetext, disambiguation)\n" - "Marks the UTF-8 encoded string literal sourceText for delayed translation in the given context\n" - "with the given disambiguation. The context is typically a class and also needs to be specified\n" - "as a string literal. The string literal disambiguation should be a short semantic tag to tell\n" - "apart otherwise identical strings."); + &Translate::translateNoop3, + "QT_TRANSLATE_NOOP3(context, sourcetext, disambiguation)\n" + "Marks the UTF-8 encoded string literal sourceText for delayed translation " + "in the given context\n" + "with the given disambiguation. The context is typically a class and also " + "needs to be specified\n" + "as a string literal. The string literal disambiguation should be a short " + "semantic tag to tell\n" + "apart otherwise identical strings."); add_varargs_method("QT_TRANSLATE_NOOP_UTF8", - &Translate::translateNoop, - "QT_TRANSLATE_NOOP_UTF8(context, sourcetext)\n" - "Same as QT_TRANSLATE_NOOP"); + &Translate::translateNoop, + "QT_TRANSLATE_NOOP_UTF8(context, sourcetext)\n" + "Same as QT_TRANSLATE_NOOP"); add_varargs_method("QT_TR_NOOP", - &Translate::trNoop, - "QT_TR_NOOP(sourcetext)\n" - "Marks the UTF-8 encoded string literal sourcetext for delayed translation in the current context"); + &Translate::trNoop, + "QT_TR_NOOP(sourcetext)\n" + "Marks the UTF-8 encoded string literal sourcetext for delayed translation " + "in the current context"); add_varargs_method("QT_TR_NOOP_UTF8", - &Translate::trNoop, - "QT_TR_NOOP_UTF8(sourcetext)\n" - "Same as QT_TR_NOOP"); + &Translate::trNoop, + "QT_TR_NOOP_UTF8(sourcetext)\n" + "Same as QT_TR_NOOP"); add_varargs_method("installTranslator", - &Translate::installTranslator, - "Install a translator for testing purposes"); + &Translate::installTranslator, + "Install a translator for testing purposes"); add_varargs_method("removeTranslators", - &Translate::removeTranslators, - "Remove test translators"); - initialize("This module is the Translate module"); // register with Python + &Translate::removeTranslators, + "Remove test translators"); + initialize("This module is the Translate module"); // register with Python } Translate::~Translate() = default; Py::Object Translate::translate(const Py::Tuple& args) { - char *context = nullptr; - char *source = nullptr; - char *disambiguation = nullptr; - int n=-1; - if (!PyArg_ParseTuple(args.ptr(), "ss|zi", &context, &source, &disambiguation, &n)) + char* context = nullptr; + char* source = nullptr; + char* disambiguation = nullptr; + int n = -1; + if (!PyArg_ParseTuple(args.ptr(), "ss|zi", &context, &source, &disambiguation, &n)) { throw Py::Exception(); + } QString str = QCoreApplication::translate(context, source, disambiguation, n); return Py::asObject(PyUnicode_FromString(str.toUtf8())); @@ -91,8 +98,9 @@ Py::Object Translate::translateNoop(const Py::Tuple& args) { PyObject* arg1 = nullptr; PyObject* arg2 = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "OO", &arg1, &arg2)) + if (!PyArg_ParseTuple(args.ptr(), "OO", &arg1, &arg2)) { throw Py::Exception(); + } return Py::Object(arg2); } @@ -101,24 +109,27 @@ Py::Object Translate::translateNoop3(const Py::Tuple& args) PyObject* arg1 = nullptr; PyObject* arg2 = nullptr; PyObject* arg3 = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "OOO", &arg1, &arg2, &arg3)) + if (!PyArg_ParseTuple(args.ptr(), "OOO", &arg1, &arg2, &arg3)) { throw Py::Exception(); + } return Py::Object(arg2); } Py::Object Translate::trNoop(const Py::Tuple& args) { PyObject* arg1 = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "O", &arg1)) + if (!PyArg_ParseTuple(args.ptr(), "O", &arg1)) { throw Py::Exception(); + } return Py::Object(arg1); } Py::Object Translate::installTranslator(const Py::Tuple& args) { char* Name = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) { throw Py::Exception(); + } QString filename = QString::fromUtf8(Name); PyMem_Free(Name); @@ -132,18 +143,19 @@ Py::Object Translate::installTranslator(const Py::Tuple& args) ok = true; } - return Py::Boolean(ok); // NOLINT + return Py::Boolean(ok); // NOLINT } Py::Object Translate::removeTranslators(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = true; for (const auto& it : translators) { ok &= QCoreApplication::removeTranslator(it.get()); } translators.clear(); - return Py::Boolean(ok); // NOLINT + return Py::Boolean(ok); // NOLINT } diff --git a/src/Base/Translate.h b/src/Base/Translate.h index 4995689e01..57ec1c3cee 100644 --- a/src/Base/Translate.h +++ b/src/Base/Translate.h @@ -34,9 +34,10 @@ #endif -namespace Base { +namespace Base +{ -class BaseExport Translate : public Py::ExtensionModule +class BaseExport Translate: public Py::ExtensionModule // NOLINT { public: Translate(); @@ -54,6 +55,6 @@ private: std::list> translators; }; -} // namespace Base +} // namespace Base -#endif // BASE_TRANSLATE_H +#endif // BASE_TRANSLATE_H diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index 64c205cdfe..b5afda9055 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... @@ -39,184 +39,196 @@ using namespace std; struct Base::TypeData { - TypeData(const char *theName, - const Type type = Type::badType(), - const Type theParent = Type::badType(), - Type::instantiationMethod method = nullptr - ):name(theName),parent(theParent),type(type),instMethod(method) { } + TypeData(const char* theName, + const Type type = Type::badType(), + const Type theParent = Type::badType(), + Type::instantiationMethod method = nullptr) + : name(theName) + , parent(theParent) + , type(type) + , instMethod(method) + {} - std::string name; - Type parent; - Type type; - Type::instantiationMethod instMethod; + std::string name; + Type parent; + Type type; + Type::instantiationMethod instMethod; }; -map Type::typemap; -vector Type::typedata; -set Type::loadModuleSet; +map Type::typemap; +vector Type::typedata; +set Type::loadModuleSet; -void *Type::createInstance() +void* Type::createInstance() { - instantiationMethod method = typedata[index]->instMethod; - return method ? (*method)() : nullptr; + instantiationMethod method = typedata[index]->instMethod; + return method ? (*method)() : nullptr; } -void *Type::createInstanceByName(const char* TypeName, bool bLoadModule) +void* Type::createInstanceByName(const char* TypeName, bool bLoadModule) { - // if not already, load the module - if (bLoadModule) - importModule(TypeName); + // if not already, load the module + if (bLoadModule) { + importModule(TypeName); + } - // now the type should be in the type map - Type t = fromName(TypeName); - if (t == badType()) - return nullptr; + // now the type should be in the type map + Type t = fromName(TypeName); + if (t == badType()) { + return nullptr; + } - return t.createInstance(); + return t.createInstance(); } void Type::importModule(const char* TypeName) { - // cut out the module name - string Mod = getModuleName(TypeName); - // ignore base modules - if (Mod != "App" && Mod != "Gui" && Mod != "Base") { - // remember already loaded modules - set::const_iterator pos = loadModuleSet.find(Mod); - if (pos == loadModuleSet.end()) { - Interpreter().loadModule(Mod.c_str()); + // cut out the module name + string Mod = getModuleName(TypeName); + // ignore base modules + if (Mod != "App" && Mod != "Gui" && Mod != "Base") { + // remember already loaded modules + set::const_iterator pos = loadModuleSet.find(Mod); + if (pos == loadModuleSet.end()) { + Interpreter().loadModule(Mod.c_str()); #ifdef FC_LOGLOADMODULE - Console().Log("Act: Module %s loaded through class %s \n",Mod.c_str(),TypeName); + Console().Log("Act: Module %s loaded through class %s \n", Mod.c_str(), TypeName); #endif - loadModuleSet.insert(Mod); + loadModuleSet.insert(Mod); + } } - } } string Type::getModuleName(const char* ClassName) { - string temp(ClassName); - std::string::size_type pos = temp.find_first_of("::"); + string temp(ClassName); + std::string::size_type pos = temp.find_first_of("::"); - if (pos != std::string::npos) - return {temp,0,pos}; - return {}; + if (pos != std::string::npos) { + return {temp, 0, pos}; + } + return {}; } Type Type::badType() { - Type bad; - bad.index = 0; - return bad; + Type bad; + bad.index = 0; + return bad; } -const Type Type::createType(const Type parent, const char *name, instantiationMethod method) +const Type Type::createType(const Type parent, const char* name, instantiationMethod method) { - Type newType; - newType.index = static_cast(Type::typedata.size()); - TypeData * typeData = new TypeData(name, newType, parent,method); - Type::typedata.push_back(typeData); + Type newType; + newType.index = static_cast(Type::typedata.size()); + TypeData* typeData = new TypeData(name, newType, parent, method); + Type::typedata.push_back(typeData); - // add to dictionary for fast lookup - Type::typemap[name] = newType.getKey(); + // add to dictionary for fast lookup + Type::typemap[name] = newType.getKey(); - return newType; + return newType; } void Type::init() { - assert(Type::typedata.size() == 0); - - - Type::typedata.push_back(new TypeData("BadType")); - Type::typemap["BadType"] = 0; + assert(Type::typedata.size() == 0); + Type::typedata.push_back(new TypeData("BadType")); + Type::typemap["BadType"] = 0; } void Type::destruct() { - for(auto it : typedata) - delete it; - typedata.clear(); - typemap.clear(); - loadModuleSet.clear(); + for (auto it : typedata) { + delete it; + } + typedata.clear(); + typemap.clear(); + loadModuleSet.clear(); } -Type Type::fromName(const char *name) +Type Type::fromName(const char* name) { - std::map::const_iterator pos; + std::map::const_iterator pos; - pos = typemap.find(name); - if (pos != typemap.end()) - return typedata[pos->second]->type; - else - return Type::badType(); + pos = typemap.find(name); + if (pos != typemap.end()) { + return typedata[pos->second]->type; + } + else { + return Type::badType(); + } } Type Type::fromKey(unsigned int key) { - if (key < typedata.size()) - return typedata[key]->type; - else - return Type::badType(); + if (key < typedata.size()) { + return typedata[key]->type; + } + else { + return Type::badType(); + } } -const char *Type::getName() const +const char* Type::getName() const { - return typedata[index]->name.c_str(); + return typedata[index]->name.c_str(); } const Type Type::getParent() const { - return typedata[index]->parent; + return typedata[index]->parent; } bool Type::isDerivedFrom(const Type type) const { - Type temp(*this); - do { - if (temp == type) - return true; - temp = temp.getParent(); - } while (temp != badType()); + Type temp(*this); + do { + if (temp == type) { + return true; + } + temp = temp.getParent(); + } while (temp != badType()); - return false; + return false; } -int Type::getAllDerivedFrom(const Type type, std::vector & List) +int Type::getAllDerivedFrom(const Type type, std::vector& List) { - int cnt = 0; + int cnt = 0; - for(auto it : typedata) - { - if (it->type.isDerivedFrom(type)) - { - List.push_back(it->type); - cnt++; + for (auto it : typedata) { + if (it->type.isDerivedFrom(type)) { + List.push_back(it->type); + cnt++; + } } - } - return cnt; + return cnt; } int Type::getNumTypes() { - return static_cast(typedata.size()); + return static_cast(typedata.size()); } -Type Type::getTypeIfDerivedFrom(const char* name , const Type parent, bool bLoadModule) +Type Type::getTypeIfDerivedFrom(const char* name, const Type parent, bool bLoadModule) { - if (bLoadModule) - importModule(name); + if (bLoadModule) { + importModule(name); + } - Type type = fromName(name); + Type type = fromName(name); - if (type.isDerivedFrom(parent)) - return type; - else - return Type::badType(); + if (type.isDerivedFrom(parent)) { + return type; + } + else { + return Type::badType(); + } } diff --git a/src/Base/Type.h b/src/Base/Type.h index 3cc85eadee..e2e93e3057 100644 --- a/src/Base/Type.h +++ b/src/Base/Type.h @@ -80,116 +80,107 @@ struct TypeData; class BaseExport Type { public: - /// Construction - Type(const Type& type) = default; - Type(Type&& type) = default; - Type() = default; - /// Destruction - ~Type() = default; + /// Construction + Type(const Type& type) = default; + Type(Type&& type) = default; + Type() = default; + /// Destruction + ~Type() = default; - /// creates a instance of this type - void *createInstance(); - /// creates a instance of the named type - static void *createInstanceByName(const char* TypeName, bool bLoadModule=false); - static void importModule(const char* TypeName); + /// creates a instance of this type + void* createInstance(); + /// creates a instance of the named type + static void* createInstanceByName(const char* TypeName, bool bLoadModule = false); + static void importModule(const char* TypeName); - using instantiationMethod = void * (*)(); + using instantiationMethod = void* (*)(); - static Type fromName(const char *name); - static Type fromKey(unsigned int key); - const char *getName() const; - const Type getParent() const; - bool isDerivedFrom(const Type type) const; + static Type fromName(const char* name); + static Type fromKey(unsigned int key); + const char* getName() const; + const Type getParent() const; + bool isDerivedFrom(const Type type) const; - static int getAllDerivedFrom(const Type type, std::vector& List); - /// Returns the given named type if is derived from parent type, otherwise return bad type - static Type getTypeIfDerivedFrom(const char* name , const Type parent, bool bLoadModule=false); + static int getAllDerivedFrom(const Type type, std::vector& List); + /// Returns the given named type if is derived from parent type, otherwise return bad type + static Type getTypeIfDerivedFrom(const char* name, const Type parent, bool bLoadModule = false); - static int getNumTypes(); + static int getNumTypes(); - static const Type createType(const Type parent, const char *name,instantiationMethod method = nullptr); + static const Type + createType(const Type parent, const char* name, instantiationMethod method = nullptr); - unsigned int getKey() const; - bool isBad() const; + unsigned int getKey() const; + bool isBad() const; - Type& operator = (const Type& type) = default; - Type& operator = (Type&& type) = default; - bool operator == (const Type type) const; - bool operator != (const Type type) const; + Type& operator=(const Type& type) = default; + Type& operator=(Type&& type) = default; + bool operator==(const Type type) const; + bool operator!=(const Type type) const; - bool operator < (const Type type) const; - bool operator <= (const Type type) const; - bool operator >= (const Type type) const; - bool operator > (const Type type) const; + bool operator<(const Type type) const; + bool operator<=(const Type type) const; + bool operator>=(const Type type) const; + bool operator>(const Type type) const; - static Type badType(); - static void init(); - static void destruct(); + static Type badType(); + static void init(); + static void destruct(); protected: - static std::string getModuleName(const char* ClassName); + static std::string getModuleName(const char* ClassName); private: - unsigned int index{0}; - - static std::map typemap; - static std::vector typedata; - static std::set loadModuleSet; + unsigned int index {0}; + static std::map typemap; + static std::vector typedata; + static std::set loadModuleSet; }; -inline unsigned int -Type::getKey() const +inline unsigned int Type::getKey() const { - return this->index; + return this->index; } -inline bool -Type::operator != (const Type type) const +inline bool Type::operator!=(const Type type) const { - return (this->getKey() != type.getKey()); + return (this->getKey() != type.getKey()); } -inline bool -Type::operator == (const Type type) const +inline bool Type::operator==(const Type type) const { - return (this->getKey() == type.getKey()); + return (this->getKey() == type.getKey()); } -inline bool -Type::operator < (const Type type) const +inline bool Type::operator<(const Type type) const { - return (this->getKey() < type.getKey()); + return (this->getKey() < type.getKey()); } -inline bool -Type::operator <= (const Type type) const +inline bool Type::operator<=(const Type type) const { - return (this->getKey() <= type.getKey()); + return (this->getKey() <= type.getKey()); } -inline bool -Type::operator >= (const Type type) const +inline bool Type::operator>=(const Type type) const { - return (this->getKey() >= type.getKey()); + return (this->getKey() >= type.getKey()); } -inline bool -Type::operator > (const Type type) const +inline bool Type::operator>(const Type type) const { - return (this->getKey() > type.getKey()); + return (this->getKey() > type.getKey()); } -inline bool -Type::isBad() const +inline bool Type::isBad() const { - return (this->index == 0); + return (this->index == 0); } -} //namespace Base +} // namespace Base -#endif // BASE_TYPE_H - +#endif // BASE_TYPE_H diff --git a/src/Base/TypePyImp.cpp b/src/Base/TypePyImp.cpp index cd7593feca..c957a5e281 100644 --- a/src/Base/TypePyImp.cpp +++ b/src/Base/TypePyImp.cpp @@ -39,75 +39,81 @@ std::string TypePy::representation() const return str.str(); } -PyObject* TypePy::fromName (PyObject *args) +PyObject* TypePy::fromName(PyObject* args) { - const char *name{}; - if (!PyArg_ParseTuple(args, "s", &name)) + const char* name {}; + if (!PyArg_ParseTuple(args, "s", &name)) { return nullptr; + } Base::Type type = Base::Type::fromName(name); return new TypePy(new Base::Type(type)); } -PyObject* TypePy::fromKey (PyObject *args) +PyObject* TypePy::fromKey(PyObject* args) { - unsigned int index{}; - if (!PyArg_ParseTuple(args, "I", &index)) + unsigned int index {}; + if (!PyArg_ParseTuple(args, "I", &index)) { return nullptr; + } Base::Type type = Base::Type::fromKey(index); return new TypePy(new Base::Type(type)); } -PyObject* TypePy::getNumTypes (PyObject *args) +PyObject* TypePy::getNumTypes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = Base::Type::getNumTypes(); return PyLong_FromLong(num); } -PyObject* TypePy::getBadType (PyObject *args) +PyObject* TypePy::getBadType(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Type type = Base::Type::badType(); return new TypePy(new Base::Type(type)); } -PyObject* TypePy::getParent(PyObject *args) +PyObject* TypePy::getParent(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Type type = getBaseTypePtr()->getParent(); return new TypePy(new Base::Type(type)); } -PyObject* TypePy::isBad(PyObject *args) +PyObject* TypePy::isBad(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool v = getBaseTypePtr()->isBad(); return PyBool_FromLong(v ? 1 : 0); } -PyObject* TypePy::isDerivedFrom(PyObject *args) +PyObject* TypePy::isDerivedFrom(PyObject* args) { Base::Type type; do { - const char *name{}; + const char* name {}; if (PyArg_ParseTuple(args, "s", &name)) { type = Base::Type::fromName(name); break; } PyErr_Clear(); - PyObject* t{}; + PyObject* t {}; if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &t)) { type = *static_cast(t)->getBaseTypePtr(); break; @@ -115,26 +121,25 @@ PyObject* TypePy::isDerivedFrom(PyObject *args) PyErr_SetString(PyExc_TypeError, "TypeId or str expected"); return nullptr; - } - while (false); + } while (false); bool v = (type != Base::Type::badType() && getBaseTypePtr()->isDerivedFrom(type)); return PyBool_FromLong(v ? 1 : 0); } -PyObject* TypePy::getAllDerivedFrom(PyObject *args) +PyObject* TypePy::getAllDerivedFrom(PyObject* args) { Base::Type type; do { - const char *name{}; + const char* name {}; if (PyArg_ParseTuple(args, "s", &name)) { type = Base::Type::fromName(name); break; } PyErr_Clear(); - PyObject* t{}; + PyObject* t {}; if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &t)) { type = *static_cast(t)->getBaseTypePtr(); break; @@ -142,34 +147,35 @@ PyObject* TypePy::getAllDerivedFrom(PyObject *args) PyErr_SetString(PyExc_TypeError, "TypeId or str expected"); return nullptr; - } - while (false); + } while (false); std::vector ary; Base::Type::getAllDerivedFrom(type, ary); Py::List res; - for (const auto & it : ary) { + for (const auto& it : ary) { res.append(Py::asObject(new TypePy(new Base::Type(it)))); } return Py::new_reference_to(res); } -PyObject* TypePy::getAllDerived(PyObject *args) +PyObject* TypePy::getAllDerived(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Base::Type type = Base::Type::fromName(getBaseTypePtr()->getName()); std::vector ary; Base::Type::getAllDerivedFrom(type, ary); Py::List res; - for (const auto & it : ary) { + for (const auto& it : ary) { res.append(Py::asObject(new TypePy(new Base::Type(it)))); } return Py::new_reference_to(res); } -namespace { +namespace +{ static void deallocPyObject(PyObject* py) { Base::PyObjectBase* pybase = static_cast(py); @@ -209,12 +215,13 @@ static PyObject* createPyObject(Base::BaseClass* base) return py; } -} +} // namespace -PyObject* TypePy::createInstance (PyObject *args) +PyObject* TypePy::createInstance(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Py::String name(getBaseTypePtr()->getName()); Py::TupleN tuple(name); @@ -222,21 +229,25 @@ PyObject* TypePy::createInstance (PyObject *args) return createInstanceByName(tuple.ptr()); } -PyObject* TypePy::createInstanceByName (PyObject *args) +PyObject* TypePy::createInstanceByName(PyObject* args) { - const char* name{}; - PyObject* load = Py_False; //NOLINT - if (!PyArg_ParseTuple(args, "s|O!", &name, &PyBool_Type, &load)) + const char* name {}; + PyObject* load = Py_False; // NOLINT + if (!PyArg_ParseTuple(args, "s|O!", &name, &PyBool_Type, &load)) { return nullptr; + } bool loadModule = Base::asBoolean(load); - Base::Type type = Base::Type::getTypeIfDerivedFrom(name, Base::BaseClass::getClassTypeId(), loadModule); - if (type.isBad()) + Base::Type type = + Base::Type::getTypeIfDerivedFrom(name, Base::BaseClass::getClassTypeId(), loadModule); + if (type.isBad()) { Py_Return; + } void* typeInstance = type.createInstance(); - if (!typeInstance) + if (!typeInstance) { Py_Return; + } Base::BaseClass* base = static_cast(typeInstance); @@ -258,15 +269,17 @@ Py::String TypePy::getModule() const std::string module(getBaseTypePtr()->getName()); std::string::size_type pos = module.find_first_of("::"); - if (pos != std::string::npos) + if (pos != std::string::npos) { module = std::string(module, 0, pos); - else + } + else { module.clear(); + } return {module}; } -PyObject *TypePy::getCustomAttributes(const char* /*attr*/) const +PyObject* TypePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Base/Unit.cpp b/src/Base/Unit.cpp index 212e293c47..dcebc1d3aa 100644 --- a/src/Base/Unit.cpp +++ b/src/Base/Unit.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include "Unit.h" @@ -34,6 +34,7 @@ using namespace Base; +// clang-format off static inline void checkPow(UnitSignature sig, double exp) { auto isInt = [](double value) { @@ -74,7 +75,7 @@ static inline void checkRange(const char * op, int length, int mass, int time, i throw Base::UnderflowError((std::string("Unit underflow in ") + std::string(op)).c_str()); } -Unit::Unit(int8_t Length, +Unit::Unit(int8_t Length, //NOLINT int8_t Mass, int8_t Time, int8_t ElectricCurrent, @@ -104,7 +105,7 @@ Unit::Unit(int8_t Length, } -Unit::Unit() +Unit::Unit() //NOLINT { Sig.Length = 0; Sig.Mass = 0; @@ -333,7 +334,7 @@ QString Unit::getString() const if (Sig.Angle > 0) { if (mult) ret<<'*'; - mult = true; + mult = true; //NOLINT ret << "deg"; if (Sig.Angle > 1) ret << "^" << Sig.Angle; @@ -431,7 +432,7 @@ QString Unit::getString() const if (Sig.Angle < 0) { if (mult) ret<<'*'; - mult = true; + mult = true; //NOLINT ret << "deg"; if (Sig.Angle < -1) ret << "^" << abs(Sig.Angle); @@ -610,3 +611,4 @@ Unit Unit::VolumetricThermalExpansionCoefficient(0, 0, 0, 0, -1); Unit Unit::Work (2, 1, -2); Unit Unit::YieldStrength (-1,1,-2); Unit Unit::YoungsModulus (-1,1,-2); +// clang-format on diff --git a/src/Base/Unit.h b/src/Base/Unit.h index 368abc786c..fc0b0db761 100644 --- a/src/Base/Unit.h +++ b/src/Base/Unit.h @@ -28,7 +28,8 @@ #include #include -namespace Base { +namespace Base +{ #define UnitSignatureLengthBits 4 #define UnitSignatureMassBits 4 @@ -42,15 +43,16 @@ namespace Base { // Hint: // https://en.cppreference.com/w/cpp/language/bit_field // https://stackoverflow.com/questions/33723631/signed-bit-field-in-c14 -struct UnitSignature{ - int32_t Length:UnitSignatureLengthBits; - int32_t Mass:UnitSignatureMassBits; - int32_t Time:UnitSignatureTimeBits; - int32_t ElectricCurrent:UnitSignatureElectricCurrentBits; - int32_t ThermodynamicTemperature:UnitSignatureThermodynamicTemperatureBits; - int32_t AmountOfSubstance:UnitSignatureAmountOfSubstanceBits; - int32_t LuminousIntensity:UnitSignatureLuminousIntensityBits; - int32_t Angle:UnitSignatureAngleBits; +struct UnitSignature +{ + int32_t Length: UnitSignatureLengthBits; + int32_t Mass: UnitSignatureMassBits; + int32_t Time: UnitSignatureTimeBits; + int32_t ElectricCurrent: UnitSignatureElectricCurrentBits; + int32_t ThermodynamicTemperature: UnitSignatureThermodynamicTemperatureBits; + int32_t AmountOfSubstance: UnitSignatureAmountOfSubstanceBits; + int32_t LuminousIntensity: UnitSignatureLuminousIntensityBits; + int32_t Angle: UnitSignatureAngleBits; }; /** * The Unit class. @@ -59,30 +61,41 @@ class BaseExport Unit { public: /// default constructor - explicit Unit(int8_t Length,int8_t Mass=0,int8_t Time=0,int8_t ElectricCurrent=0, - int8_t ThermodynamicTemperature=0, int8_t AmountOfSubstance=0, - int8_t LuminousIntensity=0, int8_t Angle=0); + explicit Unit(int8_t Length, + int8_t Mass = 0, + int8_t Time = 0, + int8_t ElectricCurrent = 0, + int8_t ThermodynamicTemperature = 0, + int8_t AmountOfSubstance = 0, + int8_t LuminousIntensity = 0, + int8_t Angle = 0); Unit(); Unit(const Unit&); explicit Unit(const QString& expr); /// Destruction - ~Unit () = default; + ~Unit() = default; /** Operators. */ //@{ - inline Unit& operator *=(const Unit& that); - inline Unit& operator /=(const Unit& that); - Unit operator *(const Unit&) const; - Unit operator /(const Unit&) const; - bool operator ==(const Unit&) const; - bool operator !=(const Unit&that) const {return !(*this == that);} - Unit& operator =(const Unit&); - Unit pow(double exp)const; + inline Unit& operator*=(const Unit& that); + inline Unit& operator/=(const Unit& that); + Unit operator*(const Unit&) const; + Unit operator/(const Unit&) const; + bool operator==(const Unit&) const; + bool operator!=(const Unit& that) const + { + return !(*this == that); + } + Unit& operator=(const Unit&); + Unit pow(double exp) const; //@} /// get the unit signature - const UnitSignature & getSignature()const {return Sig;} - bool isEmpty()const; + const UnitSignature& getSignature() const + { + return Sig; + } + bool isEmpty() const; QString getString() const; /// get the type as an string such as "Area", "Length" or "Pressure". @@ -162,18 +175,18 @@ protected: UnitSignature Sig; }; -inline Unit& Unit::operator *=(const Unit& that) +inline Unit& Unit::operator*=(const Unit& that) { *this = *this * that; return *this; } -inline Unit& Unit::operator /=(const Unit& that) +inline Unit& Unit::operator/=(const Unit& that) { *this = *this / that; return *this; } -} // namespace Base +} // namespace Base -#endif // BASE_Unit_H +#endif // BASE_Unit_H diff --git a/src/Base/UnitPyImp.cpp b/src/Base/UnitPyImp.cpp index 5e61a18720..a658aa83f6 100644 --- a/src/Base/UnitPyImp.cpp +++ b/src/Base/UnitPyImp.cpp @@ -34,26 +34,27 @@ using namespace Base; // returns a string which represents the object e.g. when printed in python std::string UnitPy::representation() const { - const UnitSignature & Sig = getUnitPtr()->getSignature(); + const UnitSignature& Sig = getUnitPtr()->getSignature(); std::stringstream ret; ret << "Unit: "; ret << getUnitPtr()->getString().toUtf8().constData() << " ("; ret << Sig.Length << ","; - ret << Sig.Mass << ","; - ret << Sig.Time << ","; - ret << Sig.ElectricCurrent << ","; + ret << Sig.Mass << ","; + ret << Sig.Time << ","; + ret << Sig.ElectricCurrent << ","; ret << Sig.ThermodynamicTemperature << ","; - ret << Sig.AmountOfSubstance << ","; - ret << Sig.LuminousIntensity << ","; - ret << Sig.Angle << ")"; + ret << Sig.AmountOfSubstance << ","; + ret << Sig.LuminousIntensity << ","; + ret << Sig.Angle << ")"; std::string type = getUnitPtr()->getTypeString().toUtf8().constData(); - if (! type.empty()) + if (!type.empty()) { ret << " [" << type << "]"; + } return ret.str(); } -PyObject *UnitPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* UnitPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of UnitPy and the Twin object return new UnitPy(new Unit); @@ -62,26 +63,26 @@ PyObject *UnitPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pytho // constructor method int UnitPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - PyObject *object{}; - Unit *self = getUnitPtr(); + PyObject* object {}; + Unit* self = getUnitPtr(); // get quantity - if (PyArg_ParseTuple(args,"O!",&(Base::QuantityPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::QuantityPy::Type), &object)) { *self = static_cast(object)->getQuantityPtr()->getUnit(); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() + PyErr_Clear(); // set by PyArg_ParseTuple() // get unit - if (PyArg_ParseTuple(args,"O!",&(Base::UnitPy::Type), &object)) { + if (PyArg_ParseTuple(args, "O!", &(Base::UnitPy::Type), &object)) { *self = *(static_cast(object)->getUnitPtr()); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() + PyErr_Clear(); // set by PyArg_ParseTuple() // get string - char* string{}; - if (PyArg_ParseTuple(args,"et", "utf-8", &string)) { + char* string {}; + if (PyArg_ParseTuple(args, "et", "utf-8", &string)) { QString qstr = QString::fromUtf8(string); PyMem_Free(string); try { @@ -93,19 +94,19 @@ int UnitPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } } - PyErr_Clear(); // set by PyArg_ParseTuple() + PyErr_Clear(); // set by PyArg_ParseTuple() - int i1=0; - int i2=0; - int i3=0; - int i4=0; - int i5=0; - int i6=0; - int i7=0; - int i8=0; - if (PyArg_ParseTuple(args, "|iiiiiiii", &i1,&i2,&i3,&i4,&i5,&i6,&i7,&i8)) { + int i1 = 0; + int i2 = 0; + int i3 = 0; + int i4 = 0; + int i5 = 0; + int i6 = 0; + int i7 = 0; + int i8 = 0; + if (PyArg_ParseTuple(args, "|iiiiiiii", &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8)) { try { - *self = Unit(i1,i2,i3,i4,i5,i6,i7,i8); + *self = Unit(i1, i2, i3, i4, i5, i6, i7, i8); return 0; } catch (const Base::OverflowError& e) { @@ -119,7 +120,7 @@ int UnitPy::PyInit(PyObject* args, PyObject* /*kwd*/) } -PyObject* UnitPy::number_add_handler(PyObject *self, PyObject *other) +PyObject* UnitPy::number_add_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(UnitPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Unit"); @@ -129,8 +130,8 @@ PyObject* UnitPy::number_add_handler(PyObject *self, PyObject *other) PyErr_SetString(PyExc_TypeError, "Second arg must be Unit"); return nullptr; } - Base::Unit *a = static_cast(self)->getUnitPtr(); - Base::Unit *b = static_cast(other)->getUnitPtr(); + Base::Unit* a = static_cast(self)->getUnitPtr(); + Base::Unit* b = static_cast(other)->getUnitPtr(); if (*a != *b) { PyErr_SetString(PyExc_TypeError, "Units not matching!"); @@ -140,7 +141,7 @@ PyObject* UnitPy::number_add_handler(PyObject *self, PyObject *other) return new UnitPy(new Unit(*a)); } -PyObject* UnitPy::number_subtract_handler(PyObject *self, PyObject *other) +PyObject* UnitPy::number_subtract_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(UnitPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Unit"); @@ -150,8 +151,8 @@ PyObject* UnitPy::number_subtract_handler(PyObject *self, PyObject *other) PyErr_SetString(PyExc_TypeError, "Second arg must be Unit"); return nullptr; } - Base::Unit *a = static_cast(self)->getUnitPtr(); - Base::Unit *b = static_cast(other)->getUnitPtr(); + Base::Unit* a = static_cast(self)->getUnitPtr(); + Base::Unit* b = static_cast(other)->getUnitPtr(); if (*a != *b) { PyErr_SetString(PyExc_TypeError, "Units not matching!"); @@ -161,7 +162,7 @@ PyObject* UnitPy::number_subtract_handler(PyObject *self, PyObject *other) return new UnitPy(new Unit(*a)); } -PyObject* UnitPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* UnitPy::number_multiply_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(UnitPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Unit"); @@ -169,10 +170,10 @@ PyObject* UnitPy::number_multiply_handler(PyObject *self, PyObject *other) } if (PyObject_TypeCheck(other, &(UnitPy::Type))) { - Base::Unit *a = static_cast(self) ->getUnitPtr(); - Base::Unit *b = static_cast(other)->getUnitPtr(); + Base::Unit* a = static_cast(self)->getUnitPtr(); + Base::Unit* b = static_cast(other)->getUnitPtr(); - return new UnitPy(new Unit( (*a) * (*b) ) ); + return new UnitPy(new Unit((*a) * (*b))); } else { PyErr_SetString(PyExc_TypeError, "A Unit can only be multiplied by a Unit"); @@ -180,26 +181,24 @@ PyObject* UnitPy::number_multiply_handler(PyObject *self, PyObject *other) } } -PyObject* UnitPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* UnitPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(UnitPy::Type)) && - PyObject_TypeCheck(w, &(UnitPy::Type))) { - const Unit * u1 = static_cast(v)->getUnitPtr(); - const Unit * u2 = static_cast(w)->getUnitPtr(); + if (PyObject_TypeCheck(v, &(UnitPy::Type)) && PyObject_TypeCheck(w, &(UnitPy::Type))) { + const Unit* u1 = static_cast(v)->getUnitPtr(); + const Unit* u2 = static_cast(w)->getUnitPtr(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for Units"); + PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Units"); return nullptr; } else if (op == Py_EQ) { - res = (*u1 == *u2) ? Py_True : Py_False; //NOLINT + res = (*u1 == *u2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } else { - res = (*u1 != *u2) ? Py_True : Py_False; //NOLINT + res = (*u1 != *u2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } @@ -213,12 +212,12 @@ PyObject* UnitPy::richCompare(PyObject *v, PyObject *w, int op) Py::String UnitPy::getType() const { - return {getUnitPtr()->getTypeString().toUtf8(),"utf-8"}; + return {getUnitPtr()->getTypeString().toUtf8(), "utf-8"}; } Py::Tuple UnitPy::getSignature() const { - const UnitSignature & Sig = getUnitPtr()->getSignature(); + const UnitSignature& Sig = getUnitPtr()->getSignature(); Py::Tuple tuple(8); tuple.setItem(0, Py::Long(Sig.Length)); tuple.setItem(1, Py::Long(Sig.Mass)); @@ -232,8 +231,7 @@ Py::Tuple UnitPy::getSignature() const } - -PyObject *UnitPy::getCustomAttributes(const char* /*attr*/) const +PyObject* UnitPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -243,96 +241,97 @@ int UnitPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject * UnitPy::number_divide_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_divide_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_remainder_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_remainder_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_divmod_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_power_handler (PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/) +PyObject* +UnitPy::number_power_handler(PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_negative_handler (PyObject* /*self*/) +PyObject* UnitPy::number_negative_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_positive_handler (PyObject* /*self*/) +PyObject* UnitPy::number_positive_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_absolute_handler (PyObject* /*self*/) +PyObject* UnitPy::number_absolute_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -int UnitPy::number_nonzero_handler (PyObject* /*self*/) +int UnitPy::number_nonzero_handler(PyObject* /*self*/) { return 1; } -PyObject * UnitPy::number_invert_handler (PyObject* /*self*/) +PyObject* UnitPy::number_invert_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_lshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_lshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_rshift_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_rshift_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_and_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_and_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_xor_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_xor_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_or_handler (PyObject* /*self*/, PyObject* /*other*/) +PyObject* UnitPy::number_or_handler(PyObject* /*self*/, PyObject* /*other*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_int_handler (PyObject* /*self*/) +PyObject* UnitPy::number_int_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; } -PyObject * UnitPy::number_float_handler (PyObject* /*self*/) +PyObject* UnitPy::number_float_handler(PyObject* /*self*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; diff --git a/src/Base/UnitsApi.cpp b/src/Base/UnitsApi.cpp index cfabc98db3..8f03ba28cd 100644 --- a/src/Base/UnitsApi.cpp +++ b/src/Base/UnitsApi.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -40,76 +40,76 @@ #include "UnitsSchemaFemMilliMeterNewton.h" #ifndef M_PI -#define M_PI 3.14159265358979323846 +#define M_PI 3.14159265358979323846 #endif #ifndef M_E -#define M_E 2.71828182845904523536 +#define M_E 2.71828182845904523536 #endif -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ +#ifndef DOUBLE_MAX +#define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ #endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ +#ifndef DOUBLE_MIN +#define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ #endif using namespace Base; // === static attributes ================================================ -UnitsSchemaPtr UnitsApi::UserPrefSystem(new UnitsSchemaInternal()); -UnitSystem UnitsApi::currentSystem = UnitSystem::SI1; +UnitsSchemaPtr UnitsApi::UserPrefSystem(new UnitsSchemaInternal()); +UnitSystem UnitsApi::currentSystem = UnitSystem::SI1; int UnitsApi::UserPrefDecimals = 2; QString UnitsApi::getDescription(UnitSystem system) { switch (system) { - case UnitSystem::SI1: - return tr("Standard (mm, kg, s, degree)"); - case UnitSystem::SI2: - return tr("MKS (m, kg, s, degree)"); - case UnitSystem::Imperial1: - return tr("US customary (in, lb)"); - case UnitSystem::ImperialDecimal: - return tr("Imperial decimal (in, lb)"); - case UnitSystem::Centimeters: - return tr("Building Euro (cm, m², m³)"); - case UnitSystem::ImperialBuilding: - return tr("Building US (ft-in, sqft, cft)"); - case UnitSystem::MmMin: - return tr("Metric small parts & CNC(mm, mm/min)"); - case UnitSystem::ImperialCivil: - return tr("Imperial for Civil Eng (ft, ft/sec)"); - case UnitSystem::FemMilliMeterNewton: - return tr("FEM (mm, N, s)"); - default: - return tr("Unknown schema"); + case UnitSystem::SI1: + return tr("Standard (mm, kg, s, degree)"); + case UnitSystem::SI2: + return tr("MKS (m, kg, s, degree)"); + case UnitSystem::Imperial1: + return tr("US customary (in, lb)"); + case UnitSystem::ImperialDecimal: + return tr("Imperial decimal (in, lb)"); + case UnitSystem::Centimeters: + return tr("Building Euro (cm, m², m³)"); + case UnitSystem::ImperialBuilding: + return tr("Building US (ft-in, sqft, cft)"); + case UnitSystem::MmMin: + return tr("Metric small parts & CNC(mm, mm/min)"); + case UnitSystem::ImperialCivil: + return tr("Imperial for Civil Eng (ft, ft/sec)"); + case UnitSystem::FemMilliMeterNewton: + return tr("FEM (mm, N, s)"); + default: + return tr("Unknown schema"); } } UnitsSchemaPtr UnitsApi::createSchema(UnitSystem system) { switch (system) { - case UnitSystem::SI1: - return std::make_unique(); - case UnitSystem::SI2: - return std::make_unique(); - case UnitSystem::Imperial1: - return std::make_unique(); - case UnitSystem::ImperialDecimal: - return std::make_unique(); - case UnitSystem::Centimeters: - return std::make_unique(); - case UnitSystem::ImperialBuilding: - return std::make_unique(); - case UnitSystem::MmMin: - return std::make_unique(); - case UnitSystem::ImperialCivil: - return std::make_unique(); - case UnitSystem::FemMilliMeterNewton: - return std::make_unique(); - default: - break; + case UnitSystem::SI1: + return std::make_unique(); + case UnitSystem::SI2: + return std::make_unique(); + case UnitSystem::Imperial1: + return std::make_unique(); + case UnitSystem::ImperialDecimal: + return std::make_unique(); + case UnitSystem::Centimeters: + return std::make_unique(); + case UnitSystem::ImperialBuilding: + return std::make_unique(); + case UnitSystem::MmMin: + return std::make_unique(); + case UnitSystem::ImperialCivil: + return std::make_unique(); + case UnitSystem::FemMilliMeterNewton: + return std::make_unique(); + default: + break; } return nullptr; @@ -118,7 +118,7 @@ UnitsSchemaPtr UnitsApi::createSchema(UnitSystem system) void UnitsApi::setSchema(UnitSystem system) { if (UserPrefSystem) { - UserPrefSystem->resetSchemaUnits(); // for schemas changed the Quantity constants + UserPrefSystem->resetSchemaUnits(); // for schemas changed the Quantity constants } UserPrefSystem = createSchema(system); @@ -130,13 +130,15 @@ void UnitsApi::setSchema(UnitSystem system) currentSystem = UnitSystem::SI1; } - UserPrefSystem->setSchemaUnits(); // if necessary a unit schema can change the constants in Quantity (e.g. mi=1.8km rather then 1.6km). + UserPrefSystem->setSchemaUnits(); // if necessary a unit schema can change the constants in + // Quantity (e.g. mi=1.8km rather then 1.6km). } QString UnitsApi::toString(const Base::Quantity& quantity, const QuantityFormat& format) { - QString value = QString::fromLatin1("'%1 %2'").arg(quantity.getValue(), 0, format.toFormat(), format.precision) - .arg(quantity.getUnit().getString()); + QString value = QString::fromLatin1("'%1 %2'") + .arg(quantity.getValue(), 0, format.toFormat(), format.precision) + .arg(quantity.getUnit().getString()); return value; } @@ -151,13 +153,13 @@ QString UnitsApi::toNumber(double value, const QuantityFormat& format) return number; } -//return true if the current user schema uses multiple units for length (ex. Ft/In) +// return true if the current user schema uses multiple units for length (ex. Ft/In) bool UnitsApi::isMultiUnitLength() { return UserPrefSystem->isMultiUnitLength(); } -//return true if the current user schema uses multiple units for angles (ex. DMS) +// return true if the current user schema uses multiple units for angles (ex. DMS) bool UnitsApi::isMultiUnitAngle() { return UserPrefSystem->isMultiUnitAngle(); @@ -170,19 +172,20 @@ std::string UnitsApi::getBasicLengthUnit() // === static translation methods ========================================== -QString UnitsApi::schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) +QString UnitsApi::schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) { - return UserPrefSystem->schemaTranslate(quant,factor,unitString); + return UserPrefSystem->schemaTranslate(quant, factor, unitString); } -double UnitsApi::toDouble(PyObject *ArgObj, const Base::Unit &u) +double UnitsApi::toDouble(PyObject* ArgObj, const Base::Unit& u) { if (PyUnicode_Check(ArgObj)) { QString str = QString::fromUtf8(PyUnicode_AsUTF8(ArgObj)); // Parse the string Quantity q = Quantity::parse(str); - if (q.getUnit() == u) + if (q.getUnit() == u) { return q.getValue(); + } throw Base::UnitsMismatchError("Wrong unit type!"); } else if (PyFloat_Check(ArgObj)) { @@ -196,9 +199,9 @@ double UnitsApi::toDouble(PyObject *ArgObj, const Base::Unit &u) } } -Quantity UnitsApi::toQuantity(PyObject *ArgObj, const Base::Unit &u) +Quantity UnitsApi::toQuantity(PyObject* ArgObj, const Base::Unit& u) { - double d{}; + double d {}; if (PyUnicode_Check(ArgObj)) { QString str = QString::fromUtf8(PyUnicode_AsUTF8(ArgObj)); // Parse the string @@ -215,7 +218,7 @@ Quantity UnitsApi::toQuantity(PyObject *ArgObj, const Base::Unit &u) throw Base::UnitsMismatchError("Wrong parameter type!"); } - return Quantity(d,u); + return Quantity(d, u); } void UnitsApi::setDecimals(int prec) diff --git a/src/Base/UnitsApi.h b/src/Base/UnitsApi.h index be630eb155..1837bae019 100644 --- a/src/Base/UnitsApi.h +++ b/src/Base/UnitsApi.h @@ -33,7 +33,8 @@ using PyObject = struct _object; using PyMethodDef = struct PyMethodDef; -namespace Base { +namespace Base +{ using UnitsSchemaPtr = std::unique_ptr; /** @@ -52,15 +53,18 @@ public: */ static void setSchema(UnitSystem s); /// return the active schema - static UnitSystem getSchema() { + static UnitSystem getSchema() + { return currentSystem; } /// Returns a brief description of a schema static QString getDescription(UnitSystem); - static QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); - static QString schemaTranslate(const Base::Quantity& quant) { // to satisfy GCC - double dummy1{}; + static QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString); + static QString schemaTranslate(const Base::Quantity& quant) + { // to satisfy GCC + double dummy1 {}; QString dummy2; return UnitsApi::schemaTranslate(quant, dummy1, dummy2); } @@ -69,17 +73,22 @@ public: * The string is a number in C locale (i.e. the decimal separator is always a dot) and if * needed represented in scientific notation. The string also includes the unit of the quantity. */ - static QString toString(const Base::Quantity& q, const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); + static QString toString(const Base::Quantity& q, + const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); /** Get a number as string for a quantity of a given format. * The string is a number in C locale (i.e. the decimal separator is always a dot) and if - * needed represented in scientific notation. The string doesn't include the unit of the quantity. + * needed represented in scientific notation. The string doesn't include the unit of the + * quantity. */ - static QString toNumber(const Base::Quantity& q, const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); + static QString toNumber(const Base::Quantity& q, + const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); /** Get a number as string for a double of a given format. * The string is a number in C locale (i.e. the decimal separator is always a dot) and if - * needed represented in scientific notation. The string doesn't include the unit of the quantity. + * needed represented in scientific notation. The string doesn't include the unit of the + * quantity. */ - static QString toNumber(double d, const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); + static QString toNumber(double d, + const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); /// generate a value for a quantity with default user preferred system static double toDouble(PyObject* args, const Base::Unit& u = Base::Unit()); @@ -92,19 +101,19 @@ public: static int getDecimals(); //@} - //double Result; + // double Result; - //return true if the current user schema uses multiple units for length (ex. Ft/In) + // return true if the current user schema uses multiple units for length (ex. Ft/In) static bool isMultiUnitLength(); - //return true if the current user schema uses multiple units for angles (ex. DMS) + // return true if the current user schema uses multiple units for angles (ex. DMS) static bool isMultiUnitAngle(); - //return the basic unit of measure for length in the current user schema. + // return the basic unit of measure for length in the current user schema. static std::string getBasicLengthUnit(); // Python interface - static PyMethodDef Methods[]; + static PyMethodDef Methods[]; /// return an instance of the given enum value static UnitsSchemaPtr createSchema(UnitSystem s); @@ -113,19 +122,19 @@ protected: static UnitsSchemaPtr UserPrefSystem; static UnitSystem currentSystem; /// number of decimals for floats - static int UserPrefDecimals; + static int UserPrefDecimals; protected: // the python API wrapper methods - static PyObject *sParseQuantity (PyObject *self,PyObject *args); - static PyObject *sListSchemas (PyObject *self,PyObject *args); - static PyObject *sGetSchema (PyObject *self,PyObject *args); - static PyObject *sSetSchema (PyObject *self,PyObject *args); - static PyObject *sSchemaTranslate (PyObject *self,PyObject *args); - static PyObject *sToNumber (PyObject *self,PyObject *args); + static PyObject* sParseQuantity(PyObject* self, PyObject* args); + static PyObject* sListSchemas(PyObject* self, PyObject* args); + static PyObject* sGetSchema(PyObject* self, PyObject* args); + static PyObject* sSetSchema(PyObject* self, PyObject* args); + static PyObject* sSchemaTranslate(PyObject* self, PyObject* args); + static PyObject* sToNumber(PyObject* self, PyObject* args); }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSAPI_H +#endif // BASE_UNITSAPI_H diff --git a/src/Base/UnitsApiPy.cpp b/src/Base/UnitsApiPy.cpp index 4c59330e53..99c41c426f 100644 --- a/src/Base/UnitsApiPy.cpp +++ b/src/Base/UnitsApiPy.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -34,7 +34,6 @@ #include "QuantityPy.h" - using namespace Base; //************************************************************************** @@ -42,43 +41,50 @@ using namespace Base; // UnitsApi Methods PyMethodDef UnitsApi::Methods[] = { - {"parseQuantity", UnitsApi::sParseQuantity, METH_VARARGS, + {"parseQuantity", + UnitsApi::sParseQuantity, + METH_VARARGS, "parseQuantity(string) -> Base.Quantity()\n\n" "calculate a mathematical expression with units to a quantity object. \n" "can be used for simple unit translation like: \n" "parseQuantity('10m')\n" "or for more complex espressions:\n" - "parseQuantity('sin(pi)/50.0 m/s^2')\n" - }, - {"listSchemas", UnitsApi::sListSchemas, METH_VARARGS, + "parseQuantity('sin(pi)/50.0 m/s^2')\n"}, + {"listSchemas", + UnitsApi::sListSchemas, + METH_VARARGS, "listSchemas() -> a tuple of schemas\n\n" - "listSchemas(int) -> description of the given schema\n\n" - }, - {"getSchema", UnitsApi::sGetSchema, METH_VARARGS, + "listSchemas(int) -> description of the given schema\n\n"}, + {"getSchema", + UnitsApi::sGetSchema, + METH_VARARGS, "getSchema() -> int\n\n" - "The int is the position of the tuple returned by listSchemas" - }, - {"setSchema", UnitsApi::sSetSchema, METH_VARARGS, + "The int is the position of the tuple returned by listSchemas"}, + {"setSchema", + UnitsApi::sSetSchema, + METH_VARARGS, "setSchema(int) -> None\n\n" - "Sets the current schema to the given number, if possible" - }, - {"schemaTranslate", UnitsApi::sSchemaTranslate, METH_VARARGS, + "Sets the current schema to the given number, if possible"}, + {"schemaTranslate", + UnitsApi::sSchemaTranslate, + METH_VARARGS, "schemaTranslate(Quantity, int) -> tuple\n\n" - "Translate a quantity to a given schema" - }, - {"toNumber", UnitsApi::sToNumber, METH_VARARGS, + "Translate a quantity to a given schema"}, + {"toNumber", + UnitsApi::sToNumber, + METH_VARARGS, "toNumber(Quantity or float, [format='g', decimals=-1]) -> str\n\n" - "Convert a quantity or float to a string" - }, + "Convert a quantity or float to a string"}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; -PyObject* UnitsApi::sParseQuantity(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sParseQuantity(PyObject* /*self*/, PyObject* args) { - char *pstr{}; - if (!PyArg_ParseTuple(args, "et", "utf-8", &pstr)) + char* pstr {}; + if (!PyArg_ParseTuple(args, "et", "utf-8", &pstr)) { return nullptr; + } Quantity rtn; QString qstr = QString::fromUtf8(pstr); @@ -94,13 +100,14 @@ PyObject* UnitsApi::sParseQuantity(PyObject * /*self*/, PyObject *args) return new QuantityPy(new Quantity(rtn)); } -PyObject* UnitsApi::sListSchemas(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sListSchemas(PyObject* /*self*/, PyObject* args) { if (PyArg_ParseTuple(args, "")) { int num = static_cast(UnitSystem::NumUnitSystemTypes); Py::Tuple tuple(num); - for (int i=0; i(i)).toStdString()}; + for (int i = 0; i < num; i++) { + const auto description { + UnitsApi::getDescription(static_cast(i)).toStdString()}; tuple.setItem(i, Py::String(description.c_str())); } @@ -108,7 +115,7 @@ PyObject* UnitsApi::sListSchemas(PyObject * /*self*/, PyObject *args) } PyErr_Clear(); - int index{}; + int index {}; if (PyArg_ParseTuple(args, "i", &index)) { int num = static_cast(UnitSystem::NumUnitSystemTypes); if (index < 0 || index >= num) { @@ -116,7 +123,8 @@ PyObject* UnitsApi::sListSchemas(PyObject * /*self*/, PyObject *args) return nullptr; } - const auto description {UnitsApi::getDescription(static_cast(index)).toStdString()}; + const auto description { + UnitsApi::getDescription(static_cast(index)).toStdString()}; return Py_BuildValue("s", description.c_str()); } @@ -124,18 +132,19 @@ PyObject* UnitsApi::sListSchemas(PyObject * /*self*/, PyObject *args) return nullptr; } -PyObject* UnitsApi::sGetSchema(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sGetSchema(PyObject* /*self*/, PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return Py_BuildValue("i", static_cast(currentSystem)); } -PyObject* UnitsApi::sSetSchema(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sSetSchema(PyObject* /*self*/, PyObject* args) { PyErr_Clear(); - int index{}; + int index {}; if (PyArg_ParseTuple(args, "i", &index)) { int num = static_cast(UnitSystem::NumUnitSystemTypes); if (index < 0 || index >= num) { @@ -147,12 +156,13 @@ PyObject* UnitsApi::sSetSchema(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* UnitsApi::sSchemaTranslate(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sSchemaTranslate(PyObject* /*self*/, PyObject* args) { - PyObject* q{}; - int index{}; - if (!PyArg_ParseTuple(args, "O!i", &(QuantityPy::Type), &q, &index)) + PyObject* q {}; + int index {}; + if (!PyArg_ParseTuple(args, "O!i", &(QuantityPy::Type), &q, &index)) { return nullptr; + } Quantity quant; quant = *static_cast(q)->getQuantityPtr(); @@ -163,26 +173,26 @@ PyObject* UnitsApi::sSchemaTranslate(PyObject * /*self*/, PyObject *args) return nullptr; } - double factor{}; + double factor {}; QString uus; QString uss = schema->schemaTranslate(quant, factor, uus); Py::Tuple res(3); - res[0] = Py::String(uss.toUtf8(),"utf-8"); + res[0] = Py::String(uss.toUtf8(), "utf-8"); res[1] = Py::Float(factor); - res[2] = Py::String(uus.toUtf8(),"utf-8"); + res[2] = Py::String(uus.toUtf8(), "utf-8"); return Py::new_reference_to(res); } -PyObject* UnitsApi::sToNumber(PyObject * /*self*/, PyObject *args) +PyObject* UnitsApi::sToNumber(PyObject* /*self*/, PyObject* args) { - double value{}; + double value {}; char* format = "g"; - int decimals{}; + int decimals {}; do { - PyObject* q{}; + PyObject* q {}; if (PyArg_ParseTuple(args, "O!|si", &(QuantityPy::Type), &q, &format, &decimals)) { value = static_cast(q)->getQuantityPtr()->getValue(); break; @@ -195,15 +205,14 @@ PyObject* UnitsApi::sToNumber(PyObject * /*self*/, PyObject *args) PyErr_SetString(PyExc_TypeError, "toNumber(Quantity or float, [format='g', decimals=-1])"); return nullptr; - } - while (false); + } while (false); if (strlen(format) != 1) { PyErr_SetString(PyExc_ValueError, "Format string hasn't length of 1"); return nullptr; } - bool ok{}; + bool ok {}; QuantityFormat qf; qf.format = QuantityFormat::toFormat(format[0], &ok); qf.precision = decimals; diff --git a/src/Base/UnitsSchema.cpp b/src/Base/UnitsSchema.cpp index f22c221ed5..288a1fa7ef 100644 --- a/src/Base/UnitsSchema.cpp +++ b/src/Base/UnitsSchema.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -34,7 +34,8 @@ using namespace Base; -QString UnitsSchema::toLocale(const Base::Quantity& quant, double factor, const QString& unitString) const +QString +UnitsSchema::toLocale(const Base::Quantity& quant, double factor, const QString& unitString) const { QLocale Lc; const QuantityFormat& format = quant.getFormat(); diff --git a/src/Base/UnitsSchema.h b/src/Base/UnitsSchema.h index 2f27921790..a2f56b9a30 100644 --- a/src/Base/UnitsSchema.h +++ b/src/Base/UnitsSchema.h @@ -28,20 +28,23 @@ #include -namespace Base { +namespace Base +{ /** Units systems */ -enum class UnitSystem { - SI1 = 0 , /** internal (mm,kg,s) SI system (http://en.wikipedia.org/wiki/International_System_of_Units) */ - SI2 = 1 , /** MKS (m,kg,s) SI system */ - Imperial1 = 2, /** the Imperial system (http://en.wikipedia.org/wiki/Imperial_units) */ +enum class UnitSystem +{ + SI1 = 0, /** internal (mm,kg,s) SI system + (http://en.wikipedia.org/wiki/International_System_of_Units) */ + SI2 = 1, /** MKS (m,kg,s) SI system */ + Imperial1 = 2, /** the Imperial system (http://en.wikipedia.org/wiki/Imperial_units) */ ImperialDecimal = 3, /** Imperial with length in inch only */ - Centimeters = 4, /** All lengths in centimeters, areas and volumes in square/cubic meters */ + Centimeters = 4, /** All lengths in centimeters, areas and volumes in square/cubic meters */ ImperialBuilding = 5, /** All lengths in feet + inches + fractions */ MmMin = 6, /** Lengths in mm, Speed in mm/min. Angle in degrees. Useful for small parts & CNC */ ImperialCivil = 7, /** Lengths in ft, Speed in ft/sec. Used in Civil Eng in North America */ FemMilliMeterNewton = 8, /** Lengths in mm, Mass in t, TimeSpan in s, thus force is in N */ - NumUnitSystemTypes // must be the last item! + NumUnitSystemTypes // must be the last item! }; @@ -54,30 +57,42 @@ class UnitsSchema public: virtual ~UnitsSchema() = default; /** Gets called if this schema gets activated. - * Here it's theoretically possible that you can change the static factors - * for certain units (e.g. mi = 1,8km instead of mi=1.6km). - */ - virtual void setSchemaUnits(){} + * Here it's theoretically possible that you can change the static factors + * for certain units (e.g. mi = 1,8km instead of mi=1.6km). + */ + virtual void setSchemaUnits() + {} /// If you use setSchemaUnits() you also have to impment this method to undo your changes! - virtual void resetSchemaUnits(){} + virtual void resetSchemaUnits() + {} /// This method translates the quantity in a string as the user may expect it. - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString)=0; + virtual QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) = 0; QString toLocale(const Base::Quantity& quant, double factor, const QString& unitString) const; - //return true if this schema uses multiple units for length (ex. Ft/In) - virtual bool isMultiUnitLength() const {return false;} + // return true if this schema uses multiple units for length (ex. Ft/In) + virtual bool isMultiUnitLength() const + { + return false; + } - //return true if this schema uses multiple units for angles (ex. DMS) - virtual bool isMultiUnitAngle() const {return false;} + // return true if this schema uses multiple units for angles (ex. DMS) + virtual bool isMultiUnitAngle() const + { + return false; + } - //return the basic length unit for this schema - virtual std::string getBasicLengthUnit() const { return {"mm"}; } + // return the basic length unit for this schema + virtual std::string getBasicLengthUnit() const + { + return {"mm"}; + } }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMA_H +#endif // BASE_UNITSSCHEMA_H diff --git a/src/Base/UnitsSchemaCentimeters.cpp b/src/Base/UnitsSchemaCentimeters.cpp index e66418578a..033e558434 100644 --- a/src/Base/UnitsSchemaCentimeters.cpp +++ b/src/Base/UnitsSchemaCentimeters.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -34,7 +34,9 @@ using namespace Base; -QString UnitsSchemaCentimeters::schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) +QString UnitsSchemaCentimeters::schemaTranslate(const Base::Quantity& quant, + double& factor, + QString& unitString) { Unit unit = quant.getUnit(); if (unit == Unit::Length) { @@ -66,7 +68,7 @@ QString UnitsSchemaCentimeters::schemaTranslate(const Base::Quantity& quant, dou } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("mm/min"); - factor = 1.0/60; + factor = 1.0 / 60; } else { // default action for all cases without special treatment: diff --git a/src/Base/UnitsSchemaCentimeters.h b/src/Base/UnitsSchemaCentimeters.h index d6020b89bd..5b57e014d5 100644 --- a/src/Base/UnitsSchemaCentimeters.h +++ b/src/Base/UnitsSchemaCentimeters.h @@ -28,7 +28,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /** * The UnitSchema class @@ -36,11 +37,15 @@ namespace Base { class UnitsSchemaCentimeters: public UnitsSchema { public: - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; - std::string getBasicLengthUnit() const override { return {"cm"}; } + std::string getBasicLengthUnit() const override + { + return {"cm"}; + } }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMACENTIMETERS_H +#endif // BASE_UNITSSCHEMACENTIMETERS_H diff --git a/src/Base/UnitsSchemaFemMilliMeterNewton.cpp b/src/Base/UnitsSchemaFemMilliMeterNewton.cpp index db0687d9bd..9baf47a920 100644 --- a/src/Base/UnitsSchemaFemMilliMeterNewton.cpp +++ b/src/Base/UnitsSchemaFemMilliMeterNewton.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -35,7 +35,9 @@ using namespace Base; -QString UnitsSchemaFemMilliMeterNewton::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString UnitsSchemaFemMilliMeterNewton::schemaTranslate(const Quantity& quant, + double& factor, + QString& unitString) { Unit unit = quant.getUnit(); if (unit == Unit::Length) { diff --git a/src/Base/UnitsSchemaFemMilliMeterNewton.h b/src/Base/UnitsSchemaFemMilliMeterNewton.h index c58de4b8e8..5b47f47d9d 100644 --- a/src/Base/UnitsSchemaFemMilliMeterNewton.h +++ b/src/Base/UnitsSchemaFemMilliMeterNewton.h @@ -29,7 +29,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /* Milli metric / Newton / Seconds unit schema for use in FEM. @@ -41,11 +42,12 @@ namespace Base { class UnitsSchemaFemMilliMeterNewton: public UnitsSchema { public: - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMAFEMMLLIMETERNEWTON_H +#endif // BASE_UNITSSCHEMAFEMMLLIMETERNEWTON_H diff --git a/src/Base/UnitsSchemaImperial1.cpp b/src/Base/UnitsSchemaImperial1.cpp index 91a8029592..99d4c10ed2 100644 --- a/src/Base/UnitsSchemaImperial1.cpp +++ b/src/Base/UnitsSchemaImperial1.cpp @@ -23,11 +23,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #ifdef __GNUC__ -# include +#include #endif #include @@ -38,7 +38,8 @@ using namespace Base; -QString UnitsSchemaImperial1::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString +UnitsSchemaImperial1::schemaTranslate(const Quantity& quant, double& factor, QString& unitString) { double UnitValue = std::abs(quant.getValue()); Unit unit = quant.getUnit(); @@ -46,32 +47,32 @@ QString UnitsSchemaImperial1::schemaTranslate(const Quantity &quant, double &fac // mm/kg/s. And all combined units have to be calculated from there! // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - if (UnitValue < 0.00000254) {// smaller then 0.001 thou -> inch and scientific notation + if (unit == Unit::Length) { // Length handling ============================ + if (UnitValue < 0.00000254) { // smaller then 0.001 thou -> inch and scientific notation unitString = QString::fromLatin1("in"); factor = 25.4; } - else if(UnitValue < 2.54) { // smaller then 0.1 inch -> Thou (mil) + else if (UnitValue < 2.54) { // smaller then 0.1 inch -> Thou (mil) unitString = QString::fromLatin1("thou"); factor = 0.0254; } - else if(UnitValue < 304.8) { + else if (UnitValue < 304.8) { unitString = QString::fromLatin1("\""); factor = 25.4; } - else if(UnitValue < 914.4) { + else if (UnitValue < 914.4) { unitString = QString::fromLatin1("\'"); factor = 304.8; } - else if(UnitValue < 1609344.0) { + else if (UnitValue < 1609344.0) { unitString = QString::fromLatin1("yd"); factor = 914.4; } - else if(UnitValue < 1609344000.0) { + else if (UnitValue < 1609344000.0) { unitString = QString::fromLatin1("mi"); factor = 1609344.0; } - else { // bigger then 1000 mi -> scientific notation + else { // bigger then 1000 mi -> scientific notation unitString = QString::fromLatin1("in"); factor = 25.4; } @@ -99,7 +100,7 @@ QString UnitsSchemaImperial1::schemaTranslate(const Quantity &quant, double &fac factor = 0.45359237; } else if (unit == Unit::Pressure) { - if (UnitValue < 6894.744) {// psi is the smallest + if (UnitValue < 6894.744) { // psi is the smallest unitString = QString::fromLatin1("psi"); factor = 6.894744825494; } @@ -107,18 +108,18 @@ QString UnitsSchemaImperial1::schemaTranslate(const Quantity &quant, double &fac unitString = QString::fromLatin1("ksi"); factor = 6894.744825494; } - else { // bigger then 1000 ksi -> psi + scientific notation + else { // bigger then 1000 ksi -> psi + scientific notation unitString = QString::fromLatin1("psi"); factor = 6.894744825494; } } - else if (unit == Unit::Stiffness) { // Conversion to lbf/in + else if (unit == Unit::Stiffness) { // Conversion to lbf/in unitString = QString::fromLatin1("lbf/in"); - factor = 4.448222/0.0254; + factor = 4.448222 / 0.0254; } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("in/min"); - factor = 25.4/60; + factor = 25.4 / 60; } else { // default action for all cases without special treatment: @@ -129,9 +130,11 @@ QString UnitsSchemaImperial1::schemaTranslate(const Quantity &quant, double &fac return toLocale(quant, factor, unitString); } -QString UnitsSchemaImperialDecimal::schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) +QString UnitsSchemaImperialDecimal::schemaTranslate(const Base::Quantity& quant, + double& factor, + QString& unitString) { - //double UnitValue = std::abs(quant.getValue()); + // double UnitValue = std::abs(quant.getValue()); Unit unit = quant.getUnit(); // for imperial user/programmer mind; UnitValue is in internal system, that means // mm/kg/s. And all combined units have to be calculated from there! @@ -169,7 +172,7 @@ QString UnitsSchemaImperialDecimal::schemaTranslate(const Base::Quantity& quant, } else if (unit == Unit::Stiffness) { unitString = QString::fromLatin1("lbf/in"); - factor = 4.448222/0.0254; + factor = 4.448222 / 0.0254; } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("in/min"); @@ -188,7 +191,9 @@ QString UnitsSchemaImperialDecimal::schemaTranslate(const Base::Quantity& quant, return toLocale(quant, factor, unitString); } -QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity& quant, + double& factor, + QString& unitString) { // this schema expresses distances in feet + inches + fractions // ex: 3'- 4 1/4" with proper rounding @@ -198,21 +203,21 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, doub factor = 25.4; // Total number of inches to format - double totalInches = std::abs(quant.getValue())/factor; + double totalInches = std::abs(quant.getValue()) / factor; // minimum denominator (8 for 1/8, 16 for 1/16, etc) - int minden{}; + int minden {}; // Outputs - int feet{}; // whole feet - int inches{}; // whole inches - int num{},den{}; // numerator and denominator of fractional val - std::stringstream output; // output stream + int feet {}; // whole feet + int inches {}; // whole inches + int num {}, den {}; // numerator and denominator of fractional val + std::stringstream output; // output stream // Intermediate values - int ntot{}; // total fractional units - int a{},b{},d{}; // used to compute greatest common denominator - int tmp{}; // temporary variable for GCD + int ntot {}; // total fractional units + int a {}, b {}, d {}; // used to compute greatest common denominator + int tmp {}; // temporary variable for GCD // Get the current user specified minimum denominator minden = quant.getFormat().getDenominator(); @@ -221,29 +226,28 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, doub ntot = static_cast(std::round(totalInches * static_cast(minden))); // If this is zero, nothing to do but return - if( ntot==0 ) + if (ntot == 0) { return QString::fromLatin1("0"); + } // Compute the whole number of feet and remaining units - feet = static_cast(std::floor(ntot / (12*minden))); - ntot = ntot - 12*minden*feet; + feet = static_cast(std::floor(ntot / (12 * minden))); + ntot = ntot - 12 * minden * feet; // Compute the remaining number of whole inches - inches = static_cast(std::floor(ntot/minden)); + inches = static_cast(std::floor(ntot / minden)); // Lastly the fractional quantities - num = ntot - inches*minden; + num = ntot - inches * minden; den = minden; // If numerator is not zero, compute greatest common divisor and reduce // fraction - if( num!=0 ) - { + if (num != 0) { // initialize a = num; b = den; - while (b != 0) - { + while (b != 0) { tmp = a % b; a = b; @@ -258,31 +262,33 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, doub // Process into string. Start with negative sign if quantity is less // than zero char plusOrMinus; - if( quant.getValue() < 0 ) - { + if (quant.getValue() < 0) { output << "-"; plusOrMinus = '-'; } - else plusOrMinus = '+'; + else { + plusOrMinus = '+'; + } bool trailingNumber = false; // Print feet if we have any - if( feet!=0 ) - { + if (feet != 0) { output << feet << "'"; trailingNumber = true; } // Print whole inches if we have any - if( inches!=0 ) - { - if (trailingNumber) output << " "; + if (inches != 0) { + if (trailingNumber) { + output << " "; + } output << inches << "\""; trailingNumber = true; } // Print fractional inches if we have any - if( num!=0 ) - { - if (trailingNumber) output << " " << plusOrMinus << " "; + if (num != 0) { + if (trailingNumber) { + output << " " << plusOrMinus << " "; + } output << num << "/" << den << "\""; } @@ -303,7 +309,7 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, doub } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("in/min"); - factor = 25.4/60; + factor = 25.4 / 60; } else { unitString = quant.getUnit().getString(); @@ -313,56 +319,58 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity &quant, doub return toLocale(quant, factor, unitString); } -QString UnitsSchemaImperialCivil::schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) +QString UnitsSchemaImperialCivil::schemaTranslate(const Base::Quantity& quant, + double& factor, + QString& unitString) { -// double UnitValue = std::abs(quant.getValue()); + // double UnitValue = std::abs(quant.getValue()); Unit unit = quant.getUnit(); // for imperial user/programmer mind; UnitValue is in internal system, that means // mm/kg/s. And all combined units have to be calculated from there! // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - unitString = QString::fromLatin1("ft"); //always ft - factor = 304.8; //12 * 25.4 + if (unit == Unit::Length) { // Length handling ============================ + unitString = QString::fromLatin1("ft"); // always ft + factor = 304.8; // 12 * 25.4 } else if (unit == Unit::Area) { - unitString = QString::fromLatin1("ft^2"); //always sq.ft + unitString = QString::fromLatin1("ft^2"); // always sq.ft factor = 92903.04; } else if (unit == Unit::Volume) { - unitString = QString::fromLatin1("ft^3"); //always cu. ft + unitString = QString::fromLatin1("ft^3"); // always cu. ft factor = 28316846.592; } else if (unit == Unit::Mass) { - unitString = QString::fromLatin1("lb"); //always lbs. + unitString = QString::fromLatin1("lb"); // always lbs. factor = 0.45359237; } else if (unit == Unit::Pressure) { - unitString = QString::fromLatin1("psi"); - factor = 6.894744825494; + unitString = QString::fromLatin1("psi"); + factor = 6.894744825494; } else if (unit == Unit::Stiffness) { unitString = QString::fromLatin1("lbf/in"); - factor = 4.448222/0.0254; + factor = 4.448222 / 0.0254; } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("mph"); - factor = 447.04; //1mm/sec => mph + factor = 447.04; // 1mm/sec => mph } // this schema expresses angles in degrees + minutes + seconds else if (unit == Unit::Angle) { unitString = QString::fromUtf8("deg"); - QString degreeString = QString::fromUtf8("\xC2\xB0"); //degree symbol - QString minuteString = QString::fromUtf8("\xE2\x80\xB2"); //prime symbol - QString secondString = QString::fromUtf8("\xE2\x80\xB3"); //double prime symbol - factor = 1.0; //1deg = 1"\xC2\xB0 " + QString degreeString = QString::fromUtf8("\xC2\xB0"); // degree symbol + QString minuteString = QString::fromUtf8("\xE2\x80\xB2"); // prime symbol + QString secondString = QString::fromUtf8("\xE2\x80\xB3"); // double prime symbol + factor = 1.0; // 1deg = 1"\xC2\xB0 " - double totalDegrees = quant.getValue()/factor; + double totalDegrees = quant.getValue() / factor; double wholeDegrees = std::floor(totalDegrees); - double sumMinutes = totalDegrees * 60.0; //quant as minutes + double sumMinutes = totalDegrees * 60.0; // quant as minutes double rawMinutes = sumMinutes - wholeDegrees * 60.0; double wholeMinutes = std::floor(rawMinutes); - double sumSeconds = totalDegrees * 3600.0; //quant as seconds + double sumSeconds = totalDegrees * 3600.0; // quant as seconds double rawSeconds = sumSeconds - (wholeDegrees * 3600.0) - (wholeMinutes * 60); int outDeg = static_cast(wholeDegrees); @@ -377,13 +385,13 @@ QString UnitsSchemaImperialCivil::schemaTranslate(const Base::Quantity& quant, d if (outSec > 0) { output << outSec << secondString.toUtf8().constData(); } -// uncomment this for decimals on seconds -// if (remainSeconds < (1.0 * pow(10.0,-Base::UnitsApi::getDecimals())) ) { -// //NOP too small to display -// } else { -// output << std::setprecision(Base::UnitsApi::getDecimals()) << std::fixed << -// rawSeconds << secondString.toStdString(); -// } + // uncomment this for decimals on seconds + // if (remainSeconds < (1.0 * pow(10.0,-Base::UnitsApi::getDecimals())) ) { + // //NOP too small to display + // } else { + // output << std::setprecision(Base::UnitsApi::getDecimals()) << std::fixed << + // rawSeconds << secondString.toStdString(); + // } return QString::fromUtf8(output.str().c_str()); } else { @@ -394,4 +402,3 @@ QString UnitsSchemaImperialCivil::schemaTranslate(const Base::Quantity& quant, d return toLocale(quant, factor, unitString); } - diff --git a/src/Base/UnitsSchemaImperial1.h b/src/Base/UnitsSchemaImperial1.h index 7eca980ef8..e7d81b2ad1 100644 --- a/src/Base/UnitsSchemaImperial1.h +++ b/src/Base/UnitsSchemaImperial1.h @@ -28,7 +28,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /** The schema class for the imperial unit system @@ -38,10 +39,14 @@ namespace Base { class UnitsSchemaImperial1: public UnitsSchema { public: - //virtual void setSchemaUnits(void); - //virtual void resetSchemaUnits(void); - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; - std::string getBasicLengthUnit() const override { return {"in"}; } + // virtual void setSchemaUnits(void); + // virtual void resetSchemaUnits(void); + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; + std::string getBasicLengthUnit() const override + { + return {"in"}; + } }; /** The schema class for the imperial unit system @@ -51,10 +56,14 @@ public: class UnitsSchemaImperialDecimal: public UnitsSchema { public: - //virtual void setSchemaUnits(void); - //virtual void resetSchemaUnits(void); - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; - std::string getBasicLengthUnit() const override { return {"in"}; } + // virtual void setSchemaUnits(void); + // virtual void resetSchemaUnits(void); + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; + std::string getBasicLengthUnit() const override + { + return {"in"}; + } }; /** The schema class for the imperial unit system @@ -64,14 +73,20 @@ public: class UnitsSchemaImperialBuilding: public UnitsSchema { public: - //virtual void setSchemaUnits(void); - //virtual void resetSchemaUnits(void); - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; - std::string getBasicLengthUnit() const override { return {"ft"}; } - - //return true if this schema uses multiple units for length (ex. Ft/In) - bool isMultiUnitLength() const override {return true;} + // virtual void setSchemaUnits(void); + // virtual void resetSchemaUnits(void); + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; + std::string getBasicLengthUnit() const override + { + return {"ft"}; + } + // return true if this schema uses multiple units for length (ex. Ft/In) + bool isMultiUnitLength() const override + { + return true; + } }; /** The schema class for Civil Engineering in the imperial unit system @@ -81,17 +96,24 @@ public: class UnitsSchemaImperialCivil: public UnitsSchema { public: - //virtual void setSchemaUnits(void); - //virtual void resetSchemaUnits(void); - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; - std::string getBasicLengthUnit() const override { return {"ft"}; } + // virtual void setSchemaUnits(void); + // virtual void resetSchemaUnits(void); + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; + std::string getBasicLengthUnit() const override + { + return {"ft"}; + } - //return true if this schema uses multiple units for angles (ex. DMS) - bool isMultiUnitAngle() const override {return true;} + // return true if this schema uses multiple units for angles (ex. DMS) + bool isMultiUnitAngle() const override + { + return true; + } }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMAIMPERIAL1_H +#endif // BASE_UNITSSCHEMAIMPERIAL1_H diff --git a/src/Base/UnitsSchemaInternal.cpp b/src/Base/UnitsSchemaInternal.cpp index d6e3ef703e..f585b2eae5 100644 --- a/src/Base/UnitsSchemaInternal.cpp +++ b/src/Base/UnitsSchemaInternal.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -35,7 +35,8 @@ using namespace Base; -QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString +UnitsSchemaInternal::schemaTranslate(const Quantity& quant, double& factor, QString& unitString) { double UnitValue = std::abs(quant.getValue()); Unit unit = quant.getUnit(); @@ -49,8 +50,8 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact // = 10e6 * kg*mm/s^3/K // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) {// Length handling ============================ - if (UnitValue < 1e-6) {// smaller than 0.001 nm -> scientific notation + if (unit == Unit::Length) { // Length handling ============================ + if (UnitValue < 1e-6) { // smaller than 0.001 nm -> scientific notation unitString = QString::fromLatin1("mm"); factor = 1.0; } @@ -74,7 +75,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("km"); factor = 1e6; } - else {// bigger than 1000 km -> scientific notation + else { // bigger than 1000 km -> scientific notation unitString = QString::fromLatin1("m"); factor = 1e3; } @@ -92,13 +93,13 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("m^2"); factor = 1e6; } - else { // bigger than 1 square kilometer + else { // bigger than 1 square kilometer unitString = QString::fromLatin1("km^2"); factor = 1e12; } } else if (unit == Unit::Volume) { - if (UnitValue < 1e3) {// smaller than 1 ul + if (UnitValue < 1e3) { // smaller than 1 ul unitString = QString::fromLatin1("mm^3"); factor = 1.0; } @@ -110,7 +111,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("l"); factor = 1e6; } - else { // bigger than 1000 l + else { // bigger than 1000 l unitString = QString::fromLatin1("m^3"); factor = 1e9; } @@ -196,7 +197,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact factor = 1.0; } else if ((unit == Unit::Pressure) || (unit == Unit::Stress)) { - if (UnitValue < 10.0) {// Pa is the smallest + if (UnitValue < 10.0) { // Pa is the smallest unitString = QString::fromLatin1("Pa"); factor = 0.001; } @@ -212,13 +213,13 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("GPa"); factor = 1e6; } - else { // bigger -> scientific notation + else { // bigger -> scientific notation unitString = QString::fromLatin1("Pa"); factor = 0.001; } } else if ((unit == Unit::Stiffness)) { - if (UnitValue < 1){// mN/m is the smallest + if (UnitValue < 1) { // mN/m is the smallest unitString = QString::fromLatin1("mN/m"); factor = 1e-3; } @@ -280,7 +281,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("kV"); factor = 1e9; } - else { // > 1000 kV scientificc notation + else { // > 1000 kV scientificc notation unitString = QString::fromLatin1("V"); factor = 1e6; } @@ -314,7 +315,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("kWh"); factor = 3.6e+12; } - else { // bigger than 1000 kWh -> scientific notation + else { // bigger than 1000 kWh -> scientific notation unitString = QString::fromLatin1("J"); factor = 1e6; } @@ -362,7 +363,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact else if (unit == Unit::Magnetization) { unitString = QString::fromLatin1("A/m"); factor = 1e-3; - } + } else if (unit == Unit::ElectricalConductance) { if (UnitValue < 1e-9) { unitString = QString::fromUtf8("\xC2\xB5S"); @@ -420,7 +421,8 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact } else if (UnitValue < 1e-9) { // \x reads everything to the end, therefore split - unitString = QString::fromUtf8("\xC2\xB5""F"); + unitString = QString::fromUtf8("\xC2\xB5" + "F"); factor = 1e-12; } else if (UnitValue < 1e-6) { @@ -517,7 +519,7 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact factor = 1e6; } else if (unit == Unit::InverseLength) { - if (UnitValue < 1e-6) {// smaller than 0.001 1/km -> scientific notation + if (UnitValue < 1e-6) { // smaller than 0.001 1/km -> scientific notation unitString = QString::fromLatin1("1/m"); factor = 1e-3; } @@ -541,13 +543,13 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact unitString = QString::fromLatin1("1/nm"); factor = 1e6; } - else {// larger -> scientific notation + else { // larger -> scientific notation unitString = QString::fromLatin1("1/m"); factor = 1e-3; } } else if (unit == Unit::InverseArea) { - if (UnitValue < 1e-12) {// smaller than 0.001 1/km^2 -> scientific notation + if (UnitValue < 1e-12) { // smaller than 0.001 1/km^2 -> scientific notation unitString = QString::fromLatin1("1/m^2"); factor = 1e-6; } diff --git a/src/Base/UnitsSchemaInternal.h b/src/Base/UnitsSchemaInternal.h index c555e58b8e..35f9c64c59 100644 --- a/src/Base/UnitsSchemaInternal.h +++ b/src/Base/UnitsSchemaInternal.h @@ -28,7 +28,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /** The standard units schema @@ -39,11 +40,12 @@ namespace Base { class UnitsSchemaInternal: public UnitsSchema { public: - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMAINTERNAL_H +#endif // BASE_UNITSSCHEMAINTERNAL_H diff --git a/src/Base/UnitsSchemaMKS.cpp b/src/Base/UnitsSchemaMKS.cpp index fdbdf42a18..e15a721ad3 100644 --- a/src/Base/UnitsSchemaMKS.cpp +++ b/src/Base/UnitsSchemaMKS.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -35,14 +35,14 @@ using namespace Base; -QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString UnitsSchemaMKS::schemaTranslate(const Quantity& quant, double& factor, QString& unitString) { double UnitValue = std::abs(quant.getValue()); Unit unit = quant.getUnit(); // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) {// Length handling ============================ - if (UnitValue < 1e-6) {// smaller than 0.001 nm -> scientific notation + if (unit == Unit::Length) { // Length handling ============================ + if (UnitValue < 1e-6) { // smaller than 0.001 nm -> scientific notation unitString = QString::fromLatin1("mm"); factor = 1.0; } @@ -66,7 +66,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("km"); factor = 1e6; } - else {// bigger than 1000 km -> scientific notation + else { // bigger than 1000 km -> scientific notation unitString = QString::fromLatin1("m"); factor = 1e3; } @@ -84,13 +84,13 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("m^2"); factor = 1e6; } - else { // bigger than 1 square kilometer + else { // bigger than 1 square kilometer unitString = QString::fromLatin1("km^2"); factor = 1e12; } } else if (unit == Unit::Volume) { - if (UnitValue < 1e3) {// smaller than 1 ul + if (UnitValue < 1e3) { // smaller than 1 ul unitString = QString::fromLatin1("mm^3"); factor = 1.0; } @@ -102,7 +102,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("l"); factor = 1e6; } - else { // bigger than 1000 l + else { // bigger than 1000 l unitString = QString::fromLatin1("m^3"); factor = 1e9; } @@ -148,7 +148,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q factor = 1000.0; } else if ((unit == Unit::Pressure) || (unit == Unit::Stress)) { - if (UnitValue < 10.0) {// Pa is the smallest + if (UnitValue < 10.0) { // Pa is the smallest unitString = QString::fromLatin1("Pa"); factor = 0.001; } @@ -164,13 +164,13 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("GPa"); factor = 1000000.0; } - else { // bigger then 1000 GPa -> scientific notation + else { // bigger then 1000 GPa -> scientific notation unitString = QString::fromLatin1("Pa"); factor = 0.001; } } else if ((unit == Unit::Stiffness)) { - if (UnitValue < 1){// mN/m is the smallest + if (UnitValue < 1) { // mN/m is the smallest unitString = QString::fromLatin1("mN/m"); factor = 1e-3; } @@ -270,7 +270,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("kV"); factor = 1e9; } - else { // > 1000 kV scientificc notation + else { // > 1000 kV scientificc notation unitString = QString::fromLatin1("V"); factor = 1e6; } @@ -310,7 +310,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q else if (unit == Unit::Magnetization) { unitString = QString::fromLatin1("A/m"); factor = 1e-3; - } + } else if (unit == Unit::ElectricalConductance) { if (UnitValue < 1e-9) { unitString = QString::fromUtf8("\xC2\xB5S"); @@ -368,7 +368,8 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q } else if (UnitValue < 1e-9) { // \x reads everything to the end, therefore split - unitString = QString::fromUtf8("\xC2\xB5""F"); + unitString = QString::fromUtf8("\xC2\xB5" + "F"); factor = 1e-12; } else if (UnitValue < 1e-6) { @@ -399,8 +400,8 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q } } else if (unit == Unit::VacuumPermittivity) { - unitString = QString::fromLatin1("F/m"); - factor = 1e-9; + unitString = QString::fromLatin1("F/m"); + factor = 1e-9; } else if (unit == Unit::Work) { if (UnitValue < 1.602176634e-10) { @@ -431,7 +432,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("kWh"); factor = 3.6e+12; } - else { // bigger than 1000 kWh -> scientific notation + else { // bigger than 1000 kWh -> scientific notation unitString = QString::fromLatin1("J"); factor = 1e6; } @@ -505,7 +506,7 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q factor = 1e6; } else if (unit == Unit::InverseLength) { - if (UnitValue < 1e-6) {// smaller than 0.001 1/km -> scientific notation + if (UnitValue < 1e-6) { // smaller than 0.001 1/km -> scientific notation unitString = QString::fromLatin1("1/m"); factor = 1e-3; } @@ -529,13 +530,13 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q unitString = QString::fromLatin1("1/nm"); factor = 1e6; } - else {// larger -> scientific notation + else { // larger -> scientific notation unitString = QString::fromLatin1("1/m"); factor = 1e-3; } } else if (unit == Unit::InverseArea) { - if (UnitValue < 1e-12) {// smaller than 0.001 1/km^2 -> scientific notation + if (UnitValue < 1e-12) { // smaller than 0.001 1/km^2 -> scientific notation unitString = QString::fromLatin1("1/m^2"); factor = 1e-6; } diff --git a/src/Base/UnitsSchemaMKS.h b/src/Base/UnitsSchemaMKS.h index e36036de81..dff1204a37 100644 --- a/src/Base/UnitsSchemaMKS.h +++ b/src/Base/UnitsSchemaMKS.h @@ -28,7 +28,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /** @@ -37,11 +38,12 @@ namespace Base { class UnitsSchemaMKS: public UnitsSchema { public: - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMAMKS_H +#endif // BASE_UNITSSCHEMAMKS_H diff --git a/src/Base/UnitsSchemaMmMin.cpp b/src/Base/UnitsSchemaMmMin.cpp index e9a857f0c7..be3196361e 100644 --- a/src/Base/UnitsSchemaMmMin.cpp +++ b/src/Base/UnitsSchemaMmMin.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifdef __GNUC__ -# include +#include #endif #include @@ -34,7 +34,8 @@ using namespace Base; -QString UnitsSchemaMmMin::schemaTranslate(const Quantity &quant, double &factor, QString &unitString) +QString +UnitsSchemaMmMin::schemaTranslate(const Quantity& quant, double& factor, QString& unitString) { Unit unit = quant.getUnit(); if (unit == Unit::Length) { @@ -47,7 +48,7 @@ QString UnitsSchemaMmMin::schemaTranslate(const Quantity &quant, double &factor, } else if (unit == Unit::Velocity) { unitString = QString::fromLatin1("mm/min"); - factor = 1./60.; + factor = 1. / 60.; } else { // default action for all cases without special treatment: diff --git a/src/Base/UnitsSchemaMmMin.h b/src/Base/UnitsSchemaMmMin.h index c2c9901bc9..cc51a38721 100644 --- a/src/Base/UnitsSchemaMmMin.h +++ b/src/Base/UnitsSchemaMmMin.h @@ -28,7 +28,8 @@ #include "UnitsSchema.h" -namespace Base { +namespace Base +{ /* Metric units schema intended for design of small parts and for CNC @@ -39,11 +40,12 @@ namespace Base { class UnitsSchemaMmMin: public UnitsSchema { public: - QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; + QString + schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString) override; }; -} // namespace Base +} // namespace Base -#endif // BASE_UNITSSCHEMAMMMIN_H +#endif // BASE_UNITSSCHEMAMMMIN_H diff --git a/src/Base/Uuid.cpp b/src/Base/Uuid.cpp index 1a800cb53f..695d7a6d8f 100644 --- a/src/Base/Uuid.cpp +++ b/src/Base/Uuid.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -71,8 +71,9 @@ void Uuid::setValue(const char* sString) { if (sString) { QUuid uuid(QString::fromLatin1(sString)); - if (uuid.isNull()) + if (uuid.isNull()) { throw std::runtime_error("invalid uuid"); + } // remove curly braces QString id = uuid.toString(); id = id.mid(1); @@ -81,7 +82,7 @@ void Uuid::setValue(const char* sString) } } -void Uuid::setValue(const std::string &sString) +void Uuid::setValue(const std::string& sString) { setValue(sString.c_str()); } diff --git a/src/Base/Uuid.h b/src/Base/Uuid.h index dadfba5736..27297a6e11 100644 --- a/src/Base/Uuid.h +++ b/src/Base/Uuid.h @@ -48,18 +48,23 @@ public: virtual ~Uuid(); void setValue(const char* sString); - void setValue(const std::string &sString); + void setValue(const std::string& sString); const std::string& getValue() const; static std::string createUuid(); - bool operator==(const Uuid &other) const {return _uuid == other._uuid;} - bool operator<(const Uuid &other) const {return _uuid < other._uuid;} + bool operator==(const Uuid& other) const + { + return _uuid == other._uuid; + } + bool operator<(const Uuid& other) const + { + return _uuid < other._uuid; + } private: std::string _uuid; }; -} //namespace Base - -#endif // BASE_UUID_H +} // namespace Base +#endif // BASE_UUID_H diff --git a/src/Base/Vector3D.cpp b/src/Base/Vector3D.cpp index 810f1e1813..2d0711ed28 100644 --- a/src/Base/Vector3D.cpp +++ b/src/Base/Vector3D.cpp @@ -31,40 +31,43 @@ using namespace Base; -template -Vector3<_Precision>::Vector3 (_Precision fx, _Precision fy, _Precision fz) - : x(fx), - y(fy), - z(fz) -{ -} +template +Vector3<_Precision>::Vector3(_Precision fx, _Precision fy, _Precision fz) + : x(fx) + , y(fy) + , z(fz) +{} -template -_Precision& Vector3<_Precision>::operator [] (unsigned short usIndex) +template +_Precision& Vector3<_Precision>::operator[](unsigned short usIndex) { - switch (usIndex) - { - case 0: return x; - case 1: return y; - case 2: return z; + switch (usIndex) { + case 0: + return x; + case 1: + return y; + case 2: + return z; } return x; } -template -const _Precision& Vector3<_Precision>::operator [] (unsigned short usIndex) const +template +const _Precision& Vector3<_Precision>::operator[](unsigned short usIndex) const { - switch (usIndex) - { - case 0: return x; - case 1: return y; - case 2: return z; + switch (usIndex) { + case 0: + return x; + case 1: + return y; + case 2: + return z; } return x; } -template -Vector3 <_Precision>Vector3<_Precision>::operator + (const Vector3<_Precision>& rcVct) const +template +Vector3<_Precision> Vector3<_Precision>::operator+(const Vector3<_Precision>& rcVct) const { Vector3<_Precision> cVctRes; cVctRes.x = x + rcVct.x; @@ -73,18 +76,18 @@ Vector3 <_Precision>Vector3<_Precision>::operator + (const Vector3<_Precision>& return cVctRes; } -template -Vector3<_Precision> Vector3<_Precision>::operator & (const Vector3<_Precision>& rcVct) const +template +Vector3<_Precision> Vector3<_Precision>::operator&(const Vector3<_Precision>& rcVct) const { Vector3<_Precision> cVctRes; - cVctRes.x = x * (_Precision) fabs(rcVct.x); - cVctRes.y = y * (_Precision) fabs(rcVct.y); - cVctRes.z = z * (_Precision) fabs(rcVct.z); + cVctRes.x = x * (_Precision)fabs(rcVct.x); + cVctRes.y = y * (_Precision)fabs(rcVct.y); + cVctRes.z = z * (_Precision)fabs(rcVct.z); return cVctRes; } -template -Vector3<_Precision> Vector3<_Precision>::operator - (const Vector3<_Precision>& rcVct) const +template +Vector3<_Precision> Vector3<_Precision>::operator-(const Vector3<_Precision>& rcVct) const { Vector3<_Precision> cVctRes; cVctRes.x = x - rcVct.x; @@ -93,14 +96,14 @@ Vector3<_Precision> Vector3<_Precision>::operator - (const Vector3<_Precision>& return cVctRes; } -template -Vector3<_Precision> Vector3<_Precision>::operator - () const +template +Vector3<_Precision> Vector3<_Precision>::operator-() const { return Vector3(-x, -y, -z); } -template -Vector3<_Precision>& Vector3<_Precision>::operator += (const Vector3<_Precision>& rcVct) +template +Vector3<_Precision>& Vector3<_Precision>::operator+=(const Vector3<_Precision>& rcVct) { x += rcVct.x; y += rcVct.y; @@ -108,8 +111,8 @@ Vector3<_Precision>& Vector3<_Precision>::operator += (const Vector3<_Precision> return *this; } -template -Vector3<_Precision>& Vector3<_Precision>::operator -= (const Vector3<_Precision>& rcVct) +template +Vector3<_Precision>& Vector3<_Precision>::operator-=(const Vector3<_Precision>& rcVct) { x -= rcVct.x; y -= rcVct.y; @@ -117,8 +120,8 @@ Vector3<_Precision>& Vector3<_Precision>::operator -= (const Vector3<_Precision> return *this; } -template -Vector3<_Precision>& Vector3<_Precision>::operator *= (_Precision fScale) +template +Vector3<_Precision>& Vector3<_Precision>::operator*=(_Precision fScale) { x *= fScale; y *= fScale; @@ -126,8 +129,8 @@ Vector3<_Precision>& Vector3<_Precision>::operator *= (_Precision fScale) return *this; } -template -Vector3<_Precision>& Vector3<_Precision>::operator /= (_Precision fDiv) +template +Vector3<_Precision>& Vector3<_Precision>::operator/=(_Precision fDiv) { x /= fDiv; y /= fDiv; @@ -135,32 +138,32 @@ Vector3<_Precision>& Vector3<_Precision>::operator /= (_Precision fDiv) return *this; } -template -Vector3<_Precision> Vector3<_Precision>::operator * (_Precision fScale) const +template +Vector3<_Precision> Vector3<_Precision>::operator*(_Precision fScale) const { - return Vector3<_Precision>(this->x*fScale,this->y*fScale,this->z*fScale); + return Vector3<_Precision>(this->x * fScale, this->y * fScale, this->z * fScale); } -template -Vector3<_Precision> Vector3<_Precision>::operator / (_Precision fDiv) const +template +Vector3<_Precision> Vector3<_Precision>::operator/(_Precision fDiv) const { - return Vector3<_Precision>(this->x/fDiv,this->y/fDiv,this->z/fDiv); + return Vector3<_Precision>(this->x / fDiv, this->y / fDiv, this->z / fDiv); } -template -_Precision Vector3<_Precision>::operator * (const Vector3<_Precision>& rcVct) const +template +_Precision Vector3<_Precision>::operator*(const Vector3<_Precision>& rcVct) const { return (x * rcVct.x) + (y * rcVct.y) + (z * rcVct.z); } -template -_Precision Vector3<_Precision>::Dot (const Vector3<_Precision>& rcVct) const +template +_Precision Vector3<_Precision>::Dot(const Vector3<_Precision>& rcVct) const { return (x * rcVct.x) + (y * rcVct.y) + (z * rcVct.z); } -template -Vector3<_Precision> Vector3<_Precision>::operator % (const Vector3<_Precision>& rcVct) const +template +Vector3<_Precision> Vector3<_Precision>::operator%(const Vector3<_Precision>& rcVct) const { Vector3<_Precision> cVctRes; cVctRes.x = (y * rcVct.z) - (z * rcVct.y); @@ -169,7 +172,7 @@ Vector3<_Precision> Vector3<_Precision>::operator % (const Vector3<_Precision>& return cVctRes; } -template +template Vector3<_Precision> Vector3<_Precision>::Cross(const Vector3<_Precision>& rcVct) const { Vector3<_Precision> cVctRes; @@ -179,185 +182,191 @@ Vector3<_Precision> Vector3<_Precision>::Cross(const Vector3<_Precision>& rcVct) return cVctRes; } -template -bool Vector3<_Precision>::IsOnLineSegment (const Vector3<_Precision>& startVct, const Vector3<_Precision>& endVct) const +template +bool Vector3<_Precision>::IsOnLineSegment(const Vector3<_Precision>& startVct, + const Vector3<_Precision>& endVct) const { Vector3<_Precision> vectorAB = endVct - startVct; Vector3<_Precision> vectorAC = *this - startVct; Vector3<_Precision> crossproduct = vectorAB.Cross(vectorAC); _Precision dotproduct = vectorAB.Dot(vectorAC); - if (crossproduct.Length() > traits_type::epsilon()) + if (crossproduct.Length() > traits_type::epsilon()) { return false; + } - if (dotproduct < 0) + if (dotproduct < 0) { return false; + } - if (dotproduct > vectorAB.Sqr()) + if (dotproduct > vectorAB.Sqr()) { return false; + } return true; } -template -bool Vector3<_Precision>::operator != (const Vector3<_Precision>& rcVct) const +template +bool Vector3<_Precision>::operator!=(const Vector3<_Precision>& rcVct) const { return !((*this) == rcVct); } -template -bool Vector3<_Precision>::operator == (const Vector3<_Precision>& rcVct) const +template +bool Vector3<_Precision>::operator==(const Vector3<_Precision>& rcVct) const { - return (fabs (x - rcVct.x) <= traits_type::epsilon()) && - (fabs (y - rcVct.y) <= traits_type::epsilon()) && - (fabs (z - rcVct.z) <= traits_type::epsilon()); + return (fabs(x - rcVct.x) <= traits_type::epsilon()) + && (fabs(y - rcVct.y) <= traits_type::epsilon()) + && (fabs(z - rcVct.z) <= traits_type::epsilon()); } -template -bool Vector3<_Precision>::IsEqual(const Vector3<_Precision> &rclPnt, _Precision tol) const +template +bool Vector3<_Precision>::IsEqual(const Vector3<_Precision>& rclPnt, _Precision tol) const { return Distance(*this, rclPnt) <= tol; } -template -Vector3<_Precision>& Vector3<_Precision>::ProjectToPlane (const Vector3<_Precision> &rclBase, - const Vector3<_Precision> &rclNorm) +template +Vector3<_Precision>& Vector3<_Precision>::ProjectToPlane(const Vector3<_Precision>& rclBase, + const Vector3<_Precision>& rclNorm) { Vector3<_Precision> clTemp(rclNorm); *this = *this - (clTemp *= ((*this - rclBase) * clTemp) / clTemp.Sqr()); return *this; } -template -void Vector3<_Precision>::ProjectToPlane (const Vector3 &rclBase, - const Vector3 &rclNorm, - Vector3 &rclProj) const +template +void Vector3<_Precision>::ProjectToPlane(const Vector3& rclBase, + const Vector3& rclNorm, + Vector3& rclProj) const { Vector3<_Precision> clTemp(rclNorm); rclProj = *this - (clTemp *= ((*this - rclBase) * clTemp) / clTemp.Sqr()); } -template -_Precision Vector3<_Precision>::DistanceToPlane (const Vector3<_Precision> &rclBase, - const Vector3<_Precision> &rclNorm) const +template +_Precision Vector3<_Precision>::DistanceToPlane(const Vector3<_Precision>& rclBase, + const Vector3<_Precision>& rclNorm) const { return ((*this - rclBase) * rclNorm) / rclNorm.Length(); } -template -_Precision Vector3<_Precision>::Length () const +template +_Precision Vector3<_Precision>::Length() const { - return static_cast<_Precision>(sqrt ((x * x) + (y * y) + (z * z))); + return static_cast<_Precision>(sqrt((x * x) + (y * y) + (z * z))); } -template -_Precision Vector3<_Precision>::DistanceToLine (const Vector3<_Precision> &rclBase, - const Vector3<_Precision> &rclDirect) const +template +_Precision Vector3<_Precision>::DistanceToLine(const Vector3<_Precision>& rclBase, + const Vector3<_Precision>& rclDirect) const { - return static_cast<_Precision>(fabs((rclDirect % Vector3(*this - rclBase)).Length() / rclDirect.Length())); + return static_cast<_Precision>( + fabs((rclDirect % Vector3(*this - rclBase)).Length() / rclDirect.Length())); } -template +template Vector3<_Precision> Vector3<_Precision>::DistanceToLineSegment(const Vector3& rclP1, const Vector3& rclP2) const { _Precision len2 = Base::DistanceP2(rclP1, rclP2); - if (len2 == 0) + if (len2 == 0) { return rclP1; + } - Vector3<_Precision> p2p1 = rclP2-rclP1; - Vector3<_Precision> pXp1 = *this-rclP1; + Vector3<_Precision> p2p1 = rclP2 - rclP1; + Vector3<_Precision> pXp1 = *this - rclP1; _Precision dot = pXp1 * p2p1; - _Precision t = clamp<_Precision>(dot/len2, 0, 1); + _Precision t = clamp<_Precision>(dot / len2, 0, 1); Vector3<_Precision> dist = t * p2p1 - pXp1; return dist; } -template -Vector3<_Precision>& Vector3<_Precision>::ProjectToLine (const Vector3<_Precision> &rclPoint, - const Vector3<_Precision> &rclLine) +template +Vector3<_Precision>& Vector3<_Precision>::ProjectToLine(const Vector3<_Precision>& rclPoint, + const Vector3<_Precision>& rclLine) { return (*this = ((((rclPoint * rclLine) / rclLine.Sqr()) * rclLine) - rclPoint)); } -template -Vector3<_Precision> Vector3<_Precision>::Perpendicular(const Vector3<_Precision> &rclBase, - const Vector3<_Precision> &rclDir) const +template +Vector3<_Precision> Vector3<_Precision>::Perpendicular(const Vector3<_Precision>& rclBase, + const Vector3<_Precision>& rclDir) const { _Precision t = ((*this - rclBase) * rclDir) / (rclDir * rclDir); return rclBase + t * rclDir; } -template -_Precision Vector3<_Precision>::Sqr () const +template +_Precision Vector3<_Precision>::Sqr() const { - return (_Precision) ((x * x) + (y * y) + (z * z)); + return (_Precision)((x * x) + (y * y) + (z * z)); } -template -void Vector3<_Precision>::Set (_Precision fX, _Precision fY, _Precision fZ) +template +void Vector3<_Precision>::Set(_Precision fX, _Precision fY, _Precision fZ) { x = fX; y = fY; z = fZ; } -template -void Vector3<_Precision>::ScaleX (_Precision f) +template +void Vector3<_Precision>::ScaleX(_Precision f) { x *= f; } -template -void Vector3<_Precision>::ScaleY (_Precision f) +template +void Vector3<_Precision>::ScaleY(_Precision f) { y *= f; } -template -void Vector3<_Precision>::ScaleZ (_Precision f) +template +void Vector3<_Precision>::ScaleZ(_Precision f) { z *= f; } -template -void Vector3<_Precision>::Scale (_Precision fX, _Precision fY, _Precision fZ) +template +void Vector3<_Precision>::Scale(_Precision fX, _Precision fY, _Precision fZ) { x *= fX; y *= fY; z *= fZ; } -template -void Vector3<_Precision>::MoveX (_Precision f) +template +void Vector3<_Precision>::MoveX(_Precision f) { x += f; } -template -void Vector3<_Precision>::MoveY (_Precision f) +template +void Vector3<_Precision>::MoveY(_Precision f) { y += f; } -template -void Vector3<_Precision>::MoveZ (_Precision f) +template +void Vector3<_Precision>::MoveZ(_Precision f) { z += f; } -template -void Vector3<_Precision>::Move (_Precision fX, _Precision fY, _Precision fZ) +template +void Vector3<_Precision>::Move(_Precision fX, _Precision fY, _Precision fZ) { x += fX; y += fY; z += fZ; } -template -void Vector3<_Precision>::RotateX (_Precision f) +template +void Vector3<_Precision>::RotateX(_Precision f) { - Vector3 cPt (*this); + Vector3 cPt(*this); _Precision fsin, fcos; fsin = static_cast<_Precision>(sin(f)); @@ -366,10 +375,10 @@ void Vector3<_Precision>::RotateX (_Precision f) z = (cPt.y * fsin) + (cPt.z * fcos); } -template -void Vector3<_Precision>::RotateY (_Precision f) +template +void Vector3<_Precision>::RotateY(_Precision f) { - Vector3 cPt (*this); + Vector3 cPt(*this); _Precision fsin, fcos; fsin = static_cast<_Precision>(sin(f)); @@ -378,10 +387,10 @@ void Vector3<_Precision>::RotateY (_Precision f) z = (cPt.z * fcos) - (cPt.x * fsin); } -template -void Vector3<_Precision>::RotateZ (_Precision f) +template +void Vector3<_Precision>::RotateZ(_Precision f) { - Vector3 cPt (*this); + Vector3 cPt(*this); _Precision fsin, fcos; fsin = static_cast<_Precision>(sin(f)); @@ -390,10 +399,10 @@ void Vector3<_Precision>::RotateZ (_Precision f) y = (cPt.x * fsin) + (cPt.y * fcos); } -template -Vector3<_Precision> & Vector3<_Precision>::Normalize () +template +Vector3<_Precision>& Vector3<_Precision>::Normalize() { - _Precision fLen = Length (); + _Precision fLen = Length(); if (fLen != static_cast<_Precision>(0.0) && fLen != static_cast<_Precision>(1.0)) { x /= fLen; y /= fLen; @@ -402,39 +411,42 @@ Vector3<_Precision> & Vector3<_Precision>::Normalize () return *this; } -template +template bool Vector3<_Precision>::IsNull() const { - _Precision n{0.0}; + _Precision n {0.0}; return (x == n) && (y == n) && (z == n); } -template -_Precision Vector3<_Precision>::GetAngle (const Vector3 &rcVect) const +template +_Precision Vector3<_Precision>::GetAngle(const Vector3& rcVect) const { _Precision len1 = Length(); _Precision len2 = rcVect.Length(); - if (len1 <= traits_type::epsilon() || len2 <= traits_type::epsilon()) - return std::numeric_limits<_Precision>::quiet_NaN(); // division by zero + if (len1 <= traits_type::epsilon() || len2 <= traits_type::epsilon()) { + return std::numeric_limits<_Precision>::quiet_NaN(); // division by zero + } _Precision dot = Dot(rcVect); dot /= len1; dot /= len2; - if (dot <= -1.0) + if (dot <= -1.0) { return traits_type::pi(); - else if (dot >= 1.0) + } + else if (dot >= 1.0) { return 0.0; + } return _Precision(acos(dot)); } -template -void Vector3<_Precision>::TransformToCoordinateSystem (const Vector3 &rclBase, - const Vector3 &rclDirX, - const Vector3 &rclDirY) +template +void Vector3<_Precision>::TransformToCoordinateSystem(const Vector3& rclBase, + const Vector3& rclDirX, + const Vector3& rclDirY) { - Vector3 clVectX, clVectY, clVectZ, clVectOld; + Vector3 clVectX, clVectY, clVectZ, clVectOld; clVectX = rclDirX; clVectY = rclDirY; @@ -451,7 +463,8 @@ void Vector3<_Precision>::TransformToCoordinateSystem (const Vector3 &rclBase, } // explicit template instantiation -namespace Base { +namespace Base +{ template class BaseExport Vector3; template class BaseExport Vector3; -} +} // namespace Base diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index e2f37a6f64..5cf75b9595 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -28,59 +28,85 @@ #include #include -#ifndef F_PI -# define F_PI 3.1415926f +#ifndef F_PI +#define F_PI 3.1415926f #endif -#ifndef D_PI -# define D_PI 3.141592653589793 +#ifndef D_PI +#define D_PI 3.141592653589793 #endif -#ifndef FLOAT_MAX -# define FLOAT_MAX 3.402823466E+38F +#ifndef FLOAT_MAX +#define FLOAT_MAX 3.402823466E+38F #endif -#ifndef FLOAT_MIN -# define FLOAT_MIN 1.175494351E-38F +#ifndef FLOAT_MIN +#define FLOAT_MIN 1.175494351E-38F #endif -#ifndef DOUBLE_MAX -# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ +#ifndef DOUBLE_MAX +#define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ #endif -#ifndef DOUBLE_MIN -# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ +#ifndef DOUBLE_MIN +#define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ #endif -namespace Base { -template -struct float_traits { }; - -template <> -struct float_traits { - using float_type = float; - static inline float_type pi() { return F_PI; } - static inline float_type epsilon() { return FLT_EPSILON; } - static inline float_type maximum() { return FLT_MAX; } +namespace Base +{ +template +struct float_traits +{ }; -template <> -struct float_traits { +template<> +struct float_traits +{ + using float_type = float; + static inline float_type pi() + { + return F_PI; + } + static inline float_type epsilon() + { + return FLT_EPSILON; + } + static inline float_type maximum() + { + return FLT_MAX; + } +}; + +template<> +struct float_traits +{ using float_type = double; - static inline float_type pi() { return D_PI; } - static inline float_type epsilon() { return DBL_EPSILON; } - static inline float_type maximum() { return DBL_MAX; } + static inline float_type pi() + { + return D_PI; + } + static inline float_type epsilon() + { + return DBL_EPSILON; + } + static inline float_type maximum() + { + return DBL_MAX; + } }; /** The Vector Base class. */ -template +template class Vector3 { public: using num_type = _Precision; using traits_type = float_traits; - static inline num_type epsilon() { return traits_type::epsilon(); } + static inline num_type epsilon() + { + return traits_type::epsilon(); + } /** @name Public data members */ //@{ @@ -90,88 +116,91 @@ public: //@} /// Construction - explicit Vector3 (_Precision fx = 0.0, _Precision fy = 0.0, _Precision fz = 0.0); - Vector3 (const Vector3<_Precision>& v) = default; - Vector3 (Vector3<_Precision>&& v) = default; - ~Vector3 () = default; + explicit Vector3(_Precision fx = 0.0, _Precision fy = 0.0, _Precision fz = 0.0); + Vector3(const Vector3<_Precision>& v) = default; + Vector3(Vector3<_Precision>&& v) = default; + ~Vector3() = default; /** @name Operator */ //@{ /// Returns a reference to a coordinate. \a usIndex must be in the range [0,2] - _Precision & operator [] (unsigned short usIndex); + _Precision& operator[](unsigned short usIndex); /// Returns a const reference to a coordinate. \a usIndex must be in the range [0,2] - const _Precision & operator [] (unsigned short usIndex) const; + const _Precision& operator[](unsigned short usIndex) const; /// Vector addition - Vector3 operator + (const Vector3<_Precision>& rcVct) const; - Vector3 operator & (const Vector3<_Precision>& rcVct) const; + Vector3 operator+(const Vector3<_Precision>& rcVct) const; + Vector3 operator&(const Vector3<_Precision>& rcVct) const; /// Vector subtraction - Vector3 operator - (const Vector3<_Precision>& rcVct) const; + Vector3 operator-(const Vector3<_Precision>& rcVct) const; /// Negative vector - Vector3 operator - () const; + Vector3 operator-() const; /// Vector summation - Vector3 & operator += (const Vector3<_Precision>& rcVct); + Vector3& operator+=(const Vector3<_Precision>& rcVct); /// Vector subtraction - Vector3 & operator -= (const Vector3<_Precision>& rcVct); + Vector3& operator-=(const Vector3<_Precision>& rcVct); /// Vector scaling - Vector3 operator * (_Precision fScale) const; - Vector3 operator / (_Precision fDiv) const; - Vector3 & operator *= (_Precision fScale); - Vector3 & operator /= (_Precision fDiv); + Vector3 operator*(_Precision fScale) const; + Vector3 operator/(_Precision fDiv) const; + Vector3& operator*=(_Precision fScale); + Vector3& operator/=(_Precision fDiv); /// Assignment - Vector3 & operator = (const Vector3<_Precision>& v) = default; - Vector3 & operator = (Vector3<_Precision>&& v) = default; + Vector3& operator=(const Vector3<_Precision>& v) = default; + Vector3& operator=(Vector3<_Precision>&& v) = default; /// Scalar product - _Precision operator * (const Vector3<_Precision>& rcVct) const; + _Precision operator*(const Vector3<_Precision>& rcVct) const; /// Scalar product - _Precision Dot (const Vector3<_Precision>& rcVct) const; + _Precision Dot(const Vector3<_Precision>& rcVct) const; /// Cross product - Vector3 operator % (const Vector3<_Precision>& rcVct) const; + Vector3 operator%(const Vector3<_Precision>& rcVct) const; /// Cross product - Vector3 Cross (const Vector3<_Precision>& rcVct) const; + Vector3 Cross(const Vector3<_Precision>& rcVct) const; /// Comparing for inequality - bool operator != (const Vector3<_Precision>& rcVct) const; + bool operator!=(const Vector3<_Precision>& rcVct) const; /// Comparing for equality - bool operator == (const Vector3<_Precision>& rcVct) const; + bool operator==(const Vector3<_Precision>& rcVct) const; //@} /// Check if Vector is on a line segment - bool IsOnLineSegment (const Vector3<_Precision>& startVct, const Vector3<_Precision>& endVct) const; + bool IsOnLineSegment(const Vector3<_Precision>& startVct, + const Vector3<_Precision>& endVct) const; /** @name Modification */ //@{ - void ScaleX (_Precision f); - void ScaleY (_Precision f); - void ScaleZ (_Precision f); - void Scale (_Precision fX, _Precision fY, _Precision fZ); - void MoveX (_Precision f); - void MoveY (_Precision f); - void MoveZ (_Precision f); - void Move (_Precision fX, _Precision fY, _Precision fZ); - void RotateX (_Precision f); - void RotateY (_Precision f); - void RotateZ (_Precision f); + void ScaleX(_Precision f); + void ScaleY(_Precision f); + void ScaleZ(_Precision f); + void Scale(_Precision fX, _Precision fY, _Precision fZ); + void MoveX(_Precision f); + void MoveY(_Precision f); + void MoveZ(_Precision f); + void Move(_Precision fX, _Precision fY, _Precision fZ); + void RotateX(_Precision f); + void RotateY(_Precision f); + void RotateZ(_Precision f); //@} - void Set (_Precision fX, _Precision fY, _Precision fZ); + void Set(_Precision fX, _Precision fY, _Precision fZ); /** @name Mathematics */ //@{ /// Length of the vector. - _Precision Length () const; + _Precision Length() const; /// Squared length of the vector. - _Precision Sqr () const; + _Precision Sqr() const; /// Set length to 1. - Vector3 & Normalize (); + Vector3& Normalize(); /// Checks whether this is the null vector bool IsNull() const; /// Get angle between both vectors. The returned value lies in the interval [0,pi]. - _Precision GetAngle (const Vector3 &rcVect) const; + _Precision GetAngle(const Vector3& rcVect) const; /** Transforms this point to the coordinate system defined by origin \a rclBase, - * vector \a vector rclDirX and vector \a vector rclDirY. - * \note \a rclDirX must be perpendicular to \a rclDirY, i.e. \a rclDirX * \a rclDirY = 0.. - */ - void TransformToCoordinateSystem (const Vector3 &rclBase, const Vector3 &rclDirX, const Vector3 &rclDirY); + * vector \a vector rclDirX and vector \a vector rclDirY. + * \note \a rclDirX must be perpendicular to \a rclDirY, i.e. \a rclDirX * \a rclDirY = 0.. + */ + void TransformToCoordinateSystem(const Vector3& rclBase, + const Vector3& rclDirX, + const Vector3& rclDirY); /** * @brief IsEqual * @param rclPnt @@ -180,77 +209,78 @@ public: * If the distance to point \a rclPnt is within the tolerance \a tol both points are considered * equal. */ - bool IsEqual(const Vector3 &rclPnt, _Precision tol) const; + bool IsEqual(const Vector3& rclPnt, _Precision tol) const; /// Projects this point onto the plane given by the base \a rclBase and the normal \a rclNorm. - Vector3 & ProjectToPlane (const Vector3 &rclBase, const Vector3 &rclNorm); + Vector3& ProjectToPlane(const Vector3& rclBase, const Vector3& rclNorm); /** * Projects this point onto the plane given by the base \a rclBase and the normal \a rclNorm * and stores the result in rclProj. */ - void ProjectToPlane (const Vector3 &rclBase, const Vector3 &rclNorm, Vector3 &rclProj) const; - /// Projects this point onto the line given by the base \a rclPoint and the direction \a rclLine. + void ProjectToPlane(const Vector3& rclBase, const Vector3& rclNorm, Vector3& rclProj) const; + /// Projects this point onto the line given by the base \a rclPoint and the direction \a + /// rclLine. /** - * Projects a point \a rclPoint onto the line defined by the origin and the direction \a rclLine. - * The result is a vector from \a rclPoint to the point on the line. The length of this vector - * is the distance from \a rclPoint to the line. - * Note: The resulting vector does not depend on the current vector. + * Projects a point \a rclPoint onto the line defined by the origin and the direction \a + * rclLine. The result is a vector from \a rclPoint to the point on the line. The length of this + * vector is the distance from \a rclPoint to the line. Note: The resulting vector does not + * depend on the current vector. */ - Vector3 & ProjectToLine (const Vector3 &rclPoint, const Vector3 &rclLine); + Vector3& ProjectToLine(const Vector3& rclPoint, const Vector3& rclLine); /** * Get the perpendicular of this point to the line defined by rclBase and rclDir. * Note: Do not mix up this method with ProjectToLine. */ - Vector3 Perpendicular(const Vector3 &rclBase, const Vector3 &rclDir) const; + Vector3 Perpendicular(const Vector3& rclBase, const Vector3& rclDir) const; /** Computes the distance to the given plane. Depending on the side this point is located * the distance can also be negative. The distance is positive if the point is at the same * side the plane normal points to, negative otherwise. */ - _Precision DistanceToPlane (const Vector3 &rclBase, const Vector3 &rclNorm) const; + _Precision DistanceToPlane(const Vector3& rclBase, const Vector3& rclNorm) const; /// Computes the distance from this point to the line given by \a rclBase and \a rclDirect. - _Precision DistanceToLine (const Vector3 &rclBase, const Vector3 &rclDirect) const; + _Precision DistanceToLine(const Vector3& rclBase, const Vector3& rclDirect) const; /** Computes the vector from this point to the point on the line segment with the shortest * distance. The line segment is defined by \a rclP1 and \a rclP2. * Note: If the projection of this point is outside the segment then the shortest distance * to \a rclP1 or \a rclP2 is computed. */ - Vector3 DistanceToLineSegment (const Vector3& rclP1, const Vector3& rclP2) const; + Vector3 DistanceToLineSegment(const Vector3& rclP1, const Vector3& rclP2) const; //@} }; // global functions /// Returns the distance between two points -template -inline _Precision Distance (const Vector3<_Precision> &v1, const Vector3<_Precision> &v2) +template +inline _Precision Distance(const Vector3<_Precision>& v1, const Vector3<_Precision>& v2) { - _Precision x=v1.x-v2.x, y=v1.y-v2.y, z=v1.z-v2.z; + _Precision x = v1.x - v2.x, y = v1.y - v2.y, z = v1.z - v2.z; return static_cast<_Precision>(sqrt((x * x) + (y * y) + (z * z))); } /// Returns the squared distance between two points -template -inline _Precision DistanceP2 (const Vector3<_Precision> &v1, const Vector3<_Precision> &v2) +template +inline _Precision DistanceP2(const Vector3<_Precision>& v1, const Vector3<_Precision>& v2) { - _Precision x=v1.x-v2.x, y=v1.y-v2.y, z=v1.z-v2.z; + _Precision x = v1.x - v2.x, y = v1.y - v2.y, z = v1.z - v2.z; return x * x + y * y + z * z; } /// Multiplication of scalar with vector. -template -inline Vector3<_Precision> operator * (_Precision fFac, const Vector3<_Precision> &rcVct) +template +inline Vector3<_Precision> operator*(_Precision fFac, const Vector3<_Precision>& rcVct) { return Vector3<_Precision>(rcVct.x * fFac, rcVct.y * fFac, rcVct.z * fFac); } -template +template inline Vector3<_Pr1> toVector(const Vector3<_Pr2>& v) { - return Vector3<_Pr1>(static_cast<_Pr1>(v.x),static_cast<_Pr1>(v.y),static_cast<_Pr1>(v.z)); + return Vector3<_Pr1>(static_cast<_Pr1>(v.x), static_cast<_Pr1>(v.y), static_cast<_Pr1>(v.z)); } using Vector3f = Vector3; using Vector3d = Vector3; -} // namespace Base +} // namespace Base -#endif // BASE_VECTOR3D_H +#endif // BASE_VECTOR3D_H diff --git a/src/Base/VectorPy.xml b/src/Base/VectorPy.xml index a434f41f11..dad1536444 100644 --- a/src/Base/VectorPy.xml +++ b/src/Base/VectorPy.xml @@ -16,21 +16,21 @@ This is the Vector export class - Base.Vector class. + Base.Vector class. This class represents a 3D float vector. -Useful to represent points in the 3D space. +Useful to represent points in the 3D space. -The following constructors are supported: +The following constructors are supported: Vector(x=0, y=0, z=0) x : float y : float -z : float +z : float Vector(vector) Copy constructor. -vector : Base.Vector +vector : Base.Vector Vector(seq) Define from a sequence of float. @@ -38,83 +38,83 @@ seq : sequence of float. - __reduce__() -> tuple + __reduce__() -> tuple Serialization of Vector objects. - add(vector2) -> Base.Vector + add(vector2) -> Base.Vector -Returns the sum of this vector and `vector2`. +Returns the sum of this vector and `vector2`. vector2 : Base.Vector - sub(vector2) -> Base.Vector + sub(vector2) -> Base.Vector -Returns the difference of this vector and `vector2`. +Returns the difference of this vector and `vector2`. vector2 : Base.Vector - negative() -> Base.Vector + negative() -> Base.Vector Returns the negative (opposite) of this vector. - scale(x, y, z) -> Base.Vector + scale(x, y, z) -> Base.Vector -Scales in-place this vector by the given factor in each component. +Scales in-place this vector by the given factor in each component. -x : float +x : float x-component factor scale. -y : float +y : float y-component factor scale. -z : float +z : float z-component factor scale. - multiply(factor) -> Base.Vector + multiply(factor) -> Base.Vector Multiplies in-place each component of this vector by a single factor. -Equivalent to scale(factor, factor, factor). +Equivalent to scale(factor, factor, factor). factor : float - dot(vector2) -> float + dot(vector2) -> float -Returns the scalar product (dot product) between this vector and `vector2`. +Returns the scalar product (dot product) between this vector and `vector2`. vector2 : Base.Vector - cross(vector2) -> Base.Vector + cross(vector2) -> Base.Vector -Returns the vector product (cross product) between this vector and `vector2`. +Returns the vector product (cross product) between this vector and `vector2`. vector2 : Base.Vector - isOnLineSegment(vector1, vector2) -> bool + isOnLineSegment(vector1, vector2) -> bool -Checks if this vector is on the line segment generated by `vector1` and `vector2`. +Checks if this vector is on the line segment generated by `vector1` and `vector2`. vector1 : Base.Vector vector2 : Base.Vector @@ -122,26 +122,26 @@ vector2 : Base.Vector - getAngle(vector2) -> float + getAngle(vector2) -> float -Returns the angle in radians between this vector and `vector2`. +Returns the angle in radians between this vector and `vector2`. vector2 : Base.Vector - normalize() -> Base.Vector + normalize() -> Base.Vector Normalizes in-place this vector to the length of 1.0. - isEqual(vector2, tol=0) -> bool + isEqual(vector2, tol=0) -> bool Checks if the distance between the points represented by this vector -and `vector2` is less or equal to the given tolerance. +and `vector2` is less or equal to the given tolerance. vector2 : Base.Vector tol : float @@ -149,14 +149,14 @@ tol : float - projectToLine(point, dir) -> Base.Vector + projectToLine(point, dir) -> Base.Vector Projects `point` on a line that goes through the origin with the direction `dir`. The result is the vector from `point` to the projected point. The operation is equivalent to dir_n.cross(dir_n.cross(point)), where `dir_n` is the vector `dir` normalized. The method modifies this vector instance according to result and does not -depend on the vector itself. +depend on the vector itself. point : Base.Vector dir : Base.Vector @@ -164,10 +164,10 @@ dir : Base.Vector - projectToPlane(base, normal) -> Base.Vector + projectToPlane(base, normal) -> Base.Vector Projects in-place this vector on a plane defined by a base point -represented by `base` and a normal defined by `normal`. +represented by `base` and a normal defined by `normal`. base : Base.Vector normal : Base.Vector @@ -175,20 +175,20 @@ normal : Base.Vector - distanceToPoint(point2) -> float + distanceToPoint(point2) -> float -Returns the distance to another point represented by `point2`. +Returns the distance to another point represented by `point2`. . point : Base.Vector - distanceToLine(base, dir) -> float + distanceToLine(base, dir) -> float Returns the distance between the point represented by this vector and a line defined by a base point represented by `base` and a -direction `dir`. +direction `dir`. base : Base.Vector dir : Base.Vector @@ -196,11 +196,11 @@ dir : Base.Vector - distanceToLineSegment(point1, point2) -> Base.Vector + distanceToLineSegment(point1, point2) -> Base.Vector Returns the vector between the point represented by this vector and the point on the line segment with the shortest distance. The line segment is defined by -`point1` and `point2`. +`point1` and `point2`. point1 : Base.Vector point2 : Base.Vector @@ -208,10 +208,10 @@ point2 : Base.Vector - distanceToPlane(base, normal) -> float + distanceToPlane(base, normal) -> float Returns the distance between this vector and a plane defined by a -base point represented by `base` and a normal defined by `normal`. +base point represented by `base` and a normal defined by `normal`. base : Base.Vector normal : Base.Vector diff --git a/src/Base/VectorPyImp.cpp b/src/Base/VectorPyImp.cpp index 9444b3b088..5ce642fbf7 100644 --- a/src/Base/VectorPyImp.cpp +++ b/src/Base/VectorPyImp.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "Vector3D.h" @@ -45,15 +45,14 @@ std::string VectorPy::representation() const Py::Float z(ptr->z); std::stringstream str; str << "Vector ("; - str << static_cast(x.repr()) << ", " - << static_cast(y.repr()) << ", " + str << static_cast(x.repr()) << ", " << static_cast(y.repr()) << ", " << static_cast(z.repr()); str << ")"; return str.str(); } -PyObject *VectorPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* VectorPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of VectorPy and the Twin object return new VectorPy(new Vector3d); @@ -62,20 +61,20 @@ PyObject *VectorPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pyt // constructor method int VectorPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - double x=0.0,y=0.0,z=0.0; - PyObject *object = nullptr; + double x = 0.0, y = 0.0, z = 0.0; + PyObject* object = nullptr; VectorPy::PointerType ptr = getVectorPtr(); - if (PyArg_ParseTuple(args, "|ddd", &x,&y,&z)) { - ptr->Set(x,y,z); + if (PyArg_ParseTuple(args, "|ddd", &x, &y, &z)) { + ptr->Set(x, y, z); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { *ptr = *(static_cast(object)->getVectorPtr()); return 0; } - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O", &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O", &object)) { try { *ptr = getVectorFromTuple(object); return 0; @@ -89,10 +88,11 @@ int VectorPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -PyObject* VectorPy::__reduce__(PyObject *args) +PyObject* VectorPy::__reduce__(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Py::Tuple tuple(2); @@ -108,7 +108,7 @@ PyObject* VectorPy::__reduce__(PyObject *args) return Py::new_reference_to(tuple); } -PyObject* VectorPy::number_add_handler(PyObject *self, PyObject *other) +PyObject* VectorPy::number_add_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); @@ -120,10 +120,10 @@ PyObject* VectorPy::number_add_handler(PyObject *self, PyObject *other) } Base::Vector3d a = static_cast(self)->value(); Base::Vector3d b = static_cast(other)->value(); - return new VectorPy(a+b); + return new VectorPy(a + b); } -PyObject* VectorPy::number_subtract_handler(PyObject *self, PyObject *other) +PyObject* VectorPy::number_subtract_handler(PyObject* self, PyObject* other) { if (!PyObject_TypeCheck(self, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); @@ -135,13 +135,13 @@ PyObject* VectorPy::number_subtract_handler(PyObject *self, PyObject *other) } Base::Vector3d a = static_cast(self)->value(); Base::Vector3d b = static_cast(other)->value(); - return new VectorPy(a-b); + return new VectorPy(a - b); } -PyObject* VectorPy::number_multiply_handler(PyObject *self, PyObject *other) +PyObject* VectorPy::number_multiply_handler(PyObject* self, PyObject* other) { if (PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d a = static_cast(self) ->value(); + Base::Vector3d a = static_cast(self)->value(); if (PyObject_TypeCheck(other, &(VectorPy::Type))) { Base::Vector3d b = static_cast(other)->value(); @@ -158,7 +158,7 @@ PyObject* VectorPy::number_multiply_handler(PyObject *self, PyObject *other) } } else if (PyObject_TypeCheck(other, &(VectorPy::Type))) { - Base::Vector3d a = static_cast(other) ->value(); + Base::Vector3d a = static_cast(other)->value(); if (PyNumber_Check(self)) { double b = PyFloat_AsDouble(self); return new VectorPy(a * b); @@ -174,12 +174,12 @@ PyObject* VectorPy::number_multiply_handler(PyObject *self, PyObject *other) } } -Py_ssize_t VectorPy::sequence_length(PyObject *) +Py_ssize_t VectorPy::sequence_length(PyObject*) { return 3; } -PyObject * VectorPy::sequence_item (PyObject *self, Py_ssize_t index) +PyObject* VectorPy::sequence_item(PyObject* self, Py_ssize_t index) { if (!PyObject_TypeCheck(self, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "first arg must be Vector"); @@ -192,18 +192,18 @@ PyObject * VectorPy::sequence_item (PyObject *self, Py_ssize_t index) VectorPy* self_ = static_cast(self); if (self_->sequence.length() == 0) { - self_->sequence = Py::List{3}; + self_->sequence = Py::List {3}; } unsigned short pos = index % 3; Base::Vector3d vec = self_->value(); - Py::Float item{vec[pos]}; + Py::Float item {vec[pos]}; self_->sequence.setItem(pos, item); return Py::new_reference_to(item); } -int VectorPy::sequence_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) +int VectorPy::sequence_ass_item(PyObject* self, Py_ssize_t index, PyObject* value) { if (!PyObject_TypeCheck(self, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "first arg must be Vector"); @@ -229,33 +229,33 @@ int VectorPy::sequence_ass_item(PyObject *self, Py_ssize_t index, PyObject *valu } // http://renesd.blogspot.de/2009/07/python3-c-api-simple-slicing-sqslice.html -PyObject * VectorPy::mapping_subscript(PyObject *self, PyObject *item) +PyObject* VectorPy::mapping_subscript(PyObject* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) + if (i == -1 && PyErr_Occurred()) { return nullptr; - if (i < 0) + } + if (i < 0) { i += sequence_length(self); + } return sequence_item(self, i); } else if (PySlice_Check(item)) { Py_ssize_t start = 0, stop = 0, step = 0, slicelength = 0, cur = 0, i = 0; PyObject* slice = item; - if (PySlice_GetIndicesEx(slice, - sequence_length(self), - &start, &stop, &step, &slicelength) < 0) { + if (PySlice_GetIndicesEx(slice, sequence_length(self), &start, &stop, &step, &slicelength) + < 0) { return nullptr; } if (slicelength <= 0) { return PyTuple_New(0); } - else if (start == 0 && step == 1 && - slicelength == sequence_length(self) && - PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d v = static_cast(self) ->value(); + else if (start == 0 && step == 1 && slicelength == sequence_length(self) + && PyObject_TypeCheck(self, &(VectorPy::Type))) { + Base::Vector3d v = static_cast(self)->value(); Py::Tuple xyz(3); xyz.setItem(0, Py::Float(v.x)); xyz.setItem(1, Py::Float(v.y)); @@ -263,7 +263,7 @@ PyObject * VectorPy::mapping_subscript(PyObject *self, PyObject *item) return Py::new_reference_to(xyz); } else if (PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d v = static_cast(self) ->value(); + Base::Vector3d v = static_cast(self)->value(); Py::Tuple xyz(static_cast(slicelength)); for (cur = start, i = 0; i < slicelength; cur += step, i++) { @@ -281,11 +281,12 @@ PyObject * VectorPy::mapping_subscript(PyObject *self, PyObject *item) return nullptr; } -PyObject* VectorPy::add(PyObject *args) +PyObject* VectorPy::add(PyObject* args) { - PyObject *obj = nullptr; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -296,11 +297,12 @@ PyObject* VectorPy::add(PyObject *args) return new VectorPy(v); } -PyObject* VectorPy::sub(PyObject *args) +PyObject* VectorPy::sub(PyObject* args) { - PyObject *obj = nullptr; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -311,36 +313,35 @@ PyObject* VectorPy::sub(PyObject *args) return new VectorPy(v); } -PyObject* VectorPy::negative(PyObject *args) +PyObject* VectorPy::negative(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } VectorPy::PointerType this_ptr = getVectorPtr(); Base::Vector3d v = -(*this_ptr); return new VectorPy(v); } -PyObject* VectorPy::richCompare(PyObject *v, PyObject *w, int op) +PyObject* VectorPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(VectorPy::Type)) && - PyObject_TypeCheck(w, &(VectorPy::Type))) { + if (PyObject_TypeCheck(v, &(VectorPy::Type)) && PyObject_TypeCheck(w, &(VectorPy::Type))) { Vector3d v1 = static_cast(v)->value(); Vector3d v2 = static_cast(w)->value(); - PyObject *res=nullptr; + PyObject* res = nullptr; if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for Vector"); + PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Vector"); return nullptr; } else if (op == Py_EQ) { - res = (v1 == v2) ? Py_True : Py_False; //NOLINT + res = (v1 == v2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } else { - res = (v1 != v2) ? Py_True : Py_False; //NOLINT + res = (v1 != v2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } @@ -352,12 +353,13 @@ PyObject* VectorPy::richCompare(PyObject *v, PyObject *w, int op) } } -PyObject* VectorPy::isEqual(PyObject *args) +PyObject* VectorPy::isEqual(PyObject* args) { - PyObject *obj = nullptr; - double tolerance=0; - if (!PyArg_ParseTuple(args, "O!d", &(VectorPy::Type), &obj, &tolerance)) + PyObject* obj = nullptr; + double tolerance = 0; + if (!PyArg_ParseTuple(args, "O!d", &(VectorPy::Type), &obj, &tolerance)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -368,33 +370,36 @@ PyObject* VectorPy::isEqual(PyObject *args) return Py::new_reference_to(eq); } -PyObject* VectorPy::scale(PyObject *args) +PyObject* VectorPy::scale(PyObject* args) { double factorX = 0.0, factorY = 0.0, factorZ = 0.0; - if (!PyArg_ParseTuple(args, "ddd", &factorX, &factorY, &factorZ)) + if (!PyArg_ParseTuple(args, "ddd", &factorX, &factorY, &factorZ)) { return nullptr; + } VectorPy::PointerType ptr = getVectorPtr(); ptr->Scale(factorX, factorY, factorZ); return Py::new_reference_to(this); } -PyObject* VectorPy::multiply(PyObject *args) +PyObject* VectorPy::multiply(PyObject* args) { double factor = 0.0; - if (!PyArg_ParseTuple(args, "d", &factor)) + if (!PyArg_ParseTuple(args, "d", &factor)) { return nullptr; + } VectorPy::PointerType ptr = getVectorPtr(); ptr->Scale(factor, factor, factor); return Py::new_reference_to(this); } -PyObject* VectorPy::dot(PyObject *args) +PyObject* VectorPy::dot(PyObject* args) { - PyObject *obj = nullptr; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -405,11 +410,12 @@ PyObject* VectorPy::dot(PyObject *args) return Py::new_reference_to(mult); } -PyObject* VectorPy::cross(PyObject *args) +PyObject* VectorPy::cross(PyObject* args) { - PyObject *obj = nullptr; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -420,11 +426,12 @@ PyObject* VectorPy::cross(PyObject *args) return new VectorPy(v); } -PyObject* VectorPy::isOnLineSegment(PyObject *args) +PyObject* VectorPy::isOnLineSegment(PyObject* args) { PyObject *start = nullptr, *end = nullptr; - if (!PyArg_ParseTuple(args, "OO",&start, &end)) + if (!PyArg_ParseTuple(args, "OO", &start, &end)) { return nullptr; + } if (!PyObject_TypeCheck(start, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -446,11 +453,12 @@ PyObject* VectorPy::isOnLineSegment(PyObject *args) return Py::new_reference_to(result); } -PyObject* VectorPy::getAngle(PyObject *args) +PyObject* VectorPy::getAngle(PyObject* args) { - PyObject *obj = nullptr; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) + PyObject* obj = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &obj)) { return nullptr; + } VectorPy* vec = static_cast(obj); @@ -461,10 +469,11 @@ PyObject* VectorPy::getAngle(PyObject *args) return Py::new_reference_to(angle); } -PyObject* VectorPy::normalize(PyObject *args) +PyObject* VectorPy::normalize(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } VectorPy::PointerType ptr = getVectorPtr(); if (ptr->Length() < Vector3d::epsilon()) { PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot normalize null vector"); @@ -476,11 +485,12 @@ PyObject* VectorPy::normalize(PyObject *args) return Py::new_reference_to(this); } -PyObject* VectorPy::projectToLine(PyObject *args) +PyObject* VectorPy::projectToLine(PyObject* args) { PyObject *base = nullptr, *line = nullptr; - if (!PyArg_ParseTuple(args, "OO",&base, &line)) + if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; + } if (!PyObject_TypeCheck(base, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -502,11 +512,12 @@ PyObject* VectorPy::projectToLine(PyObject *args) return Py::new_reference_to(this); } -PyObject* VectorPy::projectToPlane(PyObject *args) +PyObject* VectorPy::projectToPlane(PyObject* args) { PyObject *base = nullptr, *line = nullptr; - if (!PyArg_ParseTuple(args, "OO",&base, &line)) + if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; + } if (!PyObject_TypeCheck(base, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -528,11 +539,12 @@ PyObject* VectorPy::projectToPlane(PyObject *args) return Py::new_reference_to(this); } -PyObject* VectorPy::distanceToPoint(PyObject *args) +PyObject* VectorPy::distanceToPoint(PyObject* args) { - PyObject *pnt = nullptr; - if (!PyArg_ParseTuple(args, "O!",&(VectorPy::Type),&pnt)) + PyObject* pnt = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &pnt)) { return nullptr; + } VectorPy* base_vec = static_cast(pnt); VectorPy::PointerType this_ptr = getVectorPtr(); @@ -542,11 +554,12 @@ PyObject* VectorPy::distanceToPoint(PyObject *args) return Py::new_reference_to(dist); } -PyObject* VectorPy::distanceToLine(PyObject *args) +PyObject* VectorPy::distanceToLine(PyObject* args) { PyObject *base = nullptr, *line = nullptr; - if (!PyArg_ParseTuple(args, "OO",&base, &line)) + if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; + } if (!PyObject_TypeCheck(base, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -567,11 +580,12 @@ PyObject* VectorPy::distanceToLine(PyObject *args) return Py::new_reference_to(dist); } -PyObject* VectorPy::distanceToLineSegment(PyObject *args) +PyObject* VectorPy::distanceToLineSegment(PyObject* args) { PyObject *base = nullptr, *line = nullptr; - if (!PyArg_ParseTuple(args, "OO",&base, &line)) + if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; + } if (!PyObject_TypeCheck(base, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -592,11 +606,12 @@ PyObject* VectorPy::distanceToLineSegment(PyObject *args) return new VectorPy(v); } -PyObject* VectorPy::distanceToPlane(PyObject *args) +PyObject* VectorPy::distanceToPlane(PyObject* args) { PyObject *base = nullptr, *line = nullptr; - if (!PyArg_ParseTuple(args, "OO",&base, &line)) + if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; + } if (!PyObject_TypeCheck(base, &(VectorPy::Type))) { PyErr_SetString(PyExc_TypeError, "First arg must be Vector"); return nullptr; @@ -623,7 +638,7 @@ Py::Float VectorPy::getLength() const return Py::Float(ptr->Length()); } -void VectorPy::setLength(Py::Float arg) +void VectorPy::setLength(Py::Float arg) { VectorPy::PointerType ptr = getVectorPtr(); double len = ptr->Length(); @@ -631,7 +646,7 @@ void VectorPy::setLength(Py::Float arg) throw Py::RuntimeError(std::string("Cannot set length of null vector")); } - double val = static_cast(arg)/len; + double val = static_cast(arg) / len; ptr->x *= val; ptr->y *= val; ptr->z *= val; @@ -643,7 +658,7 @@ Py::Float VectorPy::getx() const return Py::Float(ptr->x); } -void VectorPy::setx(Py::Float arg) +void VectorPy::setx(Py::Float arg) { VectorPy::PointerType ptr = getVectorPtr(); ptr->x = static_cast(arg); @@ -655,7 +670,7 @@ Py::Float VectorPy::gety() const return Py::Float(ptr->y); } -void VectorPy::sety(Py::Float arg) +void VectorPy::sety(Py::Float arg) { VectorPy::PointerType ptr = getVectorPtr(); ptr->y = static_cast(arg); @@ -667,13 +682,13 @@ Py::Float VectorPy::getz() const return Py::Float(ptr->z); } -void VectorPy::setz(Py::Float arg) +void VectorPy::setz(Py::Float arg) { VectorPy::PointerType ptr = getVectorPtr(); ptr->z = static_cast(arg); } -PyObject *VectorPy::getCustomAttributes(const char* /*attr*/) const +PyObject* VectorPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -687,24 +702,24 @@ int VectorPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) // In generation script allow to more precisely define which slots // of the number protocol should be supported instead of setting all. -PyObject * VectorPy::number_divide_handler (PyObject* self, PyObject* other) +PyObject* VectorPy::number_divide_handler(PyObject* self, PyObject* other) { - if (PyObject_TypeCheck(self, &(VectorPy::Type)) && - PyNumber_Check(other)) { + if (PyObject_TypeCheck(self, &(VectorPy::Type)) && PyNumber_Check(other)) { // Vector passes PyNumber_Check because it sets nb_int and nb_float // slots of the PyNumberMethods structure. So, it must be explicitly // filered out here. if (PyObject_TypeCheck(other, &(VectorPy::Type))) { - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for /: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); return nullptr; } - Base::Vector3d vec = static_cast(self) ->value(); + Base::Vector3d vec = static_cast(self)->value(); double div = PyFloat_AsDouble(other); if (div == 0.0) { - PyErr_Format(PyExc_ZeroDivisionError, "'%s' division by zero", - Py_TYPE(self)->tp_name); + PyErr_Format(PyExc_ZeroDivisionError, "'%s' division by zero", Py_TYPE(self)->tp_name); return nullptr; } @@ -712,136 +727,151 @@ PyObject * VectorPy::number_divide_handler (PyObject* self, PyObject* other) return new VectorPy(vec); } - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for /: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); return nullptr; } -PyObject * VectorPy::number_remainder_handler (PyObject* self, PyObject* other) +PyObject* VectorPy::number_remainder_handler(PyObject* self, PyObject* other) { - if (PyObject_TypeCheck(self, &(VectorPy::Type)) && - PyObject_TypeCheck(other, &(VectorPy::Type))) - { - Base::Vector3d a = static_cast(self) ->value(); - Base::Vector3d b = static_cast(other) ->value(); + if (PyObject_TypeCheck(self, &(VectorPy::Type)) + && PyObject_TypeCheck(other, &(VectorPy::Type))) { + Base::Vector3d a = static_cast(self)->value(); + Base::Vector3d b = static_cast(other)->value(); return new VectorPy(a % b); } - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %%: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for %%: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); return nullptr; } -PyObject * VectorPy::number_divmod_handler (PyObject* self, PyObject* other) +PyObject* VectorPy::number_divmod_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for divmod(): '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for divmod(): '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); return nullptr; } -PyObject * VectorPy::number_power_handler (PyObject* self, PyObject* other, PyObject* /*arg*/) +PyObject* VectorPy::number_power_handler(PyObject* self, PyObject* other, PyObject* /*arg*/) { - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for ** or pow(): '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for ** or pow(): '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); return nullptr; } -PyObject * VectorPy::number_negative_handler (PyObject* self) +PyObject* VectorPy::number_negative_handler(PyObject* self) { if (PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d vec = static_cast(self) ->value(); + Base::Vector3d vec = static_cast(self)->value(); return new VectorPy(-vec); } - PyErr_Format(PyExc_TypeError, "bad operand type for unary -: '%s'", - Py_TYPE(self)->tp_name); + PyErr_Format(PyExc_TypeError, "bad operand type for unary -: '%s'", Py_TYPE(self)->tp_name); return nullptr; } -PyObject * VectorPy::number_positive_handler (PyObject* self) +PyObject* VectorPy::number_positive_handler(PyObject* self) { if (PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d vec = static_cast(self) ->value(); + Base::Vector3d vec = static_cast(self)->value(); return new VectorPy(vec); } - PyErr_Format(PyExc_TypeError, "bad operand type for unary +: '%s'", - Py_TYPE(self)->tp_name); + PyErr_Format(PyExc_TypeError, "bad operand type for unary +: '%s'", Py_TYPE(self)->tp_name); return nullptr; } -PyObject * VectorPy::number_absolute_handler (PyObject* self) +PyObject* VectorPy::number_absolute_handler(PyObject* self) { if (PyObject_TypeCheck(self, &(VectorPy::Type))) { - Base::Vector3d vec = static_cast(self) ->value(); + Base::Vector3d vec = static_cast(self)->value(); vec.x = fabs(vec.x); vec.y = fabs(vec.y); vec.z = fabs(vec.z); return new VectorPy(vec); } - PyErr_Format(PyExc_TypeError, "bad operand type for abs(): '%s'", - Py_TYPE(self)->tp_name); + PyErr_Format(PyExc_TypeError, "bad operand type for abs(): '%s'", Py_TYPE(self)->tp_name); return nullptr; } -int VectorPy::number_nonzero_handler (PyObject* /*self*/) +int VectorPy::number_nonzero_handler(PyObject* /*self*/) { return 1; } -PyObject * VectorPy::number_invert_handler (PyObject* self) +PyObject* VectorPy::number_invert_handler(PyObject* self) { - PyErr_Format(PyExc_TypeError, "bad operand type for unary ~: '%s'", + PyErr_Format(PyExc_TypeError, "bad operand type for unary ~: '%s'", Py_TYPE(self)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_lshift_handler(PyObject* self, PyObject* other) +{ + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for <<: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_rshift_handler(PyObject* self, PyObject* other) +{ + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for >>: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_and_handler(PyObject* self, PyObject* other) +{ + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for &: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_xor_handler(PyObject* self, PyObject* other) +{ + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for ^: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_or_handler(PyObject* self, PyObject* other) +{ + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for |: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name); + return nullptr; +} + +PyObject* VectorPy::number_int_handler(PyObject* self) +{ + PyErr_Format(PyExc_TypeError, + "int() argument must be a string or a number, not '%s'", Py_TYPE(self)->tp_name); return nullptr; } -PyObject * VectorPy::number_lshift_handler (PyObject* self, PyObject* other) +PyObject* VectorPy::number_float_handler(PyObject* self) { - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for <<: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_rshift_handler (PyObject* self, PyObject* other) -{ - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for >>: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_and_handler (PyObject* self, PyObject* other) -{ - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for &: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_xor_handler (PyObject* self, PyObject* other) -{ - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for ^: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_or_handler (PyObject* self, PyObject* other) -{ - PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for |: '%s' and '%s'", - Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_int_handler (PyObject* self) -{ - PyErr_Format(PyExc_TypeError, "int() argument must be a string or a number, not '%s'", - Py_TYPE(self)->tp_name); - return nullptr; -} - -PyObject * VectorPy::number_float_handler (PyObject* self) -{ - PyErr_Format(PyExc_TypeError, "float() argument must be a string or a number, not '%s'", + PyErr_Format(PyExc_TypeError, + "float() argument must be a string or a number, not '%s'", Py_TYPE(self)->tp_name); return nullptr; } diff --git a/src/Base/ViewProj.cpp b/src/Base/ViewProj.cpp index e627e5ad67..ff71b5950b 100644 --- a/src/Base/ViewProj.cpp +++ b/src/Base/ViewProj.cpp @@ -36,7 +36,7 @@ bool ViewProjMethod::isValid() const /*! Calculate the composed projection matrix which is a product of * projection matrix multiplied with input transformation matrix. */ -Matrix4D ViewProjMethod::getComposedProjectionMatrix () const +Matrix4D ViewProjMethod::getComposedProjectionMatrix() const { Matrix4D mat = getProjectionMatrix(); @@ -77,8 +77,8 @@ void ViewProjMethod::transformInput(const Base::Vector3d& src, Base::Vector3d& d //----------------------------------------------------------------------------- -ViewProjMatrix::ViewProjMatrix (const Matrix4D &rclMtx) - : _clMtx(rclMtx) +ViewProjMatrix::ViewProjMatrix(const Matrix4D& rclMtx) + : _clMtx(rclMtx) { double m30 = _clMtx[3][0]; double m31 = _clMtx[3][1]; @@ -101,7 +101,7 @@ ViewProjMatrix::ViewProjMatrix (const Matrix4D &rclMtx) _clMtxInv.inverseGauss(); } -Matrix4D ViewProjMatrix::getProjectionMatrix () const +Matrix4D ViewProjMatrix::getProjectionMatrix() const { // Return the same matrix as passed to the constructor Matrix4D mat(_clMtx); @@ -120,9 +120,8 @@ void perspectiveTransform(const Base::Matrix4D& mat, Vec& pnt) double m31 = mat[3][1]; double m32 = mat[3][2]; double m33 = mat[3][3]; - double w = (static_cast(pnt.x) * m30 + - static_cast(pnt.y) * m31 + - static_cast(pnt.z) * m32 + m33); + double w = (static_cast(pnt.x) * m30 + static_cast(pnt.y) * m31 + + static_cast(pnt.z) * m32 + m33); mat.multVec(pnt, pnt); pnt /= static_cast(w); @@ -137,7 +136,7 @@ Vector3f ViewProjMatrix::operator()(const Vector3f& inp) const if (!isOrthographic) { dst = src; perspectiveTransform(_clMtx, dst); - dst.Set(0.5f*dst.x+0.5f, 0.5f*dst.y+0.5f, 0.5f*dst.z+0.5f); + dst.Set(0.5f * dst.x + 0.5f, 0.5f * dst.y + 0.5f, 0.5f * dst.z + 0.5f); } else { _clMtx.multVec(src, dst); @@ -155,7 +154,7 @@ Vector3d ViewProjMatrix::operator()(const Vector3d& inp) const if (!isOrthographic) { dst = src; perspectiveTransform(_clMtx, dst); - dst.Set(0.5*dst.x+0.5, 0.5*dst.y+0.5, 0.5*dst.z+0.5); + dst.Set(0.5 * dst.x + 0.5, 0.5 * dst.y + 0.5, 0.5 * dst.z + 0.5); } else { _clMtx.multVec(src, dst); @@ -164,11 +163,11 @@ Vector3d ViewProjMatrix::operator()(const Vector3d& inp) const return dst; } -Vector3f ViewProjMatrix::inverse (const Vector3f& src) const +Vector3f ViewProjMatrix::inverse(const Vector3f& src) const { Vector3f dst; if (!isOrthographic) { - dst.Set(2.0f*src.x-1.0f, 2.0f*src.y-1.0f, 2.0f*src.z-1.0f); + dst.Set(2.0f * src.x - 1.0f, 2.0f * src.y - 1.0f, 2.0f * src.z - 1.0f); perspectiveTransform(_clMtxInv, dst); } else { @@ -178,11 +177,11 @@ Vector3f ViewProjMatrix::inverse (const Vector3f& src) const return dst; } -Vector3d ViewProjMatrix::inverse (const Vector3d& src) const +Vector3d ViewProjMatrix::inverse(const Vector3d& src) const { Vector3d dst; if (!isOrthographic) { - dst.Set(2.0*src.x-1.0, 2.0*src.y-1.0, 2.0*src.z-1.0); + dst.Set(2.0 * src.x - 1.0, 2.0 * src.y - 1.0, 2.0 * src.z - 1.0); perspectiveTransform(_clMtxInv, dst); } else { @@ -194,34 +193,34 @@ Vector3d ViewProjMatrix::inverse (const Vector3d& src) const // ---------------------------------------------------------------------------- -ViewOrthoProjMatrix::ViewOrthoProjMatrix (const Matrix4D &rclMtx) +ViewOrthoProjMatrix::ViewOrthoProjMatrix(const Matrix4D& rclMtx) : _clMtx(rclMtx) + , _clMtxInv(rclMtx) { - _clMtxInv = _clMtx; _clMtxInv.inverse(); } -Matrix4D ViewOrthoProjMatrix::getProjectionMatrix () const +Matrix4D ViewOrthoProjMatrix::getProjectionMatrix() const { return _clMtx; } -Vector3f ViewOrthoProjMatrix::operator()(const Vector3f &rclPt) const +Vector3f ViewOrthoProjMatrix::operator()(const Vector3f& rclPt) const { return Vector3f(_clMtx * rclPt); } -Vector3d ViewOrthoProjMatrix::operator()(const Vector3d &rclPt) const +Vector3d ViewOrthoProjMatrix::operator()(const Vector3d& rclPt) const { return Vector3d(_clMtx * rclPt); } -Vector3f ViewOrthoProjMatrix::inverse (const Vector3f &rclPt) const +Vector3f ViewOrthoProjMatrix::inverse(const Vector3f& rclPt) const { return Vector3f(_clMtxInv * rclPt); } -Vector3d ViewOrthoProjMatrix::inverse (const Vector3d &rclPt) const +Vector3d ViewOrthoProjMatrix::inverse(const Vector3d& rclPt) const { return Vector3d(_clMtxInv * rclPt); } diff --git a/src/Base/ViewProj.h b/src/Base/ViewProj.h index 414229c0e9..846972cd4d 100644 --- a/src/Base/ViewProj.h +++ b/src/Base/ViewProj.h @@ -28,7 +28,8 @@ #include "Matrix.h" -namespace Base { +namespace Base +{ /** * Abstract base class for all project methods. @@ -37,25 +38,26 @@ class BaseExport ViewProjMethod { public: ViewProjMethod(const ViewProjMethod&) = default; - ViewProjMethod& operator= (const ViewProjMethod&) = default; + ViewProjMethod& operator=(const ViewProjMethod&) = default; virtual ~ViewProjMethod() = default; virtual bool isValid() const; /** Convert 3D point to 2D projection plane */ - virtual Vector3f operator()(const Vector3f &rclPt) const = 0; + virtual Vector3f operator()(const Vector3f& rclPt) const = 0; /** Convert 3D point to 2D projection plane */ - virtual Vector3d operator()(const Vector3d &rclPt) const = 0; + virtual Vector3d operator()(const Vector3d& rclPt) const = 0; /** Convert a 2D point on the projection plane in 3D space */ - virtual Vector3f inverse (const Vector3f &rclPt) const = 0; + virtual Vector3f inverse(const Vector3f& rclPt) const = 0; /** Convert a 2D point on the projection plane in 3D space */ - virtual Vector3d inverse (const Vector3d &rclPt) const = 0; + virtual Vector3d inverse(const Vector3d& rclPt) const = 0; /** Calculate the projection (+ mapping) matrix */ - virtual Matrix4D getProjectionMatrix () const = 0; + virtual Matrix4D getProjectionMatrix() const = 0; /** Calculate the composed projection matrix */ - Matrix4D getComposedProjectionMatrix () const; + Matrix4D getComposedProjectionMatrix() const; /** Apply an additional transformation to the input points */ void setTransform(const Base::Matrix4D&); - const Base::Matrix4D& getTransform() const { + const Base::Matrix4D& getTransform() const + { return transform; } @@ -65,7 +67,7 @@ protected: void transformInput(const Base::Vector3d&, Base::Vector3d&) const; private: - bool hasTransform{false}; + bool hasTransform {false}; Base::Matrix4D transform; }; @@ -73,17 +75,17 @@ private: * The ViewProjMatrix class returns the result of the multiplication * of the 3D vector and the view transformation matrix. */ -class BaseExport ViewProjMatrix : public ViewProjMethod +class BaseExport ViewProjMatrix: public ViewProjMethod { public: - ViewProjMatrix (const Matrix4D &rclMtx); + ViewProjMatrix(const Matrix4D& rclMtx); - Vector3f operator()(const Vector3f &rclPt) const override; - Vector3d operator()(const Vector3d &rclPt) const override; - Vector3f inverse (const Vector3f &rclPt) const override; - Vector3d inverse (const Vector3d &rclPt) const override; + Vector3f operator()(const Vector3f& rclPt) const override; + Vector3d operator()(const Vector3d& rclPt) const override; + Vector3f inverse(const Vector3f& rclPt) const override; + Vector3d inverse(const Vector3d& rclPt) const override; - Matrix4D getProjectionMatrix () const override; + Matrix4D getProjectionMatrix() const override; protected: bool isOrthographic; @@ -96,22 +98,22 @@ protected: * Unlike ViewProjMatrix this class is not supposed to project points onto * a viewport but project points onto a plane in 3D. */ -class BaseExport ViewOrthoProjMatrix : public ViewProjMethod +class BaseExport ViewOrthoProjMatrix: public ViewProjMethod { public: - ViewOrthoProjMatrix (const Matrix4D &rclMtx); + ViewOrthoProjMatrix(const Matrix4D& rclMtx); - Vector3f operator()(const Vector3f &rclPt) const override; - Vector3d operator()(const Vector3d &rclPt) const override; - Vector3f inverse (const Vector3f &rclPt) const override; - Vector3d inverse (const Vector3d &rclPt) const override; + Vector3f operator()(const Vector3f& rclPt) const override; + Vector3d operator()(const Vector3d& rclPt) const override; + Vector3f inverse(const Vector3f& rclPt) const override; + Vector3d inverse(const Vector3d& rclPt) const override; - Matrix4D getProjectionMatrix () const override; + Matrix4D getProjectionMatrix() const override; protected: Matrix4D _clMtx, _clMtxInv; }; -} // namespace Base +} // namespace Base -#endif // BASE_VIEWPROJ_H +#endif // BASE_VIEWPROJ_H diff --git a/src/Base/Writer.cpp b/src/Base/Writer.cpp index 7d2931544f..422b3ad6b9 100644 --- a/src/Base/Writer.cpp +++ b/src/Base/Writer.cpp @@ -44,30 +44,34 @@ using namespace zipios; // boost iostream filter to escape ']]>' in text file saved into CDATA section. // It does not check if the character is valid utf8 or not. -struct cdata_filter { +struct cdata_filter +{ using char_type = char; using category = boost::iostreams::output_filter_tag; template - inline bool put(Device& dev, char c) { - switch(state) { + inline bool put(Device& dev, char c) + { + switch (state) { case 0: case 1: - if(c == ']') + if (c == ']') { ++state; - else + } + else { state = 0; + } break; case 2: - if(c == '>') { + if (c == '>') { static const char escape[] = "]]>(); auto* filteredStream = dynamic_cast(CharStream.get()); @@ -132,13 +137,15 @@ void Writer::insertAsciiFile(const char* FileName) { Base::FileInfo fi(FileName); Base::ifstream from(fi); - if (!from) + if (!from) { throw Base::FileException("Writer::insertAsciiFile() Could not open file!"); + } Stream() << "" << endl; } @@ -146,8 +153,9 @@ void Writer::insertBinFile(const char* FileName) { Base::FileInfo fi(FileName); Base::ifstream from(fi, std::ios::in | std::ios::binary | std::ios::ate); - if (!from) + if (!from) { throw Base::FileException("Writer::insertAsciiFile() Could not open file!"); + } Stream() << " Writer::getModes() const void Writer::clearMode(const std::string& mode) { std::set::iterator it = Modes.find(mode); - if (it != Modes.end()) + if (it != Modes.end()) { Modes.erase(it); + } } void Writer::clearModes() @@ -232,7 +241,7 @@ std::vector Writer::getErrors() const return Errors; } -std::string Writer::addFile(const char* Name,const Base::Persistence *Object) +std::string Writer::addFile(const char* Name, const Base::Persistence* Object) { // always check isForceXML() before requesting a file! assert(!isForceXML()); @@ -243,18 +252,18 @@ std::string Writer::addFile(const char* Name,const Base::Persistence *Object) FileList.push_back(temp); - FileNames.push_back( temp.FileName ); + FileNames.push_back(temp.FileName); // return the unique file name return temp.FileName; } -std::string Writer::getUniqueFileName(const char *Name) +std::string Writer::getUniqueFileName(const char* Name) { // name in use? std::string CleanName = (Name ? Name : ""); std::vector::const_iterator pos; - pos = find(FileNames.begin(),FileNames.end(),CleanName); + pos = find(FileNames.begin(), FileNames.end(), CleanName); if (pos == FileNames.end()) { // if not, name is OK @@ -266,16 +275,18 @@ std::string Writer::getUniqueFileName(const char *Name) FileInfo fi(CleanName); CleanName = fi.fileNamePure(); std::string ext = fi.extension(); - for (pos = FileNames.begin();pos != FileNames.end();++pos) { + for (pos = FileNames.begin(); pos != FileNames.end(); ++pos) { fi.setFile(*pos); std::string FileName = fi.fileNamePure(); - if (fi.extension() == ext) + if (fi.extension() == ext) { names.push_back(FileName); + } } std::stringstream str; str << Base::Tools::getUniqueName(CleanName, names); - if (!ext.empty()) + if (!ext.empty()) { str << "." << ext; + } return str.str(); } } @@ -288,11 +299,11 @@ const std::vector& Writer::getFilenames() const void Writer::incInd() { if (indent < 1020) { - indBuf[indent ] = ' '; - indBuf[indent+1] = ' '; - indBuf[indent+2] = ' '; - indBuf[indent+3] = ' '; - indBuf[indent+4] = '\0'; + indBuf[indent] = ' '; + indBuf[indent + 1] = ' '; + indBuf[indent + 2] = ' '; + indBuf[indent + 3] = ' '; + indBuf[indent + 4] = '\0'; indent += 4; } } @@ -311,7 +322,7 @@ void Writer::decInd() // ---------------------------------------------------------------------------- ZipWriter::ZipWriter(const char* FileName) - : ZipStream(FileName) + : ZipStream(FileName) { #ifdef _MSC_VER ZipStream.imbue(std::locale::empty()); @@ -319,11 +330,11 @@ ZipWriter::ZipWriter(const char* FileName) ZipStream.imbue(std::locale::classic()); #endif ZipStream.precision(std::numeric_limits::digits10 + 1); - ZipStream.setf(ios::fixed,ios::floatfield); + ZipStream.setf(ios::fixed, ios::floatfield); } ZipWriter::ZipWriter(std::ostream& os) - : ZipStream(os) + : ZipStream(os) { #ifdef _MSC_VER ZipStream.imbue(std::locale::empty()); @@ -331,7 +342,7 @@ ZipWriter::ZipWriter(std::ostream& os) ZipStream.imbue(std::locale::classic()); #endif ZipStream.precision(std::numeric_limits::digits10 + 1); - ZipStream.setf(ios::fixed,ios::floatfield); + ZipStream.setf(ios::fixed, ios::floatfield); } void ZipWriter::writeFiles() @@ -354,9 +365,9 @@ ZipWriter::~ZipWriter() // ---------------------------------------------------------------------------- -FileWriter::FileWriter(const char* DirName) : DirName(DirName) -{ -} +FileWriter::FileWriter(const char* DirName) + : DirName(DirName) +{} FileWriter::~FileWriter() = default; @@ -366,7 +377,7 @@ void FileWriter::putNextEntry(const char* file) this->FileStream.open(fileName.c_str(), std::ios::out | std::ios::binary); } -bool FileWriter::shouldWrite(const std::string& , const Base::Persistence *) const +bool FileWriter::shouldWrite(const std::string&, const Base::Persistence*) const { return true; } diff --git a/src/Base/Writer.h b/src/Base/Writer.h index 8f2d13465d..27684e4b4f 100644 --- a/src/Base/Writer.h +++ b/src/Base/Writer.h @@ -42,7 +42,6 @@ #include "FileInfo.h" - namespace Base { @@ -74,14 +73,14 @@ public: /// insert a binary file BASE64 coded as CDATA section in the XML file void insertBinFile(const char* FileName); /// insert text string as CDATA - void insertText(const std::string &s); + void insertText(const std::string& s); /** @name additional file writing */ //@{ /// add a write request of a persistent object - std::string addFile(const char* Name, const Base::Persistence *Object); + std::string addFile(const char* Name, const Base::Persistence* Object); /// process the requested file storing - virtual void writeFiles()=0; + virtual void writeFiles() = 0; /// get all registered file names const std::vector& getFilenames() const; /// Set mode @@ -109,14 +108,17 @@ public: /** @name pretty formatting for XML */ //@{ /// get the current indentation - const char* ind() const {return indBuf;} + const char* ind() const + { + return indBuf; + } /// increase indentation by one tab void incInd(); /// decrease indentation by one tab void decInd(); //@} - virtual std::ostream &Stream()=0; + virtual std::ostream& Stream() = 0; /** Create an output stream for storing character content * The input is assumed to be valid character with @@ -137,29 +139,30 @@ public: /** End the current character output stream * @return Returns the normal writer stream for convenience */ - std::ostream &endCharStream(); + std::ostream& endCharStream(); /// Return the current character output stream - std::ostream &charStream(); + std::ostream& charStream(); /// name for underlying file saves std::string ObjectName; protected: - std::string getUniqueFileName(const char *Name); - struct FileEntry { + std::string getUniqueFileName(const char* Name); + struct FileEntry + { std::string FileName; - const Base::Persistence *Object; + const Base::Persistence* Object; }; std::vector FileList; std::vector FileNames; std::vector Errors; std::set Modes; - short indent{0}; - char indBuf[1024]{}; + short indent {0}; + char indBuf[1024] {}; - bool forceXML{false}; - int fileVersion{1}; + bool forceXML {false}; + int fileVersion {1}; public: Writer(const Writer&) = delete; @@ -177,7 +180,7 @@ private: * \see Base::Persistence * \author Juergen Riegel */ -class BaseExport ZipWriter : public Writer +class BaseExport ZipWriter: public Writer { public: ZipWriter(const char* FileName); @@ -186,11 +189,23 @@ public: void writeFiles() override; - std::ostream &Stream() override{return ZipStream;} + std::ostream& Stream() override + { + return ZipStream; + } - void setComment(const char* str){ZipStream.setComment(str);} - void setLevel(int level){ZipStream.setLevel( level );} - void putNextEntry(const char* str){ZipStream.putNextEntry(str);} + void setComment(const char* str) + { + ZipStream.setComment(str); + } + void setLevel(int level) + { + ZipStream.setLevel(level); + } + void putNextEntry(const char* str) + { + ZipStream.putNextEntry(str); + } private: zipios::ZipOutputStream ZipStream; @@ -202,13 +217,20 @@ private: * \see Base::Persistence * \author Juergen Riegel */ -class BaseExport StringWriter : public Writer +class BaseExport StringWriter: public Writer { public: - std::ostream &Stream() override{return StrStream;} - std::string getString() const {return StrStream.str();} - void writeFiles() override{} + std::ostream& Stream() override + { + return StrStream; + } + std::string getString() const + { + return StrStream.str(); + } + void writeFiles() override + {} private: std::stringstream StrStream; @@ -219,7 +241,7 @@ private: \see Base::Persistence \author Werner Mayer */ -class BaseExport FileWriter : public Writer +class BaseExport FileWriter: public Writer { public: FileWriter(const char* DirName); @@ -228,14 +250,20 @@ public: void putNextEntry(const char* file); void writeFiles() override; - std::ostream &Stream() override{return FileStream;} - void close() {FileStream.close();} + std::ostream& Stream() override + { + return FileStream; + } + void close() + { + FileStream.close(); + } /*! This method can be re-implemented in sub-classes to avoid to write out certain objects. The default implementation always returns true. */ - virtual bool shouldWrite(const std::string& name, const Base::Persistence *Object) const; + virtual bool shouldWrite(const std::string& name, const Base::Persistence* Object) const; protected: std::string DirName; @@ -243,7 +271,7 @@ protected: }; -} //namespace Base +} // namespace Base -#endif // BASE_WRITER_H +#endif // BASE_WRITER_H diff --git a/src/Base/XMLTools.cpp b/src/Base/XMLTools.cpp index 7af95eb0b2..2fec3b5e3d 100644 --- a/src/Base/XMLTools.cpp +++ b/src/Base/XMLTools.cpp @@ -33,10 +33,15 @@ std::unique_ptr XMLTools::transcoder; void XMLTools::initialize() { if (!transcoder.get()) { - XMLTransService::Codes res{}; - transcoder.reset(XMLPlatformUtils::fgTransService->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager)); - if (res != XMLTransService::Ok) + XMLTransService::Codes res {}; + transcoder.reset(XMLPlatformUtils::fgTransService->makeNewTranscoderFor( + XMLRecognizer::UTF_8, + res, + 4096, + XMLPlatformUtils::fgMemoryManager)); + if (res != XMLTransService::Ok) { throw Base::UnicodeError("Can\'t create transcoder"); + } } } @@ -46,23 +51,28 @@ std::string XMLTools::toStdString(const XMLCh* const toTranscode) initialize(); - //char outBuff[128]; + // char outBuff[128]; static XMLByte outBuff[128]; XMLSize_t outputLength = 0; XMLSize_t eaten = 0; XMLSize_t offset = 0; XMLSize_t inputLength = XMLString::stringLen(toTranscode); - while (inputLength) - { - outputLength = transcoder->transcodeTo(toTranscode + offset, inputLength, outBuff, 128, eaten, XMLTranscoder::UnRep_RepChar); + while (inputLength) { + outputLength = transcoder->transcodeTo(toTranscode + offset, + inputLength, + outBuff, + 128, + eaten, + XMLTranscoder::UnRep_RepChar); str.append(reinterpret_cast(outBuff), outputLength); offset += eaten; inputLength -= eaten; // Bail out if nothing more was produced - if (outputLength == 0) + if (outputLength == 0) { break; + } } return str; @@ -71,8 +81,9 @@ std::string XMLTools::toStdString(const XMLCh* const toTranscode) std::basic_string XMLTools::toXMLString(const char* const fromTranscode) { std::basic_string str; - if (!fromTranscode) + if (!fromTranscode) { return str; + } initialize(); @@ -84,16 +95,21 @@ std::basic_string XMLTools::toXMLString(const char* const fromTranscode) XMLSize_t inputLength = std::string(fromTranscode).size(); unsigned char* charSizes = new unsigned char[inputLength]; - while (inputLength) - { - outputLength = transcoder->transcodeFrom(xmlBytes + offset, inputLength, outBuff, 128, eaten, charSizes); + while (inputLength) { + outputLength = transcoder->transcodeFrom(xmlBytes + offset, + inputLength, + outBuff, + 128, + eaten, + charSizes); str.append(outBuff, outputLength); offset += eaten; inputLength -= eaten; // Bail out if nothing more was produced - if (outputLength == 0) + if (outputLength == 0) { break; + } } delete[] charSizes; diff --git a/src/Base/XMLTools.h b/src/Base/XMLTools.h index d0dc66c876..2cc046b2d1 100644 --- a/src/Base/XMLTools.h +++ b/src/Base/XMLTools.h @@ -33,9 +33,9 @@ XERCES_CPP_NAMESPACE_BEGIN - class DOMNode; - class DOMElement; - class DOMDocument; +class DOMNode; +class DOMElement; +class DOMDocument; XERCES_CPP_NAMESPACE_END // Helper class @@ -58,16 +58,16 @@ private: class StrX { -public : +public: StrX(const XMLCh* const toTranscode); ~StrX(); /// Getter method const char* c_str() const; -private : +private: // This is the local code page form of the string. - char* fLocalForm; + char* fLocalForm; }; inline std::ostream& operator<<(std::ostream& target, const StrX& toDump) @@ -103,13 +103,13 @@ inline const char* StrX::c_str() const class StrXUTF8 { -public : +public: StrXUTF8(const XMLCh* const toTranscode); /// Getter method const char* c_str() const; /// string which holds the UTF-8 form - std::string str; + std::string str; }; inline std::ostream& operator<<(std::ostream& target, const StrXUTF8& toDump) @@ -140,7 +140,7 @@ inline const char* StrXUTF8::c_str() const class XStr { -public : +public: /// Constructors and Destructor XStr(const char* const toTranscode); /// @@ -150,9 +150,9 @@ public : /// Getter method const XMLCh* unicodeForm() const; -private : +private: /// This is the Unicode XMLCh format of the string. - XMLCh* fUnicodeForm; + XMLCh* fUnicodeForm; }; @@ -182,15 +182,15 @@ inline const XMLCh* XStr::unicodeForm() const class XUTF8Str { -public : +public: XUTF8Str(const char* const fromTranscode); ~XUTF8Str(); /// Getter method const XMLCh* unicodeForm() const; -private : - std::basic_string str; +private: + std::basic_string str; }; inline XUTF8Str::XUTF8Str(const char* const fromTranscode) @@ -209,4 +209,4 @@ inline const XMLCh* XUTF8Str::unicodeForm() const return str.c_str(); } -#endif // BASE_XMLTOOLS_H +#endif // BASE_XMLTOOLS_H diff --git a/src/Base/ZipHeader.cpp b/src/Base/ZipHeader.cpp index 071e58f326..b0660eaad8 100644 --- a/src/Base/ZipHeader.cpp +++ b/src/Base/ZipHeader.cpp @@ -31,7 +31,7 @@ using zipios::FileCollection; using zipios::ZipHeader; -ZipHeader::ZipHeader(std::istream &inp, int s_off, int e_off) +ZipHeader::ZipHeader(std::istream& inp, int s_off, int e_off) : _input(inp) , _vs(s_off, e_off) { @@ -39,7 +39,7 @@ ZipHeader::ZipHeader(std::istream &inp, int s_off, int e_off) } /** Create a copy of this instance. */ -FileCollection *ZipHeader::clone() const +FileCollection* ZipHeader::clone() const { return new ZipHeader(*this); } @@ -49,28 +49,34 @@ void ZipHeader::close() _valid = false; } -std::istream *ZipHeader::getInputStream(const ConstEntryPointer &entry) +std::istream* ZipHeader::getInputStream(const ConstEntryPointer& entry) { - if (!_valid) + if (!_valid) { throw zipios::InvalidStateException("Attempt to use an invalid FileCollection"); + } return getInputStream(entry->getName()); } -std::istream *ZipHeader::getInputStream(const std::string &entry_name, MatchPath matchpath) +std::istream* ZipHeader::getInputStream(const std::string& entry_name, MatchPath matchpath) { - if (!_valid) + if (!_valid) { throw zipios::InvalidStateException("Attempt to use an invalid ZipHeader"); + } zipios::ConstEntryPointer ent = getEntry(entry_name, matchpath); - if (!ent) + if (!ent) { return nullptr; - else - return new zipios::ZipInputStream(_input, - static_cast(ent.get())->getLocalHeaderOffset() + _vs.startOffset()); + } + else { + return new zipios::ZipInputStream( + _input, + static_cast(ent.get())->getLocalHeaderOffset() + + _vs.startOffset()); + } } -bool ZipHeader::init(std::istream &_zipfile) +bool ZipHeader::init(std::istream& _zipfile) { // Check stream error state if (!_zipfile) { @@ -82,11 +88,12 @@ bool ZipHeader::init(std::istream &_zipfile) return _valid; } -bool ZipHeader::readCentralDirectory(std::istream &_zipfile) +bool ZipHeader::readCentralDirectory(std::istream& _zipfile) { // Find and read eocd. - if (!readEndOfCentralDirectory(_zipfile)) + if (!readEndOfCentralDirectory(_zipfile)) { throw zipios::FCollException("Unable to find zip structure: End-of-central-directory"); + } // Position read pointer to start of first entry in central dir. _vs.vseekg(_zipfile, _eocd.offset(), std::ios::beg); @@ -95,16 +102,22 @@ bool ZipHeader::readCentralDirectory(std::istream &_zipfile) // Giving the default argument in the next line to keep Visual C++ quiet _entries.resize(_eocd.totalCount(), nullptr); while ((entry_num < _eocd.totalCount())) { - zipios::ZipCDirEntry *ent = new zipios::ZipCDirEntry; + zipios::ZipCDirEntry* ent = new zipios::ZipCDirEntry; _entries[entry_num] = ent; _zipfile >> *ent; if (!_zipfile) { - if (_zipfile.bad()) - throw zipios::IOException("Error reading zip file while reading zip file central directory"); - else if (_zipfile.fail()) - throw zipios::FCollException("Zip file consistency problem. Failure while reading zip file central directory"); - else if (_zipfile.eof()) - throw zipios::IOException("Premature end of file while reading zip file central directory"); + if (_zipfile.bad()) { + throw zipios::IOException( + "Error reading zip file while reading zip file central directory"); + } + else if (_zipfile.fail()) { + throw zipios::FCollException("Zip file consistency problem. Failure while reading " + "zip file central directory"); + } + else if (_zipfile.eof()) { + throw zipios::IOException( + "Premature end of file while reading zip file central directory"); + } } ++entry_num; } @@ -114,18 +127,22 @@ bool ZipHeader::readCentralDirectory(std::istream &_zipfile) int pos = _vs.vtellg(_zipfile); _vs.vseekg(_zipfile, 0, std::ios::end); int remaining = static_cast(_vs.vtellg(_zipfile)) - pos; - if (remaining != _eocd.eocdOffSetFromEnd()) - throw zipios::FCollException("Zip file consistency problem. Zip file data fields are inconsistent with zip file layout"); + if (remaining != _eocd.eocdOffSetFromEnd()) { + throw zipios::FCollException("Zip file consistency problem. Zip file data fields are " + "inconsistent with zip file layout"); + } // Consistency check 2, are local headers consistent with // cd headers - if (!confirmLocalHeaders(_zipfile)) - throw zipios::FCollException("Zip file consistency problem. Zip file data fields are inconsistent with zip file layout"); + if (!confirmLocalHeaders(_zipfile)) { + throw zipios::FCollException("Zip file consistency problem. Zip file data fields are " + "inconsistent with zip file layout"); + } return true; } -bool ZipHeader::readEndOfCentralDirectory(std::istream &_zipfile) +bool ZipHeader::readEndOfCentralDirectory(std::istream& _zipfile) { zipios::BackBuffer bb(_zipfile, _vs); int read_p = -1; @@ -147,14 +164,14 @@ bool ZipHeader::readEndOfCentralDirectory(std::istream &_zipfile) return found; } -bool ZipHeader::confirmLocalHeaders(std::istream &_zipfile) +bool ZipHeader::confirmLocalHeaders(std::istream& _zipfile) { zipios::Entries::const_iterator it; - zipios::ZipCDirEntry *ent{}; + zipios::ZipCDirEntry* ent {}; int inconsistencies = 0; zipios::ZipLocalEntry zlh; for (it = _entries.begin(); it != _entries.end(); ++it) { - ent = static_cast((*it).get()); + ent = static_cast((*it).get()); _vs.vseekg(_zipfile, ent->getLocalHeaderOffset(), std::ios::beg); _zipfile >> zlh; if (!_zipfile || zlh != *ent) { diff --git a/src/Base/ZipHeader.h b/src/Base/ZipHeader.h index 876d519de8..c450c58004 100644 --- a/src/Base/ZipHeader.h +++ b/src/Base/ZipHeader.h @@ -35,7 +35,8 @@ namespace zipios * The class is similar to zipios' ZipFile class with the difference that instead of * a file a std::istream can be passed. */ -class BaseExport ZipHeader : public FileCollection { +class BaseExport ZipHeader: public FileCollection +{ public: /** Opens the zip file name. If the zip "file" is embedded in a file that contains other data, e.g. a binary @@ -51,32 +52,31 @@ public: archive. @throw IOException Thrown if an I/O problem is encountered, while the directory of the specified zip archive is being read. */ - explicit ZipHeader(std::istream &inp, int s_off = 0, int e_off = 0); + explicit ZipHeader(std::istream& inp, int s_off = 0, int e_off = 0); /** Create a copy of this instance. */ - FileCollection *clone() const override; + FileCollection* clone() const override; ~ZipHeader() override = default; void close() override; - std::istream *getInputStream(const ConstEntryPointer &entry) override; - std::istream *getInputStream(const string &entry_name, MatchPath matchpath = MATCH) override; + std::istream* getInputStream(const ConstEntryPointer& entry) override; + std::istream* getInputStream(const string& entry_name, MatchPath matchpath = MATCH) override; private: std::istream& _input; VirtualSeeker _vs; - EndOfCentralDirectory _eocd; + EndOfCentralDirectory _eocd; - bool init(std::istream &_zipfile); - bool readCentralDirectory(std::istream &_zipfile); - bool readEndOfCentralDirectory(std::istream &_zipfile); - bool confirmLocalHeaders(std::istream &_zipfile); + bool init(std::istream& _zipfile); + bool readCentralDirectory(std::istream& _zipfile); + bool readEndOfCentralDirectory(std::istream& _zipfile); + bool confirmLocalHeaders(std::istream& _zipfile); void setError(std::string error_str); }; -} //namespace zipios +} // namespace zipios -#endif // ZIPIOS_ZIP_HEADER_H - +#endif // ZIPIOS_ZIP_HEADER_H diff --git a/src/Base/swigpyrun.cpp b/src/Base/swigpyrun.cpp index 370247bfb6..3213ad2a48 100644 --- a/src/Base/swigpyrun.cpp +++ b/src/Base/swigpyrun.cpp @@ -25,27 +25,27 @@ #include #if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-register" -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined (__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmissing-field-initializers" -# if __GNUC__ >= 8 -# pragma GCC diagnostic ignored "-Wcast-function-type" -# endif +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-register" +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#if __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif #endif #include "PyExport.h" #include "Exception.h" -namespace Swig_python { +namespace Swig_python +{ #define SWIG_PYTHON_NO_BUILD_NONE #include #include "swigpyrun.inl" -} +} // namespace Swig_python #if defined(__clang__) -# pragma clang diagnostic pop -#elif defined (__GNUC__) -# pragma GCC diagnostic pop +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop #endif -#endif // HAVE_SWIG - +#endif // HAVE_SWIG diff --git a/src/Base/swigpyrun.inl b/src/Base/swigpyrun.inl index 87bcce5dd1..83ed217eba 100644 --- a/src/Base/swigpyrun.inl +++ b/src/Base/swigpyrun.inl @@ -23,21 +23,23 @@ int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own) { - swig_module_info *module = SWIG_GetModule(nullptr); - if (!module) + swig_module_info* module = SWIG_GetModule(nullptr); + if (!module) { return 1; + } - swig_type_info * swig_type = nullptr; + swig_type_info* swig_type = nullptr; swig_type = SWIG_TypeQuery(TypeName); if (!swig_type) { std::stringstream str; str << "SWIG: Cannot find type information for requested type: " << TypeName; throw Base::RuntimeError(str.str()); } - + *ptr = SWIG_NewPointerObj(obj, swig_type, own); - if (!*ptr) + if (!*ptr) { throw Base::RuntimeError("Cannot convert into requested type"); + } // success return 0; @@ -45,19 +47,22 @@ int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags) { - swig_module_info *module = SWIG_GetModule(nullptr); - if (!module) + swig_module_info* module = SWIG_GetModule(nullptr); + if (!module) { return 1; + } - swig_type_info * swig_type = nullptr; + swig_type_info* swig_type = nullptr; swig_type = SWIG_TypeQuery(TypeName); - if (!swig_type) + if (!swig_type) { throw Base::RuntimeError("Cannot find type information for requested type"); + } // return value of 0 is on success - if (SWIG_ConvertPtr(obj, ptr, swig_type, flags)) + if (SWIG_ConvertPtr(obj, ptr, swig_type, flags)) { throw Base::RuntimeError("Cannot convert into requested type"); + } // success return 0; @@ -65,17 +70,19 @@ int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int void cleanupSWIG_T(const char* TypeName) { - swig_module_info *swig_module = SWIG_GetModule(nullptr); - if (!swig_module) + swig_module_info* swig_module = SWIG_GetModule(nullptr); + if (!swig_module) { return; + } - swig_type_info * swig_type = nullptr; + swig_type_info* swig_type = nullptr; swig_type = SWIG_TypeQuery(TypeName); - if (!swig_type) + if (!swig_type) { return; + } - PyObject *module{}, *dict{}; - PyObject *modules = PyImport_GetModuleDict(); + PyObject *module {}, *dict {}; + PyObject* modules = PyImport_GetModuleDict(); module = PyDict_GetItemString(modules, "__builtin__"); if (module && PyModule_Check(module)) { dict = PyModule_GetDict(module); @@ -85,16 +92,19 @@ void cleanupSWIG_T(const char* TypeName) module = PyDict_GetItemString(modules, "__main__"); if (module && PyModule_Check(module)) { PyObject* dict = PyModule_GetDict(module); - if (!dict) return; + if (!dict) { + return; + } - Py_ssize_t pos{}; - PyObject *key{}, *value{}; + Py_ssize_t pos {}; + PyObject *key {}, *value {}; pos = 0; while (PyDict_Next(dict, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { void* ptr = nullptr; - if (SWIG_ConvertPtr(value, &ptr, nullptr, 0) == 0) + if (SWIG_ConvertPtr(value, &ptr, nullptr, 0) == 0) { PyDict_SetItem(dict, key, Py_None); + } } } } @@ -105,19 +115,22 @@ void cleanupSWIG_T(const char* TypeName) int getSWIGPointerTypeObj_T(const char* TypeName, PyTypeObject** ptr) { - swig_module_info *module = SWIG_GetModule(nullptr); - if (!module) + swig_module_info* module = SWIG_GetModule(nullptr); + if (!module) { return 1; + } - swig_type_info * swig_type = nullptr; + swig_type_info* swig_type = nullptr; SwigPyClientData* clientData = nullptr; PyTypeObject* pyType = nullptr; swig_type = SWIG_TypeQuery(TypeName); - if (swig_type) + if (swig_type) { clientData = static_cast(swig_type->clientdata); + } - if (clientData) + if (clientData) { pyType = reinterpret_cast(clientData->newargs); + } if (!pyType) { std::stringstream str;