From 58e6d22339386787d4e51d092ef8cba083f095f2 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Thu, 17 Jan 2019 20:29:44 +0100 Subject: [PATCH 01/51] Added Ellipse generator --- swGeometrics/BasicShapes/Shapes2D/Ellipse.h | 57 +++++++++ swGeometrics/BasicShapes/Shapes2D/Ellipse.inl | 115 ++++++++++++++++++ .../BasicShapes/BasicShapes.vcxproj | 2 + .../BasicShapes/BasicShapes.vcxproj.filters | 6 + .../TestBasicShapes/TestBasicShapes.vcxproj | 1 + .../Tests/TestBasicShapes/TestEllipse.cpp | 104 ++++++++++++++++ 6 files changed, 285 insertions(+) create mode 100644 swGeometrics/BasicShapes/Shapes2D/Ellipse.h create mode 100644 swGeometrics/BasicShapes/Shapes2D/Ellipse.inl create mode 100644 swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp diff --git a/swGeometrics/BasicShapes/Shapes2D/Ellipse.h b/swGeometrics/BasicShapes/Shapes2D/Ellipse.h new file mode 100644 index 00000000..90274caf --- /dev/null +++ b/swGeometrics/BasicShapes/Shapes2D/Ellipse.h @@ -0,0 +1,57 @@ +#pragma once +/** +@file Ellipse.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + + +#include "swCommonLib/Common/TypesDefinitions.h" +#include "swGeometrics/GeometricsCore/Types/Accessors/DefaultAccessors.h" +#include "swGeometrics/GeometricsCore/Types/Traits/GeneratorTraits.h" + + + + +namespace sw { +namespace geom +{ + + + +/**@brief Ellipse generator. +@ingroup Shapes2D*/ +template< typename VertexType, typename IndexType, typename PositionAcc = DefaultPositionAcc< VertexType > > +class Ellipse : public GeneratorTraits< VertexType, IndexType > +{ +private: +public: + + float Width; + float Height; + uint32 Tesselation; + +public: + + inline explicit Ellipse (); + + + inline void GenerateVertex ( VertexType& vertex, Size vertexIdx ); + + template< class IndexBuffer > + inline void GenerateIndexBuffer ( IndexBuffer& idxBuffer, Size startIdx ); + + inline Size GetNumberVerticies () const; + inline Size GetNumberIndicies () const; + + inline ReturnResult ValidateParams () const; + +}; + + + +} // geom +} // sw + +#include "Ellipse.inl" diff --git a/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl b/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl new file mode 100644 index 00000000..5a6b3bc3 --- /dev/null +++ b/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl @@ -0,0 +1,115 @@ +#pragma once +/** +@file Ellipse.inl +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "Ellipse.h" + +#include "swCommonLib/Common/Converters.h" +#include "swCommonLib/Common/Exceptions/ErrorsCollector.h" + +#define _USE_MATH_DEFINES +#include + + + +namespace sw { +namespace geom +{ + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Ellipse< VertexType, IndexType, PositionAcc >::Ellipse () + : Tesselation( 10 ) + , Width( 1.0f ) + , Height( 1.0f ) +{} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline void Ellipse< VertexType, IndexType, PositionAcc >::GenerateVertex ( VertexType& vertex, Size vertexIdx ) +{ + float angleDelta = float( 2 * M_PI / Tesselation ); + float angle = angleDelta * vertexIdx; + + auto& pos = PositionAcc::Get( vertex ); + pos.x = Width * sinf( angle ); + pos.y = Height * cosf( angle ); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +template< class IndexBuffer > +inline void Ellipse< VertexType, IndexType, PositionAcc >::GenerateIndexBuffer ( IndexBuffer& idxBuffer, Size startIdx ) +{ + IndexType numVerts = (IndexType)GetNumberVerticies(); + IndexType rightIdx = 1; + IndexType leftIdx = numVerts - 1; // Last vertex. + + // Add top triangle without pair. + AddTriangleCW( idxBuffer, startIdx, 0, rightIdx, leftIdx ); + + // Add pairs of triangles from left to right side of circle. + while( leftIdx - rightIdx > 3 ) + { + AddTriangleCW( idxBuffer, startIdx, leftIdx, rightIdx, leftIdx - 1 ); + AddTriangleCW( idxBuffer, startIdx, leftIdx - 1, rightIdx, rightIdx + 1 ); + + rightIdx++; + leftIdx--; + } + + // If there's one vertex left, we need to add one triangle else. Note that if + // we have even number of verticies, two last verticies were already used to create two traingles + // in previous while loop. + if( leftIdx - rightIdx == 2 ) + AddTriangleCW( idxBuffer, startIdx, leftIdx, rightIdx, leftIdx - 1 ); +} + + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size Ellipse< VertexType, IndexType, PositionAcc >::GetNumberVerticies () const +{ + return Tesselation; +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size Ellipse< VertexType, IndexType, PositionAcc >::GetNumberIndicies () const +{ + return 3 * ( Tesselation - 2 ); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline ReturnResult Ellipse< VertexType, IndexType, PositionAcc >::ValidateParams () const +{ + ErrorsCollector collector; + + if( Tesselation <= 2 ) + collector.Add( "[Circle] Invalid parameter [Tesselation=" + Convert::ToString( Tesselation ) + "] should be greater then 2." ); + + if( Width <= 0.0f ) + collector.Add( "[Circle] Invalid parameter [Width=" + Convert::ToString( Width ) + "] should be greater then 0." ); + + if( Height <= 0.0f ) + collector.Add( "[Circle] Invalid parameter [Width=" + Convert::ToString( Height ) + "] should be greater then 0." ); + + return collector; +} + + + +} // geom +} // sw + + diff --git a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj index 11abb78f..5ae0001f 100644 --- a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj +++ b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj @@ -29,6 +29,7 @@ + @@ -43,6 +44,7 @@ + diff --git a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters index 9b8a0c43..948931dd 100644 --- a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters +++ b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters @@ -32,6 +32,9 @@ Shapes2D + + Shapes2D + @@ -43,5 +46,8 @@ Shapes2D + + Shapes2D + \ No newline at end of file diff --git a/swGeometrics/ProjectDir/Visual2015/Tests/TestBasicShapes/TestBasicShapes.vcxproj b/swGeometrics/ProjectDir/Visual2015/Tests/TestBasicShapes/TestBasicShapes.vcxproj index 372d9ccb..5be81980 100644 --- a/swGeometrics/ProjectDir/Visual2015/Tests/TestBasicShapes/TestBasicShapes.vcxproj +++ b/swGeometrics/ProjectDir/Visual2015/Tests/TestBasicShapes/TestBasicShapes.vcxproj @@ -28,6 +28,7 @@ + diff --git a/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp b/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp new file mode 100644 index 00000000..68c4e64d --- /dev/null +++ b/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp @@ -0,0 +1,104 @@ +#include "swCommonLib/External/Catch/catch.hpp" + + +#include "swGeometrics/GeometricsCore/Generators/Generator.h" +#include "swGeometrics/GeometricsCore/Types/VertexLayouts/VertexShape2D.h" +#include "swGeometrics/GeometricsCore/Types/IndexTypes.h" + +#include "swGeometrics/BasicShapes/Shapes2D/Ellipse.h" + + +using namespace sw; +using namespace sw::geom; + + +//====================================================================================// +// Helper functions +//====================================================================================// + +// ================================ // +// Defined in TestCircle.cpp +bool IsOnCircle ( const DirectX::XMFLOAT2& vertex, float radius ); + +// ================================ // +// +bool IsEllipse ( const std::vector< VertexShape2D >& verticies, float width, float height ) +{ + bool isCircle = true; + for( auto& vertex : verticies ) + { + auto scaleToCircle = DirectX::XMFLOAT2( vertex.Position.x / width, vertex.Position.y / height ); + if( !IsOnCircle( scaleToCircle, 1.0f ) ) + return false; + } + + return true; +} + + +// ================================ // +// +TEST_CASE( "Geometrics.BasicShapes.Ellipse.EvenTesselation", "[Geometrics][BasicShapes]" ) +{ + Ellipse< VertexShape2D, Index16 > ellipse; + ellipse.Width = 2.5f; + ellipse.Height = 0.5f; + ellipse.Tesselation = 30; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).Get(); + + CHECK( geometry.Verticies.size() == 30 ); + CHECK( geometry.Indicies.size() == 84 ); + + bool isCircle = IsEllipse( geometry.Verticies, 2.5f, 0.5f ); + CHECK( isCircle == true ); +} + +// ================================ // +// +TEST_CASE( "Geometrics.BasicShapes.Ellipse.OddTesselation", "[Geometrics][BasicShapes]" ) +{ + Ellipse< VertexShape2D, Index16 > ellipse; + ellipse.Width = 1.0f; + ellipse.Height = 4.0f; + ellipse.Tesselation = 31; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).Get(); + + CHECK( geometry.Verticies.size() == 31 ); + CHECK( geometry.Indicies.size() == 87 ); + + bool isCircle = IsEllipse( geometry.Verticies, 1.0f, 4.0f ); + CHECK( isCircle == true ); +} + +// ================================ // +// Circle should have Tesselation parameter set at least to 3. +TEST_CASE( "Geometrics.BasicShapes.Ellipse.ToLowTesselation", "[Geometrics][BasicShapes]" ) +{ + Ellipse< VertexShape2D, Index16 > ellipse; + ellipse.Width = 2.5f; + ellipse.Height = 0.5f; + ellipse.Tesselation = 0; + + CHECK( Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).IsValid() == false ); + + ellipse.Tesselation = 1; + CHECK( Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).IsValid() == false ); + + ellipse.Tesselation = 2; + CHECK( Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).IsValid() == false ); +} + + +// ================================ // +// Radius should be greater then 0. +TEST_CASE( "Geometrics.BasicShapes.Ellipse.NegativeRadius", "[Geometrics][BasicShapes]" ) +{ + Ellipse< VertexShape2D, Index16 > ellipse; + ellipse.Width = 2.5f; + ellipse.Height = 0.5f; + ellipse.Tesselation = 10; + + CHECK( Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).IsValid() == false ); +} From ca85bf97ed1fb03b937b622db63055aee33f3046 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Thu, 17 Jan 2019 23:28:22 +0100 Subject: [PATCH 02/51] Fix deinitialization order --- swGUI/Core/System/GUISystem.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/swGUI/Core/System/GUISystem.cpp b/swGUI/Core/System/GUISystem.cpp index 17637bf5..a46f1d77 100644 --- a/swGUI/Core/System/GUISystem.cpp +++ b/swGUI/Core/System/GUISystem.cpp @@ -66,6 +66,8 @@ GUISystem::~GUISystem() for( auto window : m_windows ) delete window; + m_renderingSystem.release(); + m_graphicApi->ReleaseAPI(); delete m_resourceManager; delete m_graphicApi; From c846c2646f6198aceb3a557734f653dc06517401 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Fri, 18 Jan 2019 20:03:58 +0100 Subject: [PATCH 03/51] Added Ellipse control --- swGUI/Core/Controls/Shapes/Ellipse.cpp | 67 +++++++++ swGUI/Core/Controls/Shapes/Ellipse.h | 49 +++++++ swGUI/Core/Media/Geometry/EllipseGeometry.cpp | 136 ++++++++++++++++++ swGUI/Core/Media/Geometry/EllipseGeometry.h | 54 +++++++ .../Visual2015/CoreGUI/CoreGUI.vcxproj | 4 + .../CoreGUI/CoreGUI.vcxproj.filters | 12 ++ .../Prototypes/PrototyperGUI/Application.cpp | 30 +++- .../PrototyperGUI/Sizeofs/Sizeofs.cpp | 4 +- swGeometrics/BasicShapes/Shapes2D/Ellipse.h | 3 + swGeometrics/BasicShapes/Shapes2D/Ellipse.inl | 12 +- .../BasicShapes/Shapes2D/EllipseWithBorder.h | 55 +++++++ .../Shapes2D/EllipseWithBorder.inl | 111 ++++++++++++++ .../BasicShapes/BasicShapes.vcxproj | 2 + .../BasicShapes/BasicShapes.vcxproj.filters | 6 + .../Tests/TestBasicShapes/TestEllipse.cpp | 6 +- 15 files changed, 542 insertions(+), 9 deletions(-) create mode 100644 swGUI/Core/Controls/Shapes/Ellipse.cpp create mode 100644 swGUI/Core/Controls/Shapes/Ellipse.h create mode 100644 swGUI/Core/Media/Geometry/EllipseGeometry.cpp create mode 100644 swGUI/Core/Media/Geometry/EllipseGeometry.h create mode 100644 swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h create mode 100644 swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.inl diff --git a/swGUI/Core/Controls/Shapes/Ellipse.cpp b/swGUI/Core/Controls/Shapes/Ellipse.cpp new file mode 100644 index 00000000..07702e9a --- /dev/null +++ b/swGUI/Core/Controls/Shapes/Ellipse.cpp @@ -0,0 +1,67 @@ +/** +@file Ellipse.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ +#include "swGUI/Core/stdafx.h" + +#include "Ellipse.h" +#include "swGUI/Core/Media/Geometry/EllipseGeometry.h" + + +namespace sw { +namespace gui +{ + + +// ================================ // +// +Ellipse::Ellipse() + : m_width( 100 ) + , m_height( 100 ) + , m_strokeThickness( 1 ) +{ + auto rectGeom = std::make_shared< EllipseGeometry >(); + rectGeom->SetWidth( m_width ); + rectGeom->SetHeight( m_height ); + rectGeom->SetThickness( m_strokeThickness ); + + SetGeometry( rectGeom ); +} + +// ================================ // +// +void Ellipse::SetWidth ( float width ) +{ + m_width = width; + + auto geom = std::static_pointer_cast< EllipseGeometry >( GetGeometry() ); + geom->SetWidth( m_width ); +} + +// ================================ // +// +void Ellipse::SetHeight ( float height ) +{ + m_height = height; + + auto geom = std::static_pointer_cast< EllipseGeometry >( GetGeometry() ); + geom->SetHeight( m_height ); +} + +// ================================ // +// +void Ellipse::SetThickness ( float thickness ) +{ + m_strokeThickness = thickness; + + auto geom = std::static_pointer_cast< EllipseGeometry >( GetGeometry() ); + geom->SetThickness( m_strokeThickness ); +} + + + +} // gui +} // sw + + diff --git a/swGUI/Core/Controls/Shapes/Ellipse.h b/swGUI/Core/Controls/Shapes/Ellipse.h new file mode 100644 index 00000000..fee57f60 --- /dev/null +++ b/swGUI/Core/Controls/Shapes/Ellipse.h @@ -0,0 +1,49 @@ +#pragma once +/** +@file Ellipse.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "Shape.h" + + + + +namespace sw { +namespace gui +{ + +/**@brief Draws ellipse shape. +@ingroup Shapes +@ingroup Controls*/ +class Ellipse : public Shape +{ + RTTR_ENABLE( Shape ); + RTTR_REGISTRATION_FRIEND; +private: + + float m_width; ///< Remove in future. This should be implemented in ArrangeCore. + float m_height; ///< Remove in future. This should be implemented in ArrangeCore. + float m_strokeThickness; + +protected: +public: + + explicit Ellipse (); + virtual ~Ellipse () = default; + + + void SetWidth ( float width ); + void SetHeight ( float height ); + void SetThickness ( float thickness ); + +}; + +DEFINE_OPTR_TYPE( Ellipse ); + + +} // gui +} // sw + + diff --git a/swGUI/Core/Media/Geometry/EllipseGeometry.cpp b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp new file mode 100644 index 00000000..9c24df2b --- /dev/null +++ b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp @@ -0,0 +1,136 @@ +/** +@file EllipseGeometry.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ +#include "swGUI/Core/stdafx.h" + +#include "EllipseGeometry.h" + +#include "swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h" +#include "swGeometrics/BasicShapes/CoordsUV/PlanarUV.h" +#include "swGeometrics/GeometricsCore/Generators/Generator.h" + +#include "swGUI/Core/Media/Geometry/Layouts/VertexShape2D.h" +#include "swCommonLib/Common/Buffers/IndexedGeometryBuffer.h" + +#include "swCommonLib/Common/Converters.h" + + +namespace sw { +namespace gui +{ + +// ================================ // +// +EllipseGeometry::EllipseGeometry() + : Geometry( Geometry::ConstantBufferMode::Disable ) +{} + +// ================================ // +// +void EllipseGeometry::SetWidth ( float width ) +{ + m_width = width; + InvalidateGeometry(); +} + +// ================================ // +// +void EllipseGeometry::SetHeight ( float height ) +{ + m_height = height; + InvalidateGeometry(); +} + +// ================================ // +// +void EllipseGeometry::SetThickness ( float thickness ) +{ + m_strokeThickness = thickness; + InvalidateGeometry(); +} + +// ================================ // +// +bool EllipseGeometry::HitTest ( const Point& point ) +{ + if( pow( point.x / ( m_width / 2.0f ), 2 ) + pow( point.y / ( m_height / 2.0f ), 2 ) < 1.0f ) + return true; + + return false; +} + +// ================================ // +// +bool EllipseGeometry::HitTest ( const Rect& rectangle ) +{ + assert( !"Implement me" ); + return false; +} + +// ================================ // +// +GeometryData EllipseGeometry::Generate () +{ + geom::EllipseWithBorder< VertexShape2D, Index16 > ellipse; + ellipse.Width = m_width; + ellipse.Height = m_height; + ellipse.StrokeThickness = m_strokeThickness; + ellipse.Tesselation = 100;/// 2 * ( m_width + m_height ); + + geom::PlanarUV< VertexShape2D > planarUV; + planarUV.MinX = 0.0f; + planarUV.MinY = -m_height; + planarUV.MaxX = m_width; + planarUV.MaxY = 0.0f; + + auto geometry = geom::Generate< geom::IndexedGeometryBuffer< VertexShape2D, Index16 > >( ellipse, planarUV ); + /// @todo Error handling or logging. + + GeometryData geomData( geometry.Get().Verticies.MoveToRawBuffer(), geometry.Get().Indicies.MoveToRawBuffer() ); + geomData.FillIdxEnd = (uint32)ellipse.GetNumberFillIndicies(); + geomData.BorderIdxEnd = (uint32)ellipse.GetNumberFillIndicies() + (uint32)ellipse.GetNumberBorderIndicies(); + geomData.ExtendedIB = false; + geomData.Topology = PrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLELIST; + + return std::move( geomData ); +} + +// ================================ // +// +BufferRange EllipseGeometry::BufferData () +{ + // Rectangle doesn't use contants buffer. + return BufferRange(); +} + +// ================================ // +// +std::string EllipseGeometry::ShaderFunctionFile () +{ + return "$(CoreGUI-Shader-Dir)/Geometry/ForwardAttributes.vsh"; +} + +// ================================ // +// +std::wstring EllipseGeometry::GeometryName () +{ + std::string geomName = "EllipseGeometry-[Width=" + + Convert::ToString( m_width ) + "][Height=" + + Convert::ToString( m_height ) + "][StrokeThickness=" + + Convert::ToString( m_strokeThickness ) + "]"; + + return Convert::FromString< std::wstring >( geomName, L"" ); +} + +// ================================ // +// +std::wstring EllipseGeometry::ConstantsName () +{ + // Rectangle doesn't use contants buffer. + return std::wstring(); +} + +} // gui +} // sw diff --git a/swGUI/Core/Media/Geometry/EllipseGeometry.h b/swGUI/Core/Media/Geometry/EllipseGeometry.h new file mode 100644 index 00000000..684c33bc --- /dev/null +++ b/swGUI/Core/Media/Geometry/EllipseGeometry.h @@ -0,0 +1,54 @@ +#pragma once +/** +@file EllipseGeometry.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "swGUI/Core/Media/Geometry/Geometry.h" + + +namespace sw { +namespace gui +{ + + +/**@brief Generates Ellipse. +@ingroup Geometries*/ +class EllipseGeometry : public Geometry +{ +private: +protected: + + float m_width; + float m_height; + float m_strokeThickness; + +public: + + explicit EllipseGeometry (); + virtual ~EllipseGeometry () = default; + + void SetWidth ( float width ); + void SetHeight ( float height ); + void SetThickness ( float thickness ); + +public: + + // Inherited via Geometry + virtual bool HitTest ( const Point& point ) override; + virtual bool HitTest ( const Rect& rectangle ) override; + virtual GeometryData Generate () override; + virtual BufferRange BufferData () override; + virtual std::string ShaderFunctionFile () override; + virtual std::wstring GeometryName () override; + virtual std::wstring ConstantsName () override; + +}; + + + +} // gui +} // sw + + diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj index bee7d41e..dfcdd2f8 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj @@ -134,6 +134,7 @@ + @@ -145,6 +146,7 @@ + @@ -206,12 +208,14 @@ + + diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters index ebb04e36..5625673e 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters @@ -321,6 +321,12 @@ Core\Media\Geometry + + Core\Media\Geometry + + + Core\Controls\Shapes + @@ -458,6 +464,12 @@ Core\Controls\Shapes + + Core\Media\Geometry + + + Core\Controls\Shapes + diff --git a/swGUI/Prototypes/PrototyperGUI/Application.cpp b/swGUI/Prototypes/PrototyperGUI/Application.cpp index 0724c249..3aaaf12a 100644 --- a/swGUI/Prototypes/PrototyperGUI/Application.cpp +++ b/swGUI/Prototypes/PrototyperGUI/Application.cpp @@ -1,6 +1,7 @@ #include "Application.h" #include "swGUI/Core/Controls/Shapes/Rectangle.h" +#include "swGUI/Core/Controls/Shapes/Ellipse.h" #include "swGUI/Core/Media/Brushes/SolidColorBrush.h" #include "PrototyperUtils.h" @@ -40,10 +41,28 @@ void AddRectangle ( HostWindow* host, BrushPtr brush, BrushPtr stroke, floa host->AddChild( std::move( rectangleControl ) ); } +// ================================ // +// +void AddEllipse ( HostWindow* host, BrushPtr brush, BrushPtr stroke, float width, float height, float broderThickness, Position pos ) +{ + EllipseOPtr ellipseControl = EllipseOPtr( new Ellipse() ); + + ellipseControl->SetFill( brush ); + ellipseControl->SetStroke( stroke ); + + ellipseControl->SetHeight( height ); + ellipseControl->SetWidth( width ); + ellipseControl->SetThickness( broderThickness ); + + ellipseControl->SetOffset( pos ); + + host->AddChild( std::move( ellipseControl ) ); +} + // ================================ // // -void AddRectangle ( HostWindow* host ) +void AddControls ( HostWindow* host ) { RectangleOPtr rectangleControl = RectangleOPtr( new Rectangle() ); @@ -61,6 +80,11 @@ void AddRectangle ( HostWindow* host ) stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 1.0, 0.0, 1.0 ) ); AddRectangle( host, stroke, brush, 100, 768, 2, Position( 400, 0 ) ); + + brush = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 1.0, 1.0 ) ); + stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); + + AddEllipse( host, stroke, brush, 100, 200, 8, Position( 200, 300 ) ); } @@ -109,8 +133,8 @@ bool Application::OnInitialized() window->PreviewMouseMove() += MouseMoveEventHandler( &MouseMoveEventReceived ); m_windows[ 0 ]->PreviewMouseMove() += MouseMoveEventHandler( &MouseMoveEventReceived ); - //AddRectangle( window ); - AddRectangle( m_windows[ 0 ] ); + //AddControls( window ); + AddControls( m_windows[ 0 ] ); return true; } diff --git a/swGUI/Prototypes/PrototyperGUI/Sizeofs/Sizeofs.cpp b/swGUI/Prototypes/PrototyperGUI/Sizeofs/Sizeofs.cpp index 98d67e40..519a80a5 100644 --- a/swGUI/Prototypes/PrototyperGUI/Sizeofs/Sizeofs.cpp +++ b/swGUI/Prototypes/PrototyperGUI/Sizeofs/Sizeofs.cpp @@ -15,6 +15,7 @@ #include "swGUI/Core/Controls/Visual.h" #include "swGUI/Core/Controls/Shapes/Rectangle.h" +#include "swGUI/Core/Controls/Shapes/Ellipse.h" #include "swGUI/Core/System/DataBinding/BindingInfo.h" @@ -70,7 +71,8 @@ void PrintControlsSizeofs () PrintSizeofType< sw::gui::Shape >( std::cout ); PrintSizeofType< sw::gui::Rectangle >( std::cout ); - + PrintSizeofType< sw::gui::Ellipse >( std::cout ); + std::cout << std::endl; } diff --git a/swGeometrics/BasicShapes/Shapes2D/Ellipse.h b/swGeometrics/BasicShapes/Shapes2D/Ellipse.h index 90274caf..d4bfdbc1 100644 --- a/swGeometrics/BasicShapes/Shapes2D/Ellipse.h +++ b/swGeometrics/BasicShapes/Shapes2D/Ellipse.h @@ -47,6 +47,9 @@ class Ellipse : public GeneratorTraits< VertexType, IndexType > inline ReturnResult ValidateParams () const; +protected: + + inline void GenerateVertex ( VertexType& vertex, Size vertexIdx, float width, float height ); }; diff --git a/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl b/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl index 5a6b3bc3..1edb91f9 100644 --- a/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl +++ b/swGeometrics/BasicShapes/Shapes2D/Ellipse.inl @@ -32,13 +32,21 @@ inline Ellipse< VertexType, IndexType, PositionAcc >::Ellipse () // template< typename VertexType, typename IndexType, typename PositionAcc > inline void Ellipse< VertexType, IndexType, PositionAcc >::GenerateVertex ( VertexType& vertex, Size vertexIdx ) +{ + GenerateVertex( vertex, vertexIdx, Width, Height ); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline void Ellipse< VertexType, IndexType, PositionAcc >::GenerateVertex ( VertexType& vertex, Size vertexIdx, float width, float height ) { float angleDelta = float( 2 * M_PI / Tesselation ); float angle = angleDelta * vertexIdx; auto& pos = PositionAcc::Get( vertex ); - pos.x = Width * sinf( angle ); - pos.y = Height * cosf( angle ); + pos.x = width * sinf( angle ) / 2.0f; + pos.y = height * cosf( angle ) / 2.0f; } // ================================ // diff --git a/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h b/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h new file mode 100644 index 00000000..3a027130 --- /dev/null +++ b/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h @@ -0,0 +1,55 @@ +#pragma once +/** +@file EllipseWithBorder.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "Ellipse.h" + + +namespace sw { +namespace geom +{ + + + + +/**@brief Ellipse with border generator for GUI. +@ingroup Shapes2D*/ +template< typename VertexType, typename IndexType, typename PositionAcc = DefaultPositionAcc< VertexType > > +class EllipseWithBorder : public Ellipse< VertexType, IndexType, PositionAcc > +{ +private: + + typedef Ellipse< VertexType, IndexType, PositionAcc > Parent; + +public: + + float StrokeThickness; + +public: + + inline explicit EllipseWithBorder (); + + + inline void GenerateVertex ( VertexType& vertex, Size vertexIdx ); + + template< class IndexBuffer > + inline void GenerateIndexBuffer ( IndexBuffer& idxBuffer, Size startIdx ); + + inline Size GetNumberVerticies () const; + inline Size GetNumberIndicies () const; + + inline Size GetNumberFillIndicies () const; + inline Size GetNumberBorderIndicies () const; + + inline ReturnResult ValidateParams () const; + +}; + + +} // geom +} // sw + +#include "EllipseWithBorder.inl" diff --git a/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.inl b/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.inl new file mode 100644 index 00000000..f619386f --- /dev/null +++ b/swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.inl @@ -0,0 +1,111 @@ +#pragma once +/** +@file EllipseWithBorder.inl +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "EllipseWithBorder.h" + + + + +namespace sw { +namespace geom +{ + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline EllipseWithBorder< VertexType, IndexType, PositionAcc >::EllipseWithBorder () + : StrokeThickness( 0 ) +{} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline void EllipseWithBorder< VertexType, IndexType, PositionAcc >::GenerateVertex ( VertexType& vertex, Size vertexIdx ) +{ + if( vertexIdx < Parent::GetNumberVerticies() ) + Parent::GenerateVertex( vertex, vertexIdx, Width, Height ); + else + Parent::GenerateVertex( vertex, vertexIdx, Width - 2 * StrokeThickness, Height - 2 * StrokeThickness ); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +template< class IndexBuffer > +inline void EllipseWithBorder< VertexType, IndexType, PositionAcc >::GenerateIndexBuffer ( IndexBuffer& idxBuffer, Size startIdx ) +{ + Parent::GenerateIndexBuffer( idxBuffer, startIdx ); + + startIdx += Parent::GetNumberIndicies(); + IndexType borderOffset = (IndexType)Parent::GetNumberVerticies(); + + IndexType idx = 0; + for( ; idx < Parent::GetNumberVerticies() - 1; ++idx ) + { + AddTriangleCW( idxBuffer, startIdx, idx + borderOffset, idx, idx + borderOffset + 1 ); + AddTriangleCW( idxBuffer, startIdx, idx + borderOffset + 1, idx, idx + 1 ); + } + + // Last triangles reference last and first vertex. + AddTriangleCW( idxBuffer, startIdx, idx + borderOffset, idx, borderOffset ); + AddTriangleCW( idxBuffer, startIdx, borderOffset, idx, 0 ); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size EllipseWithBorder< VertexType, IndexType, PositionAcc >::GetNumberVerticies () const +{ + return 2 * Parent::GetNumberVerticies(); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size EllipseWithBorder< VertexType, IndexType, PositionAcc >::GetNumberIndicies () const +{ + return Parent::GetNumberIndicies() + GetNumberBorderIndicies(); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size EllipseWithBorder< VertexType, IndexType, PositionAcc >::GetNumberFillIndicies () const +{ + return Parent::GetNumberIndicies(); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline Size EllipseWithBorder< VertexType, IndexType, PositionAcc >::GetNumberBorderIndicies () const +{ + return 6 * Parent::GetNumberVerticies(); +} + +// ================================ // +// +template< typename VertexType, typename IndexType, typename PositionAcc > +inline ReturnResult EllipseWithBorder< VertexType, IndexType, PositionAcc >::ValidateParams () const +{ + ErrorsCollector collector; + collector.Add( Parent::ValidateParams() ); + + if( Width <= 2 * StrokeThickness ) + collector.Add( "[EllipseWithBorder] Invalid parameter [StrokeThickness=" + Convert::ToString( StrokeThickness ) + "]. Width <= 2 * StrokeThickness" ); + + if( Height <= 2 * StrokeThickness ) + collector.Add( "[EllipseWithBorder] Invalid parameter [StrokeThickness=" + Convert::ToString( StrokeThickness ) + "]. Height <= 2 * StrokeThickness" ); + + return collector; +} + + +} // geom +} // sw + + diff --git a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj index 5ae0001f..7549c879 100644 --- a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj +++ b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj @@ -30,6 +30,7 @@ + @@ -45,6 +46,7 @@ + diff --git a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters index 948931dd..ddfeb4fb 100644 --- a/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters +++ b/swGeometrics/ProjectDir/Visual2015/BasicShapes/BasicShapes.vcxproj.filters @@ -35,6 +35,9 @@ Shapes2D + + Shapes2D + @@ -49,5 +52,8 @@ Shapes2D + + Shapes2D + \ No newline at end of file diff --git a/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp b/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp index 68c4e64d..37917a8b 100644 --- a/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp +++ b/swGeometrics/Tests/TestBasicShapes/TestEllipse.cpp @@ -27,7 +27,7 @@ bool IsEllipse ( const std::vector< VertexShape2D >& verticies, float width, f bool isCircle = true; for( auto& vertex : verticies ) { - auto scaleToCircle = DirectX::XMFLOAT2( vertex.Position.x / width, vertex.Position.y / height ); + auto scaleToCircle = DirectX::XMFLOAT2( 2.0f * vertex.Position.x / width, 2.0f * vertex.Position.y / height ); if( !IsOnCircle( scaleToCircle, 1.0f ) ) return false; } @@ -96,8 +96,8 @@ TEST_CASE( "Geometrics.BasicShapes.Ellipse.ToLowTesselation", "[Geometrics][Basi TEST_CASE( "Geometrics.BasicShapes.Ellipse.NegativeRadius", "[Geometrics][BasicShapes]" ) { Ellipse< VertexShape2D, Index16 > ellipse; - ellipse.Width = 2.5f; - ellipse.Height = 0.5f; + ellipse.Width = -2.5f; + ellipse.Height = -0.5f; ellipse.Tesselation = 10; CHECK( Generate< IndexedGeometry< VertexShape2D, Index16 > >( ellipse ).IsValid() == false ); From 11ef39686a3a61c07df5834e86d3ddaf6d4b15ed Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Fri, 18 Jan 2019 20:10:25 +0100 Subject: [PATCH 04/51] Ellipse Tesselation estimation based on width and height (first try) --- swGUI/Core/Media/Geometry/EllipseGeometry.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swGUI/Core/Media/Geometry/EllipseGeometry.cpp b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp index 9c24df2b..92873006 100644 --- a/swGUI/Core/Media/Geometry/EllipseGeometry.cpp +++ b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp @@ -77,7 +77,7 @@ GeometryData EllipseGeometry::Generate () ellipse.Width = m_width; ellipse.Height = m_height; ellipse.StrokeThickness = m_strokeThickness; - ellipse.Tesselation = 100;/// 2 * ( m_width + m_height ); + ellipse.Tesselation = uint32( m_width + m_height ) / 4; // Estimate tesselation based on ellipse size. geom::PlanarUV< VertexShape2D > planarUV; planarUV.MinX = 0.0f; From b92bf741998f12341fc697ca5ce06a24d87b1c02 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 20 Jan 2019 16:50:13 +0100 Subject: [PATCH 05/51] Translate2D processor added --- .../Processors/Transform/Translate2D.h | 96 +++++++++++++++++++ .../GeometricsCore/GeometricsCore.vcxproj | 1 + .../GeometricsCore.vcxproj.filters | 6 ++ .../TestGenerationFramework.vcxproj | 1 + .../TestTransforms.cpp | 45 +++++++++ 5 files changed, 149 insertions(+) create mode 100644 swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h create mode 100644 swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp diff --git a/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h b/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h new file mode 100644 index 00000000..e8360ee0 --- /dev/null +++ b/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h @@ -0,0 +1,96 @@ +#pragma once +/** +@file Translate2D.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "swCommonLib/Common/TypesDefinitions.h" +#include "swCommonLib/Common/Converters.h" +#include "swCommonLib/Common/Exceptions/ErrorsCollector.h" + +#include "swGeometrics/GeometricsCore/Types/Traits/ProcessorTraits.h" +#include "swGeometrics/GeometricsCore/Types/Accessors/DefaultAccessors.h" + + +namespace sw { +namespace geom +{ + + +/**@brief Generated planar UV mapping. +@ingroup Coordinates*/ +template< typename VertexType, typename PositionAcc = DefaultPositionAcc< VertexType > > +class Translate2D : public ProcessorTraits< VertexType > +{ +private: +public: + + float TranslateX; + float TranslateY; + +public: + + inline explicit Translate2D (); + inline explicit Translate2D ( float x, float y ); + + inline void GenerateVertex ( VertexType& vertex, Size vertexIdx ); + + + ReturnResult ValidateParams () const; +}; + +//====================================================================================// +// Implementation +//====================================================================================// + + +// ================================ // +// +template< typename VertexType, typename PositionAcc > +inline Translate2D< VertexType, PositionAcc >::Translate2D () + : TranslateX( 0.0f ) + , TranslateY( 0.0f ) +{} + +// ================================ // +// +template< typename VertexType, typename PositionAcc > +inline Translate2D< VertexType, PositionAcc >::Translate2D ( float x, float y ) + : TranslateX( x ) + , TranslateY( y ) +{} + +// ================================ // +// +template< typename VertexType, typename PositionAcc > +inline void Translate2D< VertexType, PositionAcc >::GenerateVertex ( VertexType& vertex, Size ) +{ + auto& vertexPos = PositionAcc::Get( vertex ); + + vertexPos.x += TranslateX; + vertexPos.y += TranslateY; +} + +// ================================ // +// +template< typename VertexType, typename PositionAcc > +inline ReturnResult Translate2D< VertexType, PositionAcc >::ValidateParams () const +{ + ErrorsCollector collector; + + if( isfinite( TranslateX ) ) + collector.Add( "[Translate2D] Invalid parameter [TranslateX=" + Convert::ToString( TranslateX ) + "]."); + + if( isfinite( TranslateY ) ) + collector.Add( "[Translate2D] Invalid parameter [TranslateY=" + Convert::ToString( TranslateY ) + "]."); + + return collector; +} + + + + +} // geom +} // sw + diff --git a/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj b/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj index cb7d7453..aa4d9f92 100644 --- a/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj +++ b/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj @@ -30,6 +30,7 @@ Create Create + diff --git a/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj.filters b/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj.filters index a0ebc8e4..71c45741 100644 --- a/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj.filters +++ b/swGeometrics/ProjectDir/Visual2015/GeometricsCore/GeometricsCore.vcxproj.filters @@ -25,6 +25,9 @@ {fb9386c8-df63-4a64-bce5-fb04924b00a2} + + {e0aa2870-9ed2-4cf6-bcc6-899b942a78d6} + @@ -68,5 +71,8 @@ Geometric\Types\Traits + + Geometric\Processors\Transform + \ No newline at end of file diff --git a/swGeometrics/ProjectDir/Visual2015/Tests/TestGenerationFramework/TestGenerationFramework.vcxproj b/swGeometrics/ProjectDir/Visual2015/Tests/TestGenerationFramework/TestGenerationFramework.vcxproj index d4220d29..f7aa4f80 100644 --- a/swGeometrics/ProjectDir/Visual2015/Tests/TestGenerationFramework/TestGenerationFramework.vcxproj +++ b/swGeometrics/ProjectDir/Visual2015/Tests/TestGenerationFramework/TestGenerationFramework.vcxproj @@ -24,6 +24,7 @@ + diff --git a/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp b/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp new file mode 100644 index 00000000..4d736110 --- /dev/null +++ b/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp @@ -0,0 +1,45 @@ +#include "swCommonLib/External/Catch/catch.hpp" + + +#include "swGeometrics/GeometricsCore/Generators/Generator.h" +#include "swGeometrics/GeometricsCore/Types/VertexLayouts/VertexShape2D.h" +#include "swGeometrics/GeometricsCore/Types/IndexTypes.h" + +#include "swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h" + +#include "swGeometrics/BasicShapes/Shapes2D/Rectangle.h" + + +using namespace sw; +using namespace sw::geom; + + + +// ================================ // +// +TEST_CASE( "Geometrics.Transforms.Translate2D.TranslateRect", "[Geometrics][Transform]" ) +{ + Rectangle< VertexShape2D, Index16 > rect; + rect.TopLeftX = 30; + rect.TopLeftY = 30; + rect.Height = 20; + rect.Width = 20; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( rect, Translate2D< VertexShape2D >( 3.5f, 5.3f ) ).Get(); + + // Check vertex buffer. + CHECK( geometry.Verticies.size() == 4 ); + + CHECK( geometry.Verticies[ 0 ].Position.x == 33.5f ); + CHECK( geometry.Verticies[ 0 ].Position.y == 35.3f ); + + CHECK( geometry.Verticies[ 1 ].Position.x == 53.5f ); + CHECK( geometry.Verticies[ 1 ].Position.y == 35.3f ); + + CHECK( geometry.Verticies[ 2 ].Position.x == 33.5f ); + CHECK( geometry.Verticies[ 2 ].Position.y == 15.3f ); + + CHECK( geometry.Verticies[ 3 ].Position.x == 53.5f ); + CHECK( geometry.Verticies[ 3 ].Position.y == 15.3f ); +} + From 8f690de4f1115f2451a20a42b5569965231078d0 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 20 Jan 2019 17:08:37 +0100 Subject: [PATCH 06/51] Translate2D validation fixed + tests validation --- .../Processors/Transform/Translate2D.h | 4 +- .../TestTransforms.cpp | 62 ++++++++++++++++++- 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h b/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h index e8360ee0..a81e8a55 100644 --- a/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h +++ b/swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h @@ -79,10 +79,10 @@ inline ReturnResult Translate2D< VertexType, PositionAcc >::ValidateParams ( { ErrorsCollector collector; - if( isfinite( TranslateX ) ) + if( !isfinite( TranslateX ) ) collector.Add( "[Translate2D] Invalid parameter [TranslateX=" + Convert::ToString( TranslateX ) + "]."); - if( isfinite( TranslateY ) ) + if( !isfinite( TranslateY ) ) collector.Add( "[Translate2D] Invalid parameter [TranslateY=" + Convert::ToString( TranslateY ) + "]."); return collector; diff --git a/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp b/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp index 4d736110..b83ee0e8 100644 --- a/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp +++ b/swGeometrics/Tests/TestGenerationFramework/TestTransforms.cpp @@ -10,6 +10,9 @@ #include "swGeometrics/BasicShapes/Shapes2D/Rectangle.h" +#include + + using namespace sw; using namespace sw::geom; @@ -36,10 +39,65 @@ TEST_CASE( "Geometrics.Transforms.Translate2D.TranslateRect", "[Geometrics][Tran CHECK( geometry.Verticies[ 1 ].Position.x == 53.5f ); CHECK( geometry.Verticies[ 1 ].Position.y == 35.3f ); - CHECK( geometry.Verticies[ 2 ].Position.x == 33.5f ); + CHECK( geometry.Verticies[ 2 ].Position.x == 53.5f ); CHECK( geometry.Verticies[ 2 ].Position.y == 15.3f ); - CHECK( geometry.Verticies[ 3 ].Position.x == 53.5f ); + CHECK( geometry.Verticies[ 3 ].Position.x == 33.5f ); CHECK( geometry.Verticies[ 3 ].Position.y == 15.3f ); } +// ================================ // +// +TEST_CASE( "Geometrics.Transforms.Translate2D.XisInfinity", "[Geometrics][Transform]" ) +{ + Rectangle< VertexShape2D, Index16 > rect; + rect.TopLeftX = 30; + rect.TopLeftY = 30; + rect.Height = 20; + rect.Width = 20; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( rect, Translate2D< VertexShape2D >( std::numeric_limits< float >::infinity(), 5.3f ) ); + CHECK( geometry.IsValid() == false ); +} + +// ================================ // +// +TEST_CASE( "Geometrics.Transforms.Translate2D.YisInfinity", "[Geometrics][Transform]" ) +{ + Rectangle< VertexShape2D, Index16 > rect; + rect.TopLeftX = 30; + rect.TopLeftY = 30; + rect.Height = 20; + rect.Width = 20; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( rect, Translate2D< VertexShape2D >( 5.3f, std::numeric_limits< float >::infinity() ) ); + CHECK( geometry.IsValid() == false ); +} + +// ================================ // +// +TEST_CASE( "Geometrics.Transforms.Translate2D.XisNaN", "[Geometrics][Transform]" ) +{ + Rectangle< VertexShape2D, Index16 > rect; + rect.TopLeftX = 30; + rect.TopLeftY = 30; + rect.Height = 20; + rect.Width = 20; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( rect, Translate2D< VertexShape2D >( std::numeric_limits< float >::quiet_NaN(), 5.3f ) ); + CHECK( geometry.IsValid() == false ); +} + +// ================================ // +// +TEST_CASE( "Geometrics.Transforms.Translate2D.YisNaN", "[Geometrics][Transform]" ) +{ + Rectangle< VertexShape2D, Index16 > rect; + rect.TopLeftX = 30; + rect.TopLeftY = 30; + rect.Height = 20; + rect.Width = 20; + + auto geometry = Generate< IndexedGeometry< VertexShape2D, Index16 > >( rect, Translate2D< VertexShape2D >( 5.3f, std::numeric_limits< float >::quiet_NaN() ) ); + CHECK( geometry.IsValid() == false ); +} \ No newline at end of file From 3ef3acf66943d8a8d3a8249ce2187297b36e569d Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 20 Jan 2019 17:15:59 +0100 Subject: [PATCH 07/51] Ellipse pivot moved to top left corner --- swGUI/Core/Media/Geometry/EllipseGeometry.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/swGUI/Core/Media/Geometry/EllipseGeometry.cpp b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp index 92873006..58cdfccc 100644 --- a/swGUI/Core/Media/Geometry/EllipseGeometry.cpp +++ b/swGUI/Core/Media/Geometry/EllipseGeometry.cpp @@ -10,6 +10,7 @@ #include "swGeometrics/BasicShapes/Shapes2D/EllipseWithBorder.h" #include "swGeometrics/BasicShapes/CoordsUV/PlanarUV.h" #include "swGeometrics/GeometricsCore/Generators/Generator.h" +#include "swGeometrics/GeometricsCore/Processors/Transform/Translate2D.h" #include "swGUI/Core/Media/Geometry/Layouts/VertexShape2D.h" #include "swCommonLib/Common/Buffers/IndexedGeometryBuffer.h" @@ -85,7 +86,7 @@ GeometryData EllipseGeometry::Generate () planarUV.MaxX = m_width; planarUV.MaxY = 0.0f; - auto geometry = geom::Generate< geom::IndexedGeometryBuffer< VertexShape2D, Index16 > >( ellipse, planarUV ); + auto geometry = geom::Generate< geom::IndexedGeometryBuffer< VertexShape2D, Index16 > >( ellipse, geom::Translate2D< VertexShape2D >( m_width / 2, -m_height / 2 ), planarUV ); /// @todo Error handling or logging. GeometryData geomData( geometry.Get().Verticies.MoveToRawBuffer(), geometry.Get().Indicies.MoveToRawBuffer() ); From c700ac6181cc9c88ad9698c7422a2d8a013c3420 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 15:56:10 +0100 Subject: [PATCH 08/51] Fix BufferRaw operator= --- swCommonLib/Common/Buffers/BufferRaw.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/swCommonLib/Common/Buffers/BufferRaw.h b/swCommonLib/Common/Buffers/BufferRaw.h index 5bdb8063..d65ee0e1 100644 --- a/swCommonLib/Common/Buffers/BufferRaw.h +++ b/swCommonLib/Common/Buffers/BufferRaw.h @@ -93,6 +93,8 @@ inline BufferRaw& BufferRaw::operator= ( BufferRaw&& bufferRaw ) bufferRaw.m_data = nullptr; bufferRaw.m_size = 0; + + return *this; } // ================================ // From ca3231ad592a348e6f691ef2009cd4db1a31fe47 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 15:56:56 +0100 Subject: [PATCH 09/51] Allow brush to change constants buffer --- swGUI/Core/Media/Brushes/Brush.cpp | 15 ++++++ swGUI/Core/Media/Brushes/Brush.h | 4 ++ .../System/Rendering/Drawings/Drawing.cpp | 12 ++++- .../Visual2015/CoreGUI/CoreGUI.vcxproj | 5 +- .../CoreGUI/CoreGUI.vcxproj.filters | 15 +++--- .../Utils/Mocks/Media/FakeBrush.cpp | 14 ++++- .../Utils/Mocks/Media/FakeBrush.h | 3 ++ .../Tests/TestRenderingSystem/TestDrawing.cpp | 53 +++++++++++++++++++ 8 files changed, 110 insertions(+), 11 deletions(-) diff --git a/swGUI/Core/Media/Brushes/Brush.cpp b/swGUI/Core/Media/Brushes/Brush.cpp index 9cf40887..1f27b67d 100644 --- a/swGUI/Core/Media/Brushes/Brush.cpp +++ b/swGUI/Core/Media/Brushes/Brush.cpp @@ -21,6 +21,7 @@ Brush::Brush ( ConstantBufferMode enableCB ) : m_useConstantBuffer( enableCB == ConstantBufferMode::Enable ) , m_invalidateConstants( false ) , m_invalidateTexture( false ) + , m_changeCBuffer( false ) { InvalidateShader(); } @@ -47,6 +48,13 @@ void Brush::InvalidateTexture () m_invalidateTexture = true; } +// ================================ // +// +void Brush::InvalidateConstsBuffer () +{ + m_changeCBuffer = true; +} + // ================================ // // void Brush::ShaderUpdated () @@ -68,5 +76,12 @@ void Brush::ConstantsUpdated () m_invalidateConstants = false; } +// ================================ // +// +void Brush::BufferChanged () +{ + m_changeCBuffer = false; +} + } // gui } // sw \ No newline at end of file diff --git a/swGUI/Core/Media/Brushes/Brush.h b/swGUI/Core/Media/Brushes/Brush.h index a1cdaacc..8f9ce23e 100644 --- a/swGUI/Core/Media/Brushes/Brush.h +++ b/swGUI/Core/Media/Brushes/Brush.h @@ -45,6 +45,7 @@ class Brush : public EngineObject bool m_useConstantBuffer : 1; bool m_invalidateConstants : 1; + bool m_changeCBuffer : 1; bool m_invalidateShader : 1; bool m_invalidateTexture : 1; @@ -56,6 +57,7 @@ class Brush : public EngineObject void InvalidateConstants (); void InvalidateShader (); void InvalidateTexture (); + void InvalidateConstsBuffer (); ///@} @@ -88,12 +90,14 @@ class Brush : public EngineObject void ShaderUpdated (); void TextureUpdated (); void ConstantsUpdated (); + void BufferChanged (); protected: bool NeedsShaderUpdate () const { return m_invalidateShader; } bool NeedsTextureUpdate () const { return m_invalidateTexture; } bool NeedsConstantsUpdate () const { return m_invalidateConstants; } + bool NeedsBufferChange () const { return m_changeCBuffer; } bool UsesConstantBuffer () const { return m_useConstantBuffer; } diff --git a/swGUI/Core/System/Rendering/Drawings/Drawing.cpp b/swGUI/Core/System/Rendering/Drawings/Drawing.cpp index 4392624d..1a25b28a 100644 --- a/swGUI/Core/System/Rendering/Drawings/Drawing.cpp +++ b/swGUI/Core/System/Rendering/Drawings/Drawing.cpp @@ -73,7 +73,8 @@ bool Drawing::UpdateBrushTexture ( ResourceManager* rm, Brush* brush ) // bool Drawing::UpdateBrushConstants ( ResourceManager* rm, Brush* brush ) { - if( !m_brushData.BrushConstants && brush->UsesConstantBuffer() ) + if( ( !m_brushData.BrushConstants && brush->UsesConstantBuffer() ) + || brush->NeedsBufferChange() ) { std::wstring name = brush->ConstantsName(); @@ -84,6 +85,9 @@ bool Drawing::UpdateBrushConstants ( ResourceManager* rm, Brush* brush ) constantsBuffer = rm->CreateConstantsBuffer( name, bufferRange.DataPtr, (uint32)bufferRange.DataSize ); } + if( brush->NeedsBufferChange() ) + brush->BufferChanged(); + m_brushData.BrushConstants = constantsBuffer; return true; } @@ -109,7 +113,8 @@ bool Drawing::UpdatePenTexture ( ResourceManager* rm, Brush* pen ) // bool Drawing::UpdatePenConstants ( ResourceManager* rm, Brush* pen ) { - if( !m_penData.BrushConstants && pen->UsesConstantBuffer() ) + if( ( !m_penData.BrushConstants && pen->UsesConstantBuffer() ) + || pen->NeedsBufferChange() ) { std::wstring name = pen->ConstantsName(); @@ -120,6 +125,9 @@ bool Drawing::UpdatePenConstants ( ResourceManager* rm, Brush* pen ) constantsBuffer = rm->CreateConstantsBuffer( name, bufferRange.DataPtr, (uint32)bufferRange.DataSize ); } + if( pen->NeedsBufferChange() ) + pen->BufferChanged(); + m_penData.BrushConstants = constantsBuffer; return true; } diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj index dfcdd2f8..276f4920 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj @@ -143,8 +143,8 @@ - - + + @@ -214,6 +214,7 @@ + diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters index 5625673e..0d555eae 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters @@ -198,12 +198,6 @@ Core\Media\Brushes - - Core\Media\Brushes - - - Core\Media\Brushes - Core\System\Events @@ -327,6 +321,12 @@ Core\Controls\Shapes + + Core\Media\Brushes + + + Core\Media\Brushes + @@ -470,6 +470,9 @@ Core\Controls\Shapes + + Core\Media\Brushes + diff --git a/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.cpp b/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.cpp index 5dc5ee7a..d8ca0d6a 100644 --- a/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.cpp +++ b/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.cpp @@ -18,6 +18,7 @@ namespace gui FakeBrush::FakeBrush() : Brush( Brush::ConstantBufferMode::Enable ) , m_shaderFun( "$(CoreGUI-Shader-Dir)/FakeBrush.ps" ) + , m_cBuffer( L"::FakeBrush-Constants" ) {} // ================================ // @@ -45,7 +46,7 @@ std::wstring FakeBrush::TextureSource () // std::wstring FakeBrush::ConstantsName () { - return L"::FakeBrush-Constants"; + return m_cBuffer; } // ================================ // @@ -64,6 +65,17 @@ void FakeBrush::SetTextureFile ( const std::wstring& tex ) InvalidateTexture(); } +// ================================ // +// +void FakeBrush::ChangeConstsBuffer ( const std::wstring& newBuffer ) +{ + if( m_cBuffer != newBuffer ) + { + m_cBuffer = newBuffer; + InvalidateConstsBuffer(); + } +} + } // gui } // sw \ No newline at end of file diff --git a/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.h b/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.h index efe9e6ef..02a1e83f 100644 --- a/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.h +++ b/swGUI/TestFramework/Utils/Mocks/Media/FakeBrush.h @@ -22,6 +22,7 @@ class FakeBrush : public Brush std::string m_shaderFun; std::wstring m_textureFile; + std::wstring m_cBuffer; public: @@ -41,11 +42,13 @@ class FakeBrush : public Brush using Brush::NeedsShaderUpdate; using Brush::NeedsTextureUpdate; using Brush::NeedsConstantsUpdate; + using Brush::NeedsBufferChange; public: void SetShaderFunction ( const std::string& shaderFun ); void SetTextureFile ( const std::wstring& tex ); + void ChangeConstsBuffer ( const std::wstring& newBuffer ); }; DEFINE_PTR_TYPE( FakeBrush ) diff --git a/swGUI/Tests/TestRenderingSystem/TestDrawing.cpp b/swGUI/Tests/TestRenderingSystem/TestDrawing.cpp index 7b39956f..32db5cf9 100644 --- a/swGUI/Tests/TestRenderingSystem/TestDrawing.cpp +++ b/swGUI/Tests/TestRenderingSystem/TestDrawing.cpp @@ -220,6 +220,59 @@ TEST_CASE( "GUI.Rendering.Drawing.Geometry.UpdateConstants", "[GUISystem][Render CHECK( renderingData.GeometryConstants != nullptr ); } +// ================================ // +// +TEST_CASE( "GUI.Rendering.Drawing.Brush.ChangeConstantsBuffer", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework framework( 0, nullptr ); framework.Init(); + + FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); + FakeBrushPtr brush = std::make_shared< FakeBrush >(); + + auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); + REQUIRE( renderingData.BrushConstants == nullptr ); + + drawing->UpdateBrushConstants( framework.GetResourceManager(), brush.get() ); + + auto prevBuff = renderingData.BrushConstants; + CHECK( prevBuff != nullptr ); + + brush->ChangeConstsBuffer( L"NewBuffer" ); + CHECK( brush->NeedsBufferChange() == true ); + + drawing->UpdateBrushConstants( framework.GetResourceManager(), brush.get() ); + + CHECK( prevBuff != renderingData.BrushConstants ); + CHECK( brush->NeedsBufferChange() == false ); +} + +// ================================ // +// +TEST_CASE( "GUI.Rendering.Drawing.Pen.ChangeConstantsBuffer", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework framework( 0, nullptr ); framework.Init(); + + FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); + FakeBrushPtr pen = std::make_shared< FakeBrush >(); + + auto& renderingData = CLASS_TESTER( Drawing )::GetPenRenderingData( drawing.get() ); + REQUIRE( renderingData.BrushConstants == nullptr ); + + drawing->UpdatePenConstants( framework.GetResourceManager(), pen.get() ); + + auto prevBuff = renderingData.BrushConstants; + CHECK( prevBuff != nullptr ); + + pen->ChangeConstsBuffer( L"NewBuffer" ); + CHECK( pen->NeedsBufferChange() == true ); + + drawing->UpdatePenConstants( framework.GetResourceManager(), pen.get() ); + + CHECK( prevBuff != renderingData.BrushConstants ); + CHECK( pen->NeedsBufferChange() == false ); +} + + //====================================================================================// // Geometry update //====================================================================================// From 13fd81e848556378cad364cce9ae1a75e596a14d Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 15:57:13 +0100 Subject: [PATCH 10/51] GradintBrush beginning with implementation --- swGUI/Core/Media/Brushes/GradientBrush.cpp | 127 ++++++++++++++++++ swGUI/Core/Media/Brushes/GradientBrush.h | 49 ++++++- swGUI/Core/Media/Brushes/LinearGradient.h | 27 ---- .../Core/Media/Brushes/LinearGradientBrush.h | 50 +++++++ ...RadialGradient.h => RadialGradientBrush.h} | 0 swGUI/Core/Media/Media.h | 4 +- 6 files changed, 226 insertions(+), 31 deletions(-) create mode 100644 swGUI/Core/Media/Brushes/GradientBrush.cpp delete mode 100644 swGUI/Core/Media/Brushes/LinearGradient.h create mode 100644 swGUI/Core/Media/Brushes/LinearGradientBrush.h rename swGUI/Core/Media/Brushes/{RadialGradient.h => RadialGradientBrush.h} (100%) diff --git a/swGUI/Core/Media/Brushes/GradientBrush.cpp b/swGUI/Core/Media/Brushes/GradientBrush.cpp new file mode 100644 index 00000000..ee8cb145 --- /dev/null +++ b/swGUI/Core/Media/Brushes/GradientBrush.cpp @@ -0,0 +1,127 @@ +/** +@file GradientBrush.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ +#include "swGUI/Core/stdafx.h" + +#include "GradientBrush.h" + +#include "swCommonLib/Common/Buffers/BufferTyped.h" + + +#include + + +namespace sw { +namespace gui +{ + + +// ================================ // +// +void GradientBrush::AddGradientStop ( GradientStop stop ) +{ + m_gradientStops.push_back( stop ); + std::sort( m_gradientStops.begin(), m_gradientStops.end(), []( const GradientStop& left, const GradientStop& right ) + { + if( left.Offset < right.Offset ) + return true; + return false; + } ); + + if( m_buffer.GetSize() != ExpectedBufferSize() ) + InvalidateConstants(); +} + +// ================================ // +// +void GradientBrush::RemoveGradientStop ( Size idx ) +{ + m_gradientStops.erase( m_gradientStops.begin() + idx ); + + if( m_buffer.GetSize() != ExpectedBufferSize() ) + InvalidateConstants(); +} + + +// ================================ // +// +std::wstring GradientBrush::ConstantsName () +{ + auto expSize = ExpectedBufferSize(); + return L"sw::gui::GradientBrush::CB[Size=" + Convert::FromString< std::wstring >( Convert::ToString( expSize ), L"" ) + L"]"; +} + +// ================================ // +// +std::wstring GradientBrush::TextureSource () +{ + // No texture by default. + return std::wstring(); +} + + +// ================================ // +// +BufferRange GradientBrush::PrepareBuffer ( BufferRange constants ) +{ + auto expectedSize = ExpectedBufferSize(); + if( m_buffer.GetSize() != expectedSize ) + ReallocateBuffer( expectedSize ); + + FillBufferContent( constants ); + + return BufferRange( m_buffer.GetData(), m_buffer.GetSize() ); +} + +// ================================ // +// +Size GradientBrush::ExpectedBufferSize () const +{ + auto neededSize = ConstantsSize() + GradientStopsSize(); + neededSize = neededSize + neededSize % 16; + + return neededSize; +} + +// ================================ // +// +Size GradientBrush::GradientStopsSize () const +{ + // Size of GradientStops array + size of number of array elements on the begining. + return sizeof( GradientStop ) * m_gradientStops.size() + sizeof( uint32 ); +} + +// ================================ // +// +void GradientBrush::ReallocateBuffer ( Size newSize ) +{ + BufferTyped< uint8 > bufferTyped( newSize ); + m_buffer = bufferTyped.MoveToRawBuffer(); +} + +// ================================ // +// +void GradientBrush::FillBufferContent ( BufferRange constants ) +{ + // Copy buffer from derived class. + auto dataPtr = m_buffer.GetData(); + memcpy( dataPtr, constants.DataPtr, constants.DataSize ); + + // Copy GradientStops. + dataPtr += constants.DataSize; + + uint32 numGradientStops = (uint32)m_gradientStops.size(); + memcpy( dataPtr, &numGradientStops, sizeof( uint32 ) ); + + dataPtr += sizeof( uint32 ); + + memcpy( dataPtr, m_gradientStops.data(), m_gradientStops.size() * sizeof( GradientStop ) ); +} + + + + +} // gui +} // sw diff --git a/swGUI/Core/Media/Brushes/GradientBrush.h b/swGUI/Core/Media/Brushes/GradientBrush.h index bd5511ac..3b61969d 100644 --- a/swGUI/Core/Media/Brushes/GradientBrush.h +++ b/swGUI/Core/Media/Brushes/GradientBrush.h @@ -1,24 +1,69 @@ #pragma once +/** +@file GradientBrush.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ #include "Brush.h" +#include "swCommonLib/Common/Buffers/BufferRaw.h" + +#include + namespace sw { namespace gui { -/**@brief +/**@brief Gradient point. +@ingroup Brushes*/ +struct GradientStop +{ + uint32 Color; + float Offset; +}; + + + +/**@brief Base class for gradients. @ingroup Brushes*/ class GradientBrush : public Brush { private: protected: + + std::vector< GradientStop > m_gradientStops; + BufferRaw m_buffer; + public: explicit GradientBrush () = default; - ~GradientBrush () = default; + virtual ~GradientBrush () = default; + + + virtual std::wstring ConstantsName (); + virtual std::wstring TextureSource () override; + +public: + + void AddGradientStop ( GradientStop stop ); + void RemoveGradientStop ( Size idx ); + +protected: + + BufferRange PrepareBuffer ( BufferRange constants ); + + virtual Size ConstantsSize () const = 0; + +private: + + Size ExpectedBufferSize () const; + Size GradientStopsSize () const; + void ReallocateBuffer ( Size newSize ); + void FillBufferContent ( BufferRange constants ); }; diff --git a/swGUI/Core/Media/Brushes/LinearGradient.h b/swGUI/Core/Media/Brushes/LinearGradient.h deleted file mode 100644 index a3d8899c..00000000 --- a/swGUI/Core/Media/Brushes/LinearGradient.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "GradientBrush.h" - - - -namespace sw { -namespace gui -{ - -/**@brief -@ingroup Brushes*/ -class LinearGradient : public GradientBrush -{ - RTTR_ENABLE( GradientBrush ); -private: -protected: -public: - explicit LinearGradient () = default; - ~LinearGradient () = default; - -}; - - -} // gui -} // sw - diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.h b/swGUI/Core/Media/Brushes/LinearGradientBrush.h new file mode 100644 index 00000000..6a4956b9 --- /dev/null +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.h @@ -0,0 +1,50 @@ +#pragma once +/** +@file LinearGradientBrush.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + + +#include "GradientBrush.h" + +#include "swCommonLib/Common/Buffers/StackBuffer.h" +#include "swGUI/Core/System/CommonTypes/CommonTypes.h" + + + +namespace sw { +namespace gui +{ + + +/**@brief Draws linear gradient on @ref Geometry. +@ingroup Brushes*/ +class LinearGradient : public GradientBrush +{ + RTTR_ENABLE( GradientBrush ); + RTTR_REGISTRATION_FRIEND; +public: + + struct Constants + { + Point GradientStart; + Point GradientEnd; + }; + +private: +protected: + + StackBuffer< Constants > m_constants; + +public: + explicit LinearGradient () = default; + virtual ~LinearGradient () = default; + +}; + + +} // gui +} // sw + diff --git a/swGUI/Core/Media/Brushes/RadialGradient.h b/swGUI/Core/Media/Brushes/RadialGradientBrush.h similarity index 100% rename from swGUI/Core/Media/Brushes/RadialGradient.h rename to swGUI/Core/Media/Brushes/RadialGradientBrush.h diff --git a/swGUI/Core/Media/Media.h b/swGUI/Core/Media/Media.h index 7fcd836b..d25c8112 100644 --- a/swGUI/Core/Media/Media.h +++ b/swGUI/Core/Media/Media.h @@ -16,8 +16,8 @@ // Brushes #include "Brushes/SolidColorBrush.h" -#include "Brushes/LinearGradient.h" -#include "Brushes/RadialGradient.h" +#include "Brushes/LinearGradientBrush.h" +#include "Brushes/RadialGradientBrush.h" #include "Brushes/ImageBrush.h" // Geometry From 033d801b484e088dd82ea7e3aeab769413d98ede Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 17:08:09 +0100 Subject: [PATCH 11/51] GradientBrush base class --- swGUI/Core/Media/Brushes/GradientBrush.cpp | 18 ++++++- swGUI/Core/Media/Brushes/GradientBrush.h | 14 +++++- .../Media/Brushes/LinearGradientBrush.cpp | 47 +++++++++++++++++++ .../Core/Media/Brushes/LinearGradientBrush.h | 11 ++++- .../Visual2015/CoreGUI/CoreGUI.vcxproj | 1 + .../CoreGUI/CoreGUI.vcxproj.filters | 1 + .../TestRenderingSystem.vcxproj | 1 + .../TestRenderingSystem.vcxproj.filters | 3 ++ swGUI/Tests/TestRenderingSystem/TestBrush.cpp | 34 ++++++++++++++ 9 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 swGUI/Core/Media/Brushes/LinearGradientBrush.cpp create mode 100644 swGUI/Tests/TestRenderingSystem/TestBrush.cpp diff --git a/swGUI/Core/Media/Brushes/GradientBrush.cpp b/swGUI/Core/Media/Brushes/GradientBrush.cpp index ee8cb145..ccf79bcf 100644 --- a/swGUI/Core/Media/Brushes/GradientBrush.cpp +++ b/swGUI/Core/Media/Brushes/GradientBrush.cpp @@ -18,6 +18,14 @@ namespace gui { +// ================================ // +// +GradientBrush::GradientBrush( Size constantsSize ) + : Brush( ConstantBufferMode::Enable ) + , m_buffer( BufferTyped< uint8 >( ExpectedBufferSize( constantsSize ) ).MoveToRawBuffer() ) +{} + + // ================================ // // void GradientBrush::AddGradientStop ( GradientStop stop ) @@ -44,7 +52,6 @@ void GradientBrush::RemoveGradientStop ( Size idx ) InvalidateConstants(); } - // ================================ // // std::wstring GradientBrush::ConstantsName () @@ -79,7 +86,14 @@ BufferRange GradientBrush::PrepareBuffer ( BufferRange constants ) // Size GradientBrush::ExpectedBufferSize () const { - auto neededSize = ConstantsSize() + GradientStopsSize(); + return ExpectedBufferSize( GradientStopsSize() ); +} + +// ================================ // +// +Size GradientBrush::ExpectedBufferSize ( Size constantsSize ) const +{ + auto neededSize = GradientStopsSize() + constantsSize; neededSize = neededSize + neededSize % 16; return neededSize; diff --git a/swGUI/Core/Media/Brushes/GradientBrush.h b/swGUI/Core/Media/Brushes/GradientBrush.h index 3b61969d..925aa2a4 100644 --- a/swGUI/Core/Media/Brushes/GradientBrush.h +++ b/swGUI/Core/Media/Brushes/GradientBrush.h @@ -24,6 +24,15 @@ struct GradientStop { uint32 Color; float Offset; + +// ================================ // +// + GradientStop() {} + + GradientStop( uint32 color, float offset ) + : Color( color ) + , Offset( offset ) + {} }; @@ -39,7 +48,7 @@ class GradientBrush : public Brush BufferRaw m_buffer; public: - explicit GradientBrush () = default; + explicit GradientBrush ( Size constantsSize ); virtual ~GradientBrush () = default; @@ -51,6 +60,8 @@ class GradientBrush : public Brush void AddGradientStop ( GradientStop stop ); void RemoveGradientStop ( Size idx ); + const std::vector< GradientStop >& GetGradintStops () const { return m_gradientStops; } + protected: BufferRange PrepareBuffer ( BufferRange constants ); @@ -60,6 +71,7 @@ class GradientBrush : public Brush private: Size ExpectedBufferSize () const; + Size ExpectedBufferSize ( Size constantsSize ) const; Size GradientStopsSize () const; void ReallocateBuffer ( Size newSize ); diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp new file mode 100644 index 00000000..fe190161 --- /dev/null +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp @@ -0,0 +1,47 @@ +/** +@file LinearGradientBrush.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + +#include "swGUI/Core/stdafx.h" +#include "LinearGradientBrush.h" + + + +namespace sw { +namespace gui +{ + +// ================================ // +// +LinearGradient::LinearGradient() + : GradientBrush( LinearGradient::ConstantsSize() ) +{} + + +// ================================ // +// +BufferRange LinearGradient::BufferData () +{ + return PrepareBuffer( m_constants.GetView() ); +} + +// ================================ // +// +std::string LinearGradient::ShaderFunctionFile () +{ + return std::string(); +} + +// ================================ // +// +Size LinearGradient::ConstantsSize () const +{ + return sizeof( m_constants ); +} + + +} // gui +} // sw \ No newline at end of file diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.h b/swGUI/Core/Media/Brushes/LinearGradientBrush.h index 6a4956b9..625a8dca 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.h +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.h @@ -39,11 +39,20 @@ class LinearGradient : public GradientBrush StackBuffer< Constants > m_constants; public: - explicit LinearGradient () = default; + explicit LinearGradient (); virtual ~LinearGradient () = default; + + virtual BufferRange BufferData () override; + virtual std::string ShaderFunctionFile () override; + +protected: + + virtual Size ConstantsSize () const override; }; +DEFINE_PTR_TYPE( LinearGradient ); + } // gui } // sw diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj index 276f4920..f4334d43 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj @@ -215,6 +215,7 @@ + diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters index 0d555eae..c4dcdfef 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters @@ -473,6 +473,7 @@ Core\Media\Brushes + diff --git a/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj b/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj index 8be891d7..be958be8 100644 --- a/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj +++ b/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj @@ -41,6 +41,7 @@ + diff --git a/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj.filters b/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj.filters index 3b59a5c1..67775791 100644 --- a/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/Tests/TestRenderingSystem/TestRenderingSystem.vcxproj.filters @@ -22,5 +22,8 @@ TestRenderingSystem + + TestRenderingSystem + \ No newline at end of file diff --git a/swGUI/Tests/TestRenderingSystem/TestBrush.cpp b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp new file mode 100644 index 00000000..c8aa070a --- /dev/null +++ b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp @@ -0,0 +1,34 @@ +#include "swCommonLib/External/Catch/catch.hpp" + +#include "swGUI/TestFramework/TestFramework.h" + +#include "swGUI/Core/System/Rendering/Drawings/Drawing.h" +#include "swGUI/Core/Media/Brushes/LinearGradientBrush.h" + +#include "swGUI/TestFramework/Testers/Rendering/DrawingTester.h" + + +using namespace sw; +using namespace sw::gui; + + +// ================================ // +// +TEST_CASE( "GUI.Rendering.Brush.GradientBrush.AddingGradientStops", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework framework( 0, nullptr ); framework.Init(); + LinearGradientPtr brush = std::make_shared< LinearGradient >(); + + auto constsName = brush->ConstantsName(); + + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + + CHECK( constsName != brush->ConstantsName() ); +} + + + + From c4b89e081d30352585166d383e006872a4d25cf9 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 17:16:35 +0100 Subject: [PATCH 12/51] [Test] Removing GradientStops --- swGUI/Tests/TestRenderingSystem/TestBrush.cpp | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/swGUI/Tests/TestRenderingSystem/TestBrush.cpp b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp index c8aa070a..42ebacf1 100644 --- a/swGUI/Tests/TestRenderingSystem/TestBrush.cpp +++ b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp @@ -13,7 +13,7 @@ using namespace sw::gui; // ================================ // -// +// Adding GradinetStops should cause change of buffer. TEST_CASE( "GUI.Rendering.Brush.GradientBrush.AddingGradientStops", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework framework( 0, nullptr ); framework.Init(); @@ -30,5 +30,24 @@ TEST_CASE( "GUI.Rendering.Brush.GradientBrush.AddingGradientStops", "[GUISystem] } +// ================================ // +// Adding GradinetStops should cause change of buffer. +TEST_CASE( "GUI.Rendering.Brush.GradientBrush.RemovingGradientStops", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework framework( 0, nullptr ); framework.Init(); + LinearGradientPtr brush = std::make_shared< LinearGradient >(); + + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); + + auto constsName = brush->ConstantsName(); + brush->RemoveGradientStop( 0 ); + brush->RemoveGradientStop( 0 ); + brush->RemoveGradientStop( 0 ); + + CHECK( constsName != brush->ConstantsName() ); +} From 7127e270bb893cbcb7a975d3e4b01df3a4e97592 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 27 Jan 2019 22:37:01 +0100 Subject: [PATCH 13/51] LinearGradientBrush shader compiles --- .../Media/Brushes/LinearGradientBrush.cpp | 12 +-- .../Core/Media/Brushes/LinearGradientBrush.h | 8 +- .../hlsl/Brush/LinearGradientBrush.psh | 74 +++++++++++++++++++ .../Visual2015/CoreGUI/CoreGUI.vcxproj | 6 ++ .../CoreGUI/CoreGUI.vcxproj.filters | 3 + .../TestBrushShaderCompilation.cpp | 18 +++++ .../TestPenShaderCompilation.cpp | 19 +++++ 7 files changed, 130 insertions(+), 10 deletions(-) create mode 100644 swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp index fe190161..8080ae2f 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp @@ -16,28 +16,28 @@ namespace gui // ================================ // // -LinearGradient::LinearGradient() - : GradientBrush( LinearGradient::ConstantsSize() ) +LinearGradientBrush::LinearGradientBrush() + : GradientBrush( LinearGradientBrush::ConstantsSize() ) {} // ================================ // // -BufferRange LinearGradient::BufferData () +BufferRange LinearGradientBrush::BufferData () { return PrepareBuffer( m_constants.GetView() ); } // ================================ // // -std::string LinearGradient::ShaderFunctionFile () +std::string LinearGradientBrush::ShaderFunctionFile () { - return std::string(); + return "$(CoreGUI-Shader-Dir)/Brush/LinearGradientBrush.psh"; } // ================================ // // -Size LinearGradient::ConstantsSize () const +Size LinearGradientBrush::ConstantsSize () const { return sizeof( m_constants ); } diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.h b/swGUI/Core/Media/Brushes/LinearGradientBrush.h index 625a8dca..c6632bc6 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.h +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.h @@ -21,7 +21,7 @@ namespace gui /**@brief Draws linear gradient on @ref Geometry. @ingroup Brushes*/ -class LinearGradient : public GradientBrush +class LinearGradientBrush : public GradientBrush { RTTR_ENABLE( GradientBrush ); RTTR_REGISTRATION_FRIEND; @@ -39,8 +39,8 @@ class LinearGradient : public GradientBrush StackBuffer< Constants > m_constants; public: - explicit LinearGradient (); - virtual ~LinearGradient () = default; + explicit LinearGradientBrush (); + virtual ~LinearGradientBrush () = default; virtual BufferRange BufferData () override; @@ -51,7 +51,7 @@ class LinearGradient : public GradientBrush virtual Size ConstantsSize () const override; }; -DEFINE_PTR_TYPE( LinearGradient ); +DEFINE_PTR_TYPE( LinearGradientBrush ); } // gui diff --git a/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh new file mode 100644 index 00000000..8492ccbf --- /dev/null +++ b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh @@ -0,0 +1,74 @@ + +#define MAX_GRADIENTS_STOPS 127 + + +// ================================ // +// +struct GradientStop +{ + uint Color; + float Offset; +}; + +// ================================ // +// +cbuffer LinearGradientBrushConsts : register( b0 ) +{ + float2 StartPoint; + float2 StopPoint; + uint NumStops; + GradientStop GradientStops[ MAX_GRADIENTS_STOPS ]; +} + + +// ================================ // +// +float4 LoadIntColor ( uint color ) +{ + float4 result; + result.x = color & 0xFF000000; + result.y = color & 0x00FF0000; + result.z = color & 0x0000FF00; + result.w = color & 0x000000FF; + + return result; +} + +// ================================ // +// +float4 ComputeColor ( float factor, GradientStop first, GradientStop second ) +{ + float4 firstColor = LoadIntColor( first.Color ); + float4 secondColor = LoadIntColor( second.Color ); + + return lerp( firstColor, secondColor, factor ); +} + + +// ================================ // +// +float4 BrushFunction ( float4 pos, float2 tex ) +{ + float2 gradientVec = StopPoint - StartPoint; + float2 pixelVec = tex - StartPoint; + + float factor = dot( gradientVec, pixelVec ) / dot( gradientVec, gradientVec ); + + // Handle situation, when we are before first GradientStop. + if( factor < GradientStops[ 0 ].Offset ) + return LoadIntColor( GradientStops[ 0 ].Color ); + + // Find pair of GradientStops. Our pixel shoudl be between them. + uint i = 0; + for( ; i < NumStops - 1; ++i ) + { + if( factor > GradientStops[ i ].Offset ) + { + return ComputeColor( factor, GradientStops[ i ], GradientStops[ i + 1 ] ); + } + } + + // Handle situation, when we are after last GradientStop. + return LoadIntColor( GradientStops[ NumStops - 1 ].Color ); +} + diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj index f4334d43..e21f51b3 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj @@ -270,6 +270,12 @@ + + true + true + true + true + true true diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters index c4dcdfef..cfcddce5 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters @@ -499,5 +499,8 @@ Core\Shaders\hlsl\Geometry + + Core\Shaders\hlsl\Brush + \ No newline at end of file diff --git a/swGUI/Tests/TestRenderingSystem.DX11/TestBrushShaderCompilation.cpp b/swGUI/Tests/TestRenderingSystem.DX11/TestBrushShaderCompilation.cpp index cee592a9..1ae064b7 100644 --- a/swGUI/Tests/TestRenderingSystem.DX11/TestBrushShaderCompilation.cpp +++ b/swGUI/Tests/TestRenderingSystem.DX11/TestBrushShaderCompilation.cpp @@ -8,6 +8,7 @@ // Include Brushes #include "swGUI/Core/Media/Brushes/SolidColorBrush.h" +#include "swGUI/Core/Media/Brushes/LinearGradientBrush.h" @@ -34,3 +35,20 @@ TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.SolidColorBrush", "[GUISy CHECK( renderingData.PixelShader != nullptr ); } +// ================================ // +// +TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.LinearGradientBrush", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework* framework = GetGlobalTestFramework(); + + FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); + LinearGradientBrushPtr brush = std::make_shared< LinearGradientBrush >(); + + drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); + + auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); + + INFO( "[LinearGradientBrush] Brush Shader compilation failed." ); + CHECK( renderingData.PixelShader != nullptr ); +} + diff --git a/swGUI/Tests/TestRenderingSystem.DX11/TestPenShaderCompilation.cpp b/swGUI/Tests/TestRenderingSystem.DX11/TestPenShaderCompilation.cpp index 11d7e7dd..c7866019 100644 --- a/swGUI/Tests/TestRenderingSystem.DX11/TestPenShaderCompilation.cpp +++ b/swGUI/Tests/TestRenderingSystem.DX11/TestPenShaderCompilation.cpp @@ -8,6 +8,7 @@ // Include Brushes #include "swGUI/Core/Media/Brushes/SolidColorBrush.h" +#include "swGUI/Core/Media/Brushes/LinearGradientBrush.h" @@ -41,3 +42,21 @@ TEST_CASE( "GUI.Rendering.DX11.Pen.ShaderCompilation.SolidColorBrush", "[GUISyst CHECK( renderingData.PixelShader != nullptr ); } +// ================================ // +// +TEST_CASE( "GUI.Rendering.DX11.Pen.ShaderCompilation.LinearGradientBrush", "[GUISystem][RenderingSystem][Drawing]" ) +{ + TestFramework* framework = GetGlobalTestFramework(); + + FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); + LinearGradientBrushPtr brush = std::make_shared< LinearGradientBrush >(); + + drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); + + auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); + + INFO( "[LinearGradientBrush] Brush Shader compilation failed." ); + CHECK( renderingData.PixelShader != nullptr ); +} + + From 3798dc50889f907f685cc974a5c0e25719b8a731 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 3 Feb 2019 18:16:00 +0100 Subject: [PATCH 14/51] VertexShape2D layout fixed --- swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp b/swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp index 4600c404..d79951a8 100644 --- a/swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp +++ b/swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp @@ -25,7 +25,7 @@ InputLayoutDescriptorUPtr CreateLayoutDescriptor< VertexShape2D > () { InputLayoutDescriptor* desc = ResourcesFactory::CreateInputLayoutDescriptor( GetLayoutName< VertexShape2D >() ); desc->AddRow( "POSITION", ResourceFormat::RESOURCE_FORMAT_R32G32_FLOAT, 0, 0, false, 0 ); - desc->AddRow( "TEXCOORD", ResourceFormat::RESOURCE_FORMAT_R32G32_FLOAT, 0, 16, false, 0 ); + desc->AddRow( "TEXCOORD", ResourceFormat::RESOURCE_FORMAT_R32G32_FLOAT, 0, 8, false, 0 ); return std::unique_ptr< InputLayoutDescriptor >( desc ); } From dd3a2c414261022479158353cf57f75a9870435a Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 3 Feb 2019 20:23:50 +0100 Subject: [PATCH 15/51] LinearGradient works --- swGUI/Core/Media/Brushes/GradientBrush.cpp | 22 ++++++++++++++++--- swGUI/Core/Media/Brushes/GradientBrush.h | 1 + .../Media/Brushes/LinearGradientBrush.cpp | 5 ++++- .../hlsl/Brush/LinearGradientBrush.psh | 20 +++++++++-------- .../CoreGUI/CoreGUI.vcxproj.filters | 4 +++- .../Prototypes/PrototyperGUI/Application.cpp | 10 +++++++++ 6 files changed, 48 insertions(+), 14 deletions(-) diff --git a/swGUI/Core/Media/Brushes/GradientBrush.cpp b/swGUI/Core/Media/Brushes/GradientBrush.cpp index ccf79bcf..64dfbbcc 100644 --- a/swGUI/Core/Media/Brushes/GradientBrush.cpp +++ b/swGUI/Core/Media/Brushes/GradientBrush.cpp @@ -103,8 +103,18 @@ Size GradientBrush::ExpectedBufferSize ( Size constantsSize ) const // Size GradientBrush::GradientStopsSize () const { + auto gradientStopsAlign = sizeof( GradientStop ) % 16; + // Size of GradientStops array + size of number of array elements on the begining. - return sizeof( GradientStop ) * m_gradientStops.size() + sizeof( uint32 ); + return ( sizeof( GradientStop ) + gradientStopsAlign ) * m_gradientStops.size() + NumStopsSize(); +} + +// ================================ // +// +Size GradientBrush::NumStopsSize () const +{ + // uint32 size + alignement. + return sizeof( uint32 ) + 12; } // ================================ // @@ -129,9 +139,15 @@ void GradientBrush::FillBufferContent ( BufferRange constants ) uint32 numGradientStops = (uint32)m_gradientStops.size(); memcpy( dataPtr, &numGradientStops, sizeof( uint32 ) ); - dataPtr += sizeof( uint32 ); + dataPtr += NumStopsSize(); + + for( Size i = 0; i < m_gradientStops.size(); i++ ) + { + auto gradientStopsAlign = sizeof( GradientStop ) % 16; - memcpy( dataPtr, m_gradientStops.data(), m_gradientStops.size() * sizeof( GradientStop ) ); + memcpy( dataPtr, &m_gradientStops[ i ], sizeof( GradientStop ) ); + dataPtr += ( sizeof( GradientStop ) + gradientStopsAlign ); + } } diff --git a/swGUI/Core/Media/Brushes/GradientBrush.h b/swGUI/Core/Media/Brushes/GradientBrush.h index 925aa2a4..e1c45c4f 100644 --- a/swGUI/Core/Media/Brushes/GradientBrush.h +++ b/swGUI/Core/Media/Brushes/GradientBrush.h @@ -73,6 +73,7 @@ class GradientBrush : public Brush Size ExpectedBufferSize () const; Size ExpectedBufferSize ( Size constantsSize ) const; Size GradientStopsSize () const; + Size NumStopsSize () const; void ReallocateBuffer ( Size newSize ); void FillBufferContent ( BufferRange constants ); diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp index 8080ae2f..2295a00f 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp @@ -18,7 +18,10 @@ namespace gui // LinearGradientBrush::LinearGradientBrush() : GradientBrush( LinearGradientBrush::ConstantsSize() ) -{} +{ + m_constants.GradientStart = Position( 0.5f, 0.0f ); + m_constants.GradientEnd = Position( 0.5f, 1.0f ); +} // ================================ // diff --git a/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh index 8492ccbf..6ecb59ac 100644 --- a/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh +++ b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh @@ -25,13 +25,15 @@ cbuffer LinearGradientBrushConsts : register( b0 ) // float4 LoadIntColor ( uint color ) { + // Color format 0xAARRGGBB + float4 result; - result.x = color & 0xFF000000; - result.y = color & 0x00FF0000; - result.z = color & 0x0000FF00; - result.w = color & 0x000000FF; + result.w = ( color & 0xFF000000 ) >> 24; + result.x = ( color & 0x00FF0000 ) >> 16; + result.y = ( color & 0x0000FF00 ) >> 8; + result.z = color & 0x000000FF; - return result; + return result / 255.0; } // ================================ // @@ -59,12 +61,12 @@ float4 BrushFunction ( float4 pos, float2 tex ) return LoadIntColor( GradientStops[ 0 ].Color ); // Find pair of GradientStops. Our pixel shoudl be between them. - uint i = 0; - for( ; i < NumStops - 1; ++i ) + uint i = 1; + for( ; i < NumStops; ++i ) { - if( factor > GradientStops[ i ].Offset ) + if( factor < GradientStops[ i ].Offset ) { - return ComputeColor( factor, GradientStops[ i ], GradientStops[ i + 1 ] ); + return ComputeColor( factor, GradientStops[ i - 1 ], GradientStops[ i ] ); } } diff --git a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters index cfcddce5..97e01a72 100644 --- a/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters +++ b/swGUI/ProjectDir/Visual2015/CoreGUI/CoreGUI.vcxproj.filters @@ -473,7 +473,9 @@ Core\Media\Brushes - + + Core\Media\Brushes + diff --git a/swGUI/Prototypes/PrototyperGUI/Application.cpp b/swGUI/Prototypes/PrototyperGUI/Application.cpp index 3aaaf12a..217fe784 100644 --- a/swGUI/Prototypes/PrototyperGUI/Application.cpp +++ b/swGUI/Prototypes/PrototyperGUI/Application.cpp @@ -3,6 +3,7 @@ #include "swGUI/Core/Controls/Shapes/Rectangle.h" #include "swGUI/Core/Controls/Shapes/Ellipse.h" #include "swGUI/Core/Media/Brushes/SolidColorBrush.h" +#include "swGUI/Core/Media/Brushes/LinearGradientBrush.h" #include "PrototyperUtils.h" @@ -85,6 +86,13 @@ void AddControls ( HostWindow* host ) stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); AddEllipse( host, stroke, brush, 100, 200, 8, Position( 200, 300 ) ); + + auto gradientBrush = std::make_shared< LinearGradientBrush >(); + gradientBrush->AddGradientStop( GradientStop( 0xFFFF0000, 0.0f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF0000FF, 1.0f ) ); + stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); + + AddRectangle( host, gradientBrush, stroke, 100, 768, 2, Position( 700, 0 ) ); } @@ -103,6 +111,8 @@ If you need specific gui initialization in your application override this functi You can set different GraphicApi or input api.*/ bool Application::Initialize() { + m_guiConfig.DebugGraphics = false; + bool result = true; result = result && DefaultInit( 1024, 768, "Window Tittle" ); From c984e2f6b8ec4efdb90ad6e66065664556d69959 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 3 Feb 2019 20:30:33 +0100 Subject: [PATCH 16/51] LinearGradient shader fixed to handle gradient stop offsets properly --- swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh | 5 +++++ swGUI/Prototypes/PrototyperGUI/Application.cpp | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh index 6ecb59ac..bbb1911c 100644 --- a/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh +++ b/swGUI/Core/Shaders/hlsl/Brush/LinearGradientBrush.psh @@ -40,6 +40,11 @@ float4 LoadIntColor ( uint color ) // float4 ComputeColor ( float factor, GradientStop first, GradientStop second ) { + float firstOffset = first.Offset; + float secondOffset = second.Offset; + + factor = ( factor - firstOffset ) / ( secondOffset - firstOffset ); + float4 firstColor = LoadIntColor( first.Color ); float4 secondColor = LoadIntColor( second.Color ); diff --git a/swGUI/Prototypes/PrototyperGUI/Application.cpp b/swGUI/Prototypes/PrototyperGUI/Application.cpp index 217fe784..9f90a21a 100644 --- a/swGUI/Prototypes/PrototyperGUI/Application.cpp +++ b/swGUI/Prototypes/PrototyperGUI/Application.cpp @@ -92,7 +92,14 @@ void AddControls ( HostWindow* host ) gradientBrush->AddGradientStop( GradientStop( 0xFF0000FF, 1.0f ) ); stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); - AddRectangle( host, gradientBrush, stroke, 100, 768, 2, Position( 700, 0 ) ); + AddRectangle( host, gradientBrush, stroke, 40, 768, 2, Position( 600, 0 ) ); + + gradientBrush = std::make_shared< LinearGradientBrush >(); + gradientBrush->AddGradientStop( GradientStop( 0xFFFF0000, 0.3f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF0000FF, 0.7f ) ); + stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); + + AddRectangle( host, gradientBrush, stroke, 40, 768, 2, Position( 650, 0 ) ); } From ebfa150c4311d818562eb3a72f69d6a7f5a19f32 Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Sun, 17 Feb 2019 19:46:52 +0100 Subject: [PATCH 17/51] Repair shaders texture coordinates system --- .../Media/Brushes/LinearGradientBrush.cpp | 10 ++++++++++ .../Core/Media/Brushes/LinearGradientBrush.h | 2 ++ swGUI/Core/Shaders/hlsl/Templates/Basic.psh | 15 ++++++++++++++- .../Prototypes/PrototyperGUI/Application.cpp | 19 +++++++++++++++++++ 4 files changed, 45 insertions(+), 1 deletion(-) diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp index 2295a00f..f75661e7 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.cpp @@ -38,6 +38,16 @@ std::string LinearGradientBrush::ShaderFunctionFile () return "$(CoreGUI-Shader-Dir)/Brush/LinearGradientBrush.psh"; } +// ================================ // +// +void LinearGradientBrush::SetGradientAxis ( Point start, Point end ) +{ + m_constants.GradientStart = start; + m_constants.GradientEnd = end; + + InvalidateConstants(); +} + // ================================ // // Size LinearGradientBrush::ConstantsSize () const diff --git a/swGUI/Core/Media/Brushes/LinearGradientBrush.h b/swGUI/Core/Media/Brushes/LinearGradientBrush.h index c6632bc6..0be9b5b2 100644 --- a/swGUI/Core/Media/Brushes/LinearGradientBrush.h +++ b/swGUI/Core/Media/Brushes/LinearGradientBrush.h @@ -46,6 +46,8 @@ class LinearGradientBrush : public GradientBrush virtual BufferRange BufferData () override; virtual std::string ShaderFunctionFile () override; + void SetGradientAxis ( Point start, Point end ); + protected: virtual Size ConstantsSize () const override; diff --git a/swGUI/Core/Shaders/hlsl/Templates/Basic.psh b/swGUI/Core/Shaders/hlsl/Templates/Basic.psh index 3c22e5ea..4f4ff187 100644 --- a/swGUI/Core/Shaders/hlsl/Templates/Basic.psh +++ b/swGUI/Core/Shaders/hlsl/Templates/Basic.psh @@ -9,11 +9,24 @@ struct OutputVS }; +// ================================ // +// +float2 TransformToDirectX ( float2 tex ) +{ + float2 directxTex = tex; + directxTex.y = 1.0 - directxTex.y; + + return directxTex; +} + + // ================================ // // float4 main ( OutputVS input ) : SV_Target { - float4 color = BrushFunction( input.Pos, input.Tex ); + float2 directxTex = TransformToDirectX( input.Tex ); + + float4 color = BrushFunction( input.Pos, directxTex ); return color; } diff --git a/swGUI/Prototypes/PrototyperGUI/Application.cpp b/swGUI/Prototypes/PrototyperGUI/Application.cpp index 9f90a21a..7fafe36b 100644 --- a/swGUI/Prototypes/PrototyperGUI/Application.cpp +++ b/swGUI/Prototypes/PrototyperGUI/Application.cpp @@ -100,6 +100,25 @@ void AddControls ( HostWindow* host ) stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); AddRectangle( host, gradientBrush, stroke, 40, 768, 2, Position( 650, 0 ) ); + + gradientBrush = std::make_shared< LinearGradientBrush >(); + gradientBrush->AddGradientStop( GradientStop( 0xFFFF0000, 0.0f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF00FF00, 0.4f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF0000FF, 0.7f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFFFFFF00, 1.0f ) ); + stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); + + AddRectangle( host, gradientBrush, stroke, 40, 768, 2, Position( 700, 0 ) ); + + gradientBrush = std::make_shared< LinearGradientBrush >(); + gradientBrush->SetGradientAxis( Point( 0.0f, 0.0f ), Point( 1.0f, 1.0f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFFFF0000, 0.0f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF00FF00, 0.4f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFF0000FF, 0.7f ) ); + gradientBrush->AddGradientStop( GradientStop( 0xFFFFFF00, 1.0f ) ); + stroke = std::make_shared< SolidColorBrush >( Color( 0.0, 0.0, 0.0, 1.0 ) ); + + AddRectangle( host, gradientBrush, stroke, 120, 768, 2, Position( 750, 0 ) ); } From bec78a8503aaffc92702b9e7c625cfbb43a4e55a Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Fri, 11 Oct 2019 11:19:12 +0200 Subject: [PATCH 18/51] Test compilatation fix --- swGUI/Tests/TestRenderingSystem/TestBrush.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swGUI/Tests/TestRenderingSystem/TestBrush.cpp b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp index 42ebacf1..96b58c06 100644 --- a/swGUI/Tests/TestRenderingSystem/TestBrush.cpp +++ b/swGUI/Tests/TestRenderingSystem/TestBrush.cpp @@ -17,7 +17,7 @@ using namespace sw::gui; TEST_CASE( "GUI.Rendering.Brush.GradientBrush.AddingGradientStops", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework framework( 0, nullptr ); framework.Init(); - LinearGradientPtr brush = std::make_shared< LinearGradient >(); + LinearGradientBrushPtr brush = std::make_shared< LinearGradientBrush >(); auto constsName = brush->ConstantsName(); @@ -35,7 +35,7 @@ TEST_CASE( "GUI.Rendering.Brush.GradientBrush.AddingGradientStops", "[GUISystem] TEST_CASE( "GUI.Rendering.Brush.GradientBrush.RemovingGradientStops", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework framework( 0, nullptr ); framework.Init(); - LinearGradientPtr brush = std::make_shared< LinearGradient >(); + LinearGradientBrushPtr brush = std::make_shared< LinearGradientBrush >(); brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); brush->AddGradientStop( GradientStop( 0xFFFF00FF, 0.0f ) ); From f0b4fc649df61e54bc1648dc9d01008a1330517d Mon Sep 17 00:00:00 2001 From: nieznanysprawiciel Date: Fri, 11 Oct 2019 12:04:09 +0200 Subject: [PATCH 19/51] Merge branch 'master' into Rendering (everything compiles but not work) --- sourcetreeconfig_backup | 65 +- swCommonLib/Common/Buffers/BufferTyped.h | 44 +- swCommonLib/Common/Buffers/StackBuffer.h | 21 +- swCommonLib/Common/Converters.cpp | 2 - swCommonLib/Common/Converters.h | 154 +- swCommonLib/Common/Converters/Convert.cpp | 29 + swCommonLib/Common/Converters/Convert.h | 188 + .../Common/Converters/ConvertArithmetic.h | 164 + swCommonLib/Common/Converters/ConvertEnums.h | 58 + swCommonLib/Common/Converters/ConvertTraits.h | 20 + .../Common/FileNotFoundException.cpp | 28 + .../Exceptions/Common/FileNotFoundException.h | 41 + .../Common/InvalidCodeLogicException.cpp | 39 + .../Common/InvalidCodeLogicException.h | 49 + .../Common/Exceptions/ErrorsCollector.h | 94 +- swCommonLib/Common/Exceptions/Exception.h | 17 +- swCommonLib/Common/Exceptions/Nullable.h | 182 +- .../Common/Macros/DefineFmtFormatter.h | 66 + swCommonLib/Common/Macros/ForEach.h | 55 + swCommonLib/Common/Macros/GenerateOperators.h | 56 + swCommonLib/Common/MemoryChunk.h | 3 +- swCommonLib/Common/Multithreading/QueueMT.h | 4 + swCommonLib/Common/Nullable.h | 3 +- swCommonLib/Common/ObjectDeleter.h | 89 - swCommonLib/Common/RTTR.h | 3 +- swCommonLib/Common/Version.cpp | 127 + swCommonLib/Common/Version.h | 142 +- swCommonLib/Common/fmt.h | 13 + swCommonLib/External/fmt/chrono.h | 828 +++ swCommonLib/External/fmt/color.h | 586 ++ swCommonLib/External/fmt/compile.h | 581 ++ swCommonLib/External/fmt/core.h | 1468 ++++ swCommonLib/External/fmt/format-inl.h | 1116 +++ swCommonLib/External/fmt/format.h | 3613 +++++++++ swCommonLib/External/fmt/locale.h | 77 + swCommonLib/External/fmt/ostream.h | 139 + swCommonLib/External/fmt/posix.h | 311 + swCommonLib/External/fmt/printf.h | 714 ++ swCommonLib/External/fmt/ranges.h | 365 + swCommonLib/External/fmt/safe-duration-cast.h | 293 + .../Internal/ImplHCF.cpp | 2 +- .../Visual2015/CommonBase/CommonBase.vcxproj | 17 +- .../CommonBase/CommonBase.vcxproj.filters | 66 +- swCommonLib/Projects/Visual2015/Paths.props | 2 +- .../SerializerJSON/SerializerJSON.vcxproj | 5 + .../SerializerXML/SerializerXML.vcxproj | 5 + .../TestClassHierarchy.vcxproj | 4 + .../TestClassHierarchy.vcxproj.filters | 6 + .../Tests/BuffersTest/TestBuffers.vcxproj | 1 + .../FileSystemTest/FileSystemTest.vcxproj | 1 + .../FileSystemTest.vcxproj.filters | 4 + .../Tests/TestHelpers/TestHelpers.vcxproj | 15 + .../Serializers/SerializerJson/Serializer.cpp | 10 + .../SerializerXML/Deserializer.cpp | 9 +- .../Serializers/SerializerXML/Serializer.cpp | 12 + .../System/Filesystem/filesystem/path.cpp | 2 +- .../System/Filesystem/filesystem/path.h | 21 +- swCommonLib/System/Path.h | 64 +- .../TestUtils/CatchUtils/ExtendedMacros.h | 19 + .../TestClassHierarchy/Animals/Animal.h | 6 +- .../TestClassHierarchy/Animals/Mammals/Dog.h | 11 + .../Animals/Mammals/Mammal.h | 12 + .../Animals/Registration.cpp | 7 + .../Tests/BuffersTest/BufferTypedTest.cpp | 24 + .../Tests/BuffersTest/TestStackBuffer.cpp | 69 + .../FileSystemTest/TestNormalizePath.cpp | 104 + swCommonLib/Tests/TestHCF/TestWriteFile.cpp | 4 +- .../Tests/TestHCF/TesterClasses/TestAttribs.h | 2 +- .../Tests/TestHelpers/TestConverters.cpp | 209 + .../Tests/TestHelpers/TestDefineFormatter.cpp | 101 + .../Tests/TestHelpers/TestErrorsCollector.cpp | 46 + swCommonLib/Tests/TestHelpers/TestMacros.cpp | 79 + .../Tests/TestHelpers/TestNullable.cpp | 215 + swCommonLib/Tests/TestHelpers/TestVersion.cpp | 88 + swCommonLib/Tests/TestHelpers/main.cpp | 2 + swGUI/Core/Media/Brushes/Brush.h | 8 +- swGUI/Core/Media/Brushes/GradientBrush.cpp | 9 +- swGUI/Core/Media/Brushes/GradientBrush.h | 4 +- .../Media/Brushes/LinearGradientBrush.cpp | 2 +- .../Core/Media/Brushes/LinearGradientBrush.h | 6 +- swGUI/Core/Media/Brushes/SolidColorBrush.cpp | 10 +- swGUI/Core/Media/Brushes/SolidColorBrush.h | 6 +- swGUI/Core/Media/Geometry/EllipseGeometry.cpp | 20 +- swGUI/Core/Media/Geometry/EllipseGeometry.h | 8 +- swGUI/Core/Media/Geometry/Geometry.h | 12 +- swGUI/Core/Media/Geometry/Layouts/Layouts.h | 27 +- .../Media/Geometry/Layouts/VertexShape2D.cpp | 24 +- .../Geometry/Layouts/VertexShape2D.cpp.orig | 49 + .../Media/Geometry/Layouts/VertexShape2D.h | 8 +- .../Core/Media/Geometry/RectangleGeometry.cpp | 12 +- swGUI/Core/Media/Geometry/RectangleGeometry.h | 6 +- swGUI/Core/System/GUISystem.cpp | 105 +- swGUI/Core/System/GUISystem.h | 54 +- swGUI/Core/System/HostWindow.cpp | 15 +- swGUI/Core/System/HostWindow.h | 13 +- .../System/Rendering/Drawings/Drawing.cpp | 73 +- .../Core/System/Rendering/Drawings/Drawing.h | 30 +- .../Rendering/Drawings/GeometryDrawing.cpp | 2 +- .../Rendering/Drawings/GeometryDrawing.h | 2 +- .../Core/System/Rendering/Drawings/IDrawing.h | 3 +- .../System/Rendering/RenderingHelpers.cpp | 14 +- .../Core/System/Rendering/RenderingHelpers.h | 30 +- .../Core/System/Rendering/RenderingSystem.cpp | 25 +- swGUI/Core/System/Rendering/RenderingSystem.h | 33 +- .../Rendering/Shading/ShaderProvider.cpp | 52 +- .../System/Rendering/Shading/ShaderProvider.h | 13 +- swGUI/GUI.sln | 126 +- swGUI/Native/INativeGUI.h | 7 +- swGUI/Native/MockNativeGUI/MockGUI.cpp | 4 +- swGUI/Native/MockNativeGUI/MockGUI.h | 2 +- swGUI/Native/WinAPI/WinAPIGUI.cpp | 10 +- swGUI/Native/WinAPI/WinAPIGUI.h | 17 +- .../textures/Tex1.png | Bin 0 -> 148 bytes .../textures/Tex2.png | Bin 0 -> 148 bytes .../Visual2015/CoreGUI/CoreGUI.vcxproj | 5 +- .../CoreGUI/CoreGUI.vcxproj.filters | 6 - .../Visual2015/LinkSleepingWombatGUI.props | 4 +- swGUI/ProjectDir/Visual2015/Paths.props | 2 +- .../Tests/TestGUISystem/TestGUISystem.vcxproj | 34 +- .../TestGUISystem.vcxproj.filters | 13 +- .../Prototypes/PrototyperGUI/Application.cpp | 39 +- swGUI/Prototypes/PrototyperGUI/Application.h | 16 +- swGUI/TestFramework/TestFramework.cpp | 8 +- swGUI/TestFramework/TestFramework.h | 29 +- .../Testers/Rendering/RenderingSystemTester.h | 4 +- .../Utils/Mocks/Media/FakeBrush.cpp | 16 +- .../Utils/Mocks/Media/FakeBrush.h | 22 +- .../Utils/Mocks/Media/FakeGeometry.cpp | 14 +- .../Utils/Mocks/Media/FakeGeometry.h | 18 +- .../Utils/Mocks/Rendering/FakeDrawing.cpp | 2 +- .../Utils/Mocks/Rendering/FakeDrawing.h | 2 +- .../Tests/TestGUISystem/TestEventRouting.cpp | 11 +- swGUI/Tests/TestGUISystem/TestHostWindow.cpp | 32 + .../TestGUISystem/TestHostWindowFocus.cpp | 35 +- swGUI/Tests/TestGUISystem/TestKeyEvents.cpp | 11 +- swGUI/Tests/TestGUISystem/TestMouseEvents.cpp | 15 +- .../Tests/TestGUISystem/TestRegistration.cpp | 11 +- swGUI/Tests/TestGUISystem/stdafx.cpp | 7 + swGUI/Tests/TestGUISystem/stdafx.h | 15 + .../TestRenderingSystem.DX11/TestLayouts.cpp | 2 +- .../Tests/TestRenderingSystem/TestDrawing.cpp | 52 +- .../Tests/TestRenderingSystem/TestLayouts.cpp | 2 +- .../TestShaderProvider.cpp | 28 +- .../BasicShapes/BasicShapes.vcxproj | 4 + .../GeometricsCore/GeometricsCore.vcxproj | 4 + .../Visual2015/LinkReflection.props | 31 + .../ProjectDir/Visual2015/Paths.props | 2 +- .../TestBasicShapes/TestBasicShapes.vcxproj | 4 + .../TestGenerationFramework.vcxproj | 4 + swGraphicAPI/.gitignore | 2 + .../Assets/MaterialAsset/MaterialAsset.cpp | 76 + .../Assets/MaterialAsset/MaterialAsset.h | 106 + .../MaterialAsset/MaterialAssetInitData.cpp | 58 + .../MaterialAsset/MaterialAssetInitData.h | 66 + .../Assets/MaterialAsset/MaterialCreator.cpp | 85 + .../Assets/MaterialAsset/MaterialCreator.h | 53 + .../Assets/MaterialAsset/MaterialInfo.h | 89 + .../Assets/MaterialAsset/PhongMaterialData.h | 64 + .../Assets/MaterialAsset/ShadingModelData.h | 102 + .../Assets/MaterialAsset/ShadingModels.cpp | 55 + swGraphicAPI/Assets/MaterialAsset/stdafx.cpp | 9 + swGraphicAPI/Assets/MaterialAsset/stdafx.h | 44 + swGraphicAPI/Assets/MeshAsset/stdafx.cpp | 9 + swGraphicAPI/Assets/MeshAsset/stdafx.h | 44 + .../DX11Initializer/DX11APIObjects.cpp | 98 +- .../DX11API/DX11Initializer/DX11APIObjects.h | 36 +- .../DX11Initializer/DX11ConstantsMapper.cpp | 306 +- .../DX11Initializer/DX11ConstantsMapper.h | 53 +- .../DX11Initializer/DX11DebugLayer.cpp | 30 + .../DX11API/DX11Initializer/DX11DebugLayer.h | 38 + .../DX11Initializer/DX11Initializer.cpp | 61 +- .../DX11API/DX11Initializer/DX11Initializer.h | 18 +- .../DX11API/DX11Initializer/DX11Utils.cpp | 28 +- .../DX11API/DX11Initializer/DX11Utils.h | 22 +- .../DX11API/DX11Initializer/DX11Utils.inl | 11 + .../DX11API/DX11Renderer/DX11Renderer.cpp | 69 +- .../DX11API/DX11Renderer/DX11Renderer.h | 56 +- .../DX11API/DX11Resources/DX11Buffer.cpp | 52 +- .../DX11API/DX11Resources/DX11Buffer.h | Bin 1812 -> 2078 bytes .../DX11API/DX11Resources/DX11Compiler.cpp | 127 +- .../DX11API/DX11Resources/DX11Compiler.h | 53 +- .../DX11Resources/DX11ComputeShader.cpp | Bin 3522 -> 3438 bytes .../DX11API/DX11Resources/DX11ComputeShader.h | Bin 1896 -> 2342 bytes .../DX11API/DX11Resources/DX11InputLayout.cpp | 265 +- .../DX11API/DX11Resources/DX11InputLayout.h | 32 +- .../DX11InputLayoutDescriptor.cpp | 44 - .../DX11Resources/DX11InputLayoutDescriptor.h | 31 - .../DX11Resources/DX11PipelineState.cpp | 83 +- .../DX11API/DX11Resources/DX11PipelineState.h | 74 +- .../DX11API/DX11Resources/DX11PixelShader.cpp | Bin 5092 -> 3898 bytes .../DX11API/DX11Resources/DX11PixelShader.h | Bin 2352 -> 2266 bytes .../DX11Resources/DX11RenderTarget.cpp | Bin 23496 -> 24500 bytes .../DX11API/DX11Resources/DX11RenderTarget.h | Bin 3004 -> 3522 bytes .../DX11API/DX11Resources/DX11SwapChain.cpp | 25 +- .../DX11API/DX11Resources/DX11SwapChain.h | 22 +- .../DX11API/DX11Resources/DX11Texture.cpp | 157 +- .../DX11API/DX11Resources/DX11Texture.h | Bin 3230 -> 3964 bytes .../DX11Resources/DX11VertexShader.cpp | Bin 10126 -> 3500 bytes .../DX11API/DX11Resources/DX11VertexShader.h | Bin 2934 -> 2260 bytes .../DX11Resources/ResourcesFactory.cpp | 145 +- swGraphicAPI/DX11API/stdafx.h | 1 - swGraphicAPI/GraphicAPI.sln | 139 +- .../ImageGenerators/CheckerboardGenerator.cpp | 78 + .../ImageGenerators/CheckerboardGenerator.h | 49 + .../SoilTextureLoader/SOIL/etc1_utils.cpp | 680 ++ .../SoilTextureLoader/SOIL/etc1_utils.h | 106 + .../SoilTextureLoader/SOIL/image_DXT.c | 632 ++ .../SoilTextureLoader/SOIL/image_DXT.h | 123 + .../SoilTextureLoader/SOIL/image_helper.c | 435 ++ .../SoilTextureLoader/SOIL/image_helper.h | 115 + .../Loaders/SoilTextureLoader/SOIL/jo_jpeg.h | 338 + .../SoilTextureLoader/SOIL/pkm_helper.h | 19 + .../SoilTextureLoader/SOIL/pvr_helper.h | 264 + .../SoilTextureLoader/SOIL/stb_image.h | 6582 +++++++++++++++++ .../SoilTextureLoader/SOIL/stb_image_write.h | 993 +++ .../Loaders/SoilTextureLoader/SOIL/stbi_DDS.h | 34 + .../SoilTextureLoader/SOIL/stbi_DDS_c.h | 589 ++ .../Loaders/SoilTextureLoader/SOIL/stbi_ext.h | 28 + .../SoilTextureLoader/SOIL/stbi_ext_c.h | 74 + .../Loaders/SoilTextureLoader/SOIL/stbi_pkm.h | 34 + .../SoilTextureLoader/SOIL/stbi_pkm_c.h | 227 + .../Loaders/SoilTextureLoader/SOIL/stbi_pvr.h | 34 + .../SoilTextureLoader/SOIL/stbi_pvr_c.h | 1001 +++ .../SoilTextureLoader/SoilTextureLoader.cpp | 176 + .../SoilTextureLoader/SoilTextureLoader.h | 43 + .../Loaders/SoilTextureLoader/stdafx.cpp | 9 + .../Loaders/SoilTextureLoader/stdafx.h | 40 + .../Loaders/swMaterialLoader/stdafx.cpp | 9 + .../Loaders/swMaterialLoader/stdafx.h | 43 + .../swMaterialLoader/swMaterialLoader.cpp | 548 ++ .../swMaterialLoader/swMaterialLoader.h | 88 + .../MockInitializer/MockInitializer.cpp | 16 +- .../MockAPI/MockInitializer/MockInitializer.h | 8 +- .../MockAPI/MockRenderer/MockRenderer.cpp | 13 +- .../MockAPI/MockRenderer/MockRenderer.h | 14 +- .../MockAPI/MockResources/MockBuffer.cpp | 17 +- .../MockAPI/MockResources/MockBuffer.h | Bin 1466 -> 1646 bytes .../MockResources/MockComputeShader.cpp | Bin 2504 -> 2754 bytes .../MockAPI/MockResources/MockComputeShader.h | Bin 1458 -> 1730 bytes .../MockAPI/MockResources/MockInputLayout.cpp | 13 +- .../MockAPI/MockResources/MockInputLayout.h | 12 +- .../MockInputLayoutDescriptor.cpp | 48 - .../MockResources/MockInputLayoutDescriptor.h | 45 - .../MockResources/MockPipelineState.cpp | 55 +- .../MockAPI/MockResources/MockPipelineState.h | 30 +- .../MockAPI/MockResources/MockPixelShader.cpp | Bin 3078 -> 3022 bytes .../MockAPI/MockResources/MockPixelShader.h | Bin 1940 -> 1702 bytes .../MockResources/MockRenderTarget.cpp | Bin 6576 -> 7238 bytes .../MockAPI/MockResources/MockRenderTarget.h | Bin 2034 -> 2512 bytes .../MockAPI/MockResources/MockSwapChain.cpp | 13 +- .../MockAPI/MockResources/MockSwapChain.h | 6 +- .../MockAPI/MockResources/MockTexture.cpp | 32 +- .../MockAPI/MockResources/MockTexture.h | Bin 1604 -> 2228 bytes .../MockResources/MockVertexShader.cpp | Bin 6114 -> 2498 bytes .../MockAPI/MockResources/MockVertexShader.h | Bin 2558 -> 1764 bytes .../MockResources/ResourcesFactory.cpp | 140 +- swGraphicAPI/MockAssets/GraphicAPI.h | 112 + swGraphicAPI/MockAssets/MockAsset.cpp | 39 + swGraphicAPI/MockAssets/MockAsset.h | 42 + swGraphicAPI/MockAssets/MockAssetCreator.cpp | 105 + swGraphicAPI/MockAssets/MockAssetCreator.h | 79 + swGraphicAPI/MockAssets/MockAssetLoader.cpp | 67 + swGraphicAPI/MockAssets/MockAssetLoader.h | 61 + .../MockAssets/MockCompositeAsset.cpp | 35 + swGraphicAPI/MockAssets/MockCompositeAsset.h | 47 + .../MockAssets/MockCompositeAssetCreator.cpp | 95 + .../MockAssets/MockCompositeAssetCreator.h | 73 + .../MockAssets/MockCompositeAssetLoader.cpp | 143 + .../MockAssets/MockCompositeAssetLoader.h | 73 + swGraphicAPI/MockAssets/Utils.h | 97 + swGraphicAPI/MockAssets/stdafx.cpp | 9 + swGraphicAPI/MockAssets/stdafx.h | 51 + .../Visual2015/LibraryTemplate.vcxproj | 153 + .../Visual2015/LibraryTemplateConfig.props | 21 + .../Templates/Visual2015/TestTemplate.vcxproj | 167 + .../TestAssets/material/invalid-version.swmat | 25 + .../TestAssets/material/invalid-xml.swmat | 26 + .../material/no-MaterialAsset.swmat | 2 + .../TestAssets/material/no-gs-entry.swmat | 24 + .../TestAssets/material/no-header.swmat | 2 + .../TestAssets/material/no-ps.swmat | 25 + .../material/no-textures-entry.swmat | 19 + .../TestAssets/material/no-vs.swmat | 25 + .../TestAssets/material/not-existing-ps.swmat | 25 + .../material/not-existing-texture.swmat | 22 + .../TestAssets/material/not-existing-vs.swmat | 25 + .../material/single-texture-entry.swmat | 22 + .../ProjectsDir/TestAssets/mock/example.mock | 1 + .../ProjectsDir/TestAssets/mock/example1.mock | 1 + .../ProjectsDir/TestAssets/mock/example2.mock | 1 + .../ProjectsDir/TestAssets/mock/example3.mock | 1 + .../TestAssets/shaders/hlsl/MinimalShader.csh | 19 + .../TestAssets/shaders/hlsl/MinimalShader.psh | 9 + .../TestAssets/shaders/hlsl/MinimalShader.vsh | 16 + .../TestAssets/shaders/hlsl/NotCompiing.psh | 8 + .../TestAssets/shaders/hlsl/NotCompiling.csh | 19 + .../TestAssets/shaders/hlsl/NotCompiling.vsh | 16 + .../TestAssets/texture/big-lightweight.png | Bin 0 -> 16786 bytes .../TestAssets/texture/random-pixels.bmp | Bin 0 -> 102 bytes .../TestAssets/texture/random-pixels.jpg | Bin 0 -> 788 bytes .../TestAssets/texture/random-pixels.png | Bin 0 -> 148 bytes .../Visual2015/DX11API/DX11API.vcxproj | 4 +- .../DX11API/DX11API.vcxproj.filters | 12 +- .../MaterialAsset/MaterialAsset.vcxproj | 166 + .../MaterialAsset.vcxproj.filters | 51 + .../MaterialAsset/MaterialAssetConfig.props | 21 + .../Visual2015/MeshAsset/MeshAsset.vcxproj | 156 + .../MeshAsset/MeshAsset.vcxproj.filters | 21 + .../MeshAsset/MeshAssetConfig.props | 21 + .../Visual2015/MockAPI/MockAPI.vcxproj | 2 - .../MockAPI/MockAPI.vcxproj.filters | 6 - .../Visual2015/MockAssets/MockAssets.vcxproj | 170 + .../MockAssets/MockAssets.vcxproj.filters | 66 + .../MockAssets/MockAssetsConfig.props | 21 + .../ProjectsDir/Visual2015/Paths.props | 2 +- .../ResourceManager/ResourceManager.vcxproj | 111 +- .../ResourceManager.vcxproj.filters | 352 +- .../SoilTextureLoader.vcxproj | 180 + .../SoilTextureLoader.vcxproj.filters | 87 + .../SoilTextureLoaderConfig.props | 21 + .../Tests/TestMaterial/TestMaterial.vcxproj | 195 + .../TestMaterial/TestMaterial.vcxproj.filters | 25 + .../TestMipMapGenerator.vcxproj | 175 + .../TestResourceManager.vcxproj | 220 + .../TestResourceManager.vcxproj.filters | 94 + .../TestResources/TestResources.DX11.vcxproj | 13 +- .../TestResources.DX11.vcxproj.filters | 50 + .../TestSoilTextureLoader.DX11.vcxproj | 179 + ...TestSoilTextureLoader.DX11.vcxproj.filters | 16 + .../TestSoilTextureLoader.vcxproj | 190 + .../TestSoilTextureLoader.vcxproj.filters | 14 + .../swMaterialLoader/swMaterialLoader.vcxproj | 161 + .../swMaterialLoader.vcxproj.filters | 27 + .../swMaterialLoaderConfig.props | 21 + swGraphicAPI/Rendering/GraphicAPIConstants.h | 98 +- .../Rendering/IGraphicAPIInitializer.h | 54 +- swGraphicAPI/Rendering/IRenderer.h | 40 +- swGraphicAPI/Rendering/RenderCommands.h | 52 +- .../AssetCreators/AssetsFactory.cpp | 158 + .../AssetCreators/AssetsFactory.h | 88 + .../AssetCreators/Buffers/BufferCreator.cpp | 145 + .../AssetCreators/Buffers/BufferCreator.h | 52 + .../AssetCreators/IAssetCreateInfo.h | 42 + .../AssetCreators/IAssetCreator.h | 85 + .../PipelineStates/BlendingStateCreator.cpp | 81 + .../PipelineStates/BlendingStateCreator.h | 48 + .../DepthStencilStateCreator.cpp | 81 + .../PipelineStates/DepthStencilStateCreator.h | 48 + .../PipelineStates/RasterizerStateCreator.cpp | 81 + .../PipelineStates/RasterizerStateCreator.h | 48 + .../AssetCreators/Shaders/LayoutCreator.cpp | 79 + .../AssetCreators/Shaders/LayoutCreator.h | 45 + .../AssetCreators/Shaders/ShaderCreator.h | 62 + .../AssetCreators/Shaders/ShaderCreator.inl | 179 + .../Textures/MipMapGenerator.cpp | 296 + .../AssetCreators/Textures/MipMapGenerator.h | 43 + .../Textures/RenderTargetCreator.cpp | 87 + .../Textures/RenderTargetCreator.h | 69 + .../Textures/Resampler/resampler.cpp | 1220 +++ .../Textures/Resampler/resampler.h | 196 + .../AssetCreators/Textures/TextureCreator.cpp | 119 + .../AssetCreators/Textures/TextureCreator.h | 65 + .../AsyncLoad/AssetLoadRequest.h | 67 + .../AsyncLoad/AssetLoadResponse.h | 41 + .../AsyncLoad/AssetsThread.cpp | 86 + .../ResourceManager/AsyncLoad/AssetsThread.h | 80 + .../ResourceManager/AsyncLoad/LoadBarrier.cpp | 213 + .../ResourceManager/AsyncLoad/LoadBarrier.h | 110 + .../AsyncLoad/RMAsyncThread.cpp | 42 + .../ResourceManager/AsyncLoad/RMAsyncThread.h | 50 + .../ResourceManager/Cache/CacheManager.cpp | 46 + .../ResourceManager/Cache/CacheManager.h | 43 + .../ResourceManager/Cache/IAssetCache.h | 55 + .../ResourceManager/Cache/MemoryCache.cpp | 37 + .../ResourceManager/Cache/MemoryCache.h | 40 + .../Exceptions/LoaderException.cpp | 60 + .../Exceptions/LoaderException.h | 57 + .../Exceptions/ResourceManagerException.cpp | 49 + .../Exceptions/ResourceManagerException.h | 42 + .../ResourceManager/Loaders/IAssetLoadInfo.h | 38 + .../ResourceManager/Loaders/IAssetLoader.h | 117 + .../ResourceManager/Loaders/LoadingResult.h | 98 + .../ResourceManager/Loaders/RMLoaderAPI.h | 73 + .../Loaders/RenderTargetLoadInfo.h | 63 + .../Loaders/RenderTargetLoader.cpp | 116 + .../Loaders/RenderTargetLoader.h | 45 + .../ResourceManager/Loaders/ShaderLoader.cpp | 98 + .../ResourceManager/Loaders/ShaderLoader.h | 36 + .../ResourceManager/Loaders/TextureLoadInfo.h | 69 + .../ResourceManager/Loaders/Tools/CanLoad.h | 62 + .../Loaders/Tools/LoadingContext.h | 99 + .../PathTranslators/AssetPath.cpp | 42 + .../PathTranslators/AssetPath.h | 165 + .../PathTranslators/LoadPath.h | 131 + .../PathTranslators}/PathsManager.cpp | 13 +- .../PathTranslators}/PathsManager.h | 19 +- .../ResourceManager/ResourceContainer.h | 360 +- .../ResourceManager/ResourceManager.cpp | 707 +- .../ResourceManager/ResourceManager.h | 291 +- .../ResourceManager/ResourceManagerAPI.cpp | 279 + .../ResourceManager/ResourceManagerAPI.h | 302 + swGraphicAPI/ResourceManager/stdafx.h | 14 +- swGraphicAPI/Resources/Buffers/Buffer.cpp | 59 + swGraphicAPI/Resources/Buffers/Buffer.h | 47 + .../Resources/{ => Buffers}/BufferInitData.h | 79 +- .../Resources/{ => Buffers}/IBuffer.h | 36 +- swGraphicAPI/Resources/DepthStencilState.h | 61 - swGraphicAPI/Resources/IRenderTarget.h | 18 - swGraphicAPI/Resources/IShader.h | 34 - swGraphicAPI/Resources/IShaderInputLayout.h | 23 - swGraphicAPI/Resources/MeshResources.cpp | 222 +- swGraphicAPI/Resources/MeshResources.h | 445 +- .../{ => PipelineStates}/BlendingState.h | 59 +- .../PipelineStates/DepthStencilState.h | 75 + .../{ => PipelineStates}/RasterizerState.h | 53 +- swGraphicAPI/Resources/Resource.cpp | 318 + swGraphicAPI/Resources/ResourceObject.h | 166 +- swGraphicAPI/Resources/ResourcePtr.h | 248 +- swGraphicAPI/Resources/ResourcesFactory.h | 92 +- .../Shaders/Exceptions/CompilationException.h | 54 + swGraphicAPI/Resources/Shaders/IShader.h | 37 + .../Resources/Shaders/IShaderInputLayout.h | 31 + swGraphicAPI/Resources/Shaders/InputLayout.h | 38 + .../Resources/Shaders/LayoutInitData.h | 96 + swGraphicAPI/Resources/Shaders/Layouts.cpp | 91 + .../Resources/Shaders/ShaderInitData.h | 76 + swGraphicAPI/Resources/Shaders/Shaders.cpp | 82 + swGraphicAPI/Resources/Shaders/Shaders.h | 169 + swGraphicAPI/Resources/SwapChain.h | 63 +- swGraphicAPI/Resources/Texture.cpp | 99 - swGraphicAPI/Resources/Texture.h | 157 - .../Resources/Textures/IRenderTarget.h | 31 + .../Resources/Textures/RenderTarget.cpp | 56 + .../Resources/Textures/RenderTarget.h | 128 + swGraphicAPI/Resources/Textures/Texture.cpp | 105 + swGraphicAPI/Resources/Textures/Texture.h | 216 + .../Resources/Textures/TextureInitData.h | 80 + .../Tests/TestMaterial/TestCreation.cpp | 71 + .../TestMaterial/TestSWMaterialLoader.cpp | 190 + .../TestMaterial/TestSWMaterialSaver.cpp | 170 + swGraphicAPI/Tests/TestMaterial/Utils.h | 89 + swGraphicAPI/Tests/TestMaterial/main.cpp | 3 + .../Tests/TestMipMapGenerator/TestMipMaps.cpp | 64 + .../Tests/TestMipMapGenerator/main.cpp | 3 + .../TestResourceManager/LoadBarrierTest.cpp | 249 + .../TestResourceManager/TestAssetPath.cpp | 180 + .../TestResourceManager/TestAssetsFactory.cpp | 75 + .../TestCreators/TestBufferCreator.cpp | 47 + .../TestResourceManager/TestLoadPath.cpp | 68 + .../TestLoaders/TestRenderTargetLoader.cpp | 49 + .../TestLoaders/TestShaderLoader.cpp | 67 + .../TestResourceManager/TestLoadingResult.cpp | 140 + .../TestResourceManager}/TestPathsManager.cpp | 22 +- .../TestAssetsCreation.cpp | 125 + .../TestAssetsLoadingAsync.cpp | 107 + .../TestAssetsLoadingSync.cpp | 123 + .../TestResourceManager/TestAssetsRemoval.cpp | 118 + .../TestResourceManager/TestListAssets.cpp | 36 + .../TestResourceManager/TestLoaders.cpp | 41 + .../TestResourceManager/TestPathAliases.cpp | 87 + .../TestResourceManagerAPI.cpp | 97 + .../TestResourceManager/TestResourcePtr.cpp | 43 + .../Utils/Tests/TestMockCompositeAsset.cpp | 85 + .../Tests/TestResourceManager/main.cpp | 3 + .../Tests/TestResourceManager/stdafx.cpp | 7 + .../Tests/TestResourceManager/stdafx.h | 25 + .../Tests/TestResources.DX11/GraphicAPI.h | 54 - .../TestResources.DX11/TestBlendingState.cpp | 14 +- .../TestCreators/TestBlendingStateCreator.cpp | 35 + .../TestCreators/TestBufferCreator.cpp | 124 + .../TestDepthStencilStateCreator.cpp | 33 + .../TestCreators/TestLayoutCreator.cpp | 120 + .../TestRasterizerStateCreator.cpp | 32 + .../TestCreators/TestRenderTargetCreator.cpp | 72 + .../TestCreators/TestShaderCreator.cpp | 122 + .../TestCreators/TestTextureCreator.cpp | 81 + .../TestLoaders/TestRenderTargetLoader.cpp | 65 + .../TestLoaders/TestShaderLoader.cpp | 65 + .../Tests/TestResources.DX11/main.cpp | 4 + .../TestFilesLoading.cpp | 104 + .../TestMipMapGeneration.cpp | 45 + .../Tests/TestSoilTextureLoader.DX11/main.cpp | 7 + .../TestTextureLoading.cpp | 78 + .../Tests/TestSoilTextureLoader/main.cpp | 3 + .../ProjectsDir/Visual2015/Paths.props | 2 +- swLibraries-Versions.xml | 74 + 486 files changed, 47030 insertions(+), 4027 deletions(-) delete mode 100644 swCommonLib/Common/Converters.cpp create mode 100644 swCommonLib/Common/Converters/Convert.cpp create mode 100644 swCommonLib/Common/Converters/Convert.h create mode 100644 swCommonLib/Common/Converters/ConvertArithmetic.h create mode 100644 swCommonLib/Common/Converters/ConvertEnums.h create mode 100644 swCommonLib/Common/Converters/ConvertTraits.h create mode 100644 swCommonLib/Common/Exceptions/Common/FileNotFoundException.cpp create mode 100644 swCommonLib/Common/Exceptions/Common/FileNotFoundException.h create mode 100644 swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.cpp create mode 100644 swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.h create mode 100644 swCommonLib/Common/Macros/DefineFmtFormatter.h create mode 100644 swCommonLib/Common/Macros/ForEach.h create mode 100644 swCommonLib/Common/Macros/GenerateOperators.h delete mode 100644 swCommonLib/Common/ObjectDeleter.h create mode 100644 swCommonLib/Common/Version.cpp create mode 100644 swCommonLib/Common/fmt.h create mode 100644 swCommonLib/External/fmt/chrono.h create mode 100644 swCommonLib/External/fmt/color.h create mode 100644 swCommonLib/External/fmt/compile.h create mode 100644 swCommonLib/External/fmt/core.h create mode 100644 swCommonLib/External/fmt/format-inl.h create mode 100644 swCommonLib/External/fmt/format.h create mode 100644 swCommonLib/External/fmt/locale.h create mode 100644 swCommonLib/External/fmt/ostream.h create mode 100644 swCommonLib/External/fmt/posix.h create mode 100644 swCommonLib/External/fmt/printf.h create mode 100644 swCommonLib/External/fmt/ranges.h create mode 100644 swCommonLib/External/fmt/safe-duration-cast.h create mode 100644 swCommonLib/TestUtils/CatchUtils/ExtendedMacros.h create mode 100644 swCommonLib/Tests/BuffersTest/TestStackBuffer.cpp create mode 100644 swCommonLib/Tests/FileSystemTest/TestNormalizePath.cpp create mode 100644 swCommonLib/Tests/TestHelpers/TestConverters.cpp create mode 100644 swCommonLib/Tests/TestHelpers/TestDefineFormatter.cpp create mode 100644 swCommonLib/Tests/TestHelpers/TestMacros.cpp create mode 100644 swCommonLib/Tests/TestHelpers/TestNullable.cpp create mode 100644 swCommonLib/Tests/TestHelpers/TestVersion.cpp create mode 100644 swGUI/Core/Media/Geometry/Layouts/VertexShape2D.cpp.orig create mode 100644 swGUI/ProjectDir/Output/WorkingDir-RenderingSystem/textures/Tex1.png create mode 100644 swGUI/ProjectDir/Output/WorkingDir-RenderingSystem/textures/Tex2.png create mode 100644 swGUI/Tests/TestGUISystem/TestHostWindow.cpp create mode 100644 swGUI/Tests/TestGUISystem/stdafx.cpp create mode 100644 swGUI/Tests/TestGUISystem/stdafx.h create mode 100644 swGeometrics/ProjectDir/Visual2015/LinkReflection.props create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialAsset.cpp create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialAsset.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialAssetInitData.cpp create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialAssetInitData.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialCreator.cpp create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialCreator.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/MaterialInfo.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/PhongMaterialData.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/ShadingModelData.h create mode 100644 swGraphicAPI/Assets/MaterialAsset/ShadingModels.cpp create mode 100644 swGraphicAPI/Assets/MaterialAsset/stdafx.cpp create mode 100644 swGraphicAPI/Assets/MaterialAsset/stdafx.h create mode 100644 swGraphicAPI/Assets/MeshAsset/stdafx.cpp create mode 100644 swGraphicAPI/Assets/MeshAsset/stdafx.h create mode 100644 swGraphicAPI/DX11API/DX11Initializer/DX11DebugLayer.cpp create mode 100644 swGraphicAPI/DX11API/DX11Initializer/DX11DebugLayer.h delete mode 100644 swGraphicAPI/DX11API/DX11Resources/DX11InputLayoutDescriptor.cpp delete mode 100644 swGraphicAPI/DX11API/DX11Resources/DX11InputLayoutDescriptor.h create mode 100644 swGraphicAPI/ImageGenerators/CheckerboardGenerator.cpp create mode 100644 swGraphicAPI/ImageGenerators/CheckerboardGenerator.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/etc1_utils.cpp create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/etc1_utils.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/image_DXT.c create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/image_DXT.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/image_helper.c create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/image_helper.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/jo_jpeg.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/pkm_helper.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/pvr_helper.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stb_image.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stb_image_write.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_DDS.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_DDS_c.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_ext.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_ext_c.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_pkm.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_pkm_c.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_pvr.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SOIL/stbi_pvr_c.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SoilTextureLoader.cpp create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/SoilTextureLoader.h create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/stdafx.cpp create mode 100644 swGraphicAPI/Loaders/SoilTextureLoader/stdafx.h create mode 100644 swGraphicAPI/Loaders/swMaterialLoader/stdafx.cpp create mode 100644 swGraphicAPI/Loaders/swMaterialLoader/stdafx.h create mode 100644 swGraphicAPI/Loaders/swMaterialLoader/swMaterialLoader.cpp create mode 100644 swGraphicAPI/Loaders/swMaterialLoader/swMaterialLoader.h delete mode 100644 swGraphicAPI/MockAPI/MockResources/MockInputLayoutDescriptor.cpp delete mode 100644 swGraphicAPI/MockAPI/MockResources/MockInputLayoutDescriptor.h create mode 100644 swGraphicAPI/MockAssets/GraphicAPI.h create mode 100644 swGraphicAPI/MockAssets/MockAsset.cpp create mode 100644 swGraphicAPI/MockAssets/MockAsset.h create mode 100644 swGraphicAPI/MockAssets/MockAssetCreator.cpp create mode 100644 swGraphicAPI/MockAssets/MockAssetCreator.h create mode 100644 swGraphicAPI/MockAssets/MockAssetLoader.cpp create mode 100644 swGraphicAPI/MockAssets/MockAssetLoader.h create mode 100644 swGraphicAPI/MockAssets/MockCompositeAsset.cpp create mode 100644 swGraphicAPI/MockAssets/MockCompositeAsset.h create mode 100644 swGraphicAPI/MockAssets/MockCompositeAssetCreator.cpp create mode 100644 swGraphicAPI/MockAssets/MockCompositeAssetCreator.h create mode 100644 swGraphicAPI/MockAssets/MockCompositeAssetLoader.cpp create mode 100644 swGraphicAPI/MockAssets/MockCompositeAssetLoader.h create mode 100644 swGraphicAPI/MockAssets/Utils.h create mode 100644 swGraphicAPI/MockAssets/stdafx.cpp create mode 100644 swGraphicAPI/MockAssets/stdafx.h create mode 100644 swGraphicAPI/ProjectsDir/Templates/Visual2015/LibraryTemplate.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Templates/Visual2015/LibraryTemplateConfig.props create mode 100644 swGraphicAPI/ProjectsDir/Templates/Visual2015/TestTemplate.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/invalid-version.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/invalid-xml.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-MaterialAsset.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-gs-entry.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-header.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-ps.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-textures-entry.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/no-vs.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/not-existing-ps.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/not-existing-texture.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/not-existing-vs.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/material/single-texture-entry.swmat create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/mock/example.mock create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/mock/example1.mock create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/mock/example2.mock create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/mock/example3.mock create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/MinimalShader.csh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/MinimalShader.psh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/MinimalShader.vsh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/NotCompiing.psh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/NotCompiling.csh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/shaders/hlsl/NotCompiling.vsh create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/texture/big-lightweight.png create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/texture/random-pixels.bmp create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/texture/random-pixels.jpg create mode 100644 swGraphicAPI/ProjectsDir/TestAssets/texture/random-pixels.png create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MaterialAsset/MaterialAsset.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MaterialAsset/MaterialAsset.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MaterialAsset/MaterialAssetConfig.props create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MeshAsset/MeshAsset.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MeshAsset/MeshAsset.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MeshAsset/MeshAssetConfig.props create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MockAssets/MockAssets.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MockAssets/MockAssets.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/MockAssets/MockAssetsConfig.props create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/SoilTextureLoader/SoilTextureLoader.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/SoilTextureLoader/SoilTextureLoader.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/SoilTextureLoader/SoilTextureLoaderConfig.props create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestMaterial/TestMaterial.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestMaterial/TestMaterial.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestMipMapsGenerator/TestMipMapGenerator.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestResourceManager/TestResourceManager.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestResourceManager/TestResourceManager.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestResources/TestResources.DX11.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestSoilTextureLoader/TestSoilTextureLoader.DX11.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestSoilTextureLoader/TestSoilTextureLoader.DX11.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestSoilTextureLoader/TestSoilTextureLoader.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/Tests/TestSoilTextureLoader/TestSoilTextureLoader.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/swMaterialLoader/swMaterialLoader.vcxproj create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/swMaterialLoader/swMaterialLoader.vcxproj.filters create mode 100644 swGraphicAPI/ProjectsDir/Visual2015/swMaterialLoader/swMaterialLoaderConfig.props create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/AssetsFactory.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/AssetsFactory.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Buffers/BufferCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Buffers/BufferCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/IAssetCreateInfo.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/IAssetCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/BlendingStateCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/BlendingStateCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/DepthStencilStateCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/DepthStencilStateCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/RasterizerStateCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/PipelineStates/RasterizerStateCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Shaders/LayoutCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Shaders/LayoutCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Shaders/ShaderCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Shaders/ShaderCreator.inl create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/MipMapGenerator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/MipMapGenerator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/RenderTargetCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/RenderTargetCreator.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/Resampler/resampler.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/Resampler/resampler.h create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/TextureCreator.cpp create mode 100644 swGraphicAPI/ResourceManager/AssetCreators/Textures/TextureCreator.h create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/AssetLoadRequest.h create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/AssetLoadResponse.h create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/AssetsThread.cpp create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/AssetsThread.h create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/LoadBarrier.cpp create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/LoadBarrier.h create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/RMAsyncThread.cpp create mode 100644 swGraphicAPI/ResourceManager/AsyncLoad/RMAsyncThread.h create mode 100644 swGraphicAPI/ResourceManager/Cache/CacheManager.cpp create mode 100644 swGraphicAPI/ResourceManager/Cache/CacheManager.h create mode 100644 swGraphicAPI/ResourceManager/Cache/IAssetCache.h create mode 100644 swGraphicAPI/ResourceManager/Cache/MemoryCache.cpp create mode 100644 swGraphicAPI/ResourceManager/Cache/MemoryCache.h create mode 100644 swGraphicAPI/ResourceManager/Exceptions/LoaderException.cpp create mode 100644 swGraphicAPI/ResourceManager/Exceptions/LoaderException.h create mode 100644 swGraphicAPI/ResourceManager/Exceptions/ResourceManagerException.cpp create mode 100644 swGraphicAPI/ResourceManager/Exceptions/ResourceManagerException.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/IAssetLoadInfo.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/IAssetLoader.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/LoadingResult.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/RMLoaderAPI.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/RenderTargetLoadInfo.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/RenderTargetLoader.cpp create mode 100644 swGraphicAPI/ResourceManager/Loaders/RenderTargetLoader.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/ShaderLoader.cpp create mode 100644 swGraphicAPI/ResourceManager/Loaders/ShaderLoader.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/TextureLoadInfo.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/Tools/CanLoad.h create mode 100644 swGraphicAPI/ResourceManager/Loaders/Tools/LoadingContext.h create mode 100644 swGraphicAPI/ResourceManager/PathTranslators/AssetPath.cpp create mode 100644 swGraphicAPI/ResourceManager/PathTranslators/AssetPath.h create mode 100644 swGraphicAPI/ResourceManager/PathTranslators/LoadPath.h rename {swGUI/Core/System/Config => swGraphicAPI/ResourceManager/PathTranslators}/PathsManager.cpp (96%) rename {swGUI/Core/System/Config => swGraphicAPI/ResourceManager/PathTranslators}/PathsManager.h (78%) create mode 100644 swGraphicAPI/ResourceManager/ResourceManagerAPI.cpp create mode 100644 swGraphicAPI/ResourceManager/ResourceManagerAPI.h create mode 100644 swGraphicAPI/Resources/Buffers/Buffer.cpp create mode 100644 swGraphicAPI/Resources/Buffers/Buffer.h rename swGraphicAPI/Resources/{ => Buffers}/BufferInitData.h (61%) rename swGraphicAPI/Resources/{ => Buffers}/IBuffer.h (82%) delete mode 100644 swGraphicAPI/Resources/DepthStencilState.h delete mode 100644 swGraphicAPI/Resources/IRenderTarget.h delete mode 100644 swGraphicAPI/Resources/IShader.h delete mode 100644 swGraphicAPI/Resources/IShaderInputLayout.h rename swGraphicAPI/Resources/{ => PipelineStates}/BlendingState.h (55%) create mode 100644 swGraphicAPI/Resources/PipelineStates/DepthStencilState.h rename swGraphicAPI/Resources/{ => PipelineStates}/RasterizerState.h (54%) create mode 100644 swGraphicAPI/Resources/Resource.cpp create mode 100644 swGraphicAPI/Resources/Shaders/Exceptions/CompilationException.h create mode 100644 swGraphicAPI/Resources/Shaders/IShader.h create mode 100644 swGraphicAPI/Resources/Shaders/IShaderInputLayout.h create mode 100644 swGraphicAPI/Resources/Shaders/InputLayout.h create mode 100644 swGraphicAPI/Resources/Shaders/LayoutInitData.h create mode 100644 swGraphicAPI/Resources/Shaders/Layouts.cpp create mode 100644 swGraphicAPI/Resources/Shaders/ShaderInitData.h create mode 100644 swGraphicAPI/Resources/Shaders/Shaders.cpp create mode 100644 swGraphicAPI/Resources/Shaders/Shaders.h delete mode 100644 swGraphicAPI/Resources/Texture.cpp delete mode 100644 swGraphicAPI/Resources/Texture.h create mode 100644 swGraphicAPI/Resources/Textures/IRenderTarget.h create mode 100644 swGraphicAPI/Resources/Textures/RenderTarget.cpp create mode 100644 swGraphicAPI/Resources/Textures/RenderTarget.h create mode 100644 swGraphicAPI/Resources/Textures/Texture.cpp create mode 100644 swGraphicAPI/Resources/Textures/Texture.h create mode 100644 swGraphicAPI/Resources/Textures/TextureInitData.h create mode 100644 swGraphicAPI/Tests/TestMaterial/TestCreation.cpp create mode 100644 swGraphicAPI/Tests/TestMaterial/TestSWMaterialLoader.cpp create mode 100644 swGraphicAPI/Tests/TestMaterial/TestSWMaterialSaver.cpp create mode 100644 swGraphicAPI/Tests/TestMaterial/Utils.h create mode 100644 swGraphicAPI/Tests/TestMaterial/main.cpp create mode 100644 swGraphicAPI/Tests/TestMipMapGenerator/TestMipMaps.cpp create mode 100644 swGraphicAPI/Tests/TestMipMapGenerator/main.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/LoadBarrierTest.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestAssetPath.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestAssetsFactory.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestCreators/TestBufferCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestLoadPath.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestLoaders/TestRenderTargetLoader.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestLoaders/TestShaderLoader.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestLoadingResult.cpp rename {swGUI/Tests/TestGUISystem => swGraphicAPI/Tests/TestResourceManager}/TestPathsManager.cpp (86%) create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestAssetsCreation.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestAssetsLoadingAsync.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestAssetsLoadingSync.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestAssetsRemoval.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestListAssets.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestLoaders.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestPathAliases.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourceManager/TestResourceManagerAPI.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/TestResourcePtr.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/Utils/Tests/TestMockCompositeAsset.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/main.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/stdafx.cpp create mode 100644 swGraphicAPI/Tests/TestResourceManager/stdafx.h delete mode 100644 swGraphicAPI/Tests/TestResources.DX11/GraphicAPI.h create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestBlendingStateCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestBufferCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestDepthStencilStateCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestLayoutCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestRasterizerStateCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestRenderTargetCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestShaderCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestCreators/TestTextureCreator.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestLoaders/TestRenderTargetLoader.cpp create mode 100644 swGraphicAPI/Tests/TestResources.DX11/TestLoaders/TestShaderLoader.cpp create mode 100644 swGraphicAPI/Tests/TestSoilTextureLoader.DX11/TestFilesLoading.cpp create mode 100644 swGraphicAPI/Tests/TestSoilTextureLoader.DX11/TestMipMapGeneration.cpp create mode 100644 swGraphicAPI/Tests/TestSoilTextureLoader.DX11/main.cpp create mode 100644 swGraphicAPI/Tests/TestSoilTextureLoader/TestTextureLoading.cpp create mode 100644 swGraphicAPI/Tests/TestSoilTextureLoader/main.cpp diff --git a/sourcetreeconfig_backup b/sourcetreeconfig_backup index c6445198..109b84c7 100644 --- a/sourcetreeconfig_backup +++ b/sourcetreeconfig_backup @@ -43,4 +43,67 @@ swLibraries-Development - \ No newline at end of file + + +{ + "$id": "1", + "AutoRefresh": true, + "AutoRefreshRemotes": true, + "CommitTextLinks": [], + "DraftCommitMsg": "", + "IncomingSavedCount": 0, + "LastCheckedRemotes": "2019-10-10T13:46:49.1340647+02:00", + "LastUsedView": 1, + "LogBranchFilterIndex": 0, + "OutgoingSavedCount": 0, + "SidebarExpandedItems": [ + "Branches", + "Remotes", + "Stashes", + "Subtrees" + ], + "SidebarWidth": 210.0, + "SubtreeLinks": [], + "RemoteProjectLinks": [ + { + "$id": "2", + "BaseUrl": "https://www.github.com", + "Identifier": "nieznanysprawiciel/swLibraries", + "RemoteName": "origin", + "Type": 0, + "Username": "nieznanysprawiciel", + "CloneUrl": null, + "ProjectUrl": null, + "AccountId": "", + "AvatarUrl": null, + "DisplayName": "origin: https://www.github.com" + } + ], + "SubtreeLinks" : [ + { + "SourcePathUrl": "git@github.com:nieznanysprawiciel/swCommonLib.git", + "Prefix": "swCommonLib", + "Refspec": "swLibraries-Development" + }, + { + "SourcePathUrl": "git@github.com:nieznanysprawiciel/swGraphicAPI.git", + "Prefix": "swGraphicAPI", + "Refspec": "swLibraries-Development" + }, + { + "SourcePathUrl": "git@github.com:nieznanysprawiciel/swInputLibrary.git", + "Prefix": "swInputLibrary", + "Refspec": "swLibraries-Development" + }, + { + "SourcePathUrl": "git@github.com:nieznanysprawiciel/swGUI.git", + "Prefix": "swGUI", + "Refspec": "swLibraries-Development" + }, + { + "SourcePathUrl": "git@github.com:nieznanysprawiciel/swGeometrics.git", + "Prefix": "swGeometrics", + "Refspec": "swLibraries-Development" + } + ] +} \ No newline at end of file diff --git a/swCommonLib/Common/Buffers/BufferTyped.h b/swCommonLib/Common/Buffers/BufferTyped.h index cfc31dd4..c2314375 100644 --- a/swCommonLib/Common/Buffers/BufferTyped.h +++ b/swCommonLib/Common/Buffers/BufferTyped.h @@ -34,7 +34,7 @@ class BufferTyped explicit BufferTyped ( Size numElements ); explicit BufferTyped ( BufferRaw&& rawBuffer ); explicit BufferTyped ( const BufferTyped& buffer ) = delete; - explicit BufferTyped ( BufferTyped&& buffer ); + BufferTyped ( BufferTyped&& buffer ); ~BufferTyped (); @@ -42,11 +42,17 @@ class BufferTyped BufferTyped< ContentType, Alloc >& operator= ( const BufferTyped& ) = delete; BufferTyped< ContentType, Alloc >& operator= ( BufferTyped&& ); +private: + + /**@brief Stealing constructor takes ownership of memory.*/ + explicit BufferTyped ( ContentType*&& data, Size numElements ); + public: TypeID GetType () const { return TypeID::get< ContentType >(); } Size GetSize () const { return m_count * sizeof( ContentType ); } Size ElementsCount () const { return m_count; } + Size ElementSize () const { return sizeof( ContentType ); } uint8* GetRawData () { return reinterpret_cast< uint8* >( m_data ); } const uint8* GetRawData () const { return reinterpret_cast< const uint8* >( m_data ); } bool IsValid () const { return m_data != nullptr; } @@ -60,6 +66,14 @@ class BufferTyped /**@brief Creates raw buffer. Note that new buffer will be owner of memory and this object ends empty.*/ BufferRaw MoveToRawBuffer (); + +public: + static BufferRaw CreateEmpty (); + +public: + + /**@brief Takes ownership of memory.*/ + static BufferTyped< ContentType, Alloc > StealMemory ( ContentType*&& data, Size numElements ); }; @@ -121,6 +135,17 @@ inline BufferTyped< ContentType, Alloc >::BufferTyped ( BufferTyped< ContentTyp other.m_count = 0; } +// ================================ // +// +template< typename ContentType, class Alloc > +inline BufferTyped< ContentType, Alloc >::BufferTyped ( ContentType*&& data, Size numElements ) + : m_data( std::move( data ) ) + , m_count( numElements ) +{ + data = nullptr; + // Don't allocate. +} + // ================================ // // template< typename ContentType, class Alloc > @@ -176,6 +201,23 @@ inline BufferRaw BufferTyped< ContentType, Alloc >::MoveToRawBuffer () return rawBuffer; } +// ================================ // +// +template< typename ContentType, class Alloc > +inline BufferRaw BufferTyped< ContentType, Alloc >::CreateEmpty () +{ + BufferTyped< ContentType > buffer( 0 ); + return buffer.MoveToRawBuffer(); +} + +// ================================ // +// +template< typename ContentType, class Alloc > +inline BufferTyped< ContentType, Alloc > BufferTyped< ContentType, Alloc >::StealMemory ( ContentType*&& data, Size numElements ) +{ + return BufferTyped< ContentType, Alloc >( std::move( data ), numElements ); +} + } // sw diff --git a/swCommonLib/Common/Buffers/StackBuffer.h b/swCommonLib/Common/Buffers/StackBuffer.h index 20a124e9..e4c51d0c 100644 --- a/swCommonLib/Common/Buffers/StackBuffer.h +++ b/swCommonLib/Common/Buffers/StackBuffer.h @@ -40,7 +40,7 @@ namespace impl template< typename StructType, Size align > constexpr Size ComputePadding () { - return align - sizeof( StructType ) % align; + return ( align - sizeof( StructType ) % align ) % align; } // ================================ // @@ -51,6 +51,20 @@ constexpr Size SizeofWithPadding () return sizeof( StructType ) + ComputePadding< StructType, align >(); } +// ================================ // +// Inherit this struct to force padding. +template< Size size > +struct PaddingStruct +{ + uint8 Padding[ size ]; +}; + +// ================================ // +// +template<> +struct PaddingStruct< 0 > +{}; + } // impl @@ -60,13 +74,10 @@ constexpr Size SizeofWithPadding () You can use this structure for storing constants buffers data, since they need to be 16 bytes multiply.*/ template< typename StructType, Size align = 16 > -class StackBufferA : public StructType +class StackBufferA : public StructType, impl::PaddingStruct< impl::ComputePadding< StructType, align >() > { typedef StackBufferA< StructType, align >* ThisType; private: - - uint8 Padding[ impl::ComputePadding< StructType, align >() ]; - public: explicit StackBufferA() diff --git a/swCommonLib/Common/Converters.cpp b/swCommonLib/Common/Converters.cpp deleted file mode 100644 index c159354e..00000000 --- a/swCommonLib/Common/Converters.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "Converters.h" - diff --git a/swCommonLib/Common/Converters.h b/swCommonLib/Common/Converters.h index c670e507..e428a5b6 100644 --- a/swCommonLib/Common/Converters.h +++ b/swCommonLib/Common/Converters.h @@ -1,151 +1,13 @@ #pragma once +/** +@file Converters.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. -#include -#include -#include - - - - -class Convert -{ -private: - - template< typename SrcType > - static inline std::string EnumToString ( SrcType defaultVal ); - - template< typename SrcType > - static inline SrcType StringToEnum ( const std::string& value, SrcType defaultValue ); - -public: - - template< typename SrcType > - static inline typename std::enable_if< std::is_enum< SrcType >::value, std::string >::type - ToString ( const SrcType& val ); - - template< typename SrcType > - static inline typename std::enable_if< std::is_enum< SrcType >::value, SrcType >::type - FromString ( const std::string& val, const SrcType& defaultValue ); - - template< typename SrcType > - static inline typename std::enable_if< !std::is_enum< SrcType >::value, std::string >::type - ToString ( const SrcType& val ); - - template< typename SrcType > - static inline typename std::enable_if< !std::is_enum< SrcType >::value, SrcType >::type - FromString ( const std::string& val, const SrcType& defaultValue ); - - - - template<> - static inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::string >::type - ToString< std::wstring > ( const std::wstring& value ); - - template<> - static inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::wstring >::type - FromString< std::wstring > ( const std::string& value, const std::wstring& defaultValue ); - -}; - - -template< typename SrcType > -inline typename std::enable_if< !std::is_enum< SrcType >::value, std::string >::type - Convert::ToString ( const SrcType& val ) -{ - return std::to_string( val ); -} - -template< typename SrcType > -inline typename std::enable_if< !std::is_enum< SrcType >::value, SrcType >::type - Convert::FromString ( const std::string& val, const SrcType& defaultValue ) -{ - static_assert( false, "Specialize template" ); - return SrcType(); -} - - -//====================================================================================// -// Public template specialization for enum types -//====================================================================================// - -/**@brief Konwertuje enuma do stringa.*/ -template< typename SrcType > -inline typename std::enable_if< std::is_enum< SrcType >::value, std::string >::type - Convert::ToString ( const SrcType& val ) -{ - return EnumToString( val ); -} - -/**@brief Konwertuje stringa do enuma.*/ -template< typename SrcType > -inline typename std::enable_if< std::is_enum< SrcType >::value, SrcType >::type - Convert::FromString ( const std::string& val, const SrcType& defaultValue ) -{ - return StringToEnum( val, defaultValue ); -} - -//====================================================================================// -// Wstring to string -//====================================================================================// - -template<> -inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::string >::type - Convert::ToString< std::wstring > ( const std::wstring& value ) -{ - typedef std::codecvt_utf8 convert_type; - std::wstring_convert converter; - return converter.to_bytes( value ); -} - -template<> -inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::wstring >::type - Convert::FromString< std::wstring > ( const std::string& value, const std::wstring& defaultValue ) -{ - typedef std::codecvt_utf8 convert_type; - std::wstring_convert converter; - return converter.from_bytes( value ); -} - -//====================================================================================// -// Private enum helpers -//====================================================================================// - - -template< typename SrcType > -std::string Convert::EnumToString ( SrcType value ) -{ - static_assert( std::is_enum< SrcType >::value, "Type is not enum" ); - - auto type = rttr::type::get< SrcType >(); - - assert( type.is_valid() ); /// Type haven't been registered. - assert( type.is_enumeration() ); - - rttr::enumeration enumVal = type.get_enumeration(); - - return enumVal.value_to_name( value ); -} - - -template< typename SrcType > -SrcType Convert::StringToEnum ( const std::string& value, SrcType defaultValue ) -{ - static_assert( std::is_enum< SrcType >::value, "Type is not enum" ); - - auto type = rttr::type::get< SrcType >(); - - assert( type.is_valid() ); /// Type haven't been registered. - assert( type.is_enumeration() ); - - rttr::enumeration enumVal = type.get_enumeration(); - - rttr::variant result = enumVal.value_to_name( value ); - if( !result.is_valid() ) - return defaultValue; - - return result.get_value< SrcType >(); -} - +@todo This file includes swCommonLib/Common/Converters/Convert.h for backward compatibility. +In future we should remove this header. +*/ +#include "swCommonLib/Common/Converters/Convert.h" diff --git a/swCommonLib/Common/Converters/Convert.cpp b/swCommonLib/Common/Converters/Convert.cpp new file mode 100644 index 00000000..76ac271b --- /dev/null +++ b/swCommonLib/Common/Converters/Convert.cpp @@ -0,0 +1,29 @@ +/** +@file Convert.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + +#include "Convert.h" + + + +namespace impl +{ + +/**@brief Exception returned when conversion fails. + +This is hack to avoid allocating new exception each time conversion fails. +Other solution would be to return std::optional when we move to c++17.*/ +auto conversionException = std::make_shared< sw::RuntimeException >( "Conversion between types failed." ); + +// ================================ // +// +sw::ExceptionPtr ConversionException () +{ + return std::static_pointer_cast< sw::Exception >( conversionException ); +} + +} + diff --git a/swCommonLib/Common/Converters/Convert.h b/swCommonLib/Common/Converters/Convert.h new file mode 100644 index 00000000..6a00debb --- /dev/null +++ b/swCommonLib/Common/Converters/Convert.h @@ -0,0 +1,188 @@ +#pragma once +/** +@file Convert.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + +#include +#include +#include + +#include "swCommonLib/Common/Exceptions/Nullable.h" +#include "swCommonLib/Common/Macros/DefineFmtFormatter.h" +#include "ConvertTraits.h" + + + + +/**@brief Class for converting to/from string.*/ +class Convert +{ +private: + + template< typename SrcType > + static inline std::string EnumToString ( SrcType defaultVal ); + + template< typename DstType > + static inline sw::Nullable< DstType > StringToEnum ( const std::string& value ); + +public: + + template< typename SrcType > + static inline typename std::enable_if< std::is_enum< SrcType >::value, std::string >::type + ToString ( const SrcType& val ); + + template< typename DstType > + static inline DstType FromString ( const std::string& val, const DstType& defaultValue ); + + template< typename DstType > + static inline sw::Nullable< typename std::enable_if< std::is_enum< DstType >::value, DstType >::type > + FromString ( const std::string& val ); + + template< typename SrcType > + static inline typename std::enable_if< !std::is_enum< SrcType >::value, std::string >::type + ToString ( const SrcType& val ); + + template< typename DstType > + static inline sw::Nullable< typename std::enable_if< std::is_arithmetic< DstType >::value, DstType >::type > + FromString ( const std::string& val ); + + template< typename DstType > + static inline sw::Nullable< typename std::enable_if< is_not_specialized< DstType >::value, DstType >::type > + FromString ( const std::string& val ); + + template<> + static inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::string >::type + ToString< std::wstring > ( const std::wstring& value ); + + template< typename DstType > + static inline sw::Nullable< typename std::enable_if< std::is_same< DstType, std::wstring >::value, std::wstring >::type > + FromString ( const std::string& value ); + +public: + + /**@brief Type conversion to string using rttr.*/ + template< typename Type > + static inline std::string ToString (); +}; + + +namespace impl +{ + sw::ExceptionPtr ConversionException (); +} + +#include "ConvertArithmetic.h" +#include "ConvertEnums.h" + + +// ================================ // +// +template< typename SrcType > +inline typename std::enable_if< !std::is_enum< SrcType >::value, std::string >::type + Convert::ToString ( const SrcType& val ) +{ + return std::to_string( val ); +} + +// ================================ // +// +template< typename DstType > +inline DstType Convert::FromString ( const std::string& val, const DstType& defaultValue ) +{ + auto result = Convert::FromString< DstType >( val ); + + if( result.IsValid() ) + return result.Get(); + + return defaultValue; +} + +// ================================ // +// +template< typename DstType > +static inline sw::Nullable< typename std::enable_if< is_not_specialized< DstType >::value, DstType >::type > + Convert::FromString ( const std::string& val ) +{ + static_assert( false, "Specialize template" ); + return ::impl::ConversionException(); +} + + +//====================================================================================// +// Public template specialization for enum types +//====================================================================================// + +/**@brief Converts enum to string.*/ +template< typename SrcType > +inline typename std::enable_if< std::is_enum< SrcType >::value, std::string >::type + Convert::ToString ( const SrcType& val ) +{ + return EnumToString( val ); +} + +/**@brief Converts string to enum.*/ +template< typename DstType > +inline sw::Nullable< typename std::enable_if< std::is_enum< DstType >::value, DstType >::type > + Convert::FromString ( const std::string& val ) +{ + return StringToEnum< DstType >( val ); +} + +//====================================================================================// +// Wstring to string +//====================================================================================// + +// ================================ // +// +template<> +static inline typename std::enable_if< !std::is_enum< std::wstring >::value, std::string >::type + Convert::ToString< std::wstring > ( const std::wstring& value ) +{ + typedef std::codecvt_utf8< wchar_t > convert_type; + std::wstring_convert< convert_type, wchar_t > converter; + return converter.to_bytes( value ); +} + +// ================================ // +// +template< typename SrcType > +inline sw::Nullable< typename std::enable_if< std::is_same< SrcType, std::wstring >::value, std::wstring >::type > + Convert::FromString ( const std::string& value ) +{ + typedef std::codecvt_utf8< wchar_t > convert_type; + std::wstring_convert< convert_type, wchar_t > converter; + return converter.from_bytes( value ); +} + +//====================================================================================// +// Arithemetic types +//====================================================================================// + +// ================================ // +// +template< typename DstType > +static inline sw::Nullable< typename std::enable_if< std::is_arithmetic< DstType >::value, DstType >::type > + Convert::FromString ( const std::string& val ) +{ + return ::impl::ConvertArithmetic< DstType >( val ); +} + + +//====================================================================================// +// Type conversion to string +//====================================================================================// + +// ================================ // +// +template< typename Type > +inline std::string Convert::ToString () +{ + return TypeID::get< Type >().get_name().to_string(); +} + +DEFINE_FMT_FORMATTER( TypeID, "{}", get_name().to_string() ); + + diff --git a/swCommonLib/Common/Converters/ConvertArithmetic.h b/swCommonLib/Common/Converters/ConvertArithmetic.h new file mode 100644 index 00000000..84a11d25 --- /dev/null +++ b/swCommonLib/Common/Converters/ConvertArithmetic.h @@ -0,0 +1,164 @@ +#pragma once +/** +@file ConvertArithmetic.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + + +#include + + +namespace impl +{ + +// ================================ // +// +template< typename ElementType > +inline bool IsCorrectSign ( const std::string& str ) +{ + if( str.size() > 1 ) + return str[ 0 ] != '-'; + return true; +} + +// ================================ // +// +template<> inline bool IsCorrectSign< int64 > ( const std::string& str ) { return true; } +template<> inline bool IsCorrectSign< int32 > ( const std::string& str ) { return true; } +template<> inline bool IsCorrectSign< int16 > ( const std::string& str ) { return true; } +template<> inline bool IsCorrectSign< int8 > ( const std::string& str ) { return true; } +template<> inline bool IsCorrectSign< float > ( const std::string& str ) { return true; } +template<> inline bool IsCorrectSign< double > ( const std::string& str ) { return true; } + + + +/**@brief Converts string to numeric types. Uses strol function from std.*/ +template< typename ElementType > +inline ElementType ConvertArithmeticImpl ( const char* valueBegin, char** checkEndPtr ) +{ + assert( false ); + return false; +} + + +// ================================ // +// +template<> +inline uint32 ConvertArithmeticImpl< uint32 > ( const char* valueBegin, char** checkEndPtr ) +{ + return strtoul( valueBegin, checkEndPtr, 10 ); +} + +// ================================ // +// +template<> +inline int32 ConvertArithmeticImpl< int32 > ( const char* valueBegin, char** checkEndPtr ) +{ + return strtol( valueBegin, checkEndPtr, 10 ); +} + +// ================================ // +// +template<> +inline uint64 ConvertArithmeticImpl< uint64 > ( const char* valueBegin, char** checkEndPtr ) +{ + return strtoull( valueBegin, checkEndPtr, 10 ); +} + +// ================================ // +// +template<> +inline int64 ConvertArithmeticImpl< int64 > ( const char* valueBegin, char** checkEndPtr ) +{ + return strtoll( valueBegin, checkEndPtr, 10 ); +} + + +// ================================ // +// +template<> +inline bool ConvertArithmeticImpl< bool > ( const char* valueBegin, char** checkEndPtr ) +{ + const char* trueString = "true"; + const char* falseString = "false"; + + *checkEndPtr = const_cast< char* >( valueBegin ); + const char* referenceString; + bool returnValue; + + if( **checkEndPtr == 't' ) + { + returnValue = true; + referenceString = trueString; + } + else if( **checkEndPtr == 'f' ) + { + returnValue = false; + referenceString = falseString; + } + else + return false; + + int i = 0; + do + { + ++i; + *checkEndPtr += 1; + } while( **checkEndPtr == *( referenceString + i ) && **checkEndPtr != '\0' ); + + return returnValue; +} + +// ================================ // +// +template<> +inline double ConvertArithmeticImpl< double > ( const char* valueBegin, char** checkEndPtr ) +{ + return strtod( valueBegin, checkEndPtr ); +} + +// ================================ // +// +template<> +inline float ConvertArithmeticImpl< float > ( const char* valueBegin, char** checkEndPtr ) +{ + return (float)ConvertArithmeticImpl< double >( valueBegin, checkEndPtr ); +} + +// ================================ // +// +template< typename ElementType > +inline sw::Nullable< ElementType > ConvertArithmetic ( const std::string& str ) +{ + // strto** functions can't handle negative numbers. + if( !IsCorrectSign< ElementType >( str ) ) + return ::impl::ConversionException(); + + const char* attribValue = str.c_str(); + char* checkEndPtr = nullptr; // After conversion we will get here pointer to byte after last parsed element. + + errno = 0; // strto** functions can return ERANGE if value will be out of range. + + auto value = ConvertArithmeticImpl< ElementType >( attribValue, &checkEndPtr ); + auto errnoVal = errno; + + if( checkEndPtr == attribValue || // If we are on the begining, no conversion was performed. + *checkEndPtr != '\0' || // If we didn't reached terminator character, this means error. + errno == ERANGE ) + return ::impl::ConversionException(); + + // Max value for type indicates coversion error. But not for bool. + if( value == std::numeric_limits< ElementType >::max() && + !std::is_same< ElementType, bool >::value ) + return ::impl::ConversionException(); + + return value; +} + +} // impl + + + + diff --git a/swCommonLib/Common/Converters/ConvertEnums.h b/swCommonLib/Common/Converters/ConvertEnums.h new file mode 100644 index 00000000..df772a22 --- /dev/null +++ b/swCommonLib/Common/Converters/ConvertEnums.h @@ -0,0 +1,58 @@ +#pragma once +/** +@file ConvertEnums.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + + + +//====================================================================================// +// Private enum helpers +//====================================================================================// + +// ================================ // +// +template< typename SrcType > +std::string Convert::EnumToString ( SrcType value ) +{ + static_assert( std::is_enum< SrcType >::value, "Type is not enum" ); + + auto type = rttr::type::get< SrcType >(); + + assert( type.is_valid() ); /// Type haven't been registered. + assert( type.is_enumeration() ); + + rttr::enumeration enumVal = type.get_enumeration(); + + return enumVal.value_to_name( value ).to_string(); +} + +// ================================ // +// +template< typename DstType > +sw::Nullable< DstType > Convert::StringToEnum ( const std::string& value ) +{ + static_assert( std::is_enum< DstType >::value, "Type is not enum" ); + + auto type = rttr::type::get< DstType >(); + + assert( type.is_valid() ); /// Leave assert, beacause it shouldn't happen. + if( !type.is_enumeration() ) + return "Type [" + type.get_name().to_string() + "] is not an Enum."; + + rttr::enumeration enumVal = type.get_enumeration(); + + rttr::variant result = enumVal.name_to_value( value ); + + // Note: Don't return error message. Failing conversion is common thing + // and we don't want to hurt performance. + if( !result.is_valid() ) + return ::impl::ConversionException(); + + return result.get_value< DstType >(); +} + + + diff --git a/swCommonLib/Common/Converters/ConvertTraits.h b/swCommonLib/Common/Converters/ConvertTraits.h new file mode 100644 index 00000000..f5a53343 --- /dev/null +++ b/swCommonLib/Common/Converters/ConvertTraits.h @@ -0,0 +1,20 @@ +#pragma once +/** +@file ConvertTraits.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include + +#include + + + +template< typename Type > +struct is_not_specialized +{ + static const bool value = !std::is_enum< Type >::value && + !std::is_same< Type, std::wstring >::value && + !std::is_arithmetic< Type >::value; +}; diff --git a/swCommonLib/Common/Exceptions/Common/FileNotFoundException.cpp b/swCommonLib/Common/Exceptions/Common/FileNotFoundException.cpp new file mode 100644 index 00000000..e59085ea --- /dev/null +++ b/swCommonLib/Common/Exceptions/Common/FileNotFoundException.cpp @@ -0,0 +1,28 @@ +/** +@file FileNotFoundException.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + +#include "FileNotFoundException.h" + + +namespace sw +{ + +// ================================ // +// +FileNotFoundException::FileNotFoundException ( filesystem::Path filePath ) + : m_path( std::move( filePath ) ) +{} + +// ================================ // +// +std::string FileNotFoundException::ErrorMessage () const +{ + return "File [" + m_path.String() + "] not found."; +} + +} // sw + diff --git a/swCommonLib/Common/Exceptions/Common/FileNotFoundException.h b/swCommonLib/Common/Exceptions/Common/FileNotFoundException.h new file mode 100644 index 00000000..35a3d857 --- /dev/null +++ b/swCommonLib/Common/Exceptions/Common/FileNotFoundException.h @@ -0,0 +1,41 @@ +#pragma once +/** +@file FileNotFoundException.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "swCommonLib/Common/Exceptions/Exception.h" +#include "swCommonLib/System/Path.h" + + +namespace sw +{ + + +/**@brief +@ingroup Helpers*/ +class FileNotFoundException : public Exception +{ + RTTR_ENABLE( Exception ); +private: +protected: + + filesystem::Path m_path; + +public: + explicit FileNotFoundException ( filesystem::Path filePath ); + virtual ~FileNotFoundException () = default; + +public: + + virtual std::string ErrorMessage () const; + + const filesystem::Path& GetFilePath () const { return m_path; } +}; + + + + +} // sw + diff --git a/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.cpp b/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.cpp new file mode 100644 index 00000000..e6cc8a67 --- /dev/null +++ b/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.cpp @@ -0,0 +1,39 @@ +/** +@file InvalidCodeLogicException.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + +#include "InvalidCodeLogicException.h" + +#include "swCommonLib/Common/Converters.h" + + +namespace sw +{ + +// ================================ // +// +InvalidCodeLogicException::InvalidCodeLogicException ( std::string message, std::string filePath, uint32 line ) + : RuntimeException( std::move( message ) ) + , m_path( std::move( filePath ) ) + , m_line( line ) +{} + +// ================================ // +// +std::string InvalidCodeLogicException::ErrorMessage () const +{ + return RuntimeException::ErrorMessage() + " We shouldn't be here. Code is invalid, check file [" + m_path + "], line " + Convert::ToString( m_line ) + "."; +} + +// ================================ // +// +InvalidCodeLogicExceptionPtr InvalidCodeLogicException::Create ( std::string message, std::string filePath, uint32 line ) +{ + return std::make_shared< InvalidCodeLogicException >( std::move( message ), std::move( filePath ), line ); +} + +} // sw + diff --git a/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.h b/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.h new file mode 100644 index 00000000..e7cd3775 --- /dev/null +++ b/swCommonLib/Common/Exceptions/Common/InvalidCodeLogicException.h @@ -0,0 +1,49 @@ +#pragma once +/** +@file InvalidCodeLogicException.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "swCommonLib/Common/Exceptions/Exception.h" +#include "swCommonLib/System/Path.h" + + +namespace sw +{ + +class InvalidCodeLogicException; +DEFINE_PTR_TYPE( InvalidCodeLogicException ); + + + +/**@brief Exception thrown when code reaches state, that it shouldn't reach. +It indicates, that something is wrong in program logic. +@ingroup Helpers*/ +class InvalidCodeLogicException : public RuntimeException +{ + RTTR_ENABLE( RuntimeException ); +private: +protected: + + std::string m_path; + uint32 m_line; + +public: + explicit InvalidCodeLogicException ( std::string message, std::string filePath, uint32 line ); + virtual ~InvalidCodeLogicException () = default; + +public: + + virtual std::string ErrorMessage () const; + +public: + + static InvalidCodeLogicExceptionPtr Create ( std::string message, std::string filePath, uint32 line ); +}; + + + + +} // sw + diff --git a/swCommonLib/Common/Exceptions/ErrorsCollector.h b/swCommonLib/Common/Exceptions/ErrorsCollector.h index 3847c855..99c8acf5 100644 --- a/swCommonLib/Common/Exceptions/ErrorsCollector.h +++ b/swCommonLib/Common/Exceptions/ErrorsCollector.h @@ -44,12 +44,73 @@ class ErrorsCollector inline void Add ( ExceptionsListPtr list ); inline void Add ( const ErrorsCollector& collector ); + template< typename ErrorType > + inline void Add ( const std::shared_ptr< ErrorType >& exception ); + + /**@brief Checks if returned result was success. Adds exception, if it wasnt't. + + Proposed usage: + @code + ErrorsCollector collector; + + auto result = SomeFunction(); + if( collector.Success( result ) ) + { + // Do something with result here, because it's valid. + result.Get(); + } + @endcode + */ + template< typename ReturnType > + inline bool Success ( const Nullable< ReturnType >& result ); + + /**@brief Checks if returned result was success. Moves value of Nullable if it was valid. + Returns defaultVal, if it was invalid, and collects error. + + This function is meant to defer error handling or collect warning. + + Proposed usage: + @code + ReturnResult SomeClass::Function() + { + ErrorsCollector collector; + + member_pointer1 = collector.OnError( SomeFunction1(), nullptr ) ); + member_pointer2 = collector.OnError( SomeFunction2(), nullptr ) ); + + return collector.Get(); + } + @endcode + + Note that this helps us avoid cubersome ifs that check errors like this: + + @code + ReturnResult SomeClass::Function() + { + ErrorsCollector collector; + + auto result1 = SomeFunction1(); + if( result1.IsValid() ) + member_pointer1 = result1.Get(); + + auto result2 = SomeFunction1(); + if( result2.IsValid() ) + member_pointer2 = result2.Get(); + + return collector.Get(); + } + @endcode + */ + template< typename ReturnType > + inline ReturnType OnError ( Nullable< ReturnType >&& result, ReturnType defaultVal ); + inline operator ReturnResult (); inline ReturnResult Get (); inline bool IsList () const { return m_multipleRaised; } inline ExceptionsListPtr GetExceptionsList () const; + inline ExceptionPtr GetException () const { return m_exception; } }; //====================================================================================// @@ -84,7 +145,7 @@ inline void ErrorsCollector::Add ( ExceptionPtr newException ) } else if( m_multipleRaised ) { - ExceptionsListPtr list = std::static_pointer_cast( m_exception ); + ExceptionsListPtr list = std::static_pointer_cast< ExceptionsList >( m_exception ); list->AddException( newException ); } else @@ -157,6 +218,37 @@ inline ExceptionsListPtr ErrorsCollector::GetExceptionsList () const return nullptr; } +// ================================ // +// +template< typename ErrorType > +inline void ErrorsCollector::Add ( const std::shared_ptr< ErrorType >& exception ) +{ + Add( std::static_pointer_cast< Exception >( exception ) ); +} + +// ================================ // +// +template< typename ReturnType > +inline bool ErrorsCollector::Success ( const Nullable< ReturnType >& result ) +{ + if( result.IsValid() ) + return true; + + Add( result.GetError() ); + return false; +} + +// ================================ // +// +template< typename ReturnType > +inline ReturnType ErrorsCollector::OnError ( Nullable< ReturnType >&& result, ReturnType defaultVal ) +{ + if( result.IsValid() ) + return std::move( result ).Get(); + + Add( result.GetError() ); + return std::move( defaultVal ); +} } // sw diff --git a/swCommonLib/Common/Exceptions/Exception.h b/swCommonLib/Common/Exceptions/Exception.h index 6b93282d..033abd6d 100644 --- a/swCommonLib/Common/Exceptions/Exception.h +++ b/swCommonLib/Common/Exceptions/Exception.h @@ -1,7 +1,14 @@ #pragma once +/** +@file Exception.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + #include "swCommonLib/Common/TypesDefinitions.h" +#include "swCommonLib/Common/RTTR.h" #include #include @@ -12,6 +19,10 @@ namespace sw { /**@defgroup Exceptions + +Library functions providing utilities for error handling. This library uses Alexandrescu Expected +approach, to return value or Exception as return type. + @ingroup Helpers*/ @@ -19,6 +30,7 @@ namespace sw @ingroup Exceptions*/ class Exception : public std::exception { + RTTR_ENABLE(); private: protected: public: @@ -44,6 +56,7 @@ DEFINE_PTR_TYPE( Exception ) @ingroup Exceptions*/ class RuntimeException : public Exception { + RTTR_ENABLE( Exception ); private: protected: @@ -53,8 +66,8 @@ class RuntimeException : public Exception // ================================ // // - explicit RuntimeException ( const std::string& message ) - : m_errorMessage( message ) + explicit RuntimeException ( std::string message ) + : m_errorMessage( std::move( message ) ) {} virtual ~RuntimeException () = default; diff --git a/swCommonLib/Common/Exceptions/Nullable.h b/swCommonLib/Common/Exceptions/Nullable.h index 8fd5f885..736ec58a 100644 --- a/swCommonLib/Common/Exceptions/Nullable.h +++ b/swCommonLib/Common/Exceptions/Nullable.h @@ -29,8 +29,46 @@ enum class Result : uint8 }; +namespace impl +{ + +// ================================ // +// +template< typename From, typename To > +struct IsBaseConversion +{ + // ================================ // + // Note: Visual Studio can't handle constexpr functions in std::enable_if + static constexpr inline bool Value () + { + using DecayedFrom = std::remove_pointer< typename From >::type; + using DecayedTo = std::remove_pointer< typename To >::type; + + return !std::is_same< DecayedFrom, DecayedTo >::value && + std::is_base_of< DecayedTo, DecayedFrom >::value;// && + std::is_pointer< From >::value && + std::is_pointer< To >::value; + } + +public: + + const static bool value = IsBaseConversion::Value(); +}; + + +} // impl + + /**@brief Alexandrescu Expected type for error handling. + +@todo Rethink exceptions handling. We can't throw typed exceptions, because +we use std::shared_ptr instead of std::exception_ptr. It's not posible to copy +polymorphic type and throw exception wants to do this. + +@todo We should wrap exception throwing inside macro. If exceptions are disabled +we should handle fails different way. + @ingroup Exceptions*/ template< typename ContentType > class Nullable @@ -55,19 +93,22 @@ class Nullable Nullable ( const ContentType& content ); Nullable ( const ErrorType& error ); Nullable ( const std::string& error ); - Nullable ( const Nullable< ContentType > & that ); + Nullable ( const Nullable< ContentType >& that ); ~Nullable (); template< typename ExceptionType > Nullable ( std::shared_ptr< ExceptionType > error ); - bool IsValid (); - std::string GetErrorReason (); - ErrorType GetError (); + template< typename DerivedClass, typename std::enable_if< impl::IsBaseConversion< DerivedClass, ContentType >::value >::type* = nullptr > + Nullable ( Nullable< DerivedClass >&& other ); - bool operator== ( const ContentType & that ); - bool operator!= ( const ContentType & that ); - Nullable< ContentType >& operator= ( const Nullable< ContentType > & that ); + bool IsValid () const; + std::string GetErrorReason () const; + ErrorType GetError () const; + + bool operator== ( const ContentType& that ); + bool operator!= ( const ContentType& that ); + Nullable< ContentType >& operator= ( const Nullable< ContentType >& that ); const ContentType & Get () const&; operator const ContentType & () const&; @@ -76,7 +117,13 @@ class Nullable operator ContentType & () &; ContentType && Get () &&; - operator ContentType && () &&; + operator ContentType && () && = delete; + +public: + + template< typename Type, typename std::enable_if< impl::IsBaseConversion< ContentType, Type >::value, void >::type* = nullptr > + Nullable< Type > Move (); + public: @@ -110,16 +157,23 @@ class Nullable< void > template< typename ExceptionType > Nullable ( std::shared_ptr< ExceptionType > error ); - bool IsValid (); - std::string GetErrorReason (); - ErrorType GetError (); + Nullable< void >& operator= ( const Nullable< void >& that ); + + bool IsValid () const; + std::string GetErrorReason () const; + ErrorType GetError () const; }; +Nullable< void > operator&& ( const Nullable< void >& that, const Nullable< void >& second ); + typedef Nullable< void > ReturnResult; +#define ReturnIfInvalid( nullable ) if( !nullable.IsValid() ) return nullable.GetError(); + + // ========================================================================= // // Implementation // ========================================================================= // @@ -163,8 +217,8 @@ inline Nullable< ContentType >::Nullable ( const std::string& error ) // ================================ // // template< typename ContentType > -inline Nullable< ContentType >::Nullable ( const Nullable< ContentType > & that ) - : m_isValid( that.m_isValid ) +inline Nullable< ContentType >::Nullable ( const Nullable< ContentType >& that ) + : m_isValid( that.m_isValid ) { if( m_isValid ) new( &Content ) ContentType( that.Content ); @@ -182,6 +236,35 @@ inline Nullable< ContentType >::Nullable ( std::shared_ptr< ExceptionType > er static_assert( std::is_base_of< typename ErrorType::element_type, ExceptionType >::value, "ExceptionType should be derived from ErrorType" ); } +// ================================ // +// +template< typename ContentType > +template< typename DerivedClass, typename std::enable_if< impl::IsBaseConversion< DerivedClass, ContentType >::value >::type* > +inline Nullable< ContentType >::Nullable ( Nullable< DerivedClass >&& other ) + : m_isValid( other.IsValid() ) + , Error( nullptr ) +{ + if( m_isValid ) + Content = std::move( other ).Get(); + else + Error = other.GetError(); +} + +// ================================ // +// +template< typename ContentType > +template< typename Type, typename std::enable_if< impl::IsBaseConversion< ContentType, Type >::value, void >::type* > +inline Nullable< Type > Nullable< ContentType >::Move () +{ + bool wasValid = IsValid(); + //m_isValid = false; // We don't change validity. We don't want to call Error destructor on Nullable destruction. + + if( wasValid ) + return Nullable< Type >( std::move( Content ) ); + else + return Nullable< Type >( Error ); // Error is shared_ptr, we don't have to move. +} + // ================================ // // template< typename ContentType > @@ -196,7 +279,7 @@ inline Nullable< ContentType >::~Nullable () // ================================ // // template< typename ContentType > -inline bool Nullable< ContentType >::IsValid() +inline bool Nullable< ContentType >::IsValid () const { return m_isValid; } @@ -204,7 +287,7 @@ inline bool Nullable< ContentType >::IsValid() // ================================ // // template< typename ContentType > -inline std::string Nullable< ContentType >::GetErrorReason () +inline std::string Nullable< ContentType >::GetErrorReason () const { if( Error ) return Error->ErrorMessage(); @@ -214,7 +297,7 @@ inline std::string Nullable< ContentType >::GetErrorReason () // ================================ // // template< typename ContentType > -inline typename Nullable< ContentType >::ErrorType Nullable< ContentType >::GetError () +inline typename Nullable< ContentType >::ErrorType Nullable< ContentType >::GetError () const { if( m_isValid ) assert( false ); // FIXME: error handling(?) @@ -260,30 +343,35 @@ Nullable< ContentType >& Nullable< ContentType >::operator= ( const Nullable< // ================================ // // template< typename ContentType > -inline const ContentType & Nullable< ContentType >::Get () const& +inline const ContentType& Nullable< ContentType >::Get () const& { - if( !m_isValid ) - assert( false ); // FIXME: error handling(?) + if( !m_isValid ) + throw RuntimeException( Error->ErrorMessage() ); return Content; } // ================================ // // template< typename ContentType > -inline ContentType & Nullable< ContentType >::Get () & +inline ContentType& Nullable< ContentType >::Get () & { - if( !m_isValid ) - throw Error; + if( !m_isValid ) + { + // Note: we lose exception type information, but throw statement copies + // exception and we can't copy polymorphic type, so this is best option at least for now. + /// @todo We should rethink exceptions handling in future. + throw RuntimeException( Error->ErrorMessage() ); + } return Content; } // ================================ // // template< typename ContentType > -inline ContentType && Nullable< ContentType >::Get () && +inline ContentType&& Nullable< ContentType >::Get () && { if( !m_isValid ) - throw Error; + throw RuntimeException( Error->ErrorMessage() ); return std::move( Content ); } @@ -303,13 +391,13 @@ inline Nullable< ContentType >::operator ContentType & () & return Get(); } -// ================================ // -// -template< typename ContentType > -inline Nullable< ContentType >::operator ContentType && () && -{ - return Get(); -} +//// ================================ // +//// +//template< typename ContentType > +//inline Nullable< ContentType >::operator ContentType && () && +//{ +// return std::move( Get() ); +//} //====================================================================================// // Creating Nullable from error @@ -375,17 +463,43 @@ inline Nullable< void >::Nullable ( Result result ) : m_isValid( result == Result::Success ), Error( nullptr ) {} +// ================================ // +// +inline Nullable< void >& Nullable< void >::operator= ( const Nullable< void >& that ) +{ + m_isValid = that.IsValid(); + Error = that.Error; + + return *this; +} + +// ================================ // +// +inline Nullable< void > operator&& ( const Nullable< void >& obj1, const Nullable< void >& obj2 ) +{ + if( obj1.IsValid() && obj2.IsValid() ) + return Result::Success; + + /// @todo Maybe we should handle situation, when both are errors. + if( !obj1.IsValid() ) + return obj1.GetError(); + + if( !obj2.IsValid() ) + return obj2.GetError(); + + return Result::Success; +} // ================================ // // -inline bool Nullable< void >::IsValid() +inline bool Nullable< void >::IsValid () const { return m_isValid; } // ================================ // // -inline std::string Nullable< void >::GetErrorReason () +inline std::string Nullable< void >::GetErrorReason () const { if( Error ) return Error->ErrorMessage(); @@ -394,7 +508,7 @@ inline std::string Nullable< void >::GetErrorReason () // ================================ // // -inline typename Nullable< void >::ErrorType Nullable< void >::GetError () +inline typename Nullable< void >::ErrorType Nullable< void >::GetError () const { if( m_isValid ) assert( false ); // FIXME: error handling(?) diff --git a/swCommonLib/Common/Macros/DefineFmtFormatter.h b/swCommonLib/Common/Macros/DefineFmtFormatter.h new file mode 100644 index 00000000..61d439f8 --- /dev/null +++ b/swCommonLib/Common/Macros/DefineFmtFormatter.h @@ -0,0 +1,66 @@ +#pragma once +/** +@file DefineFmtFormatter.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "ForEach.h" +#include "swCommonLib/Common/fmt.h" + + +#define _MAKE_STR( x ) #x +#define MAKE_STR( x ) _MAKE_STR( x ) + +#define _APPEND_INST( member ) d.member + + +/**@brief Defines formatter for fmt library. +Use this macro outside namespace.*/ +#define DEFINE_FMT_FORMATTER( ClassType, FormatString, ... ) \ +template<> \ +struct ::fmt::formatter< ClassType > \ +{ \ + template< typename ParseContext > \ + auto parse( ParseContext& ctx ) { return ctx.begin(); } \ + \ + template< typename FormatContext > \ + auto format( const ClassType& d, FormatContext& ctx ) { \ + return format_to( ctx.out(), FormatString, FOR_EACH( _APPEND_INST ,__VA_ARGS__ ) ); \ + } \ +}; + + +#define _FORMAT_STRING_STRUCT_ENTRY( member ) member={} + +#define _FORMAT_STRING_STRUCT( ... )\ +[ FOR_EACH( _FORMAT_STRING_STRUCT_ENTRY, __VA_ARGS__ ) ] + + +/**@brief Defines fmt formatter for structure using default format.*/ +#define DEFINE_DEFAULT_FMT_STRUCT_FORMATTER( ClassType, ... ) \ + DEFINE_FMT_FORMATTER( ClassType, MAKE_STR( _FORMAT_STRING_STRUCT( __VA_ARGS__ ) ), __VA_ARGS__ ) + + +/**@brief Defines formatter for fmt library. +Use this macro outside namespace.*/ +#define DEFINE_FMT_FORMATTER_ATOMIC_TYPE( ClassType, Function ) \ +template<> \ +struct ::fmt::formatter< ClassType > \ +{ \ + template< typename ParseContext > \ + auto parse( ParseContext& ctx ) { return ctx.begin(); } \ + \ + template< typename FormatContext > \ + auto format( const ClassType& d, FormatContext& ctx ) { \ + return format_to( ctx.out(), "{}", Function( d ) ); \ + } \ +}; + + +/**@brief Defines fmt library formatter for enum type. Uses Convert::ToString. +To use formatter for enum, it must be defined in rttr. +Use this macro outside namespace.*/ +#define DEFINE_FMT_FORMATTER_ENUM( EnumType ) \ + DEFINE_FMT_FORMATTER_ATOMIC_TYPE( EnumType, Convert::ToString ) + diff --git a/swCommonLib/Common/Macros/ForEach.h b/swCommonLib/Common/Macros/ForEach.h new file mode 100644 index 00000000..76f60858 --- /dev/null +++ b/swCommonLib/Common/Macros/ForEach.h @@ -0,0 +1,55 @@ +#pragma once +/** +@file ForEach.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + + + +namespace sw +{ + +// ============================================================================== // +// Implements FOR_EACH macros for use in combination with other macros. +// https://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros + + +#define EXPAND( ... ) __VA_ARGS__ + +#define _FOR_EACH_1(WHAT, X) WHAT(X) +#define _FOR_EACH_2(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_1(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_3(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_2(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_4(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_3(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_5(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_4(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_6(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_5(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_7(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_6(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_8(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_7(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_9(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_8(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_10(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_9(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_11(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_10(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_12(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_11(WHAT, __VA_ARGS__) ) +#define _FOR_EACH_13(WHAT, X, ...) WHAT(X), EXPAND( _FOR_EACH_12(WHAT, __VA_ARGS__) ) +//... repeat as needed + +#define _CHOOSE_FOR_EACH(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,NAME,...) NAME +#define FOR_EACH( action, ... ) \ + EXPAND( _CHOOSE_FOR_EACH( __VA_ARGS__, \ + _FOR_EACH_13, \ + _FOR_EACH_12, \ + _FOR_EACH_11, \ + _FOR_EACH_10, \ + _FOR_EACH_9, \ + _FOR_EACH_8, \ + _FOR_EACH_7, \ + _FOR_EACH_6, \ + _FOR_EACH_5, \ + _FOR_EACH_4, \ + _FOR_EACH_3, \ + _FOR_EACH_2, \ + _FOR_EACH_1, )(action,__VA_ARGS__) ) + + + +} // sw + diff --git a/swCommonLib/Common/Macros/GenerateOperators.h b/swCommonLib/Common/Macros/GenerateOperators.h new file mode 100644 index 00000000..03372b84 --- /dev/null +++ b/swCommonLib/Common/Macros/GenerateOperators.h @@ -0,0 +1,56 @@ +#pragma once +/** +@file GenerateOperators.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "ForEach.h" +#include + + +namespace sw +{ + +#define _APPEND_INSTANCE( instance, member ) instance.member +#define _APPEND_INSTANCE_OBJ1( member ) _APPEND_INSTANCE( obj1, member ) +#define _APPEND_INSTANCE_OBJ2( member ) _APPEND_INSTANCE( obj2, member ) + +#define _GENERATE_OPERATOR( OP, ClassType, ... ) \ +inline bool operator##OP( const ClassType& obj1, const ClassType& obj2 )\ +{ \ + return std::tie( FOR_EACH( _APPEND_INSTANCE_OBJ1, __VA_ARGS__ ) ) \ + OP std::tie( FOR_EACH( _APPEND_INSTANCE_OBJ2, __VA_ARGS__ ) ); \ +} + +/**@brief Generates operator== function for ClassType. +Pass all class members as variadic parameters.*/ +#define GENERATE_EQUAL_OPERATOR( ClassType, ... ) \ + _GENERATE_OPERATOR( ==, ClassType, __VA_ARGS__ ) + +/**@brief Generates operator!= function for ClassType. +Pass all class members as variadic parameters.*/ +#define GENERATE_NON_EQUAL_OPERATOR( ClassType, ... ) \ + _GENERATE_OPERATOR( !=, ClassType, __VA_ARGS__ ) + +/**@brief Generates operator== and operator!= for ClassType.*/ +#define GENERATE_EQUALITY_OPERATORS( ClassType, ... ) \ + _GENERATE_OPERATOR( ==, ClassType, __VA_ARGS__ ) \ + _GENERATE_OPERATOR( !=, ClassType, __VA_ARGS__ ) + +/**@brief Generates whole family of operators <, <=, >, >= function for ClassType. +Pass all class members as variadic parameters.*/ +#define GENERATE_ORDERING_OPERATORS( ClassType, ... ) \ + _GENERATE_OPERATOR( <, ClassType, __VA_ARGS__ ) \ + _GENERATE_OPERATOR( <=, ClassType, __VA_ARGS__ ) \ + _GENERATE_OPERATOR( >, ClassType, __VA_ARGS__ ) \ + _GENERATE_OPERATOR( >=, ClassType, __VA_ARGS__ ) + +/**@brief Generates all comparision operators. +Pass all class members as variadic parameters.*/ +#define GENERATE_RELATIONAL_OPERATORS( ClassType, ... ) \ + GENERATE_ORDERING_OPERATORS( ClassType, __VA_ARGS__ ) \ + GENERATE_EQUALITY_OPERATORS( ClassType, __VA_ARGS__ ) + +} // sw + diff --git a/swCommonLib/Common/MemoryChunk.h b/swCommonLib/Common/MemoryChunk.h index 1cd9c0f9..c27c771d 100644 --- a/swCommonLib/Common/MemoryChunk.h +++ b/swCommonLib/Common/MemoryChunk.h @@ -4,7 +4,8 @@ #include -/**@brief Klasa przechowuje pamiêæ o dowolnym przeznaczeniu.*/ +/**@brief Klasa przechowuje pamiêæ o dowolnym przeznaczeniu. +@deprecated Use classes from swCommonLib/Common/Buffers/ instead.*/ class MemoryChunk { private: diff --git a/swCommonLib/Common/Multithreading/QueueMT.h b/swCommonLib/Common/Multithreading/QueueMT.h index e94d4199..9f816843 100644 --- a/swCommonLib/Common/Multithreading/QueueMT.h +++ b/swCommonLib/Common/Multithreading/QueueMT.h @@ -43,6 +43,8 @@ inline void QueueMT< ContentType >::Push ( const ContentType& element ) { std::lock_guard< std::mutex > guard( m_accesslock ); m_queue.push( element ); + + m_condition.notify_one(); } /**@brief */ @@ -51,6 +53,8 @@ inline void QueueMT< ContentType >::Push ( ContentType&& element ) { std::lock_guard< std::mutex > guard( m_accesslock ); m_queue.push( std::move( element ) ); + + m_condition.notify_one(); } diff --git a/swCommonLib/Common/Nullable.h b/swCommonLib/Common/Nullable.h index f6970553..c28f7967 100644 --- a/swCommonLib/Common/Nullable.h +++ b/swCommonLib/Common/Nullable.h @@ -14,6 +14,7 @@ enum class NullableInit /**@brief Returns value or error. +@deprecated Use new Nullable placed in Common/Exceptions/Nullable.h @ingroup Helpers*/ template< typename ResultType > struct Nullable @@ -84,5 +85,5 @@ struct Nullable }; -#define ReturnIfInvalid( nullable ) if( !nullable.IsValid ) return std::move( nullable.ErrorString ); + diff --git a/swCommonLib/Common/ObjectDeleter.h b/swCommonLib/Common/ObjectDeleter.h deleted file mode 100644 index 2a026d78..00000000 --- a/swCommonLib/Common/ObjectDeleter.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once -/**@file ObjectDeleter.h -@author nieznanysprawiciel -@copyright Plik jest czêœci¹ silnika graficznego SWEngine. - -@brief Klasy s³u¿¹ce do zapewnienia ograniczonej mo¿liwoœci kasowania niektórych obiektów silnika, -które maj¹ prywatne destruktory. -*/ - -class ResourceObject; -template class ResourceContainer; -template< class ResourceType > class ResourceContainer; -template<> class ResourceContainer< ResourceObject >; - -namespace sw -{ -class AssetsManager; -} // sw - -/** -@ingroup Helpers - -@brief You can specify classes that can delete objects with private constructors. - -Niektóre obiekty s¹ zadeklarowane z prywatnym (chronionym) destruktorem, w celu uniemo¿liwienia -skasowania ich przez niepowo³ane klasy. Jednak¿e musi istnieæ jakiœ dostêp do destruktorów, -aby nie powodowaæ wycieków pamiêci. Do kasowania obiektów s³u¿y klasa ObjectDeleter. Aby stworzyæ -obiekt tej klasy potrzebny jest "klucz", którym jest w³asnie ta klasa. - -Klucz ma prywatne konstruktory, w zwi¹zku z czym mo¿e zostaæ stworzony jedynie przez klasy, -które s¹ z nim zaprzyjaŸnione. Domyœlnie klasami zaprzyjaŸnionymi s¹ ResourceManager i ResourceContainer, -aby stworzyæ klucz dla innych typów klas, nale¿y napisaæ specjalizacjê tego szablonu. - -Odddelegowanie innej klasy do kasowania obiektów ma za zadanie zlikwidowanie niewygodnych zale¿noœci. -Dziêki temu obiekty, które maj¹ byæ kasowane, nie musz¹ siê przyjaŸniæ bezpoœrednio z klasami, które mog¹ je usuwaæ. -Wystarczy, ¿e zadeklaruj¹ przyjaŸñ z obiektem ObjectDeleter. Taka przyjaŸñ jest niegroŸna, poniewa¿ -klasa ta nie s³u¿y do niczego innego ni¿ kasowanie obiektów, wiêc jesteœmy pewni, ¿e zmiany wprowadzone -w klasie deklaruj¹cej przyjaŸñ nie bêd¹ psu³y ca³ego kodu aplikacji. -*/ -template class ObjectDeleterKey -{ - friend class ResourceManager; - friend class sw::AssetsManager; - friend class ResourceContainer; - friend class ResourceContainer< ResourceObject >; - friend class RenderTargetObject; -private: - ObjectDeleterKey() = default; /// class ObjectDeleter -{ -private: - ObjectDeleter() = default; ///& deleter_key ) {}; ///& deleter_key ) - { - delete object; - } -}; diff --git a/swCommonLib/Common/RTTR.h b/swCommonLib/Common/RTTR.h index 3f3ca2e1..7e3c51e6 100644 --- a/swCommonLib/Common/RTTR.h +++ b/swCommonLib/Common/RTTR.h @@ -4,7 +4,7 @@ #undef max #undef min -#include "swCommonLib/Common//TypesDefinitions.h" +#include "swCommonLib/Common/TypesDefinitions.h" #include "swCommonLib/Reflection/src/rttr/type.h" #include "swCommonLib/Reflection/src/rttr/rttr_enable.h" @@ -186,4 +186,3 @@ class StaticActor : public Object #define BIND_AS_PTR ( rttr::policy::prop::bind_as_ptr ) #define BIND_AS_REF ( rttr::policy::prop::as_reference_wrapper ) - diff --git a/swCommonLib/Common/Version.cpp b/swCommonLib/Common/Version.cpp new file mode 100644 index 00000000..38d32caf --- /dev/null +++ b/swCommonLib/Common/Version.cpp @@ -0,0 +1,127 @@ +#include "Version.h" +/** +@file Version.cpp +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +#include "Version.h" + +#include + + +namespace sw +{ + + + +namespace impl +{ + std::regex sVersionRegex( "^([[:digit:]]{1,9}).([[:digit:]]{1,9}).([[:digit:]]{1,9}).([[:digit:]]{1,9})$" ); +} + + + +/**@brief Creates Version from string.*/ +Nullable< Version > Version::From ( const std::string& versionStr ) +{ + std::smatch match; + + if( std::regex_match( versionStr, match, impl::sVersionRegex ) ) + { + // If it already matched regex, it should be convertible to uint32. + return Version( Convert::FromString< uint32 >( match[ 1 ], 0 ), + Convert::FromString< uint32 >( match[ 2 ], 0 ), + Convert::FromString< uint32 >( match[ 3 ], 0 ), + Convert::FromString< uint32 >( match[ 4 ], 0 ) ); + } + else + { + return "Can't convert string [" + versionStr + "] to Version type."; + } +} + +// ================================ // +// +bool Version::IsBackwardCompatibileWith ( const Version& olderVersion ) const +{ + // If one of versions is below zero, we can't count + // on compatibility between versions if they aren't equal. + if( olderVersion.Major == 0 || + Major == 0 ) + { + if( olderVersion.Major == Major && + olderVersion.Minor == Minor ) + return true; + return false; + } + + // Major version change breaks compatibility. + if( olderVersion.Major != Major ) + return false; + + if( olderVersion.Minor > Minor ) + return false; + + return true; +} + +// ================================ // +// +std::string Version::ToString () const +{ + return Convert::ToString( Major ) + "." + + Convert::ToString( Minor ) + "." + + Convert::ToString( Patch ) + "." + + Convert::ToString( Build ); +} + +// ================================ // +// +bool Version::operator< ( const Version& other ) +{ + if( Major < other.Major ) + return true; + else if( Major == other.Major ) + { + if( Minor < other.Minor ) + return true; + else if( Minor == other.Minor ) + { + if( Patch < other.Patch ) + return true; + else if( Build == other.Build && Build < other.Build ) + return true; + } + } + + return false; +} + +// ================================ // +// +bool Version::operator== ( const Version& other ) +{ + return Major == other.Major + && Minor == other.Minor + && Patch == other.Patch + && Build == other.Build; +} + +// ================================ // +// +std::ostream& operator<< ( std::ostream& stream, const Version& ver ) +{ + stream << ver.Major; + stream << '.'; + stream << ver.Minor; + stream << '.'; + stream << ver.Patch; + stream << '.'; + stream << ver.Build; + return stream; +} + +} // sw + + diff --git a/swCommonLib/Common/Version.h b/swCommonLib/Common/Version.h index bae350dd..f412dddf 100644 --- a/swCommonLib/Common/Version.h +++ b/swCommonLib/Common/Version.h @@ -6,83 +6,87 @@ */ #include "swCommonLib/Common/TypesDefinitions.h" +#include "swCommonLib/Common/Converters.h" +#include "swCommonLib/Common/Exceptions/Nullable.h" #include +namespace sw +{ + + /**@brief Standard version structure. -Based on: http://sourcey.com/comparing-version-strings-in-cpp/ +Version follows semantic versioning guidlines: +https://semver.org/ + +* Major changes when you make incompatibile API changes. +* Minor changes whne functionalities are added with backward compatibility. +* Patch changes when bug fixes are made without changes to API. +* Build is optional number that you can add to identify your builds, releases or whatever you want. + +The exception from above rules are versions with Major equal to zero. This means +that library is still in development process, API is unstable and everything can change between version. + */ struct Version { - uint32 Major; - uint32 Minor; - uint32 Revision; - uint32 Build; - -// ================================ // -// - /**@brief Contructs Lowest version.*/ - Version() - { - Major = 1; - Minor = 0; - Revision = 0; - Build = 0; - } - - /**@brief */ - Version ( const std::string& version ) - { - std::sscanf( version.c_str(), "%d.%d.%d.%d", &Major, &Minor, &Revision, &Build ); - if( Major < 0 ) Major = 0; - if( Minor < 0 ) Minor = 0; - if( Revision < 0 ) Revision = 0; - if( Build < 0 ) Build = 0; - } - - /**@brief Version comparision.*/ - bool operator< ( const Version& other ) - { - if( Major < other.Major ) - return true; - else if( Major == other.Major ) - { - if( Minor < other.Minor ) - return true; - else if( Minor == other.Minor ) - { - if( Revision < other.Revision ) - return true; - else if( Build == other.Build && Build < other.Build ) - return true; - } - } - - return false; - } - - /**@brief Version comparision.*/ - bool operator== ( const Version& other ) - { - return Major == other.Major - && Minor == other.Minor - && Revision == other.Revision - && Build == other.Build; - } - - /**@brief */ - friend std::ostream& operator<< ( std::ostream& stream, const Version& ver ) - { - stream << ver.Major; - stream << '.'; - stream << ver.Minor; - stream << '.'; - stream << ver.Revision; - stream << '.'; - stream << ver.Build; - return stream; - } + uint32 Major; + uint32 Minor; + uint32 Patch; + uint32 Build; + + // ================================ // + // + /**@brief Contructs Lowest version.*/ + explicit Version () + { + Major = 0; + Minor = 1; + Patch = 0; + Build = 0; + } + + // ================================ // + // + explicit Version ( uint32 major, uint32 minor, uint32 patch, uint32 build ) + : Major( major ) + , Minor( minor ) + , Patch( patch ) + , Build( build ) + {} + + // ================================ // + // + explicit Version ( uint32 major, uint32 minor, uint32 patch ) + : Major( major ) + , Minor( minor ) + , Patch( patch ) + , Build( 0 ) + {} + + + /**@brief Creates Version from string.*/ + static Nullable< Version > From ( const std::string& versionStr ); + + /**@brief Version comparision.*/ + bool operator< ( const Version& other ); + + /**@brief Version comparision.*/ + bool operator== ( const Version& other ); + + /**@brief Conversts to string. + String has the same fromat as Version::From function expects as input.*/ + std::string ToString () const; + + /**@brief Checks compatibility between two versions.*/ + bool IsBackwardCompatibileWith ( const Version& olderVersion ) const; + + /**@brief */ + friend std::ostream& operator<< ( std::ostream& stream, const Version& ver ); }; + +} // sw + diff --git a/swCommonLib/Common/fmt.h b/swCommonLib/Common/fmt.h new file mode 100644 index 00000000..6180fb5a --- /dev/null +++ b/swCommonLib/Common/fmt.h @@ -0,0 +1,13 @@ +#pragma once +/** +@file fmt.h +@author nieznanysprawiciel +@copyright File is part of Sleeping Wombat Libraries. +*/ + +// This is kind of joke!! +// Disable including windows.h. +#define FMT_USE_WINDOWS_H 0 + +#include "swCommonLib/External/fmt/format.h" + diff --git a/swCommonLib/External/fmt/chrono.h b/swCommonLib/External/fmt/chrono.h new file mode 100644 index 00000000..e0fd21b1 --- /dev/null +++ b/swCommonLib/External/fmt/chrono.h @@ -0,0 +1,828 @@ +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#include "format.h" +#include "locale.h" + +#include +#include +#include +#include + +// enable safe chrono durations, unless explicitly disabled +#ifndef FMT_SAFE_DURATION_CAST +# define FMT_SAFE_DURATION_CAST 1 +#endif + +#if FMT_SAFE_DURATION_CAST +# include "safe-duration-cast.h" +#endif + +FMT_BEGIN_NAMESPACE + +// Prevents expansion of a preceding token as a function-style macro. +// Usage: f FMT_NOMACRO() +#define FMT_NOMACRO + +namespace internal { +inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); } +inline null<> localtime_s(...) { return null<>(); } +inline null<> gmtime_r(...) { return null<>(); } +inline null<> gmtime_s(...) { return null<>(); } +} // namespace internal + +// Thread-safe replacement for std::localtime +inline std::tm localtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { + using namespace fmt::internal; + return handle(localtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + + bool handle(internal::null<>) { + using namespace fmt::internal; + return fallback(localtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER + bool fallback(internal::null<>) { + using namespace fmt::internal; + std::tm* tm = std::localtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher lt(time); + // Too big time values may be unsupported. + if (!lt.run()) FMT_THROW(format_error("time_t value out of range")); + return lt.tm_; +} + +// Thread-safe replacement for std::gmtime +inline std::tm gmtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { + using namespace fmt::internal; + return handle(gmtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + + bool handle(internal::null<>) { + using namespace fmt::internal; + return fallback(gmtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER + bool fallback(internal::null<>) { + std::tm* tm = std::gmtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher gt(time); + // Too big time values may be unsupported. + if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); + return gt.tm_; +} + +namespace internal { +inline std::size_t strftime(char* str, std::size_t count, const char* format, + const std::tm* time) { + return std::strftime(str, count, format, time); +} + +inline std::size_t strftime(wchar_t* str, std::size_t count, + const wchar_t* format, const std::tm* time) { + return std::wcsftime(str, count, format, time); +} +} // namespace internal + +template struct formatter { + template + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + if (it != ctx.end() && *it == ':') ++it; + auto end = it; + while (end != ctx.end() && *end != '}') ++end; + tm_format.reserve(internal::to_unsigned(end - it + 1)); + tm_format.append(it, end); + tm_format.push_back('\0'); + return end; + } + + template + auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) { + basic_memory_buffer buf; + std::size_t start = buf.size(); + for (;;) { + std::size_t size = buf.capacity() - start; + std::size_t count = + internal::strftime(&buf[start], size, &tm_format[0], &tm); + if (count != 0) { + buf.resize(start + count); + break; + } + if (size >= tm_format.size() * 256) { + // If the buffer is 256 times larger than the format string, assume + // that `strftime` gives an empty result. There doesn't seem to be a + // better way to distinguish the two cases: + // https://github.com/fmtlib/fmt/issues/367 + break; + } + const std::size_t MIN_GROWTH = 10; + buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH)); + } + return std::copy(buf.begin(), buf.end(), ctx.out()); + } + + basic_memory_buffer tm_format; +}; + +namespace internal { +template FMT_CONSTEXPR const char* get_units() { + return nullptr; +} +template <> FMT_CONSTEXPR const char* get_units() { return "as"; } +template <> FMT_CONSTEXPR const char* get_units() { return "fs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ps"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ns"; } +template <> FMT_CONSTEXPR const char* get_units() { return "µs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ms"; } +template <> FMT_CONSTEXPR const char* get_units() { return "cs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ds"; } +template <> FMT_CONSTEXPR const char* get_units>() { return "s"; } +template <> FMT_CONSTEXPR const char* get_units() { return "das"; } +template <> FMT_CONSTEXPR const char* get_units() { return "hs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ks"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ms"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Gs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ts"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ps"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Es"; } +template <> FMT_CONSTEXPR const char* get_units>() { + return "m"; +} +template <> FMT_CONSTEXPR const char* get_units>() { + return "h"; +} + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. å二 instead of 12 in ja_JP locale. + alternative +}; + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin, + const Char* end, + Handler&& handler) { + auto ptr = begin; + while (ptr != end) { + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case '%': + handler.on_text(ptr - 1, ptr); + break; + case 'n': { + const char newline[] = "\n"; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const char tab[] = "\t"; + handler.on_text(tab, tab + 1); + break; + } + // Day of the week: + case 'a': + handler.on_abbr_weekday(); + break; + case 'A': + handler.on_full_weekday(); + break; + case 'w': + handler.on_dec0_weekday(numeric_system::standard); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::standard); + break; + // Month: + case 'b': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard); + break; + case 'I': + handler.on_12_hour(numeric_system::standard); + break; + case 'M': + handler.on_minute(numeric_system::standard); + break; + case 'S': + handler.on_second(numeric_system::standard); + break; + // Other: + case 'c': + handler.on_datetime(numeric_system::standard); + break; + case 'x': + handler.on_loc_date(numeric_system::standard); + break; + case 'X': + handler.on_loc_time(numeric_system::standard); + break; + case 'D': + handler.on_us_date(); + break; + case 'F': + handler.on_iso_date(); + break; + case 'r': + handler.on_12_hour_time(); + break; + case 'R': + handler.on_24_hour_time(); + break; + case 'T': + handler.on_iso_time(); + break; + case 'p': + handler.on_am_pm(); + break; + case 'Q': + handler.on_duration_value(); + break; + case 'q': + handler.on_duration_unit(); + break; + case 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'c': + handler.on_datetime(numeric_system::alternative); + break; + case 'x': + handler.on_loc_date(numeric_system::alternative); + break; + case 'X': + handler.on_loc_time(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + } + case 'O': + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'w': + handler.on_dec0_weekday(numeric_system::alternative); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::alternative); + break; + case 'H': + handler.on_24_hour(numeric_system::alternative); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative); + break; + case 'M': + handler.on_minute(numeric_system::alternative); + break; + case 'S': + handler.on_second(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + default: + FMT_THROW(format_error("invalid format")); + } + begin = ptr; + } + if (begin != ptr) handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); } + + template void on_text(const Char*, const Char*) {} + FMT_NORETURN void on_abbr_weekday() { report_no_date(); } + FMT_NORETURN void on_full_weekday() { report_no_date(); } + FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_abbr_month() { report_no_date(); } + FMT_NORETURN void on_full_month() { report_no_date(); } + void on_24_hour(numeric_system) {} + void on_12_hour(numeric_system) {} + void on_minute(numeric_system) {} + void on_second(numeric_system) {} + FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); } + FMT_NORETURN void on_us_date() { report_no_date(); } + FMT_NORETURN void on_iso_date() { report_no_date(); } + void on_12_hour_time() {} + void on_24_hour_time() {} + void on_iso_time() {} + void on_am_pm() {} + void on_duration_value() {} + void on_duration_unit() {} + FMT_NORETURN void on_utc_offset() { report_no_date(); } + FMT_NORETURN void on_tz_name() { report_no_date(); } +}; + +template ::value)> +inline bool isnan(T) { + return false; +} +template ::value)> +inline bool isnan(T value) { + return std::isnan(value); +} + +template ::value)> +inline bool isfinite(T) { + return true; +} +template ::value)> +inline bool isfinite(T value) { + return std::isfinite(value); +} + +// Converts value to int and checks that it's in the range [0, upper). +template ::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT(value >= 0 && value <= upper, "invalid value"); + (void)upper; + return static_cast(value); +} +template ::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT( + std::isnan(value) || (value >= 0 && value <= static_cast(upper)), + "invalid value"); + (void)upper; + return static_cast(value); +} + +template ::value)> +inline T mod(T x, int y) { + return x % y; +} +template ::value)> +inline T mod(T x, int y) { + return std::fmod(x, static_cast(y)); +} + +// If T is an integral type, maps T to its unsigned counterpart, otherwise +// leaves it unchanged (unlike std::make_unsigned). +template ::value> +struct make_unsigned_or_unchanged { + using type = T; +}; + +template struct make_unsigned_or_unchanged { + using type = typename std::make_unsigned::type; +}; + +#if FMT_SAFE_DURATION_CAST +// throwing version of safe_duration_cast +template +To fmt_safe_duration_cast(std::chrono::duration from) { + int ec; + To to = safe_duration_cast::safe_duration_cast(from, ec); + if (ec) FMT_THROW(format_error("cannot format duration")); + return to; +} +#endif + +template ::value)> +inline std::chrono::duration get_milliseconds( + std::chrono::duration d) { + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + using CommonSecondsType = + typename std::common_type::type; + const auto d_as_common = fmt_safe_duration_cast(d); + const auto d_as_whole_seconds = + fmt_safe_duration_cast(d_as_common); + // this conversion should be nonproblematic + const auto diff = d_as_common - d_as_whole_seconds; + const auto ms = + fmt_safe_duration_cast>(diff); + return ms; +#else + auto s = std::chrono::duration_cast(d); + return std::chrono::duration_cast(d - s); +#endif +} + +template ::value)> +inline std::chrono::duration get_milliseconds( + std::chrono::duration d) { + using common_type = typename std::common_type::type; + auto ms = mod(d.count() * static_cast(Period::num) / + static_cast(Period::den) * 1000, + 1000); + return std::chrono::duration(static_cast(ms)); +} + +template +OutputIt format_chrono_duration_value(OutputIt out, Rep val, int precision) { + if (precision >= 0) return format_to(out, "{:.{}f}", val, precision); + return format_to(out, std::is_floating_point::value ? "{:g}" : "{}", + val); +} + +template +static OutputIt format_chrono_duration_unit(OutputIt out) { + if (const char* unit = get_units()) return format_to(out, "{}", unit); + if (Period::den == 1) return format_to(out, "[{}]s", Period::num); + return format_to(out, "[{}/{}]s", Period::num, Period::den); +} + +template +struct chrono_formatter { + FormatContext& context; + OutputIt out; + int precision; + // rep is unsigned to avoid overflow. + using rep = + conditional_t::value && sizeof(Rep) < sizeof(int), + unsigned, typename make_unsigned_or_unchanged::type>; + rep val; + using seconds = std::chrono::duration; + seconds s; + using milliseconds = std::chrono::duration; + bool negative; + + using char_type = typename FormatContext::char_type; + + explicit chrono_formatter(FormatContext& ctx, OutputIt o, + std::chrono::duration d) + : context(ctx), out(o), val(d.count()), negative(false) { + if (d.count() < 0) { + val = 0 - val; + negative = true; + } + + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + // might need checked conversion (rep!=Rep) + auto tmpval = std::chrono::duration(val); + s = fmt_safe_duration_cast(tmpval); +#else + s = std::chrono::duration_cast( + std::chrono::duration(val)); +#endif + } + + // returns true if nan or inf, writes to out. + bool handle_nan_inf() { + if (isfinite(val)) { + return false; + } + if (isnan(val)) { + write_nan(); + return true; + } + // must be +-inf + if (val > 0) { + write_pinf(); + } else { + write_ninf(); + } + return true; + } + + Rep hour() const { return static_cast(mod((s.count() / 3600), 24)); } + + Rep hour12() const { + Rep hour = static_cast(mod((s.count() / 3600), 12)); + return hour <= 0 ? 12 : hour; + } + + Rep minute() const { return static_cast(mod((s.count() / 60), 60)); } + Rep second() const { return static_cast(mod(s.count(), 60)); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + time.tm_min = to_nonnegative_int(minute(), 60); + time.tm_sec = to_nonnegative_int(second(), 60); + return time; + } + + void write_sign() { + if (negative) { + *out++ = '-'; + negative = false; + } + } + + void write(Rep value, int width) { + write_sign(); + if (isnan(value)) return write_nan(); + uint32_or_64_or_128_t n = to_unsigned( + to_nonnegative_int(value, max_value())); + int num_digits = internal::count_digits(n); + if (width > num_digits) out = std::fill_n(out, width - num_digits, '0'); + out = format_decimal(out, n, num_digits); + } + + void write_nan() { std::copy_n("nan", 3, out); } + void write_pinf() { std::copy_n("inf", 3, out); } + void write_ninf() { std::copy_n("-inf", 4, out); } + + void format_localized(const tm& time, const char* format) { + if (isnan(val)) return write_nan(); + auto locale = context.locale().template get(); + auto& facet = std::use_facet>(locale); + std::basic_ostringstream os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, format + std::strlen(format)); + auto str = os.str(); + std::copy(str.begin(), str.end(), out); + } + + void on_text(const char_type* begin, const char_type* end) { + std::copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset() {} + void on_tz_name() {} + + void on_24_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + format_localized(time, "%OH"); + } + + void on_12_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour12(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour12(), 12); + format_localized(time, "%OI"); + } + + void on_minute(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(minute(), 2); + auto time = tm(); + time.tm_min = to_nonnegative_int(minute(), 60); + format_localized(time, "%OM"); + } + + void on_second(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) { + write(second(), 2); +#if FMT_SAFE_DURATION_CAST + // convert rep->Rep + using duration_rep = std::chrono::duration; + using duration_Rep = std::chrono::duration; + auto tmpval = fmt_safe_duration_cast(duration_rep{val}); +#else + auto tmpval = std::chrono::duration(val); +#endif + auto ms = get_milliseconds(tmpval); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(ms.count(), 3); + } + return; + } + auto time = tm(); + time.tm_sec = to_nonnegative_int(second(), 60); + format_localized(time, "%OS"); + } + + void on_12_hour_time() { + if (handle_nan_inf()) return; + + format_localized(time(), "%r"); + } + + void on_24_hour_time() { + if (handle_nan_inf()) { + *out++ = ':'; + handle_nan_inf(); + return; + } + + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + if (handle_nan_inf()) return; + write(second(), 2); + } + + void on_am_pm() { + if (handle_nan_inf()) return; + format_localized(time(), "%p"); + } + + void on_duration_value() { + if (handle_nan_inf()) return; + write_sign(); + out = format_chrono_duration_value(out, val, precision); + } + + void on_duration_unit() { out = format_chrono_duration_unit(out); } +}; +} // namespace internal + +template +struct formatter, Char> { + private: + basic_format_specs specs; + int precision; + using arg_ref_type = internal::arg_ref; + arg_ref_type width_ref; + arg_ref_type precision_ref; + mutable basic_string_view format_str; + using duration = std::chrono::duration; + + struct spec_handler { + formatter& f; + basic_parse_context& context; + basic_string_view format_str; + + template FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) { + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char* msg) { FMT_THROW(format_error(msg)); } + void on_fill(Char fill) { f.specs.fill[0] = fill; } + void on_align(align_t align) { f.specs.align = align; } + void on_width(unsigned width) { f.specs.width = width; } + void on_precision(unsigned _precision) { f.precision = _precision; } + void end_precision() {} + + template void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + + template void on_dynamic_precision(Id arg_id) { + f.precision_ref = make_arg_ref(arg_id); + } + }; + + using iterator = typename basic_parse_context::iterator; + struct parse_range { + iterator begin; + iterator end; + }; + + FMT_CONSTEXPR parse_range do_parse(basic_parse_context& ctx) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end || *begin == '}') return {begin, begin}; + spec_handler handler{*this, ctx, format_str}; + begin = internal::parse_align(begin, end, handler); + if (begin == end) return {begin, begin}; + begin = internal::parse_width(begin, end, handler); + if (begin == end) return {begin, begin}; + if (*begin == '.') { + if (std::is_floating_point::value) + begin = internal::parse_precision(begin, end, handler); + else + handler.on_error("precision not allowed for this argument type"); + } + end = parse_chrono_format(begin, end, internal::chrono_format_checker()); + return {begin, end}; + } + + public: + formatter() : precision(-1) {} + + FMT_CONSTEXPR auto parse(basic_parse_context& ctx) + -> decltype(ctx.begin()) { + auto range = do_parse(ctx); + format_str = basic_string_view( + &*range.begin, internal::to_unsigned(range.end - range.begin)); + return range.end; + } + + template + auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. + basic_memory_buffer buf; + auto out = std::back_inserter(buf); + using range = internal::output_range; + internal::basic_writer w(range(ctx.out())); + internal::handle_dynamic_spec(specs.width, + width_ref, ctx); + internal::handle_dynamic_spec( + precision, precision_ref, ctx); + if (begin == end || *begin == '}') { + out = internal::format_chrono_duration_value(out, d.count(), precision); + internal::format_chrono_duration_unit(out); + } else { + internal::chrono_formatter f( + ctx, out, d); + f.precision = precision; + parse_chrono_format(begin, end, f); + } + w.write(buf.data(), buf.size(), specs); + return w.out(); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/swCommonLib/External/fmt/color.h b/swCommonLib/External/fmt/color.h new file mode 100644 index 00000000..f2dd24f2 --- /dev/null +++ b/swCommonLib/External/fmt/color.h @@ -0,0 +1,586 @@ +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; + +// rgb is a struct for red, green and blue colors. +// Using the name "rgb" makes some editors show the color in a tooltip. +struct rgb { + FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {} + FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {} + FMT_CONSTEXPR rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {} + FMT_CONSTEXPR rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), + g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + +namespace internal { + +// color is a struct of either a rgb color or a terminal color. +struct color_type { + FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true), + value{} { + value.rgb_color = static_cast(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) | + (static_cast(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(), + value{} { + value.term_color = static_cast(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; +} // namespace internal + +// Experimental text formatting support. +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems(em) {} + + FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) | + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator|(text_style lhs, + const text_style& rhs) { + return lhs |= rhs; + } + + FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) & + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator&(text_style lhs, + const text_style& rhs) { + return lhs &= rhs; + } + + FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { + return set_foreground_color; + } + FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { + return set_background_color; + } + FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { + return static_cast(ems) != 0; + } + FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT { + assert(has_foreground() && "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR internal::color_type get_background() const FMT_NOEXCEPT { + assert(has_background() && "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + assert(has_emphasis() && "no emphasis specified for this style"); + return ems; + } + + private: + FMT_CONSTEXPR text_style(bool is_foreground, + internal::color_type text_color) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems() { + if (is_foreground) { + foreground_color = text_color; + set_foreground_color = true; + } else { + background_color = text_color; + set_background_color = true; + } + } + + friend FMT_CONSTEXPR_DECL text_style fg(internal::color_type foreground) + FMT_NOEXCEPT; + friend FMT_CONSTEXPR_DECL text_style bg(internal::color_type background) + FMT_NOEXCEPT; + + internal::color_type foreground_color; + internal::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +FMT_CONSTEXPR text_style fg(internal::color_type foreground) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/true, foreground); +} + +FMT_CONSTEXPR text_style bg(internal::color_type background) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/false, background); +} + +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} + +namespace internal { + +template struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(internal::color_type text_color, + const char* esc) FMT_NOEXCEPT { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { + bool is_background = esc == internal::data::background_color; + uint32_t value = text_color.value.term_color; + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) value += 10u; + + std::size_t index = 0; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(esc[i]); + } + rgb color(text_color.value.rgb_color); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + buffer[19] = static_cast(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast(em); + if (em_bits & static_cast(emphasis::bold)) em_codes[0] = 1; + if (em_bits & static_cast(emphasis::italic)) em_codes[1] = 3; + if (em_bits & static_cast(emphasis::underline)) em_codes[2] = 4; + if (em_bits & static_cast(emphasis::strikethrough)) + em_codes[3] = 9; + + std::size_t index = 0; + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; } + + FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; } + FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT { + return buffer + std::strlen(buffer); + } + + private: + Char buffer[7u + 3u * 4u + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, + char delimiter) FMT_NOEXCEPT { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } +}; + +template +FMT_CONSTEXPR ansi_color_escape make_foreground_color( + internal::color_type foreground) FMT_NOEXCEPT { + return ansi_color_escape(foreground, internal::data::foreground_color); +} + +template +FMT_CONSTEXPR ansi_color_escape make_background_color( + internal::color_type background) FMT_NOEXCEPT { + return ansi_color_escape(background, internal::data::background_color); +} + +template +FMT_CONSTEXPR ansi_color_escape make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape(em); +} + +template +inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template inline void reset_color(FILE* stream) FMT_NOEXCEPT { + fputs(internal::data::reset_color, stream); +} + +template <> inline void reset_color(FILE* stream) FMT_NOEXCEPT { + fputs(internal::data::wreset_color, stream); +} + +template +inline void reset_color(basic_memory_buffer& buffer) FMT_NOEXCEPT { + const char* begin = data::reset_color; + const char* end = begin + sizeof(data::reset_color) - 1; + buffer.append(begin, end); +} + +template +std::basic_string vformat(const text_style& ts, + basic_string_view format_str, + basic_format_args > args) { + basic_memory_buffer buffer; + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + ansi_color_escape escape = make_emphasis(ts.get_emphasis()); + buffer.append(escape.begin(), escape.end()); + } + if (ts.has_foreground()) { + has_style = true; + ansi_color_escape escape = + make_foreground_color(ts.get_foreground()); + buffer.append(escape.begin(), escape.end()); + } + if (ts.has_background()) { + has_style = true; + ansi_color_escape escape = + make_background_color(ts.get_background()); + buffer.append(escape.begin(), escape.end()); + } + internal::vformat_to(buffer, format_str, args); + if (has_style) { + reset_color(buffer); + } + return fmt::to_string(buffer); +} +} // namespace internal + +template > +void vprint(std::FILE* f, const text_style& ts, const S& format, + basic_format_args > args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + internal::fputs(internal::make_emphasis(ts.get_emphasis()), f); + } + if (ts.has_foreground()) { + has_style = true; + internal::fputs( + internal::make_foreground_color(ts.get_foreground()), f); + } + if (ts.has_background()) { + has_style = true; + internal::fputs( + internal::make_background_color(ts.get_background()), f); + } + vprint(f, format, args); + if (has_style) { + internal::reset_color(f); + } +} + +/** + Formats a string and prints it to the specified file stream using ANSI + escape sequences to specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template ::value)> +void print(std::FILE* f, const text_style& ts, const S& format_str, + const Args&... args) { + internal::check_format_string(format_str); + using context = buffer_context >; + format_arg_store as{args...}; + vprint(f, ts, format_str, basic_format_args(as)); +} + +/** + Formats a string and prints it to stdout using ANSI escape sequences to + specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template ::value)> +void print(const text_style& ts, const S& format_str, const Args&... args) { + return print(stdout, ts, format_str, args...); +} + +template > +inline std::basic_string vformat( + const text_style& ts, const S& format_str, + basic_format_args > args) { + return internal::vformat(ts, to_string_view(format_str), args); +} + +/** + \rst + Formats arguments and returns the result as a string using ANSI + escape sequences to specify text formatting. + + **Example**:: + + #include + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}", 42); + \endrst +*/ +template > +inline std::basic_string format(const text_style& ts, const S& format_str, + const Args&... args) { + return internal::vformat( + ts, to_string_view(format_str), + {internal::make_args_checked(format_str, args...)}); +} + +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/swCommonLib/External/fmt/compile.h b/swCommonLib/External/fmt/compile.h new file mode 100644 index 00000000..337bed31 --- /dev/null +++ b/swCommonLib/External/fmt/compile.h @@ -0,0 +1,581 @@ +// Formatting library for C++ - experimental format string compilation +// +// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COMPILE_H_ +#define FMT_COMPILE_H_ + +#include +#include "format.h" + +FMT_BEGIN_NAMESPACE +namespace internal { + +// Part of a compiled format string. It can be either literal text or a +// replacement field. +template struct format_part { + enum class kind { arg_index, arg_name, text, replacement }; + + struct replacement { + arg_ref arg_id; + dynamic_format_specs specs; + }; + + kind part_kind; + union value { + unsigned arg_index; + basic_string_view str; + replacement repl; + + FMT_CONSTEXPR value(unsigned index = 0) : arg_index(index) {} + FMT_CONSTEXPR value(basic_string_view s) : str(s) {} + FMT_CONSTEXPR value(replacement r) : repl(r) {} + } val; + // Position past the end of the argument id. + const Char* arg_id_end = nullptr; + + FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {}) + : part_kind(k), val(v) {} + + static FMT_CONSTEXPR format_part make_arg_index(unsigned index) { + return format_part(kind::arg_index, index); + } + static FMT_CONSTEXPR format_part make_arg_name(basic_string_view name) { + return format_part(kind::arg_name, name); + } + static FMT_CONSTEXPR format_part make_text(basic_string_view text) { + return format_part(kind::text, text); + } + static FMT_CONSTEXPR format_part make_replacement(replacement repl) { + return format_part(kind::replacement, repl); + } +}; + +template struct part_counter { + unsigned num_parts = 0; + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) ++num_parts; + } + + FMT_CONSTEXPR void on_arg_id() { ++num_parts; } + FMT_CONSTEXPR void on_arg_id(unsigned) { ++num_parts; } + FMT_CONSTEXPR void on_arg_id(basic_string_view) { ++num_parts; } + + FMT_CONSTEXPR void on_replacement_field(const Char*) {} + + FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, + const Char* end) { + // Find the matching brace. + unsigned brace_counter = 0; + for (; begin != end; ++begin) { + if (*begin == '{') { + ++brace_counter; + } else if (*begin == '}') { + if (brace_counter == 0u) break; + --brace_counter; + } + } + return begin; + } + + FMT_CONSTEXPR void on_error(const char*) {} +}; + +// Counts the number of parts in a format string. +template +FMT_CONSTEXPR unsigned count_parts(basic_string_view format_str) { + part_counter counter; + parse_format_string(format_str, counter); + return counter.num_parts; +} + +template +class format_string_compiler : public error_handler { + private: + using part = format_part; + + PartHandler handler_; + part part_; + basic_string_view format_str_; + basic_parse_context parse_context_; + + public: + FMT_CONSTEXPR format_string_compiler(basic_string_view format_str, + PartHandler handler) + : handler_(handler), + format_str_(format_str), + parse_context_(format_str) {} + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) + handler_(part::make_text({begin, to_unsigned(end - begin)})); + } + + FMT_CONSTEXPR void on_arg_id() { + part_ = part::make_arg_index(parse_context_.next_arg_id()); + } + + FMT_CONSTEXPR void on_arg_id(unsigned id) { + parse_context_.check_arg_id(id); + part_ = part::make_arg_index(id); + } + + FMT_CONSTEXPR void on_arg_id(basic_string_view id) { + part_ = part::make_arg_name(id); + } + + FMT_CONSTEXPR void on_replacement_field(const Char* ptr) { + part_.arg_id_end = ptr; + handler_(part_); + } + + FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, + const Char* end) { + auto repl = typename part::replacement(); + dynamic_specs_handler> handler(repl.specs, + parse_context_); + auto it = parse_format_specs(begin, end, handler); + if (*it != '}') on_error("missing '}' in format string"); + repl.arg_id = part_.part_kind == part::kind::arg_index + ? arg_ref(part_.val.arg_index) + : arg_ref(part_.val.str); + auto part = part::make_replacement(repl); + part.arg_id_end = begin; + handler_(part); + return it; + } +}; + +// Compiles a format string and invokes handler(part) for each parsed part. +template +FMT_CONSTEXPR void compile_format_string(basic_string_view format_str, + PartHandler handler) { + parse_format_string( + format_str, + format_string_compiler(format_str, handler)); +} + +template +void format_arg(basic_parse_context& parse_ctx, + Context& ctx, Id arg_id) { + ctx.advance_to( + visit_format_arg(arg_formatter(ctx, &parse_ctx), ctx.arg(arg_id))); +} + +// vformat_to is defined in a subnamespace to prevent ADL. +namespace cf { +template +auto vformat_to(Range out, CompiledFormat& cf, basic_format_args args) + -> typename Context::iterator { + using char_type = typename Context::char_type; + basic_parse_context parse_ctx(to_string_view(cf.format_str_)); + Context ctx(out.begin(), args); + + const auto& parts = cf.parts(); + for (auto part_it = std::begin(parts); part_it != std::end(parts); + ++part_it) { + const auto& part = *part_it; + const auto& value = part.val; + + using format_part_t = format_part; + switch (part.part_kind) { + case format_part_t::kind::text: { + const auto text = value.str; + auto output = ctx.out(); + auto&& it = reserve(output, text.size()); + it = std::copy_n(text.begin(), text.size(), it); + ctx.advance_to(output); + break; + } + + case format_part_t::kind::arg_index: + advance_to(parse_ctx, part.arg_id_end); + internal::format_arg(parse_ctx, ctx, value.arg_index); + break; + + case format_part_t::kind::arg_name: + advance_to(parse_ctx, part.arg_id_end); + internal::format_arg(parse_ctx, ctx, value.str); + break; + + case format_part_t::kind::replacement: { + const auto& arg_id_value = value.repl.arg_id.val; + const auto arg = value.repl.arg_id.kind == arg_id_kind::index + ? ctx.arg(arg_id_value.index) + : ctx.arg(arg_id_value.name); + + auto specs = value.repl.specs; + + handle_dynamic_spec(specs.width, specs.width_ref, ctx); + handle_dynamic_spec(specs.precision, + specs.precision_ref, ctx); + + error_handler h; + numeric_specs_checker checker(h, arg.type()); + if (specs.align == align::numeric) checker.require_numeric_argument(); + if (specs.sign != sign::none) checker.check_sign(); + if (specs.alt) checker.require_numeric_argument(); + if (specs.precision >= 0) checker.check_precision(); + + advance_to(parse_ctx, part.arg_id_end); + ctx.advance_to( + visit_format_arg(arg_formatter(ctx, nullptr, &specs), arg)); + break; + } + } + } + return ctx.out(); +} +} // namespace cf + +struct basic_compiled_format {}; + +template +struct compiled_format_base : basic_compiled_format { + using char_type = char_t; + using parts_container = std::vector>; + + parts_container compiled_parts; + + explicit compiled_format_base(basic_string_view format_str) { + compile_format_string(format_str, + [this](const format_part& part) { + compiled_parts.push_back(part); + }); + } + + const parts_container& parts() const { return compiled_parts; } +}; + +template struct format_part_array { + format_part data[N] = {}; + FMT_CONSTEXPR format_part_array() = default; +}; + +template +FMT_CONSTEXPR format_part_array compile_to_parts( + basic_string_view format_str) { + format_part_array parts; + unsigned counter = 0; + // This is not a lambda for compatibility with older compilers. + struct { + format_part* parts; + unsigned* counter; + FMT_CONSTEXPR void operator()(const format_part& part) { + parts[(*counter)++] = part; + } + } collector{parts.data, &counter}; + compile_format_string(format_str, collector); + if (counter < N) { + parts.data[counter] = + format_part::make_text(basic_string_view()); + } + return parts; +} + +template constexpr const T& constexpr_max(const T& a, const T& b) { + return (a < b) ? b : a; +} + +template +struct compiled_format_base::value>> + : basic_compiled_format { + using char_type = char_t; + + FMT_CONSTEXPR explicit compiled_format_base(basic_string_view) {} + +// Workaround for old compilers. Format string compilation will not be +// performed there anyway. +#if FMT_USE_CONSTEXPR + static FMT_CONSTEXPR_DECL const unsigned num_format_parts = + constexpr_max(count_parts(to_string_view(S())), 1u); +#else + static const unsigned num_format_parts = 1; +#endif + + using parts_container = format_part[num_format_parts]; + + const parts_container& parts() const { + static FMT_CONSTEXPR_DECL const auto compiled_parts = + compile_to_parts( + internal::to_string_view(S())); + return compiled_parts.data; + } +}; + +template +class compiled_format : private compiled_format_base { + public: + using typename compiled_format_base::char_type; + + private: + basic_string_view format_str_; + + template + friend auto cf::vformat_to(Range out, CompiledFormat& cf, + basic_format_args args) -> + typename Context::iterator; + + public: + compiled_format() = delete; + explicit constexpr compiled_format(basic_string_view format_str) + : compiled_format_base(format_str), format_str_(format_str) {} +}; + +#ifdef __cpp_if_constexpr +template struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template +constexpr const auto& get(const T& first, const Args&... rest) { + static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); + if constexpr (N == 0) + return first; + else + return get(rest...); +} + +template struct get_type_impl; + +template struct get_type_impl> { + using type = remove_cvref_t(std::declval()...))>; +}; + +template +using get_type = typename get_type_impl::type; + +template struct text { + basic_string_view data; + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&...) const { + // TODO: reserve + return copy_str(data.begin(), data.end(), out); + } +}; + +template +constexpr text make_text(basic_string_view s, size_t pos, + size_t size) { + return {{&s[pos], size}}; +} + +template , int> = 0> +OutputIt format_default(OutputIt out, T value) { + // TODO: reserve + format_int fi(value); + return std::copy(fi.data(), fi.data() + fi.size(), out); +} + +template +OutputIt format_default(OutputIt out, Char value) { + *out++ = value; + return out; +} + +template +OutputIt format_default(OutputIt out, const Char* value) { + auto length = std::char_traits::length(value); + return copy_str(value, value + length, out); +} + +// A replacement field that refers to argument N. +template struct field { + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&... args) const { + // This ensures that the argument type is convertile to `const T&`. + const T& arg = get(args...); + return format_default(out, arg); + } +}; + +template struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template + OutputIt format(OutputIt out, const Args&... args) const { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template +constexpr concat make_concat(L lhs, R rhs) { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template +constexpr size_t parse_text(basic_string_view str, size_t pos) { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template +constexpr auto compile_format_string(S format_str); + +template +constexpr auto parse_tail(T head, S format_str) { + if constexpr (POS != to_string_view(format_str).size()) { + constexpr auto tail = compile_format_string(format_str); + if constexpr (std::is_same, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template +constexpr auto compile_format_string(S format_str) { + using char_type = typename S::char_type; + constexpr basic_string_view str = format_str; + if constexpr (str[POS] == '{') { + if (POS + 1 == str.size()) + throw format_error("unmatched '{' in format string"); + if constexpr (str[POS + 1] == '{') { + return parse_tail(make_text(str, POS, 1), format_str); + } else if constexpr (str[POS + 1] == '}') { + using type = get_type; + if constexpr (std::is_same::value) { + return parse_tail(field(), + format_str); + } else { + return unknown_format(); + } + } else { + return unknown_format(); + } + } else if constexpr (str[POS] == '}') { + if (POS + 1 == str.size()) + throw format_error("unmatched '}' in format string"); + return parse_tail(make_text(str, POS, 1), format_str); + } else { + constexpr auto end = parse_text(str, POS + 1); + return parse_tail(make_text(str, POS, end - POS), + format_str); + } +} +#endif // __cpp_if_constexpr +} // namespace internal + +#if FMT_USE_CONSTEXPR +# ifdef __cpp_if_constexpr +template ::value)> +constexpr auto compile(S format_str) { + constexpr basic_string_view str = format_str; + if constexpr (str.size() == 0) { + return internal::make_text(str, 0, 0); + } else { + constexpr auto result = + internal::compile_format_string, 0, 0>( + format_str); + if constexpr (std::is_same, + internal::unknown_format>()) { + return internal::compiled_format(to_string_view(format_str)); + } else { + return result; + } + } +} + +template ::value)> +std::basic_string format(const CompiledFormat& cf, const Args&... args) { + basic_memory_buffer buffer; + using range = buffer_range; + using context = buffer_context; + cf.format(std::back_inserter(buffer), args...); + return to_string(buffer); +} + +template ::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + return cf.format(out, args...); +} +# else +template ::value)> +constexpr auto compile(S format_str) -> internal::compiled_format { + return internal::compiled_format(to_string_view(format_str)); +} +# endif // __cpp_if_constexpr +#endif // FMT_USE_CONSTEXPR + +// Compiles the format string which must be a string literal. +template +auto compile(const Char (&format_str)[N]) + -> internal::compiled_format { + return internal::compiled_format( + basic_string_view(format_str, N - 1)); +} + +template ::value)> +std::basic_string format(const CompiledFormat& cf, const Args&... args) { + basic_memory_buffer buffer; + using range = buffer_range; + using context = buffer_context; + internal::cf::vformat_to(range(buffer), cf, + {make_format_args(args...)}); + return to_string(buffer); +} + +template ::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + using char_type = typename CompiledFormat::char_type; + using range = internal::output_range; + using context = format_context_t; + return internal::cf::vformat_to( + range(out), cf, {make_format_args(args...)}); +} + +template ::value)> +format_to_n_result format_to_n(OutputIt out, size_t n, + const CompiledFormat& cf, + const Args&... args) { + auto it = + format_to(internal::truncating_iterator(out, n), cf, args...); + return {it.base(), it.count()}; +} + +template +std::size_t formatted_size(const CompiledFormat& cf, const Args&... args) { + return format_to( + internal::counting_iterator(), + cf, args...) + .count(); +} + +FMT_END_NAMESPACE + +#endif // FMT_COMPILE_H_ diff --git a/swCommonLib/External/fmt/core.h b/swCommonLib/External/fmt/core.h new file mode 100644 index 00000000..8cdc9cdc --- /dev/null +++ b/swCommonLib/External/fmt/core.h @@ -0,0 +1,1468 @@ +// Formatting library for C++ - the core API +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CORE_H_ +#define FMT_CORE_H_ + +#include +#include // std::FILE +#include +#include +#include +#include + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 60000 + +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif + +#if defined(__has_include) && !defined(__INTELLISENSE__) && \ + !(defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1600) +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif + +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#if defined(__GNUC__) && !defined(__clang__) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif + +#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) +# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION +#else +# define FMT_HAS_GXX_CXX11 0 +#endif + +#ifdef _MSC_VER +# define FMT_MSC_VER _MSC_VER +#else +# define FMT_MSC_VER 0 +#endif + +// Check if relaxed C++14 constexpr is supported. +// GCC doesn't allow throw in constexpr until version 6 (bug 67371). +#ifndef FMT_USE_CONSTEXPR +# define FMT_USE_CONSTEXPR \ + (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \ + (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +# define FMT_CONSTEXPR_DECL constexpr +#else +# define FMT_CONSTEXPR inline +# define FMT_CONSTEXPR_DECL +#endif + +#ifndef FMT_OVERRIDE +# if FMT_HAS_FEATURE(cxx_override) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_OVERRIDE override +# else +# define FMT_OVERRIDE +# endif +#endif + +// Check if exceptions are disabled. +#ifndef FMT_EXCEPTIONS +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + FMT_MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif +#endif + +// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). +#ifndef FMT_USE_NOEXCEPT +# define FMT_USE_NOEXCEPT 0 +#endif + +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_DETECTED_NOEXCEPT noexcept +# define FMT_HAS_CXX11_NOEXCEPT 1 +#else +# define FMT_DETECTED_NOEXCEPT throw() +# define FMT_HAS_CXX11_NOEXCEPT 0 +#endif + +#ifndef FMT_NOEXCEPT +# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT +# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT +# else +# define FMT_NOEXCEPT +# endif +#endif + +// [[noreturn]] is disabled on MSVC because of bogus unreachable code warnings. +#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifndef FMT_DEPRECATED +# if (FMT_HAS_CPP_ATTRIBUTE(deprecated) && __cplusplus >= 201402L) || \ + FMT_MSC_VER >= 1900 +# define FMT_DEPRECATED [[deprecated]] +# else +# if defined(__GNUC__) || defined(__clang__) +# define FMT_DEPRECATED __attribute__((deprecated)) +# elif FMT_MSC_VER +# define FMT_DEPRECATED __declspec(deprecated) +# else +# define FMT_DEPRECATED /* deprecated */ +# endif +# endif +#endif + +// Workaround broken [[deprecated]] in the Intel compiler and NVCC. +#if defined(__INTEL_COMPILER) || defined(__NVCC__) || defined(__CUDACC__) +# define FMT_DEPRECATED_ALIAS +#else +# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ + FMT_MSC_VER >= 1900 +# define FMT_INLINE_NAMESPACE inline namespace +# define FMT_END_NAMESPACE \ + } \ + } +# else +# define FMT_INLINE_NAMESPACE namespace +# define FMT_END_NAMESPACE \ + } \ + using namespace v6; \ + } +# endif +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + FMT_INLINE_NAMESPACE v6 { +#endif + +#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) +# ifdef FMT_EXPORT +# define FMT_API __declspec(dllexport) +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# define FMT_EXTERN_TEMPLATE_API FMT_API +# endif +#endif +#ifndef FMT_API +# define FMT_API +#endif +#ifndef FMT_EXTERN_TEMPLATE_API +# define FMT_EXTERN_TEMPLATE_API +#endif + +#ifndef FMT_HEADER_ONLY +# define FMT_EXTERN extern +#else +# define FMT_EXTERN +#endif + +#ifndef FMT_ASSERT +# define FMT_ASSERT(condition, message) assert((condition) && message) +#endif + +// libc++ supports string_view in pre-c++17. +#if (FMT_HAS_INCLUDE() && \ + (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ + (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +# include +# define FMT_USE_STRING_VIEW +#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L +# include +# define FMT_USE_EXPERIMENTAL_STRING_VIEW +#endif + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other types for pre-C++14 systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; + +struct monostate {}; + +// An enable_if helper to be used in template parameters which results in much +// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed +// to workaround a bug in MSVC 2019 (see #1140 and #1186). +#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0 + +namespace internal { + +// A workaround for gcc 4.8 to make void_t work in a SFINAE context. +template struct void_t_impl { using type = void; }; + +#if defined(FMT_USE_STRING_VIEW) +template using std_string_view = std::basic_string_view; +#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) +template +using std_string_view = std::experimental::basic_string_view; +#else +template struct std_string_view {}; +#endif + +#ifdef FMT_USE_INT128 +// Do nothing. +#elif defined(__SIZEOF_INT128__) +# define FMT_USE_INT128 1 +using int128_t = __int128_t; +using uint128_t = __uint128_t; +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +struct int128_t {}; +struct uint128_t {}; +#endif + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { + FMT_ASSERT(value >= 0, "negative value"); + return static_cast::type>(value); +} +} // namespace internal + +template +using void_t = typename internal::void_t_impl::type; + +/** + An implementation of ``std::basic_string_view`` for pre-C++17. It provides a + subset of the API. ``fmt::basic_string_view`` is used for format strings even + if ``std::string_view`` is available to prevent issues when a library is + compiled with a different ``-std`` option than the client code (which is not + recommended). + */ +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using char_type = Char; + using iterator = const Char*; + + FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {} + + /** Constructs a string reference object from a C string and a size. */ + FMT_CONSTEXPR basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT + : data_(s), + size_(count) {} + + /** + \rst + Constructs a string reference object from a C string computing + the size with ``std::char_traits::length``. + \endrst + */ + basic_string_view(const Char* s) + : data_(s), size_(std::char_traits::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template + FMT_CONSTEXPR basic_string_view(const std::basic_string& s) + FMT_NOEXCEPT : data_(s.data()), + size_(s.size()) {} + + template < + typename S, + FMT_ENABLE_IF(std::is_same>::value)> + FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()), + size_(s.size()) {} + + /** Returns a pointer to the string data. */ + FMT_CONSTEXPR const Char* data() const { return data_; } + + /** Returns the string size. */ + FMT_CONSTEXPR size_t size() const { return size_; } + + FMT_CONSTEXPR iterator begin() const { return data_; } + FMT_CONSTEXPR iterator end() const { return data_ + size_; } + + FMT_CONSTEXPR const Char& operator[](size_t pos) const { return data_[pos]; } + + FMT_CONSTEXPR void remove_prefix(size_t n) { + data_ += n; + size_ -= n; + } + + // Lexicographically compare this string reference to other. + int compare(basic_string_view other) const { + size_t str_size = size_ < other.size_ ? size_ : other.size_; + int result = std::char_traits::compare(data_, other.data_, str_size); + if (result == 0) + result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + return result; + } + + friend bool operator==(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) == 0; + } + friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) != 0; + } + friend bool operator<(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) < 0; + } + friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) <= 0; + } + friend bool operator>(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) > 0; + } + friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view; +using wstring_view = basic_string_view; + +#ifndef __cpp_char8_t +// A UTF-8 code unit type. +enum char8_t : unsigned char {}; +#endif + +/** Specifies if ``T`` is a character type. Can be specialized by users. */ +template struct is_char : std::false_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; + +/** + \rst + Returns a string view of `s`. In order to add custom string type support to + {fmt} provide an overload of `to_string_view` for it in the same namespace as + the type for the argument-dependent lookup to work. + + **Example**:: + + namespace my_ns { + inline string_view to_string_view(const my_string& s) { + return {s.data(), s.length()}; + } + } + std::string message = fmt::format(my_string("The answer is {}"), 42); + \endrst + */ +template ::value)> +inline basic_string_view to_string_view(const Char* s) { + return s; +} + +template +inline basic_string_view to_string_view( + const std::basic_string& s) { + return {s.data(), s.size()}; +} + +template +inline basic_string_view to_string_view(basic_string_view s) { + return s; +} + +template >::value)> +inline basic_string_view to_string_view( + internal::std_string_view s) { + return s; +} + +// A base class for compile-time strings. It is defined in the fmt namespace to +// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42). +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template ::value)> +constexpr basic_string_view to_string_view(const S& s) { + return s; +} + +namespace internal { +void to_string_view(...); +using fmt::v6::to_string_view; + +// Specifies whether S is a string type convertible to fmt::basic_string_view. +// It should be a constexpr function but MSVC 2017 fails to compile it in +// enable_if and MSVC 2015 fails to compile it as an alias template. +template +struct is_string : std::is_class()))> { +}; + +template struct char_t_impl {}; +template struct char_t_impl::value>> { + using result = decltype(to_string_view(std::declval())); + using type = typename result::char_type; +}; + +struct error_handler { + FMT_CONSTEXPR error_handler() {} + FMT_CONSTEXPR error_handler(const error_handler&) {} + + // This function is intentionally not constexpr to give a compile-time error. + FMT_NORETURN FMT_API void on_error(const char* message); +}; +} // namespace internal + +/** String's character type. */ +template using char_t = typename internal::char_t_impl::type; + +// Parsing context consisting of a format string range being parsed and an +// argument counter for automatic indexing. +template +class basic_parse_context : private ErrorHandler { + private: + basic_string_view format_str_; + int next_arg_id_; + + public: + using char_type = Char; + using iterator = typename basic_string_view::iterator; + + explicit FMT_CONSTEXPR basic_parse_context(basic_string_view format_str, + ErrorHandler eh = ErrorHandler()) + : ErrorHandler(eh), format_str_(format_str), next_arg_id_(0) {} + + // Returns an iterator to the beginning of the format string range being + // parsed. + FMT_CONSTEXPR iterator begin() const FMT_NOEXCEPT { + return format_str_.begin(); + } + + // Returns an iterator past the end of the format string range being parsed. + FMT_CONSTEXPR iterator end() const FMT_NOEXCEPT { return format_str_.end(); } + + // Advances the begin iterator to ``it``. + FMT_CONSTEXPR void advance_to(iterator it) { + format_str_.remove_prefix(internal::to_unsigned(it - begin())); + } + + // Returns the next argument index. + FMT_CONSTEXPR int next_arg_id() { + if (next_arg_id_ >= 0) return next_arg_id_++; + on_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + + FMT_CONSTEXPR bool check_arg_id(int) { + if (next_arg_id_ > 0) { + on_error("cannot switch from automatic to manual argument indexing"); + return false; + } + next_arg_id_ = -1; + return true; + } + + FMT_CONSTEXPR void check_arg_id(basic_string_view) {} + + FMT_CONSTEXPR void on_error(const char* message) { + ErrorHandler::on_error(message); + } + + FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; } +}; + +using format_parse_context = basic_parse_context; +using wformat_parse_context = basic_parse_context; + +using parse_context FMT_DEPRECATED_ALIAS = basic_parse_context; +using wparse_context FMT_DEPRECATED_ALIAS = basic_parse_context; + +template class basic_format_arg; +template class basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +template +struct FMT_DEPRECATED convert_to_int + : bool_constant::value && + std::is_convertible::value> {}; + +namespace internal { + +// Specifies if T has an enabled formatter specialization. A type can be +// formattable even if it doesn't have a formatter e.g. via a conversion. +template +using has_formatter = + std::is_constructible>; + +/** A contiguous memory buffer with an optional growing ability. */ +template class buffer { + private: + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + T* ptr_; + std::size_t size_; + std::size_t capacity_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + buffer(std::size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {} + + buffer(T* p = nullptr, std::size_t sz = 0, std::size_t cap = 0) FMT_NOEXCEPT + : ptr_(p), + size_(sz), + capacity_(cap) {} + + /** Sets the buffer data and capacity. */ + void set(T* buf_data, std::size_t buf_capacity) FMT_NOEXCEPT { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + /** Increases the buffer capacity to hold at least *capacity* elements. */ + virtual void grow(std::size_t capacity) = 0; + + public: + using value_type = T; + using const_reference = const T&; + + virtual ~buffer() {} + + T* begin() FMT_NOEXCEPT { return ptr_; } + T* end() FMT_NOEXCEPT { return ptr_ + size_; } + + /** Returns the size of this buffer. */ + std::size_t size() const FMT_NOEXCEPT { return size_; } + + /** Returns the capacity of this buffer. */ + std::size_t capacity() const FMT_NOEXCEPT { return capacity_; } + + /** Returns a pointer to the buffer data. */ + T* data() FMT_NOEXCEPT { return ptr_; } + + /** Returns a pointer to the buffer data. */ + const T* data() const FMT_NOEXCEPT { return ptr_; } + + /** + Resizes the buffer. If T is a POD type new elements may not be initialized. + */ + void resize(std::size_t new_size) { + reserve(new_size); + size_ = new_size; + } + + /** Clears this buffer. */ + void clear() { size_ = 0; } + + /** Reserves space to store at least *capacity* elements. */ + void reserve(std::size_t new_capacity) { + if (new_capacity > capacity_) grow(new_capacity); + } + + void push_back(const T& value) { + reserve(size_ + 1); + ptr_[size_++] = value; + } + + /** Appends data to the end of the buffer. */ + template void append(const U* begin, const U* end); + + T& operator[](std::size_t index) { return ptr_[index]; } + const T& operator[](std::size_t index) const { return ptr_[index]; } +}; + +// A container-backed buffer. +template +class container_buffer : public buffer { + private: + Container& container_; + + protected: + void grow(std::size_t capacity) FMT_OVERRIDE { + container_.resize(capacity); + this->set(&container_[0], capacity); + } + + public: + explicit container_buffer(Container& c) + : buffer(c.size()), container_(c) {} +}; + +// Extracts a reference to the container from back_insert_iterator. +template +inline Container& get_container(std::back_insert_iterator it) { + using bi_iterator = std::back_insert_iterator; + struct accessor : bi_iterator { + accessor(bi_iterator iter) : bi_iterator(iter) {} + using bi_iterator::container; + }; + return *accessor(it).container; +} + +template +struct fallback_formatter { + fallback_formatter() = delete; +}; + +// Specifies if T has an enabled fallback_formatter specialization. +template +using has_fallback_formatter = + std::is_constructible>; + +template struct named_arg_base; +template struct named_arg; + +enum type { + none_type, + named_arg_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant : std::integral_constant {} + +FMT_TYPE_CONSTANT(const named_arg_base&, named_arg_type); +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_t, int128_type); +FMT_TYPE_CONSTANT(uint128_t, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +FMT_CONSTEXPR bool is_integral_type(type t) { + FMT_ASSERT(t != named_arg_type, "invalid argument type"); + return t > none_type && t <= last_integer_type; +} + +FMT_CONSTEXPR bool is_arithmetic_type(type t) { + FMT_ASSERT(t != named_arg_type, "invalid argument type"); + return t > none_type && t <= last_numeric_type; +} + +template struct string_value { + const Char* data; + std::size_t size; +}; + +template struct custom_value { + using parse_context = basic_parse_context; + const void* value; + void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx); +}; + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_t int128_value; + uint128_t uint128_value; + bool bool_value; + char_type char_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value string; + custom_value custom; + const named_arg_base* named_arg; + }; + + FMT_CONSTEXPR value(int val = 0) : int_value(val) {} + FMT_CONSTEXPR value(unsigned val) : uint_value(val) {} + value(long long val) : long_long_value(val) {} + value(unsigned long long val) : ulong_long_value(val) {} + value(int128_t val) : int128_value(val) {} + value(uint128_t val) : uint128_value(val) {} + value(double val) : double_value(val) {} + value(long double val) : long_double_value(val) {} + value(bool val) : bool_value(val) {} + value(char_type val) : char_value(val) {} + value(const char_type* val) { string.data = val; } + value(basic_string_view val) { + string.data = val.data(); + string.size = val.size(); + } + value(const void* val) : pointer(val) {} + + template value(const T& val) { + custom.value = &val; + // Get the formatter type through the context to allow different contexts + // have different extension points, e.g. `formatter` for `format` and + // `printf_formatter` for `printf`. + custom.format = format_custom_arg< + T, conditional_t::value, + typename Context::template formatter_type, + fallback_formatter>>; + } + + value(const named_arg_base& val) { named_arg = &val; } + + private: + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom_arg(const void* arg, + basic_parse_context& parse_ctx, + Context& ctx) { + Formatter f; + parse_ctx.advance_to(f.parse(parse_ctx)); + ctx.advance_to(f.format(*static_cast(arg), ctx)); + } +}; + +template +FMT_CONSTEXPR basic_format_arg make_arg(const T& value); + +// To minimize the number of types we need to deal with, long is translated +// either to int or to long long depending on its size. +enum { long_short = sizeof(long) == sizeof(int) }; +using long_type = conditional_t; +using ulong_type = conditional_t; + +// Maps formatting arguments to core types. +template struct arg_mapper { + using char_type = typename Context::char_type; + + FMT_CONSTEXPR int map(signed char val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned char val) { return val; } + FMT_CONSTEXPR int map(short val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned short val) { return val; } + FMT_CONSTEXPR int map(int val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned val) { return val; } + FMT_CONSTEXPR long_type map(long val) { return val; } + FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; } + FMT_CONSTEXPR long long map(long long val) { return val; } + FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; } + FMT_CONSTEXPR int128_t map(int128_t val) { return val; } + FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; } + FMT_CONSTEXPR bool map(bool val) { return val; } + + template ::value)> + FMT_CONSTEXPR char_type map(T val) { + static_assert( + std::is_same::value || std::is_same::value, + "mixing character types is disallowed"); + return val; + } + + FMT_CONSTEXPR double map(float val) { return static_cast(val); } + FMT_CONSTEXPR double map(double val) { return val; } + FMT_CONSTEXPR long double map(long double val) { return val; } + + FMT_CONSTEXPR const char_type* map(char_type* val) { return val; } + FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; } + template ::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + static_assert(std::is_same>::value, + "mixing character types is disallowed"); + return to_string_view(val); + } + template , T>::value && + !is_string::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + return basic_string_view(val); + } + template , T>::value && + !std::is_constructible, T>::value && + !is_string::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + return std_string_view(val); + } + FMT_CONSTEXPR const char* map(const signed char* val) { + static_assert(std::is_same::value, "invalid string type"); + return reinterpret_cast(val); + } + FMT_CONSTEXPR const char* map(const unsigned char* val) { + static_assert(std::is_same::value, "invalid string type"); + return reinterpret_cast(val); + } + + FMT_CONSTEXPR const void* map(void* val) { return val; } + FMT_CONSTEXPR const void* map(const void* val) { return val; } + FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; } + template FMT_CONSTEXPR int map(const T*) { + // Formatting of arbitrary pointers is disallowed. If you want to output + // a pointer cast it to "void *" or "const void *". In particular, this + // forbids formatting of "[const] volatile char *" which is printed as bool + // by iostreams. + static_assert(!sizeof(T), "formatting of non-void pointers is disallowed"); + return 0; + } + + template ::value && + !has_formatter::value && + !has_fallback_formatter::value)> + FMT_CONSTEXPR auto map(const T& val) -> decltype( + map(static_cast::type>(val))) { + return map(static_cast::type>(val)); + } + template ::value && !is_char::value && + (has_formatter::value || + has_fallback_formatter::value))> + FMT_CONSTEXPR const T& map(const T& val) { + return val; + } + + template + FMT_CONSTEXPR const named_arg_base& map( + const named_arg& val) { + auto arg = make_arg(val.value); + std::memcpy(val.data, &arg, sizeof(arg)); + return val; + } +}; + +// A type constant after applying arg_mapper. +template +using mapped_type_constant = + type_constant().map(std::declval())), + typename Context::char_type>; + +// Maximum number of arguments with packed types. +enum { max_packed_args = 15 }; +enum : unsigned long long { is_unpacked_bit = 1ull << 63 }; + +template class arg_map; +} // namespace internal + +// A formatting argument. It is a trivially copyable/constructible type to +// allow storage in basic_memory_buffer. +template class basic_format_arg { + private: + internal::value value_; + internal::type type_; + + template + friend FMT_CONSTEXPR basic_format_arg internal::make_arg( + const T& value); + + template + friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, + const basic_format_arg& arg) + -> decltype(vis(0)); + + friend class basic_format_args; + friend class internal::arg_map; + + using char_type = typename Context::char_type; + + public: + class handle { + public: + explicit handle(internal::custom_value custom) : custom_(custom) {} + + void format(basic_parse_context& parse_ctx, Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + + private: + internal::custom_value custom_; + }; + + FMT_CONSTEXPR basic_format_arg() : type_(internal::none_type) {} + + FMT_CONSTEXPR explicit operator bool() const FMT_NOEXCEPT { + return type_ != internal::none_type; + } + + internal::type type() const { return type_; } + + bool is_integral() const { return internal::is_integral_type(type_); } + bool is_arithmetic() const { return internal::is_arithmetic_type(type_); } +}; + +/** + \rst + Visits an argument dispatching to the appropriate visit method based on + the argument type. For example, if the argument type is ``double`` then + ``vis(value)`` will be called with the value of type ``double``. + \endrst + */ +template +FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, + const basic_format_arg& arg) + -> decltype(vis(0)) { + using char_type = typename Context::char_type; + switch (arg.type_) { + case internal::none_type: + break; + case internal::named_arg_type: + FMT_ASSERT(false, "invalid argument type"); + break; + case internal::int_type: + return vis(arg.value_.int_value); + case internal::uint_type: + return vis(arg.value_.uint_value); + case internal::long_long_type: + return vis(arg.value_.long_long_value); + case internal::ulong_long_type: + return vis(arg.value_.ulong_long_value); +#if FMT_USE_INT128 + case internal::int128_type: + return vis(arg.value_.int128_value); + case internal::uint128_type: + return vis(arg.value_.uint128_value); +#else + case internal::int128_type: + case internal::uint128_type: + break; +#endif + case internal::bool_type: + return vis(arg.value_.bool_value); + case internal::char_type: + return vis(arg.value_.char_value); + case internal::double_type: + return vis(arg.value_.double_value); + case internal::long_double_type: + return vis(arg.value_.long_double_value); + case internal::cstring_type: + return vis(arg.value_.string.data); + case internal::string_type: + return vis(basic_string_view(arg.value_.string.data, + arg.value_.string.size)); + case internal::pointer_type: + return vis(arg.value_.pointer); + case internal::custom_type: + return vis(typename basic_format_arg::handle(arg.value_.custom)); + } + return vis(monostate()); +} + +namespace internal { +// A map from argument names to their values for named arguments. +template class arg_map { + private: + arg_map(const arg_map&) = delete; + void operator=(const arg_map&) = delete; + + using char_type = typename Context::char_type; + + struct entry { + basic_string_view name; + basic_format_arg arg; + }; + + entry* map_; + unsigned size_; + + void push_back(value val) { + const auto& named = *val.named_arg; + map_[size_] = {named.name, named.template deserialize()}; + ++size_; + } + + public: + arg_map() : map_(nullptr), size_(0) {} + void init(const basic_format_args& args); + ~arg_map() { delete[] map_; } + + basic_format_arg find(basic_string_view name) const { + // The list is unsorted, so just return the first matching name. + for (entry *it = map_, *end = map_ + size_; it != end; ++it) { + if (it->name == name) return it->arg; + } + return {}; + } +}; + +// A type-erased reference to an std::locale to avoid heavy include. +class locale_ref { + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + locale_ref() : locale_(nullptr) {} + template explicit locale_ref(const Locale& loc); + + template Locale get() const; +}; + +template constexpr unsigned long long encode_types() { return 0; } + +template +constexpr unsigned long long encode_types() { + return mapped_type_constant::value | + (encode_types() << 4); +} + +template +FMT_CONSTEXPR basic_format_arg make_arg(const T& value) { + basic_format_arg arg; + arg.type_ = mapped_type_constant::value; + arg.value_ = arg_mapper().map(value); + return arg; +} + +template +inline value make_arg(const T& val) { + return arg_mapper().map(val); +} + +template +inline basic_format_arg make_arg(const T& value) { + return make_arg(value); +} +} // namespace internal + +// Formatting context. +template class basic_format_context { + public: + /** The character type for the output. */ + using char_type = Char; + + private: + OutputIt out_; + basic_format_args args_; + internal::arg_map map_; + internal::locale_ref loc_; + + basic_format_context(const basic_format_context&) = delete; + void operator=(const basic_format_context&) = delete; + + public: + using iterator = OutputIt; + using format_arg = basic_format_arg; + template using formatter_type = formatter; + + /** + Constructs a ``basic_format_context`` object. References to the arguments are + stored in the object so make sure they have appropriate lifetimes. + */ + basic_format_context(OutputIt out, + basic_format_args ctx_args, + internal::locale_ref loc = internal::locale_ref()) + : out_(out), args_(ctx_args), loc_(loc) {} + + format_arg arg(int id) const { return args_.get(id); } + + // Checks if manual indexing is used and returns the argument with the + // specified name. + format_arg arg(basic_string_view name); + + internal::error_handler error_handler() { return {}; } + void on_error(const char* message) { error_handler().on_error(message); } + + // Returns an iterator to the beginning of the output range. + iterator out() { return out_; } + + // Advances the begin iterator to ``it``. + void advance_to(iterator it) { out_ = it; } + + internal::locale_ref locale() { return loc_; } +}; + +template +using buffer_context = + basic_format_context>, + Char>; +using format_context = buffer_context; +using wformat_context = buffer_context; + +/** + \rst + An array of references to arguments. It can be implicitly converted into + `~fmt::basic_format_args` for passing into type-erased formatting functions + such as `~fmt::vformat`. + \endrst + */ +template class format_arg_store { + private: + static const size_t num_args = sizeof...(Args); + static const bool is_packed = num_args < internal::max_packed_args; + + using value_type = conditional_t, + basic_format_arg>; + + // If the arguments are not packed, add one more element to mark the end. + value_type data_[num_args + (num_args == 0 ? 1 : 0)]; + + friend class basic_format_args; + + public: + static constexpr unsigned long long types = + is_packed ? internal::encode_types() + : internal::is_unpacked_bit | num_args; + FMT_DEPRECATED static constexpr unsigned long long TYPES = types; + + format_arg_store(const Args&... args) + : data_{internal::make_arg(args)...} {} +}; + +/** + \rst + Constructs an `~fmt::format_arg_store` object that contains references to + arguments and can be implicitly converted to `~fmt::format_args`. `Context` + can be omitted in which case it defaults to `~fmt::context`. + See `~fmt::arg` for lifetime considerations. + \endrst + */ +template +inline format_arg_store make_format_args( + const Args&... args) { + return {args...}; +} + +/** Formatting arguments. */ +template class basic_format_args { + public: + using size_type = int; + using format_arg = basic_format_arg; + + private: + // To reduce compiled code size per formatting function call, types of first + // max_packed_args arguments are passed in the types_ field. + unsigned long long types_; + union { + // If the number of arguments is less than max_packed_args, the argument + // values are stored in values_, otherwise they are stored in args_. + // This is done to reduce compiled code size as storing larger objects + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. + const internal::value* values_; + const format_arg* args_; + }; + + bool is_packed() const { return (types_ & internal::is_unpacked_bit) == 0; } + + internal::type type(int index) const { + int shift = index * 4; + return static_cast((types_ & (0xfull << shift)) >> shift); + } + + friend class internal::arg_map; + + void set_data(const internal::value* values) { values_ = values; } + void set_data(const format_arg* args) { args_ = args; } + + format_arg do_get(int index) const { + format_arg arg; + if (!is_packed()) { + auto num_args = max_size(); + if (index < num_args) arg = args_[index]; + return arg; + } + if (index > internal::max_packed_args) return arg; + arg.type_ = type(index); + if (arg.type_ == internal::none_type) return arg; + internal::value& val = arg.value_; + val = values_[index]; + return arg; + } + + public: + basic_format_args() : types_(0) {} + + /** + \rst + Constructs a `basic_format_args` object from `~fmt::format_arg_store`. + \endrst + */ + template + basic_format_args(const format_arg_store& store) + : types_(static_cast(store.types)) { + set_data(store.data_); + } + + /** + \rst + Constructs a `basic_format_args` object from a dynamic set of arguments. + \endrst + */ + basic_format_args(const format_arg* args, int count) + : types_(internal::is_unpacked_bit | internal::to_unsigned(count)) { + set_data(args); + } + + /** Returns the argument at specified index. */ + format_arg get(int index) const { + format_arg arg = do_get(index); + if (arg.type_ == internal::named_arg_type) + arg = arg.value_.named_arg->template deserialize(); + return arg; + } + + int max_size() const { + unsigned long long max_packed = internal::max_packed_args; + return static_cast(is_packed() ? max_packed + : types_ & ~internal::is_unpacked_bit); + } +}; + +/** An alias to ``basic_format_args``. */ +// It is a separate type rather than an alias to make symbols readable. +struct format_args : basic_format_args { + template + format_args(Args&&... args) + : basic_format_args(std::forward(args)...) {} +}; +struct wformat_args : basic_format_args { + template + wformat_args(Args&&... args) + : basic_format_args(std::forward(args)...) {} +}; + +template struct is_contiguous : std::false_type {}; + +template +struct is_contiguous> : std::true_type {}; + +template +struct is_contiguous> : std::true_type {}; + +namespace internal { + +template +struct is_contiguous_back_insert_iterator : std::false_type {}; +template +struct is_contiguous_back_insert_iterator> + : is_contiguous {}; + +template struct named_arg_base { + basic_string_view name; + + // Serialized value. + mutable char data[sizeof(basic_format_arg>)]; + + named_arg_base(basic_string_view nm) : name(nm) {} + + template basic_format_arg deserialize() const { + basic_format_arg arg; + std::memcpy(&arg, data, sizeof(basic_format_arg)); + return arg; + } +}; + +template struct named_arg : named_arg_base { + const T& value; + + named_arg(basic_string_view name, const T& val) + : named_arg_base(name), value(val) {} +}; + +template ::value)> +inline void check_format_string(const S&) { +#if defined(FMT_ENFORCE_COMPILE_STRING) + static_assert(is_compile_string::value, + "FMT_ENFORCE_COMPILE_STRING requires all format strings to " + "utilize FMT_STRING() or fmt()."); +#endif +} +template ::value)> +void check_format_string(S); + +struct view {}; +template struct bool_pack; +template +using all_true = + std::is_same, bool_pack>; + +template > +inline format_arg_store, remove_reference_t...> +make_args_checked(const S& format_str, + const remove_reference_t&... args) { + static_assert(all_true<(!std::is_base_of>() || + !std::is_reference())...>::value, + "passing views as lvalues is disallowed"); + check_format_string>...>(format_str); + return {args...}; +} + +template +std::basic_string vformat(basic_string_view format_str, + basic_format_args> args); + +template +typename buffer_context::iterator vformat_to( + buffer& buf, basic_string_view format_str, + basic_format_args> args); +} // namespace internal + +/** + \rst + Returns a named argument to be used in a formatting function. + + The named argument holds a reference and does not extend the lifetime + of its arguments. + Consequently, a dangling reference can accidentally be created. + The user should take care to only pass this function temporaries when + the named argument is itself a temporary, as per the following example. + + **Example**:: + + fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23)); + \endrst + */ +template > +inline internal::named_arg arg(const S& name, const T& arg) { + static_assert(internal::is_string::value, ""); + return {name, arg}; +} + +// Disable nested named arguments, e.g. ``arg("a", arg("b", 42))``. +template +void arg(S, internal::named_arg) = delete; + +/** Formats a string and writes the output to ``out``. */ +// GCC 8 and earlier cannot handle std::back_insert_iterator with +// vformat_to(...) overload, so SFINAE on iterator type instead. +template , + FMT_ENABLE_IF( + internal::is_contiguous_back_insert_iterator::value)> +OutputIt vformat_to(OutputIt out, const S& format_str, + basic_format_args> args) { + using container = remove_reference_t; + internal::container_buffer buf((internal::get_container(out))); + internal::vformat_to(buf, to_string_view(format_str), args); + return out; +} + +template ::value&& internal::is_string::value)> +inline std::back_insert_iterator format_to( + std::back_insert_iterator out, const S& format_str, + Args&&... args) { + return vformat_to( + out, to_string_view(format_str), + {internal::make_args_checked(format_str, args...)}); +} + +template > +inline std::basic_string vformat( + const S& format_str, basic_format_args> args) { + return internal::vformat(to_string_view(format_str), args); +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + #include + std::string message = fmt::format("The answer is {}", 42); + \endrst +*/ +// Pass char_t as a default template parameter instead of using +// std::basic_string> to reduce the symbol size. +template > +inline std::basic_string format(const S& format_str, Args&&... args) { + return internal::vformat( + to_string_view(format_str), + {internal::make_args_checked(format_str, args...)}); +} + +FMT_API void vprint(std::FILE* f, string_view format_str, format_args args); +FMT_API void vprint(std::FILE* f, wstring_view format_str, wformat_args args); + +/** + \rst + Prints formatted data to the file *f*. For wide format strings, + *f* should be in wide-oriented mode set via ``fwide(f, 1)`` or + ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. + + **Example**:: + + fmt::print(stderr, "Don't {}!", "panic"); + \endrst + */ +template ::value)> +inline void print(std::FILE* f, const S& format_str, Args&&... args) { + vprint(f, to_string_view(format_str), + internal::make_args_checked(format_str, args...)); +} + +FMT_API void vprint(string_view format_str, format_args args); +FMT_API void vprint(wstring_view format_str, wformat_args args); + +/** + \rst + Prints formatted data to ``stdout``. + + **Example**:: + + fmt::print("Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +template ::value)> +inline void print(const S& format_str, Args&&... args) { + vprint(to_string_view(format_str), + internal::make_args_checked(format_str, args...)); +} +FMT_END_NAMESPACE + +#endif // FMT_CORE_H_ diff --git a/swCommonLib/External/fmt/format-inl.h b/swCommonLib/External/fmt/format-inl.h new file mode 100644 index 00000000..62de4bff --- /dev/null +++ b/swCommonLib/External/fmt/format-inl.h @@ -0,0 +1,1116 @@ +// Formatting library for C++ +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_FORMAT_INL_H_ +#define FMT_FORMAT_INL_H_ + +#include "format.h" + +#include + +#include +#include +#include +#include +#include +#include // for std::ptrdiff_t +#include // for std::memmove +#include +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +# include +#endif + +#if FMT_USE_WINDOWS_H +# if !defined(FMT_HEADER_ONLY) && !defined(WIN32_LEAN_AND_MEAN) +# define WIN32_LEAN_AND_MEAN +# endif +# if defined(NOMINMAX) || defined(FMT_WIN_MINMAX) +# include +# else +# define NOMINMAX +# include +# undef NOMINMAX +# endif +#endif + +#if FMT_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable : 4127) // conditional expression is constant +# pragma warning(disable : 4702) // unreachable code +#endif + +// Dummy implementations of strerror_r and strerror_s called if corresponding +// system functions are not available. +inline fmt::internal::null<> strerror_r(int, char*, ...) { + return fmt::internal::null<>(); +} +inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) { + return fmt::internal::null<>(); +} + +FMT_BEGIN_NAMESPACE +namespace internal { + +#ifndef _MSC_VER +# define FMT_SNPRINTF snprintf +#else // _MSC_VER +inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { + va_list args; + va_start(args, format); + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); + va_end(args); + return result; +} +# define FMT_SNPRINTF fmt_snprintf +#endif // _MSC_VER + +using format_func = void (*)(internal::buffer&, int, string_view); + +// A portable thread-safe version of strerror. +// Sets buffer to point to a string describing the error code. +// This can be either a pointer to a string stored in buffer, +// or a pointer to some static immutable string. +// Returns one of the following values: +// 0 - success +// ERANGE - buffer is not large enough to store the error message +// other - failure +// Buffer should be at least of size 1. +FMT_FUNC int safe_strerror(int error_code, char*& buffer, + std::size_t buffer_size) FMT_NOEXCEPT { + FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); + + class dispatcher { + private: + int error_code_; + char*& buffer_; + std::size_t buffer_size_; + + // A noop assignment operator to avoid bogus warnings. + void operator=(const dispatcher&) {} + + // Handle the result of XSI-compliant version of strerror_r. + int handle(int result) { + // glibc versions before 2.13 return result in errno. + return result == -1 ? errno : result; + } + + // Handle the result of GNU-specific version of strerror_r. + int handle(char* message) { + // If the buffer is full then the message is probably truncated. + if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) + return ERANGE; + buffer_ = message; + return 0; + } + + // Handle the case when strerror_r is not available. + int handle(internal::null<>) { + return fallback(strerror_s(buffer_, buffer_size_, error_code_)); + } + + // Fallback to strerror_s when strerror_r is not available. + int fallback(int result) { + // If the buffer is full then the message is probably truncated. + return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE + : result; + } + +#if !FMT_MSC_VER + // Fallback to strerror if strerror_r and strerror_s are not available. + int fallback(internal::null<>) { + errno = 0; + buffer_ = strerror(error_code_); + return errno; + } +#endif + + public: + dispatcher(int err_code, char*& buf, std::size_t buf_size) + : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} + + int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } + }; + return dispatcher(error_code, buffer, buffer_size).run(); +} + +FMT_FUNC void format_error_code(internal::buffer& out, int error_code, + string_view message) FMT_NOEXCEPT { + // Report error code making sure that the output fits into + // inline_buffer_size to avoid dynamic memory allocation and potential + // bad_alloc. + out.resize(0); + static const char SEP[] = ": "; + static const char ERROR_STR[] = "error "; + // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. + std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; + auto abs_value = static_cast>(error_code); + if (internal::is_negative(error_code)) { + abs_value = 0 - abs_value; + ++error_code_size; + } + error_code_size += internal::to_unsigned(internal::count_digits(abs_value)); + internal::writer w(out); + if (message.size() <= inline_buffer_size - error_code_size) { + w.write(message); + w.write(SEP); + } + w.write(ERROR_STR); + w.write(error_code); + assert(out.size() <= inline_buffer_size); +} + +// A wrapper around fwrite that throws on error. +FMT_FUNC void fwrite_fully(const void* ptr, size_t size, size_t count, + FILE* stream) { + size_t written = std::fwrite(ptr, size, count, stream); + if (written < count) { + FMT_THROW(system_error(errno, "cannot write to file")); + } +} + +FMT_FUNC void report_error(format_func func, int error_code, + string_view message) FMT_NOEXCEPT { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_fully because the latter may throw. + (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr); + std::fputc('\n', stderr); +} +} // namespace internal + +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +namespace internal { + +template +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template Locale locale_ref::get() const { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + +template FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet>(loc.get()) + .thousands_sep(); +} +template FMT_FUNC Char decimal_point_impl(locale_ref loc) { + return std::use_facet>(loc.get()) + .decimal_point(); +} +} // namespace internal +#else +template +FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { + return FMT_STATIC_THOUSANDS_SEPARATOR; +} +template +FMT_FUNC Char internal::decimal_point_impl(locale_ref) { + return '.'; +} +#endif + +FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT {} +FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT {} + +FMT_FUNC void system_error::init(int err_code, string_view format_str, + format_args args) { + error_code_ = err_code; + memory_buffer buffer; + format_system_error(buffer, err_code, vformat(format_str, args)); + std::runtime_error& base = *this; + base = std::runtime_error(to_string(buffer)); +} + +namespace internal { + +template <> FMT_FUNC int count_digits<4>(internal::fallback_uintptr n) { + // Assume little endian; pointer formatting is implementation-defined anyway. + int i = static_cast(sizeof(void*)) - 1; + while (i > 0 && n.value[i] == 0) --i; + auto char_digits = std::numeric_limits::digits / 4; + return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; +} + +template +int format_float(char* buf, std::size_t size, const char* format, int precision, + T value) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about nonliteral format string. + auto snprintf_ptr = FMT_SNPRINTF; + return precision < 0 ? snprintf_ptr(buf, size, format, value) + : snprintf_ptr(buf, size, format, precision, value); +} + +template +const char basic_data::digits[] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + +template +const char basic_data::hex_digits[] = "0123456789abcdef"; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, \ + factor * 1000000, factor * 10000000, factor * 100000000, \ + factor * 1000000000 + +template +const uint64_t basic_data::powers_of_10_64[] = { + 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull), + 10000000000000000000ull}; + +template +const uint32_t basic_data::zero_or_powers_of_10_32[] = {0, + FMT_POWERS_OF_10(1)}; + +template +const uint64_t basic_data::zero_or_powers_of_10_64[] = { + 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull), + 10000000000000000000ull}; + +// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. +// These are generated by support/compute-powers.py. +template +const uint64_t basic_data::pow10_significands[] = { + 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, + 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, + 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, + 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, + 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, + 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, + 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, + 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, + 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, + 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, + 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, + 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, + 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, + 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, + 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, + 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, + 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, + 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, + 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, + 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, + 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, + 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, + 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, + 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, + 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, + 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, + 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, + 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, + 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, +}; + +// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding +// to significands above. +template +const int16_t basic_data::pow10_exponents[] = { + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, + -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, + -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, + -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, + -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, + 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, + 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, + 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; + +template +const char basic_data::foreground_color[] = "\x1b[38;2;"; +template +const char basic_data::background_color[] = "\x1b[48;2;"; +template const char basic_data::reset_color[] = "\x1b[0m"; +template const wchar_t basic_data::wreset_color[] = L"\x1b[0m"; + +template struct bits { + static FMT_CONSTEXPR_DECL const int value = + static_cast(sizeof(T) * std::numeric_limits::digits); +}; + +class fp; +template fp normalize(fp value); + +// A handmade floating-point number f * pow(2, e). +class fp { + private: + using significand_type = uint64_t; + + // All sizes are in bits. + // Subtract 1 to account for an implicit most significant bit in the + // normalized form. + static FMT_CONSTEXPR_DECL const int double_significand_size = + std::numeric_limits::digits - 1; + static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = + 1ull << double_significand_size; + + public: + significand_type f; + int e; + + static FMT_CONSTEXPR_DECL const int significand_size = + bits::value; + + fp() : f(0), e(0) {} + fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 double. It is a template to prevent compile + // errors on platforms where double is not IEEE754. + template explicit fp(Double d) { + // Assume double is in the format [sign][exponent][significand]. + using limits = std::numeric_limits; + const int exponent_size = + bits::value - double_significand_size - 1; // -1 for sign + const uint64_t significand_mask = implicit_bit - 1; + const uint64_t exponent_mask = (~0ull >> 1) & ~significand_mask; + const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; + auto u = bit_cast(d); + auto biased_e = (u & exponent_mask) >> double_significand_size; + f = u & significand_mask; + if (biased_e != 0) + f += implicit_bit; + else + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + e = static_cast(biased_e - exponent_bias - double_significand_size); + } + + // Normalizes the value converted from double and multiplied by (1 << SHIFT). + template friend fp normalize(fp value) { + // Handle subnormals. + const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = + fp::significand_size - fp::double_significand_size - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; + } + + // Computes lower and upper boundaries (m^- and m^+ in the Grisu paper), where + // a boundary is a value half way between the number and its predecessor + // (lower) or successor (upper). The upper boundary is normalized and lower + // has the same exponent but may be not normalized. + void compute_boundaries(fp& lower, fp& upper) const { + lower = + f == implicit_bit ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1); + // 1 in normalize accounts for the exponent shift above. + upper = normalize<1>(fp((f << 1) + 1, e - 1)); + lower.f <<= lower.e - upper.e; + lower.e = upper.e; + } +}; + +// Returns an fp number representing x - y. Result may not be normalized. +inline fp operator-(fp x, fp y) { + FMT_ASSERT(x.f >= y.f && x.e == y.e, "invalid operands"); + return fp(x.f - y.f, x.e); +} + +// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest +// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be +// normalized. +FMT_FUNC fp operator*(fp x, fp y) { + int exp = x.e + y.e + 64; +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(x.f) * y.f; + auto f = static_cast(product >> 64); + if ((static_cast(product) & (1ULL << 63)) != 0) ++f; + return fp(f, exp); +#else + // Multiply 32-bit parts of significands. + uint64_t mask = (1ULL << 32) - 1; + uint64_t a = x.f >> 32, b = x.f & mask; + uint64_t c = y.f >> 32, d = y.f & mask; + uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; + // Compute mid 64-bit of result and round. + uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); + return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), exp); +#endif +} + +// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its +// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. +FMT_FUNC fp get_cached_power(int min_exponent, int& pow10_exponent) { + const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10) + int index = static_cast( + std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10)); + // Decimal exponent of the first (smallest) cached power of 10. + const int first_dec_exp = -348; + // Difference between 2 consecutive decimal exponents in cached powers of 10. + const int dec_exp_step = 8; + index = (index - first_dec_exp - 1) / dec_exp_step + 1; + pow10_exponent = first_dec_exp + index * dec_exp_step; + return fp(data::pow10_significands[index], data::pow10_exponents[index]); +} + +class bigint { + private: + // A bigint is stored as an array of bigits (big digits), with bigit at index + // 0 being the least significant one. + using bigit = uint32_t; + using double_bigit = uint64_t; + basic_memory_buffer bigits_; + + static FMT_CONSTEXPR_DECL const int bigit_bits = bits::value; + + friend struct formatter; + + void assign(uint64_t n) { + int num_bigits = bits::value / bigit_bits; + bigits_.resize(num_bigits); + for (int i = 0; i < num_bigits; ++i) { + bigits_[i] = n & ~bigit(0); + n >>= bigit_bits; + } + } + + public: + bigint() {} + explicit bigint(uint64_t n) { assign(n); } + + // Assigns pow(10, exp) to this bigint. + void assign_pow10(int exp) { + assert(exp >= 0); + if (exp == 0) return assign(1); + // Find the top bit. + int bitmask = 1; + while (exp >= bitmask) bitmask <<= 1; + bitmask >>= 1; + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + assign(5); + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + void square() { + // TODO + } + + bigint& operator<<=(int shift) { + assert(shift >= 0 && shift < bigit_bits); + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = shift != 0 ? bigits_[i] >> (bigit_bits - shift) : 0; + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + bigint& operator*=(uint32_t value) { + assert(value > 0); + // Verify that the computation doesn't overflow. + constexpr double_bigit max32 = max_value(); + constexpr double_bigit max64 = max_value(); + static_assert(max32 * max32 <= max64 - max32, ""); + bigit carry = 0; + const double_bigit wide_value = value; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } +}; + +enum round_direction { unknown, up, down }; + +// Given the divisor (normally a power of 10), the remainder = v % divisor for +// some number v and the error, returns whether v should be rounded up, down, or +// whether the rounding direction can't be determined due to error. +// error should be less than divisor / 2. +inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder, + uint64_t error) { + FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow. + FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow. + FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow. + // Round down if (remainder + error) * 2 <= divisor. + if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2) + return down; + // Round up if (remainder - error) * 2 >= divisor. + if (remainder >= error && + remainder - error >= divisor - (remainder - error)) { + return up; + } + return unknown; +} + +namespace digits { +enum result { + more, // Generate more digits. + done, // Done generating digits. + error // Digit generation cancelled due to an error. +}; +} + +// Generates output using the Grisu digit-gen algorithm. +// error: the size of the region (lower, upper) outside of which numbers +// definitely do not round to value (Delta in Grisu3). +template +digits::result grisu_gen_digits(fp value, uint64_t error, int& exp, + Handler& handler) { + fp one(1ull << -value.e, value.e); + // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be + // zero because it contains a product of two 64-bit numbers with MSB set (due + // to normalization) - 1, shifted right by at most 60 bits. + uint32_t integral = static_cast(value.f >> -one.e); + FMT_ASSERT(integral != 0, ""); + FMT_ASSERT(integral == value.f >> -one.e, ""); + // The fractional part of scaled value (p2 in Grisu) c = value % one. + uint64_t fractional = value.f & (one.f - 1); + exp = count_digits(integral); // kappa in Grisu. + // Divide by 10 to prevent overflow. + auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e, + value.f / 10, error * 10, exp); + if (result != digits::more) return result; + // Generate digits for the integral part. This can produce up to 10 digits. + do { + uint32_t digit = 0; + // This optimization by miloyip reduces the number of integer divisions by + // one per iteration. + switch (exp) { + case 10: + digit = integral / 1000000000; + integral %= 1000000000; + break; + case 9: + digit = integral / 100000000; + integral %= 100000000; + break; + case 8: + digit = integral / 10000000; + integral %= 10000000; + break; + case 7: + digit = integral / 1000000; + integral %= 1000000; + break; + case 6: + digit = integral / 100000; + integral %= 100000; + break; + case 5: + digit = integral / 10000; + integral %= 10000; + break; + case 4: + digit = integral / 1000; + integral %= 1000; + break; + case 3: + digit = integral / 100; + integral %= 100; + break; + case 2: + digit = integral / 10; + integral %= 10; + break; + case 1: + digit = integral; + integral = 0; + break; + default: + FMT_ASSERT(false, "invalid number of digits"); + } + --exp; + uint64_t remainder = + (static_cast(integral) << -one.e) + fractional; + result = handler.on_digit(static_cast('0' + digit), + data::powers_of_10_64[exp] << -one.e, remainder, + error, exp, true); + if (result != digits::more) return result; + } while (exp > 0); + // Generate digits for the fractional part. + for (;;) { + fractional *= 10; + error *= 10; + char digit = + static_cast('0' + static_cast(fractional >> -one.e)); + fractional &= one.f - 1; + --exp; + result = handler.on_digit(digit, one.f, fractional, error, exp, false); + if (result != digits::more) return result; + } +} + +// The fixed precision digit handler. +struct fixed_handler { + char* buf; + int size; + int precision; + int exp10; + bool fixed; + + digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error, + int& exp) { + // Non-fixed formats require at least one digit and no precision adjustment. + if (!fixed) return digits::more; + // Adjust fixed precision by exponent because it is relative to decimal + // point. + precision += exp + exp10; + // Check if precision is satisfied just by leading zeros, e.g. + // format("{:.2f}", 0.001) gives "0.00" without generating any digits. + if (precision > 0) return digits::more; + if (precision < 0) return digits::done; + auto dir = get_round_direction(divisor, remainder, error); + if (dir == unknown) return digits::error; + buf[size++] = dir == up ? '1' : '0'; + return digits::done; + } + + digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, + uint64_t error, int, bool integral) { + FMT_ASSERT(remainder < divisor, ""); + buf[size++] = digit; + if (size < precision) return digits::more; + if (!integral) { + // Check if error * 2 < divisor with overflow prevention. + // The check is not needed for the integral part because error = 1 + // and divisor > (1 << 32) there. + if (error >= divisor || error >= divisor - error) return digits::error; + } else { + FMT_ASSERT(error == 1 && divisor > 2, ""); + } + auto dir = get_round_direction(divisor, remainder, error); + if (dir != up) return dir == down ? digits::done : digits::error; + ++buf[size - 1]; + for (int i = size - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; + buf[size++] = '0'; + } + return digits::done; + } +}; + +// The shortest representation digit handler. +template struct grisu_shortest_handler { + char* buf; + int size; + // Distance between scaled value and upper bound (wp_W in Grisu3). + uint64_t diff; + + digits::result on_start(uint64_t, uint64_t, uint64_t, int&) { + return digits::more; + } + + // Decrement the generated number approaching value from above. + void round(uint64_t d, uint64_t divisor, uint64_t& remainder, + uint64_t error) { + while ( + remainder < d && error - remainder >= divisor && + (remainder + divisor < d || d - remainder >= remainder + divisor - d)) { + --buf[size - 1]; + remainder += divisor; + } + } + + // Implements Grisu's round_weed. + digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, + uint64_t error, int exp, bool integral) { + buf[size++] = digit; + if (remainder >= error) return digits::more; + if (GRISU_VERSION != 3) { + uint64_t d = integral ? diff : diff * data::powers_of_10_64[-exp]; + round(d, divisor, remainder, error); + return digits::done; + } + uint64_t unit = integral ? 1 : data::powers_of_10_64[-exp]; + uint64_t up = (diff - 1) * unit; // wp_Wup + round(up, divisor, remainder, error); + uint64_t down = (diff + 1) * unit; // wp_Wdown + if (remainder < down && error - remainder >= divisor && + (remainder + divisor < down || + down - remainder > remainder + divisor - down)) { + return digits::error; + } + return 2 * unit <= remainder && remainder <= error - 4 * unit + ? digits::done + : digits::error; + } +}; + +FMT_FUNC void fallback_format(const fp& value, int exp10) { + (void)value; // TODO + (void)exp10; +} + +template > +FMT_API bool grisu_format(Double value, buffer& buf, int precision, + unsigned options, int& exp) { + FMT_ASSERT(value >= 0, "value is negative"); + const bool fixed = (options & grisu_options::fixed) != 0; + if (value <= 0) { // <= instead of == to silence a warning. + if (precision <= 0 || !fixed) { + exp = 0; + buf.push_back('0'); + } else { + exp = -precision; + buf.resize(to_unsigned(precision)); + std::uninitialized_fill_n(buf.data(), precision, '0'); + } + return true; + } + + const fp fp_value(value); + const int min_exp = -60; // alpha in Grisu. + int cached_exp10 = 0; // K in Grisu. + if (precision != -1) { + if (precision > 17) return false; + fp normalized = normalize(fp_value); + const auto cached_pow = get_cached_power( + min_exp - (normalized.e + fp::significand_size), cached_exp10); + normalized = normalized * cached_pow; + fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed}; + if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) + return false; + buf.resize(to_unsigned(handler.size)); + } else { + fp lower, upper; // w^- and w^+ in the Grisu paper. + fp_value.compute_boundaries(lower, upper); + // Find a cached power of 10 such that multiplying upper by it will bring + // the exponent in the range [min_exp, -32]. + const auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. + min_exp - (upper.e + fp::significand_size), cached_exp10); + fp normalized = normalize(fp_value); + normalized = normalized * cached_pow; + lower = lower * cached_pow; // \tilde{M}^- in Grisu. + upper = upper * cached_pow; // \tilde{M}^+ in Grisu. + assert(min_exp <= upper.e && upper.e <= -32); + auto result = digits::result(); + int size = 0; + if ((options & grisu_options::grisu3) != 0) { + --lower.f; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}. + ++upper.f; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}. + // Numbers outside of (lower, upper) definitely do not round to value. + grisu_shortest_handler<3> handler{buf.data(), 0, (upper - normalized).f}; + result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler); + size = handler.size; + if (result == digits::error) { + fallback_format(fp_value, exp - cached_exp10); + return false; + } + } else { + ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. + --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. + grisu_shortest_handler<2> handler{buf.data(), 0, (upper - normalized).f}; + result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler); + size = handler.size; + assert(result != digits::error); + } + buf.resize(to_unsigned(size)); + } + exp -= cached_exp10; + return true; +} + +template +char* sprintf_format(Double value, internal::buffer& buf, + sprintf_specs specs) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() != 0, "empty buffer"); + + // Build format string. + enum { max_format_size = 10 }; // longest format: %#-*.*Lg + char format[max_format_size]; + char* format_ptr = format; + *format_ptr++ = '%'; + if (specs.alt || !specs.type) *format_ptr++ = '#'; + if (specs.precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same::value) *format_ptr++ = 'L'; + + char type = specs.type; + + if (type == '%') + type = 'f'; + else if (type == 0 || type == 'n') + type = 'g'; +#if FMT_MSC_VER + if (type == 'F') { + // MSVC's printf doesn't support 'F'. + type = 'f'; + } +#endif + *format_ptr++ = type; + *format_ptr = '\0'; + + // Format using snprintf. + char* start = nullptr; + char* decimal_point_pos = nullptr; + for (;;) { + std::size_t buffer_size = buf.capacity(); + start = &buf[0]; + int result = + format_float(start, buffer_size, format, specs.precision, value); + if (result >= 0) { + unsigned n = internal::to_unsigned(result); + if (n < buf.capacity()) { + // Find the decimal point. + auto p = buf.data(), end = p + n; + if (*p == '+' || *p == '-') ++p; + if (specs.type != 'a' && specs.type != 'A') { + while (p < end && *p >= '0' && *p <= '9') ++p; + if (p < end && *p != 'e' && *p != 'E') { + decimal_point_pos = p; + if (!specs.type) { + // Keep only one trailing zero after the decimal point. + ++p; + if (*p == '0') ++p; + while (p != end && *p >= '1' && *p <= '9') ++p; + char* where = p; + while (p != end && *p == '0') ++p; + if (p == end || *p < '0' || *p > '9') { + if (p != end) std::memmove(where, p, to_unsigned(end - p)); + n -= static_cast(p - where); + } + } + } + } + buf.resize(n); + break; // The buffer is large enough - continue with formatting. + } + buf.reserve(n + 1); + } else { + // If result is negative we ask to increase the capacity by at least 1, + // but as std::vector, the buffer grows exponentially. + buf.reserve(buf.capacity() + 1); + } + } + return decimal_point_pos; +} +} // namespace internal + +template <> struct formatter { + format_parse_context::iterator parse(format_parse_context& ctx) { + return ctx.begin(); + } + + format_context::iterator format(const internal::bigint& n, + format_context& ctx) { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1]; + if (first) { + if (value == 0 && i > 1) continue; + out = format_to(out, "{:x}", value); + first = false; + continue; + } + out = format_to(out, "{:08x}", value); + } + return out; + } +}; + +#if FMT_USE_WINDOWS_H + +FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) { + static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; + if (s.size() > INT_MAX) + FMT_THROW(windows_error(ERROR_INVALID_PARAMETER, ERROR_MSG)); + int s_size = static_cast(s.size()); + if (s_size == 0) { + // MultiByteToWideChar does not support zero length, handle separately. + buffer_.resize(1); + buffer_[0] = 0; + return; + } + + int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), + s_size, nullptr, 0); + if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG)); + buffer_.resize(length + 1); + length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, + &buffer_[0], length); + if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG)); + buffer_[length] = 0; +} + +FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) { + if (int error_code = convert(s)) { + FMT_THROW(windows_error(error_code, + "cannot convert string from UTF-16 to UTF-8")); + } +} + +FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) { + if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER; + int s_size = static_cast(s.size()); + if (s_size == 0) { + // WideCharToMultiByte does not support zero length, handle separately. + buffer_.resize(1); + buffer_[0] = 0; + return 0; + } + + int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0, + nullptr, nullptr); + if (length == 0) return GetLastError(); + buffer_.resize(length + 1); + length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0], + length, nullptr, nullptr); + if (length == 0) return GetLastError(); + buffer_[length] = 0; + return 0; +} + +FMT_FUNC void windows_error::init(int err_code, string_view format_str, + format_args args) { + error_code_ = err_code; + memory_buffer buffer; + internal::format_windows_error(buffer, err_code, vformat(format_str, args)); + std::runtime_error& base = *this; + base = std::runtime_error(to_string(buffer)); +} + +FMT_FUNC void internal::format_windows_error(internal::buffer& out, + int error_code, + string_view message) FMT_NOEXCEPT { + FMT_TRY { + wmemory_buffer buf; + buf.resize(inline_buffer_size); + for (;;) { + wchar_t* system_message = &buf[0]; + int result = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, + error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message, + static_cast(buf.size()), nullptr); + if (result != 0) { + utf16_to_utf8 utf8_message; + if (utf8_message.convert(system_message) == ERROR_SUCCESS) { + internal::writer w(out); + w.write(message); + w.write(": "); + w.write(utf8_message); + return; + } + break; + } + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) + break; // Can't get error message, report error code instead. + buf.resize(buf.size() * 2); + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +#endif // FMT_USE_WINDOWS_H + +FMT_FUNC void format_system_error(internal::buffer& out, int error_code, + string_view message) FMT_NOEXCEPT { + FMT_TRY { + memory_buffer buf; + buf.resize(inline_buffer_size); + for (;;) { + char* system_message = &buf[0]; + int result = + internal::safe_strerror(error_code, system_message, buf.size()); + if (result == 0) { + internal::writer w(out); + w.write(message); + w.write(": "); + w.write(system_message); + return; + } + if (result != ERANGE) + break; // Can't get error message, report error code instead. + buf.resize(buf.size() * 2); + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +FMT_FUNC void internal::error_handler::on_error(const char* message) { + FMT_THROW(format_error(message)); +} + +FMT_FUNC void report_system_error(int error_code, + fmt::string_view message) FMT_NOEXCEPT { + report_error(format_system_error, error_code, message); +} + +#if FMT_USE_WINDOWS_H +FMT_FUNC void report_windows_error(int error_code, + fmt::string_view message) FMT_NOEXCEPT { + report_error(internal::format_windows_error, error_code, message); +} +#endif + +FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { + memory_buffer buffer; + internal::vformat_to(buffer, format_str, + basic_format_args>(args)); + internal::fwrite_fully(buffer.data(), 1, buffer.size(), f); +} + +FMT_FUNC void vprint(std::FILE* f, wstring_view format_str, wformat_args args) { + wmemory_buffer buffer; + internal::vformat_to(buffer, format_str, args); + buffer.push_back(L'\0'); + if (std::fputws(buffer.data(), f) == -1) { + FMT_THROW(system_error(errno, "cannot write to file")); + } +} + +FMT_FUNC void vprint(string_view format_str, format_args args) { + vprint(stdout, format_str, args); +} + +FMT_FUNC void vprint(wstring_view format_str, wformat_args args) { + vprint(stdout, format_str, args); +} + +FMT_END_NAMESPACE + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +#endif // FMT_FORMAT_INL_H_ diff --git a/swCommonLib/External/fmt/format.h b/swCommonLib/External/fmt/format.h new file mode 100644 index 00000000..e198233b --- /dev/null +++ b/swCommonLib/External/fmt/format.h @@ -0,0 +1,3613 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - present, Victor Zverovich + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + --- Optional exception to the license --- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into a machine-executable object form of such + source code, you may redistribute such embedded portions in such object form + without including the above copyright and permission notices. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core.h" + +#ifdef __clang__ +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif + +#ifdef __INTEL_COMPILER +# define FMT_ICC_VERSION __INTEL_COMPILER +#elif defined(__ICL) +# define FMT_ICC_VERSION __ICL +#else +# define FMT_ICC_VERSION 0 +#endif + +#ifdef __NVCC__ +# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__) +#else +# define FMT_CUDA_VERSION 0 +#endif + +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif + +#ifndef FMT_THROW +# if FMT_EXCEPTIONS +# if FMT_MSC_VER +FMT_BEGIN_NAMESPACE +namespace internal { +template inline void do_throw(const Exception& x) { + // Silence unreachable code warnings in MSVC because these are nearly + // impossible to fix in a generic code. + volatile bool b = true; + if (b) throw x; +} +} // namespace internal +FMT_END_NAMESPACE +# define FMT_THROW(x) fmt::internal::do_throw(x) +# else +# define FMT_THROW(x) throw x +# endif +# else +# define FMT_THROW(x) \ + do { \ + static_cast(sizeof(x)); \ + assert(false); \ + } while (false) +# endif +#endif + +#ifndef FMT_USE_USER_DEFINED_LITERALS +// For Intel and NVIDIA compilers both they and the system gcc/msc support UDLs. +# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \ + FMT_MSC_VER >= 1900) && \ + (!(FMT_ICC_VERSION || FMT_CUDA_VERSION) || FMT_ICC_VERSION >= 1500 || \ + FMT_CUDA_VERSION >= 700) +# define FMT_USE_USER_DEFINED_LITERALS 1 +# else +# define FMT_USE_USER_DEFINED_LITERALS 0 +# endif +#endif + +#ifndef FMT_USE_UDL_TEMPLATE +// EDG front end based compilers (icc, nvcc) do not support UDL templates yet +// and GCC 9 warns about them. +# if FMT_USE_USER_DEFINED_LITERALS && FMT_ICC_VERSION == 0 && \ + FMT_CUDA_VERSION == 0 && \ + ((FMT_GCC_VERSION >= 600 && FMT_GCC_VERSION <= 900 && \ + __cplusplus >= 201402L) || \ + FMT_CLANG_VERSION >= 304) +# define FMT_USE_UDL_TEMPLATE 1 +# else +# define FMT_USE_UDL_TEMPLATE 0 +# endif +#endif + +// __builtin_clz is broken in clang with Microsoft CodeGen: +// https://github.com/fmtlib/fmt/issues/519 +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif + +// Some compilers masquerade as both MSVC and GCC-likes or otherwise support +// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the +// MSVC intrinsics if the clz and clzll builtins are not available. +#if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED) +# include // _BitScanReverse, _BitScanReverse64 + +FMT_BEGIN_NAMESPACE +namespace internal { +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# ifndef __clang__ +# pragma intrinsic(_BitScanReverse) +# endif +inline uint32_t clz(uint32_t x) { + unsigned long r = 0; + _BitScanReverse(&r, x); + + assert(x != 0); + // Static analysis complains about using uninitialized data + // "r", but the only way that can happen is if "x" is 0, + // which the callers guarantee to not happen. +# pragma warning(suppress : 6102) + return 31 - r; +} +# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) + +# if defined(_WIN64) && !defined(__clang__) +# pragma intrinsic(_BitScanReverse64) +# endif + +inline uint32_t clzll(uint64_t x) { + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 - (r + 32); + + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + + assert(x != 0); + // Static analysis complains about using uninitialized data + // "r", but the only way that can happen is if "x" is 0, + // which the callers guarantee to not happen. +# pragma warning(suppress : 6102) + return 63 - r; +} +# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) +} // namespace internal +FMT_END_NAMESPACE +#endif + +#ifndef FMT_NUMERIC_ALIGN +# define FMT_NUMERIC_ALIGN 1 +#endif + +FMT_BEGIN_NAMESPACE +namespace internal { + +// A fallback implementation of uintptr_t for systems that lack it. +struct fallback_uintptr { + unsigned char value[sizeof(void*)]; +}; +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +#else +using uintptr_t = fallback_uintptr; +#endif + +// An equivalent of `*reinterpret_cast(&source)` that doesn't produce +// undefined behavior (e.g. due to type aliasing). +// Example: uint64_t d = bit_cast(2.718); +template +inline Dest bit_cast(const Source& source) { + static_assert(sizeof(Dest) == sizeof(Source), "size mismatch"); + Dest dest; + std::memcpy(&dest, &source, sizeof(dest)); + return dest; +} + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr T max_value() { + return (std::numeric_limits::max)(); +} + +// An approximation of iterator_t for pre-C++20 systems. +template +using iterator_t = decltype(std::begin(std::declval())); + +// Detect the iterator category of *any* given type in a SFINAE-friendly way. +// Unfortunately, older implementations of std::iterator_traits are not safe +// for use in a SFINAE-context. +template +struct iterator_category : std::false_type {}; + +template struct iterator_category { + using type = std::random_access_iterator_tag; +}; + +template +struct iterator_category> { + using type = typename It::iterator_category; +}; + +// Detect if *any* given type models the OutputIterator concept. +template class is_output_iterator { + // Check for mutability because all iterator categories derived from + // std::input_iterator_tag *may* also meet the requirements of an + // OutputIterator, thereby falling into the category of 'mutable iterators' + // [iterator.requirements.general] clause 4. The compiler reveals this + // property only at the point of *actually dereferencing* the iterator! + template + static decltype(*(std::declval())) test(std::input_iterator_tag); + template static char& test(std::output_iterator_tag); + template static const char& test(...); + + using type = decltype(test(typename iterator_category::type{})); + + public: + static const bool value = !std::is_const>::value; +}; + +// A workaround for std::string not having mutable data() until C++17. +template inline Char* get_data(std::basic_string& s) { + return &s[0]; +} +template +inline typename Container::value_type* get_data(Container& c) { + return c.data(); +} + +#ifdef _SECURE_SCL +// Make a checked iterator to avoid MSVC warnings. +template using checked_ptr = stdext::checked_array_iterator; +template checked_ptr make_checked(T* p, std::size_t size) { + return {p, size}; +} +#else +template using checked_ptr = T*; +template inline T* make_checked(T* p, std::size_t) { return p; } +#endif + +template ::value)> +inline checked_ptr reserve( + std::back_insert_iterator& it, std::size_t n) { + Container& c = get_container(it); + std::size_t size = c.size(); + c.resize(size + n); + return make_checked(get_data(c) + size, n); +} + +template +inline Iterator& reserve(Iterator& it, std::size_t) { + return it; +} + +// An output iterator that counts the number of objects written to it and +// discards them. +template class counting_iterator { + private: + std::size_t count_; + mutable T blackhole_; + + public: + using iterator_category = std::output_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + using _Unchecked_type = counting_iterator; // Mark iterator as checked. + + counting_iterator() : count_(0) {} + + std::size_t count() const { return count_; } + + counting_iterator& operator++() { + ++count_; + return *this; + } + + counting_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + + T& operator*() const { return blackhole_; } +}; + +template class truncating_iterator_base { + protected: + OutputIt out_; + std::size_t limit_; + std::size_t count_; + + truncating_iterator_base(OutputIt out, std::size_t limit) + : out_(out), limit_(limit), count_(0) {} + + public: + using iterator_category = std::output_iterator_tag; + using difference_type = void; + using pointer = void; + using reference = void; + using _Unchecked_type = + truncating_iterator_base; // Mark iterator as checked. + + OutputIt base() const { return out_; } + std::size_t count() const { return count_; } +}; + +// An output iterator that truncates the output and counts the number of objects +// written to it. +template ::value_type>::type> +class truncating_iterator; + +template +class truncating_iterator + : public truncating_iterator_base { + using traits = std::iterator_traits; + + mutable typename traits::value_type blackhole_; + + public: + using value_type = typename traits::value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator++() { + if (this->count_++ < this->limit_) ++this->out_; + return *this; + } + + truncating_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template +class truncating_iterator + : public truncating_iterator_base { + public: + using value_type = typename OutputIt::container_type::value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator=(value_type val) { + if (this->count_++ < this->limit_) this->out_ = val; + return *this; + } + + truncating_iterator& operator++() { return *this; } + truncating_iterator& operator++(int) { return *this; } + truncating_iterator& operator*() { return *this; } +}; + +// A range with the specified output iterator and value type. +template +class output_range { + private: + OutputIt it_; + + public: + using value_type = T; + using iterator = OutputIt; + struct sentinel {}; + + explicit output_range(OutputIt it) : it_(it) {} + OutputIt begin() const { return it_; } + sentinel end() const { return {}; } // Sentinel is not used yet. +}; + +template +inline size_t count_code_points(basic_string_view s) { + return s.size(); +} + +// Counts the number of code points in a UTF-8 string. +inline size_t count_code_points(basic_string_view s) { + const char8_t* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80) ++num_code_points; + } + return num_code_points; +} + +inline char8_t to_char8_t(char c) { return static_cast(c); } + +template +using needs_conversion = bool_constant< + std::is_same::value_type, + char>::value && + std::is_same::value>; + +template ::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template ::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::transform(begin, end, it, to_char8_t); +} + +#ifndef FMT_USE_GRISU +# define FMT_USE_GRISU 1 +#endif + +template constexpr bool use_grisu() { + return FMT_USE_GRISU && std::numeric_limits::is_iec559 && + sizeof(T) <= sizeof(double); +} + +template +template +void buffer::append(const U* begin, const U* end) { + std::size_t new_size = size_ + to_unsigned(end - begin); + reserve(new_size); + std::uninitialized_copy(begin, end, make_checked(ptr_, capacity_) + size_); + size_ = new_size; +} +} // namespace internal + +// A range with an iterator appending to a buffer. +template +class buffer_range : public internal::output_range< + std::back_insert_iterator>, T> { + public: + using iterator = std::back_insert_iterator>; + using internal::output_range::output_range; + buffer_range(internal::buffer& buf) + : internal::output_range(std::back_inserter(buf)) {} +}; + +// A UTF-8 string view. +class u8string_view : public basic_string_view { + public: + u8string_view(const char* s) + : basic_string_view(reinterpret_cast(s)) {} + u8string_view(const char* s, size_t count) FMT_NOEXCEPT + : basic_string_view(reinterpret_cast(s), count) { + } +}; + +#if FMT_USE_USER_DEFINED_LITERALS +inline namespace literals { +inline u8string_view operator"" _u(const char* s, std::size_t n) { + return {s, n}; +} +} // namespace literals +#endif + +// The number of characters to store in the basic_memory_buffer object itself +// to avoid dynamic memory allocation. +enum { inline_buffer_size = 500 }; + +/** + \rst + A dynamically growing memory buffer for trivially copyable/constructible types + with the first ``SIZE`` elements stored in the object itself. + + You can use one of the following type aliases for common character types: + + +----------------+------------------------------+ + | Type | Definition | + +================+==============================+ + | memory_buffer | basic_memory_buffer | + +----------------+------------------------------+ + | wmemory_buffer | basic_memory_buffer | + +----------------+------------------------------+ + + **Example**:: + + fmt::memory_buffer out; + format_to(out, "The answer is {}.", 42); + + This will append the following output to the ``out`` object: + + .. code-block:: none + + The answer is 42. + + The output can be converted to an ``std::string`` with ``to_string(out)``. + \endrst + */ +template > +class basic_memory_buffer : private Allocator, public internal::buffer { + private: + T store_[SIZE]; + + // Deallocate memory allocated by the buffer. + void deallocate() { + T* data = this->data(); + if (data != store_) Allocator::deallocate(data, this->capacity()); + } + + protected: + void grow(std::size_t size) FMT_OVERRIDE; + + public: + using value_type = T; + using const_reference = const T&; + + explicit basic_memory_buffer(const Allocator& alloc = Allocator()) + : Allocator(alloc) { + this->set(store_, SIZE); + } + ~basic_memory_buffer() { deallocate(); } + + private: + // Move data from other to this buffer. + void move(basic_memory_buffer& other) { + Allocator &this_alloc = *this, &other_alloc = other; + this_alloc = std::move(other_alloc); + T* data = other.data(); + std::size_t size = other.size(), capacity = other.capacity(); + if (data == other.store_) { + this->set(store_, capacity); + std::uninitialized_copy(other.store_, other.store_ + size, + internal::make_checked(store_, capacity)); + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + } + this->resize(size); + } + + public: + /** + \rst + Constructs a :class:`fmt::basic_memory_buffer` object moving the content + of the other object to it. + \endrst + */ + basic_memory_buffer(basic_memory_buffer&& other) { move(other); } + + /** + \rst + Moves the content of the other ``basic_memory_buffer`` object to this one. + \endrst + */ + basic_memory_buffer& operator=(basic_memory_buffer&& other) { + assert(this != &other); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. + Allocator get_allocator() const { return *this; } +}; + +template +void basic_memory_buffer::grow(std::size_t size) { +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if (size > 1000) throw std::runtime_error("fuzz mode - won't grow that much"); +#endif + std::size_t old_capacity = this->capacity(); + std::size_t new_capacity = old_capacity + old_capacity / 2; + if (size > new_capacity) new_capacity = size; + T* old_data = this->data(); + T* new_data = std::allocator_traits::allocate(*this, new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + std::uninitialized_copy(old_data, old_data + this->size(), + internal::make_checked(new_data, new_capacity)); + this->set(new_data, new_capacity); + // deallocate must not throw according to the standard, but even if it does, + // the buffer already uses the new storage and will deallocate it in + // destructor. + if (old_data != store_) Allocator::deallocate(old_data, old_capacity); +} + +using memory_buffer = basic_memory_buffer; +using wmemory_buffer = basic_memory_buffer; + +/** A formatting error such as invalid format string. */ +class FMT_API format_error : public std::runtime_error { + public: + explicit format_error(const char* message) : std::runtime_error(message) {} + explicit format_error(const std::string& message) + : std::runtime_error(message) {} + ~format_error() FMT_NOEXCEPT; +}; + +namespace internal { + +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +template ::is_signed)> +FMT_CONSTEXPR bool is_negative(T value) { + return value < 0; +} +template ::is_signed)> +FMT_CONSTEXPR bool is_negative(T) { + return false; +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of T. +template +using uint32_or_64_or_128_t = conditional_t< + std::numeric_limits::digits <= 32, uint32_t, + conditional_t::digits <= 64, uint64_t, uint128_t>>; + +// Static data is placed in this class template for the header-only config. +template struct FMT_EXTERN_TEMPLATE_API basic_data { + static const uint64_t powers_of_10_64[]; + static const uint32_t zero_or_powers_of_10_32[]; + static const uint64_t zero_or_powers_of_10_64[]; + static const uint64_t pow10_significands[]; + static const int16_t pow10_exponents[]; + static const char digits[]; + static const char hex_digits[]; + static const char foreground_color[]; + static const char background_color[]; + static const char reset_color[5]; + static const wchar_t wreset_color[5]; +}; + +FMT_EXTERN template struct basic_data; + +// This is a struct rather than an alias to avoid shadowing warnings in gcc. +struct data : basic_data<> {}; + +#ifdef FMT_BUILTIN_CLZLL +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +inline int count_digits(uint64_t n) { + // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 + // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. + int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; + return t - (n < data::zero_or_powers_of_10_64[t]) + 1; +} +#else +// Fallback version of count_digits used when __builtin_clz is not available. +inline int count_digits(uint64_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#endif + +#if FMT_USE_INT128 +inline int count_digits(uint128_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#endif + +// Counts the number of digits in n. BITS = log2(radix). +template inline int count_digits(UInt n) { + int num_digits = 0; + do { + ++num_digits; + } while ((n >>= BITS) != 0); + return num_digits; +} + +template <> int count_digits<4>(internal::fallback_uintptr n); + +#if FMT_HAS_CPP_ATTRIBUTE(always_inline) +# define FMT_ALWAYS_INLINE __attribute__((always_inline)) +#else +# define FMT_ALWAYS_INLINE +#endif + +template +inline char* lg(uint32_t n, Handler h) FMT_ALWAYS_INLINE; + +// Computes g = floor(log10(n)) and calls h.on(n); +template inline char* lg(uint32_t n, Handler h) { + return n < 100 ? n < 10 ? h.template on<0>(n) : h.template on<1>(n) + : n < 1000000 + ? n < 10000 ? n < 1000 ? h.template on<2>(n) + : h.template on<3>(n) + : n < 100000 ? h.template on<4>(n) + : h.template on<5>(n) + : n < 100000000 ? n < 10000000 ? h.template on<6>(n) + : h.template on<7>(n) + : n < 1000000000 ? h.template on<8>(n) + : h.template on<9>(n); +} + +// An lg handler that formats a decimal number. +// Usage: lg(n, decimal_formatter(buffer)); +class decimal_formatter { + private: + char* buffer_; + + void write_pair(unsigned N, uint32_t index) { + std::memcpy(buffer_ + N, data::digits + index * 2, 2); + } + + public: + explicit decimal_formatter(char* buf) : buffer_(buf) {} + + template char* on(uint32_t u) { + if (N == 0) { + *buffer_ = static_cast(u) + '0'; + } else if (N == 1) { + write_pair(0, u); + } else { + // The idea of using 4.32 fixed-point numbers is based on + // https://github.com/jeaiii/itoa + unsigned n = N - 1; + unsigned a = n / 5 * n * 53 / 16; + uint64_t t = + ((1ULL << (32 + a)) / data::zero_or_powers_of_10_32[n] + 1 - n / 9); + t = ((t * u) >> a) + n / 5 * 4; + write_pair(0, t >> 32); + for (unsigned i = 2; i < N; i += 2) { + t = 100ULL * static_cast(t); + write_pair(i, t >> 32); + } + if (N % 2 == 0) { + buffer_[N] = + static_cast((10ULL * static_cast(t)) >> 32) + '0'; + } + } + return buffer_ += N + 1; + } +}; + +#ifdef FMT_BUILTIN_CLZ +// Optional version of count_digits for better performance on 32-bit platforms. +inline int count_digits(uint32_t n) { + int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; + return t - (n < data::zero_or_powers_of_10_32[t]) + 1; +} +#endif + +template FMT_API Char thousands_sep_impl(locale_ref loc); +template inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl(loc)); +} +template <> inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl(loc); +} + +template FMT_API Char decimal_point_impl(locale_ref loc); +template inline Char decimal_point(locale_ref loc) { + return Char(decimal_point_impl(loc)); +} +template <> inline wchar_t decimal_point(locale_ref loc) { + return decimal_point_impl(loc); +} + +// Formats a decimal unsigned integer value writing into buffer. +// add_thousands_sep is called after writing each char to add a thousands +// separator if necessary. +template +inline Char* format_decimal(Char* buffer, UInt value, int num_digits, + F add_thousands_sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); + buffer += num_digits; + Char* end = buffer; + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + unsigned index = static_cast((value % 100) * 2); + value /= 100; + *--buffer = static_cast(data::digits[index + 1]); + add_thousands_sep(buffer); + *--buffer = static_cast(data::digits[index]); + add_thousands_sep(buffer); + } + if (value < 10) { + *--buffer = static_cast('0' + value); + return end; + } + unsigned index = static_cast(value * 2); + *--buffer = static_cast(data::digits[index + 1]); + add_thousands_sep(buffer); + *--buffer = static_cast(data::digits[index]); + return end; +} + +template constexpr int digits10() noexcept { + return std::numeric_limits::digits10; +} +template <> constexpr int digits10() noexcept { return 38; } +template <> constexpr int digits10() noexcept { return 38; } + +template +inline Iterator format_decimal(Iterator out, UInt value, int num_digits, + F add_thousands_sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); + // Buffer should be large enough to hold all digits (<= digits10 + 1). + enum { max_size = digits10() + 1 }; + Char buffer[max_size + max_size / 3]; + auto end = format_decimal(buffer, value, num_digits, add_thousands_sep); + return internal::copy_str(buffer, end, out); +} + +template +inline It format_decimal(It out, UInt value, int num_digits) { + return format_decimal(out, value, num_digits, [](Char*) {}); +} + +template +inline Char* format_uint(Char* buffer, UInt value, int num_digits, + bool upper = false) { + buffer += num_digits; + Char* end = buffer; + do { + const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits; + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= BASE_BITS) != 0); + return end; +} + +template +Char* format_uint(Char* buffer, internal::fallback_uintptr n, int num_digits, + bool = false) { + auto char_digits = std::numeric_limits::digits / 4; + int start = (num_digits + char_digits - 1) / char_digits - 1; + if (int start_digits = num_digits % char_digits) { + unsigned value = n.value[start--]; + buffer = format_uint(buffer, value, start_digits); + } + for (; start >= 0; --start) { + unsigned value = n.value[start]; + buffer += char_digits; + auto p = buffer; + for (int i = 0; i < char_digits; ++i) { + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--p = static_cast(data::hex_digits[digit]); + value >>= BASE_BITS; + } + } + return buffer; +} + +template +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { + // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). + char buffer[std::numeric_limits::digits / BASE_BITS + 1]; + format_uint(buffer, value, num_digits, upper); + return internal::copy_str(buffer, buffer + num_digits, out); +} + +#ifndef _WIN32 +# define FMT_USE_WINDOWS_H 0 +#elif !defined(FMT_USE_WINDOWS_H) +# define FMT_USE_WINDOWS_H 1 +#endif + +// Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. +// All the functionality that relies on it will be disabled too. +#if FMT_USE_WINDOWS_H +// A converter from UTF-8 to UTF-16. +// It is only provided for Windows since other systems support UTF-8 natively. +class utf8_to_utf16 { + private: + wmemory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + operator wstring_view() const { return wstring_view(&buffer_[0], size()); } + size_t size() const { return buffer_.size() - 1; } + const wchar_t* c_str() const { return &buffer_[0]; } + std::wstring str() const { return std::wstring(&buffer_[0], size()); } +}; + +// A converter from UTF-16 to UTF-8. +// It is only provided for Windows since other systems support UTF-8 natively. +class utf16_to_utf8 { + private: + memory_buffer buffer_; + + public: + utf16_to_utf8() {} + FMT_API explicit utf16_to_utf8(wstring_view s); + operator string_view() const { return string_view(&buffer_[0], size()); } + size_t size() const { return buffer_.size() - 1; } + const char* c_str() const { return &buffer_[0]; } + std::string str() const { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a system error code instead of + // throwing exception on conversion error. This method may still throw + // in case of memory allocation error. + FMT_API int convert(wstring_view s); +}; + +FMT_API void format_windows_error(fmt::internal::buffer& out, + int error_code, + fmt::string_view message) FMT_NOEXCEPT; +#endif + +template struct null {}; + +// Workaround an array initialization issue in gcc 4.8. +template struct fill_t { + private: + Char data_[6]; + + public: + FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; } + FMT_CONSTEXPR const Char& operator[](size_t index) const { + return data_[index]; + } + + static FMT_CONSTEXPR fill_t make() { + auto fill = fill_t(); + fill[0] = Char(' '); + return fill; + } +}; +} // namespace internal + +// We cannot use enum classes as bit fields because of a gcc bug +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414. +namespace align { +enum type { none, left, right, center, numeric }; +} +using align_t = align::type; + +namespace sign { +enum type { none, minus, plus, space }; +} +using sign_t = sign::type; + +// Format specifiers for built-in and string types. +template struct basic_format_specs { + int width; + int precision; + char type; + align_t align : 4; + sign_t sign : 3; + bool alt : 1; // Alternate form ('#'). + internal::fill_t fill; + + constexpr basic_format_specs() + : width(0), + precision(-1), + type(0), + align(align::none), + sign(sign::none), + alt(false), + fill(internal::fill_t::make()) {} +}; + +using format_specs = basic_format_specs; + +namespace internal { + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template It write_exponent(int exp, It it) { + FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); + if (exp < 0) { + *it++ = static_cast('-'); + exp = -exp; + } else { + *it++ = static_cast('+'); + } + if (exp >= 100) { + *it++ = static_cast(static_cast('0' + exp / 100)); + exp %= 100; + } + const char* d = data::digits + exp * 2; + *it++ = static_cast(d[0]); + *it++ = static_cast(d[1]); + return it; +} + +struct gen_digits_params { + int num_digits; + bool fixed; + bool upper; + bool trailing_zeros; +}; + +// The number is given as v = digits * pow(10, exp). +template +It grisu_prettify(const char* digits, int size, int exp, It it, + gen_digits_params params, Char decimal_point) { + // pow(10, full_exp - 1) <= v <= pow(10, full_exp). + int full_exp = size + exp; + if (!params.fixed) { + // Insert a decimal point after the first digit and add an exponent. + *it++ = static_cast(*digits); + if (size > 1) *it++ = decimal_point; + exp += size - 1; + it = copy_str(digits + 1, digits + size, it); + if (size < params.num_digits) + it = std::fill_n(it, params.num_digits - size, static_cast('0')); + *it++ = static_cast(params.upper ? 'E' : 'e'); + return write_exponent(exp, it); + } + if (size <= full_exp) { + // 1234e7 -> 12340000000[.0+] + it = copy_str(digits, digits + size, it); + it = std::fill_n(it, full_exp - size, static_cast('0')); + int num_zeros = (std::max)(params.num_digits - full_exp, 1); + if (params.trailing_zeros) { + *it++ = decimal_point; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if (num_zeros > 1000) + throw std::runtime_error("fuzz mode - avoiding excessive cpu use"); +#endif + it = std::fill_n(it, num_zeros, static_cast('0')); + } + } else if (full_exp > 0) { + // 1234e-2 -> 12.34[0+] + it = copy_str(digits, digits + full_exp, it); + if (!params.trailing_zeros) { + // Remove trailing zeros. + while (size > full_exp && digits[size - 1] == '0') --size; + if (size != full_exp) *it++ = decimal_point; + return copy_str(digits + full_exp, digits + size, it); + } + *it++ = decimal_point; + it = copy_str(digits + full_exp, digits + size, it); + if (params.num_digits > size) { + // Add trailing zeros. + int num_zeros = params.num_digits - size; + it = std::fill_n(it, num_zeros, static_cast('0')); + } + } else { + // 1234e-6 -> 0.001234 + *it++ = static_cast('0'); + int num_zeros = -full_exp; + if (params.num_digits >= 0 && params.num_digits < num_zeros) + num_zeros = params.num_digits; + if (!params.trailing_zeros) + while (size > 0 && digits[size - 1] == '0') --size; + if (num_zeros != 0 || size != 0) { + *it++ = decimal_point; + it = std::fill_n(it, num_zeros, static_cast('0')); + it = copy_str(digits, digits + size, it); + } + } + return it; +} + +namespace grisu_options { +enum { fixed = 1, grisu3 = 2 }; +} + +// Formats value using the Grisu algorithm: +// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf +template +FMT_API bool grisu_format(Double, buffer&, int, unsigned, int&); +template +inline bool grisu_format(Double, buffer&, int, unsigned, int&) { + return false; +} + +struct sprintf_specs { + int precision; + char type; + bool alt : 1; + + template + constexpr sprintf_specs(basic_format_specs specs) + : precision(specs.precision), type(specs.type), alt(specs.alt) {} + + constexpr bool has_precision() const { return precision >= 0; } +}; + +template +char* sprintf_format(Double, internal::buffer&, sprintf_specs); + +template +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { + switch (spec) { + case 0: + case 'd': + handler.on_dec(); + break; + case 'x': + case 'X': + handler.on_hex(); + break; + case 'b': + case 'B': + handler.on_bin(); + break; + case 'o': + handler.on_oct(); + break; + case 'n': + handler.on_num(); + break; + default: + handler.on_error(); + } +} + +template +FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler&& handler) { + switch (spec) { + case 0: + case 'g': + case 'G': + handler.on_general(); + break; + case 'e': + case 'E': + handler.on_exp(); + break; + case 'f': + case 'F': + handler.on_fixed(); + break; + case '%': + handler.on_percent(); + break; + case 'a': + case 'A': + handler.on_hex(); + break; + case 'n': + handler.on_num(); + break; + default: + handler.on_error(); + break; + } +} + +template +FMT_CONSTEXPR void handle_char_specs(const basic_format_specs* specs, + Handler&& handler) { + if (!specs) return handler.on_char(); + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align == align::numeric || specs->sign != sign::none || specs->alt) + handler.on_error("invalid format specifier for char"); + handler.on_char(); +} + +template +FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) { + if (spec == 0 || spec == 's') + handler.on_string(); + else if (spec == 'p') + handler.on_pointer(); + else + handler.on_error("invalid type specifier"); +} + +template +FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 's') eh.on_error("invalid type specifier"); +} + +template +FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier"); +} + +template class int_type_checker : private ErrorHandler { + public: + FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_dec() {} + FMT_CONSTEXPR void on_hex() {} + FMT_CONSTEXPR void on_bin() {} + FMT_CONSTEXPR void on_oct() {} + FMT_CONSTEXPR void on_num() {} + + FMT_CONSTEXPR void on_error() { + ErrorHandler::on_error("invalid type specifier"); + } +}; + +template +class float_type_checker : private ErrorHandler { + public: + FMT_CONSTEXPR explicit float_type_checker(ErrorHandler eh) + : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_general() {} + FMT_CONSTEXPR void on_exp() {} + FMT_CONSTEXPR void on_fixed() {} + FMT_CONSTEXPR void on_percent() {} + FMT_CONSTEXPR void on_hex() {} + FMT_CONSTEXPR void on_num() {} + + FMT_CONSTEXPR void on_error() { + ErrorHandler::on_error("invalid type specifier"); + } +}; + +template +class char_specs_checker : public ErrorHandler { + private: + char type_; + + public: + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) + : ErrorHandler(eh), type_(type) {} + + FMT_CONSTEXPR void on_int() { + handle_int_type_spec(type_, int_type_checker(*this)); + } + FMT_CONSTEXPR void on_char() {} +}; + +template +class cstring_type_checker : public ErrorHandler { + public: + FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh) + : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_string() {} + FMT_CONSTEXPR void on_pointer() {} +}; + +template +void arg_map::init(const basic_format_args& args) { + if (map_) return; + map_ = new entry[internal::to_unsigned(args.max_size())]; + if (args.is_packed()) { + for (int i = 0;; ++i) { + internal::type arg_type = args.type(i); + if (arg_type == internal::none_type) return; + if (arg_type == internal::named_arg_type) push_back(args.values_[i]); + } + } + for (int i = 0, n = args.max_size(); i < n; ++i) { + auto type = args.args_[i].type_; + if (type == internal::named_arg_type) push_back(args.args_[i].value_); + } +} + +// This template provides operations for formatting and writing data into a +// character range. +template class basic_writer { + public: + using char_type = typename Range::value_type; + using iterator = typename Range::iterator; + using format_specs = basic_format_specs; + + private: + iterator out_; // Output iterator. + internal::locale_ref locale_; + + // Attempts to reserve space for n extra characters in the output range. + // Returns a pointer to the reserved range or a reference to out_. + auto reserve(std::size_t n) -> decltype(internal::reserve(out_, n)) { + return internal::reserve(out_, n); + } + + template struct padded_int_writer { + size_t size_; + string_view prefix; + char_type fill; + std::size_t padding; + F f; + + size_t size() const { return size_; } + size_t width() const { return size_; } + + template void operator()(It&& it) const { + if (prefix.size() != 0) + it = internal::copy_str(prefix.begin(), prefix.end(), it); + it = std::fill_n(it, padding, fill); + f(it); + } + }; + + // Writes an integer in the format + // + // where are written by f(it). + template + void write_int(int num_digits, string_view prefix, format_specs specs, F f) { + std::size_t size = prefix.size() + internal::to_unsigned(num_digits); + char_type fill = specs.fill[0]; + std::size_t padding = 0; + if (specs.align == align::numeric) { + auto unsiged_width = internal::to_unsigned(specs.width); + if (unsiged_width > size) { + padding = unsiged_width - size; + size = unsiged_width; + } + } else if (specs.precision > num_digits) { + size = prefix.size() + internal::to_unsigned(specs.precision); + padding = internal::to_unsigned(specs.precision - num_digits); + fill = static_cast('0'); + } + if (specs.align == align::none) specs.align = align::right; + write_padded(specs, padded_int_writer{size, prefix, fill, padding, f}); + } + + // Writes a decimal integer. + template void write_decimal(Int value) { + auto abs_value = static_cast>(value); + bool is_negative = internal::is_negative(value); + if (is_negative) abs_value = 0 - abs_value; + int num_digits = internal::count_digits(abs_value); + auto&& it = + reserve((is_negative ? 1 : 0) + static_cast(num_digits)); + if (is_negative) *it++ = static_cast('-'); + it = internal::format_decimal(it, abs_value, num_digits); + } + + // The handle_int_type_spec handler that writes an integer. + template struct int_writer { + using unsigned_type = uint32_or_64_or_128_t; + + basic_writer& writer; + const Specs& specs; + unsigned_type abs_value; + char prefix[4]; + unsigned prefix_size; + + string_view get_prefix() const { return string_view(prefix, prefix_size); } + + int_writer(basic_writer& w, Int value, const Specs& s) + : writer(w), + specs(s), + abs_value(static_cast(value)), + prefix_size(0) { + if (internal::is_negative(value)) { + prefix[0] = '-'; + ++prefix_size; + abs_value = 0 - abs_value; + } else if (specs.sign != sign::none && specs.sign != sign::minus) { + prefix[0] = specs.sign == sign::plus ? '+' : ' '; + ++prefix_size; + } + } + + struct dec_writer { + unsigned_type abs_value; + int num_digits; + + template void operator()(It&& it) const { + it = internal::format_decimal(it, abs_value, num_digits); + } + }; + + void on_dec() { + int num_digits = internal::count_digits(abs_value); + writer.write_int(num_digits, get_prefix(), specs, + dec_writer{abs_value, num_digits}); + } + + struct hex_writer { + int_writer& self; + int num_digits; + + template void operator()(It&& it) const { + it = internal::format_uint<4, char_type>(it, self.abs_value, num_digits, + self.specs.type != 'x'); + } + }; + + void on_hex() { + if (specs.alt) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = specs.type; + } + int num_digits = internal::count_digits<4>(abs_value); + writer.write_int(num_digits, get_prefix(), specs, + hex_writer{*this, num_digits}); + } + + template struct bin_writer { + unsigned_type abs_value; + int num_digits; + + template void operator()(It&& it) const { + it = internal::format_uint(it, abs_value, num_digits); + } + }; + + void on_bin() { + if (specs.alt) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = static_cast(specs.type); + } + int num_digits = internal::count_digits<1>(abs_value); + writer.write_int(num_digits, get_prefix(), specs, + bin_writer<1>{abs_value, num_digits}); + } + + void on_oct() { + int num_digits = internal::count_digits<3>(abs_value); + if (specs.alt && specs.precision <= num_digits && abs_value != 0) { + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + prefix[prefix_size++] = '0'; + } + writer.write_int(num_digits, get_prefix(), specs, + bin_writer<3>{abs_value, num_digits}); + } + + enum { sep_size = 1 }; + + struct num_writer { + unsigned_type abs_value; + int size; + char_type sep; + + template void operator()(It&& it) const { + basic_string_view s(&sep, sep_size); + // Index of a decimal digit with the least significant digit having + // index 0. + unsigned digit_index = 0; + it = internal::format_decimal( + it, abs_value, size, [s, &digit_index](char_type*& buffer) { + if (++digit_index % 3 != 0) return; + buffer -= s.size(); + std::uninitialized_copy(s.data(), s.data() + s.size(), + internal::make_checked(buffer, s.size())); + }); + } + }; + + void on_num() { + char_type sep = internal::thousands_sep(writer.locale_); + if (!sep) return on_dec(); + int num_digits = internal::count_digits(abs_value); + int size = num_digits + sep_size * ((num_digits - 1) / 3); + writer.write_int(size, get_prefix(), specs, + num_writer{abs_value, size, sep}); + } + + FMT_NORETURN void on_error() { + FMT_THROW(format_error("invalid type specifier")); + } + }; + + enum { inf_size = 3 }; // This is an enum to workaround a bug in MSVC. + + struct inf_or_nan_writer { + char sign; + bool as_percentage; + const char* str; + + size_t size() const { + return static_cast(inf_size + (sign ? 1 : 0) + + (as_percentage ? 1 : 0)); + } + size_t width() const { return size(); } + + template void operator()(It&& it) const { + if (sign) *it++ = static_cast(sign); + it = internal::copy_str( + str, str + static_cast(inf_size), it); + if (as_percentage) *it++ = static_cast('%'); + } + }; + + struct double_writer { + char sign; + internal::buffer& buffer; + char* decimal_point_pos; + char_type decimal_point; + + size_t size() const { return buffer.size() + (sign ? 1 : 0); } + size_t width() const { return size(); } + + template void operator()(It&& it) { + if (sign) *it++ = static_cast(sign); + auto begin = buffer.begin(); + if (decimal_point_pos) { + it = internal::copy_str(begin, decimal_point_pos, it); + *it++ = decimal_point; + begin = decimal_point_pos + 1; + } + it = internal::copy_str(begin, buffer.end(), it); + } + }; + + class grisu_writer { + private: + internal::buffer& digits_; + size_t size_; + char sign_; + int exp_; + internal::gen_digits_params params_; + char_type decimal_point_; + + public: + grisu_writer(char sign, internal::buffer& digits, int exp, + const internal::gen_digits_params& params, + char_type decimal_point) + : digits_(digits), + sign_(sign), + exp_(exp), + params_(params), + decimal_point_(decimal_point) { + int num_digits = static_cast(digits.size()); + int full_exp = num_digits + exp - 1; + int precision = params.num_digits > 0 ? params.num_digits : 11; + params_.fixed |= full_exp >= -4 && full_exp < precision; + auto it = internal::grisu_prettify( + digits.data(), num_digits, exp, internal::counting_iterator(), + params_, '.'); + size_ = it.count(); + } + + size_t size() const { return size_ + (sign_ ? 1 : 0); } + size_t width() const { return size(); } + + template void operator()(It&& it) { + if (sign_) *it++ = static_cast(sign_); + int num_digits = static_cast(digits_.size()); + it = internal::grisu_prettify(digits_.data(), num_digits, exp_, + it, params_, decimal_point_); + } + }; + + template struct str_writer { + const Char* s; + size_t size_; + + size_t size() const { return size_; } + size_t width() const { + return internal::count_code_points(basic_string_view(s, size_)); + } + + template void operator()(It&& it) const { + it = internal::copy_str(s, s + size_, it); + } + }; + + template struct pointer_writer { + UIntPtr value; + int num_digits; + + size_t size() const { return to_unsigned(num_digits) + 2; } + size_t width() const { return size(); } + + template void operator()(It&& it) const { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + it = internal::format_uint<4, char_type>(it, value, num_digits); + } + }; + + public: + /** Constructs a ``basic_writer`` object. */ + explicit basic_writer(Range out, + internal::locale_ref loc = internal::locale_ref()) + : out_(out.begin()), locale_(loc) {} + + iterator out() const { return out_; } + + // Writes a value in the format + // + // where is written by f(it). + template void write_padded(const format_specs& specs, F&& f) { + // User-perceived width (in code points). + unsigned width = to_unsigned(specs.width); + size_t size = f.size(); // The number of code units. + size_t num_code_points = width != 0 ? f.width() : size; + if (width <= num_code_points) return f(reserve(size)); + auto&& it = reserve(width + (size - num_code_points)); + char_type fill = specs.fill[0]; + std::size_t padding = width - num_code_points; + if (specs.align == align::right) { + it = std::fill_n(it, padding, fill); + f(it); + } else if (specs.align == align::center) { + std::size_t left_padding = padding / 2; + it = std::fill_n(it, left_padding, fill); + f(it); + it = std::fill_n(it, padding - left_padding, fill); + } else { + f(it); + it = std::fill_n(it, padding, fill); + } + } + + void write(int value) { write_decimal(value); } + void write(long value) { write_decimal(value); } + void write(long long value) { write_decimal(value); } + + void write(unsigned value) { write_decimal(value); } + void write(unsigned long value) { write_decimal(value); } + void write(unsigned long long value) { write_decimal(value); } + +#if FMT_USE_INT128 + void write(int128_t value) { write_decimal(value); } + void write(uint128_t value) { write_decimal(value); } +#endif + + // Writes a formatted integer. + template + void write_int(T value, const Spec& spec) { + internal::handle_int_type_spec(spec.type, + int_writer(*this, value, spec)); + } + + void write(double value, const format_specs& specs = format_specs()) { + write_double(value, specs); + } + + /** + \rst + Formats *value* using the general format for floating-point numbers + (``'g'``) and writes it to the buffer. + \endrst + */ + void write(long double value, const format_specs& specs = format_specs()) { + write_double(value, specs); + } + + // Formats a floating-point number (double or long double). + template ()> + void write_double(T value, const format_specs& specs); + + /** Writes a character to the buffer. */ + void write(char value) { + auto&& it = reserve(1); + *it++ = value; + } + + template ::value)> + void write(Char value) { + auto&& it = reserve(1); + *it++ = value; + } + + /** + \rst + Writes *value* to the buffer. + \endrst + */ + void write(string_view value) { + auto&& it = reserve(value.size()); + it = internal::copy_str(value.begin(), value.end(), it); + } + void write(wstring_view value) { + static_assert(std::is_same::value, ""); + auto&& it = reserve(value.size()); + it = std::copy(value.begin(), value.end(), it); + } + + // Writes a formatted string. + template + void write(const Char* s, std::size_t size, const format_specs& specs) { + write_padded(specs, str_writer{s, size}); + } + + template + void write(basic_string_view s, + const format_specs& specs = format_specs()) { + const Char* data = s.data(); + std::size_t size = s.size(); + if (specs.precision >= 0 && internal::to_unsigned(specs.precision) < size) + size = internal::to_unsigned(specs.precision); + write(data, size, specs); + } + + template + void write_pointer(UIntPtr value, const format_specs* specs) { + int num_digits = internal::count_digits<4>(value); + auto pw = pointer_writer{value, num_digits}; + if (!specs) return pw(reserve(to_unsigned(num_digits) + 2)); + format_specs specs_copy = *specs; + if (specs_copy.align == align::none) specs_copy.align = align::right; + write_padded(specs_copy, pw); + } +}; + +using writer = basic_writer>; + +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + +template +class arg_formatter_base { + public: + using char_type = typename Range::value_type; + using iterator = typename Range::iterator; + using format_specs = basic_format_specs; + + private: + using writer_type = basic_writer; + writer_type writer_; + format_specs* specs_; + + struct char_writer { + char_type value; + + size_t size() const { return 1; } + size_t width() const { return 1; } + + template void operator()(It&& it) const { *it++ = value; } + }; + + void write_char(char_type value) { + if (specs_) + writer_.write_padded(*specs_, char_writer{value}); + else + writer_.write(value); + } + + void write_pointer(const void* p) { + writer_.write_pointer(internal::bit_cast(p), specs_); + } + + protected: + writer_type& writer() { return writer_; } + FMT_DEPRECATED format_specs* spec() { return specs_; } + format_specs* specs() { return specs_; } + iterator out() { return writer_.out(); } + + void write(bool value) { + string_view sv(value ? "true" : "false"); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); + } + + void write(const char_type* value) { + if (!value) { + FMT_THROW(format_error("string pointer is null")); + } else { + auto length = std::char_traits::length(value); + basic_string_view sv(value, length); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); + } + } + + public: + arg_formatter_base(Range r, format_specs* s, locale_ref loc) + : writer_(r, loc), specs_(s) {} + + iterator operator()(monostate) { + FMT_ASSERT(false, "invalid argument type"); + return out(); + } + + template ::value)> + iterator operator()(T value) { + if (specs_) + writer_.write_int(value, *specs_); + else + writer_.write(value); + return out(); + } + + iterator operator()(char_type value) { + internal::handle_char_specs( + specs_, char_spec_handler(*this, static_cast(value))); + return out(); + } + + iterator operator()(bool value) { + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); + write(value != 0); + return out(); + } + + template ::value)> + iterator operator()(T value) { + writer_.write_double(value, specs_ ? *specs_ : format_specs()); + return out(); + } + + struct char_spec_handler : ErrorHandler { + arg_formatter_base& formatter; + char_type value; + + char_spec_handler(arg_formatter_base& f, char_type val) + : formatter(f), value(val) {} + + void on_int() { + if (formatter.specs_) + formatter.writer_.write_int(value, *formatter.specs_); + else + formatter.writer_.write(value); + } + void on_char() { formatter.write_char(value); } + }; + + struct cstring_spec_handler : internal::error_handler { + arg_formatter_base& formatter; + const char_type* value; + + cstring_spec_handler(arg_formatter_base& f, const char_type* val) + : formatter(f), value(val) {} + + void on_string() { formatter.write(value); } + void on_pointer() { formatter.write_pointer(value); } + }; + + iterator operator()(const char_type* value) { + if (!specs_) return write(value), out(); + internal::handle_cstring_type_spec(specs_->type, + cstring_spec_handler(*this, value)); + return out(); + } + + iterator operator()(basic_string_view value) { + if (specs_) { + internal::check_string_type_spec(specs_->type, internal::error_handler()); + writer_.write(value, *specs_); + } else { + writer_.write(value); + } + return out(); + } + + iterator operator()(const void* value) { + if (specs_) + check_pointer_type_spec(specs_->type, internal::error_handler()); + write_pointer(value); + return out(); + } +}; + +template FMT_CONSTEXPR bool is_name_start(Char c) { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template +FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end, + ErrorHandler&& eh) { + assert(begin != end && '0' <= *begin && *begin <= '9'); + if (*begin == '0') { + ++begin; + return 0; + } + unsigned value = 0; + // Convert to unsigned to prevent a warning. + constexpr unsigned max_int = max_value(); + unsigned big = max_int / 10; + do { + // Check for overflow. + if (value > big) { + value = max_int + 1; + break; + } + value = value * 10 + unsigned(*begin - '0'); + ++begin; + } while (begin != end && '0' <= *begin && *begin <= '9'); + if (value > max_int) eh.on_error("number is too big"); + return static_cast(value); +} + +template class custom_formatter { + private: + using char_type = typename Context::char_type; + + basic_parse_context& parse_ctx_; + Context& ctx_; + + public: + explicit custom_formatter(basic_parse_context& parse_ctx, + Context& ctx) + : parse_ctx_(parse_ctx), ctx_(ctx) {} + + bool operator()(typename basic_format_arg::handle h) const { + h.format(parse_ctx_, ctx_); + return true; + } + + template bool operator()(T) const { return false; } +}; + +template +using is_integer = + bool_constant::value && !std::is_same::value && + !std::is_same::value && + !std::is_same::value>; + +template class width_checker { + public: + explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {} + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative width"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("width is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +template class precision_checker { + public: + explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {} + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative precision"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("precision is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +// A format specifier handler that sets fields in basic_format_specs. +template class specs_setter { + public: + explicit FMT_CONSTEXPR specs_setter(basic_format_specs& specs) + : specs_(specs) {} + + FMT_CONSTEXPR specs_setter(const specs_setter& other) + : specs_(other.specs_) {} + + FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; } + FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill[0] = fill; } + FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; } + FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; } + FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; } + FMT_CONSTEXPR void on_hash() { specs_.alt = true; } + + FMT_CONSTEXPR void on_zero() { + specs_.align = align::numeric; + specs_.fill[0] = Char('0'); + } + + FMT_CONSTEXPR void on_width(int width) { specs_.width = width; } + FMT_CONSTEXPR void on_precision(int precision) { + specs_.precision = precision; + } + FMT_CONSTEXPR void end_precision() {} + + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast(type); + } + + protected: + basic_format_specs& specs_; +}; + +template class numeric_specs_checker { + public: + FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, internal::type arg_type) + : error_handler_(eh), arg_type_(arg_type) {} + + FMT_CONSTEXPR void require_numeric_argument() { + if (!is_arithmetic_type(arg_type_)) + error_handler_.on_error("format specifier requires numeric argument"); + } + + FMT_CONSTEXPR void check_sign() { + require_numeric_argument(); + if (is_integral_type(arg_type_) && arg_type_ != int_type && + arg_type_ != long_long_type && arg_type_ != internal::char_type) { + error_handler_.on_error("format specifier requires signed argument"); + } + } + + FMT_CONSTEXPR void check_precision() { + if (is_integral_type(arg_type_) || arg_type_ == internal::pointer_type) + error_handler_.on_error("precision not allowed for this argument type"); + } + + private: + ErrorHandler& error_handler_; + internal::type arg_type_; +}; + +// A format specifier handler that checks if specifiers are consistent with the +// argument type. +template class specs_checker : public Handler { + public: + FMT_CONSTEXPR specs_checker(const Handler& handler, internal::type arg_type) + : Handler(handler), checker_(*this, arg_type) {} + + FMT_CONSTEXPR specs_checker(const specs_checker& other) + : Handler(other), checker_(*this, other.arg_type_) {} + + FMT_CONSTEXPR void on_align(align_t align) { + if (align == align::numeric) checker_.require_numeric_argument(); + Handler::on_align(align); + } + + FMT_CONSTEXPR void on_plus() { + checker_.check_sign(); + Handler::on_plus(); + } + + FMT_CONSTEXPR void on_minus() { + checker_.check_sign(); + Handler::on_minus(); + } + + FMT_CONSTEXPR void on_space() { + checker_.check_sign(); + Handler::on_space(); + } + + FMT_CONSTEXPR void on_hash() { + checker_.require_numeric_argument(); + Handler::on_hash(); + } + + FMT_CONSTEXPR void on_zero() { + checker_.require_numeric_argument(); + Handler::on_zero(); + } + + FMT_CONSTEXPR void end_precision() { checker_.check_precision(); } + + private: + numeric_specs_checker checker_; +}; + +template