Initial commit

This commit is contained in:
jaseg 2021-01-24 18:44:56 +01:00
commit f7b4cc602b
230 changed files with 25005 additions and 0 deletions

View file

@ -0,0 +1,21 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
PROJECT(polyclipping)
SET(CMAKE_BUILD_TYPE "Release" CACHE STRING "Release type")
# The header name clipper.hpp is too generic, so install in a subdirectory
SET(CMAKE_INSTALL_INCDIR "${CMAKE_INSTALL_PREFIX}/include/polyclipping")
SET(CMAKE_INSTALL_LIBDIR "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}")
SET(CMAKE_INSTALL_PKGCONFIGDIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig")
SET(PCFILE "${CMAKE_CURRENT_BINARY_DIR}/polyclipping.pc")
SET(BUILD_SHARED_LIBS ON CACHE BOOL
"Build shared libraries (.dll/.so) instead of static ones (.lib/.a)")
ADD_LIBRARY(polyclipping clipper.cpp)
CONFIGURE_FILE (polyclipping.pc.cmakein "${PCFILE}" @ONLY)
INSTALL (FILES clipper.hpp DESTINATION "${CMAKE_INSTALL_INCDIR}")
INSTALL (TARGETS polyclipping LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
INSTALL (FILES "${PCFILE}" DESTINATION "${CMAKE_INSTALL_PKGCONFIGDIR}")
SET_TARGET_PROPERTIES(polyclipping PROPERTIES VERSION 22.0.0 SOVERSION 22 )

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,406 @@
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.4.2 *
* Date : 27 February 2017 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2017 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
#ifndef clipper_hpp
#define clipper_hpp
#define CLIPPER_VERSION "6.4.2"
//use_int32: When enabled 32bit ints are used instead of 64bit ints. This
//improve performance but coordinate values are limited to the range +/- 46340
//#define use_int32
//use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
//#define use_xyz
//use_lines: Enables line clipping. Adds a very minor cost to performance.
#define use_lines
//use_deprecated: Enables temporary support for the obsolete functions
//#define use_deprecated
#include <vector>
#include <list>
#include <set>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
#include <queue>
namespace ClipperLib {
enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
enum PolyType { ptSubject, ptClip };
//By far the most widely used winding rules for polygon filling are
//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
//see http://glprogramming.com/red/chapter11.html
enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
#ifdef use_int32
typedef int cInt;
static cInt const loRange = 0x7FFF;
static cInt const hiRange = 0x7FFF;
#else
typedef signed long long cInt;
static cInt const loRange = 0x3FFFFFFF;
static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
typedef signed long long long64; //used by Int128 class
typedef unsigned long long ulong64;
#endif
struct IntPoint {
cInt X;
cInt Y;
#ifdef use_xyz
cInt Z;
IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
#else
IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
#endif
friend inline bool operator== (const IntPoint& a, const IntPoint& b)
{
return a.X == b.X && a.Y == b.Y;
}
friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
{
return a.X != b.X || a.Y != b.Y;
}
};
//------------------------------------------------------------------------------
typedef std::vector< IntPoint > Path;
typedef std::vector< Path > Paths;
inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
std::ostream& operator <<(std::ostream &s, const IntPoint &p);
std::ostream& operator <<(std::ostream &s, const Path &p);
std::ostream& operator <<(std::ostream &s, const Paths &p);
struct DoublePoint
{
double X;
double Y;
DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
};
//------------------------------------------------------------------------------
#ifdef use_xyz
typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
#endif
enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
enum JoinType {jtSquare, jtRound, jtMiter};
enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
class PolyNode;
typedef std::vector< PolyNode* > PolyNodes;
class PolyNode
{
public:
PolyNode();
virtual ~PolyNode(){};
Path Contour;
PolyNodes Childs;
PolyNode* Parent;
PolyNode* GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
//PolyNode& operator =(PolyNode& other);
unsigned Index; //node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode* GetNextSiblingUp() const;
void AddChild(PolyNode& child);
friend class Clipper; //to access Index
friend class ClipperOffset;
};
class PolyTree: public PolyNode
{
public:
~PolyTree(){ Clear(); };
PolyNode* GetFirst() const;
void Clear();
int Total() const;
private:
//PolyTree& operator =(PolyTree& other);
PolyNodes AllNodes;
friend class Clipper; //to access AllNodes
};
bool Orientation(const Path &poly);
double Area(const Path &poly);
int PointInPolygon(const IntPoint &pt, const Path &path);
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
void CleanPolygon(Path& poly, double distance = 1.415);
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
void CleanPolygons(Paths& polys, double distance = 1.415);
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
void ReversePath(Path& p);
void ReversePaths(Paths& p);
struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
//enums that are used internally ...
enum EdgeSide { esLeft = 1, esRight = 2};
//forward declarations (for stuff used internally) ...
struct TEdge;
struct IntersectNode;
struct LocalMinimum;
struct OutPt;
struct OutRec;
struct Join;
typedef std::vector < OutRec* > PolyOutList;
typedef std::vector < TEdge* > EdgeList;
typedef std::vector < Join* > JoinList;
typedef std::vector < IntersectNode* > IntersectList;
//------------------------------------------------------------------------------
//ClipperBase is the ancestor to the Clipper class. It should not be
//instantiated directly. This class simply abstracts the conversion of sets of
//polygon coordinates into edge objects that are stored in a LocalMinima list.
class ClipperBase
{
public:
ClipperBase();
virtual ~ClipperBase();
virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
virtual void Clear();
IntRect GetBounds();
bool PreserveCollinear() {return m_PreserveCollinear;};
void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
protected:
void DisposeLocalMinimaList();
TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
virtual void Reset();
TEdge* ProcessBound(TEdge* E, bool IsClockwise);
void InsertScanbeam(const cInt Y);
bool PopScanbeam(cInt &Y);
bool LocalMinimaPending();
bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);
OutRec* CreateOutRec();
void DisposeAllOutRecs();
void DisposeOutRec(PolyOutList::size_type index);
void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
void DeleteFromAEL(TEdge *e);
void UpdateEdgeIntoAEL(TEdge *&e);
typedef std::vector<LocalMinimum> MinimaList;
MinimaList::iterator m_CurrentLM;
MinimaList m_MinimaList;
bool m_UseFullRange;
EdgeList m_edges;
bool m_PreserveCollinear;
bool m_HasOpenPaths;
PolyOutList m_PolyOuts;
TEdge *m_ActiveEdges;
typedef std::priority_queue<cInt> ScanbeamList;
ScanbeamList m_Scanbeam;
};
//------------------------------------------------------------------------------
class Clipper : public virtual ClipperBase
{
public:
Clipper(int initOptions = 0);
bool Execute(ClipType clipType,
Paths &solution,
PolyFillType fillType = pftEvenOdd);
bool Execute(ClipType clipType,
Paths &solution,
PolyFillType subjFillType,
PolyFillType clipFillType);
bool Execute(ClipType clipType,
PolyTree &polytree,
PolyFillType fillType = pftEvenOdd);
bool Execute(ClipType clipType,
PolyTree &polytree,
PolyFillType subjFillType,
PolyFillType clipFillType);
bool ReverseSolution() { return m_ReverseOutput; };
void ReverseSolution(bool value) {m_ReverseOutput = value;};
bool StrictlySimple() {return m_StrictSimple;};
void StrictlySimple(bool value) {m_StrictSimple = value;};
//set the callback function for z value filling on intersections (otherwise Z is 0)
#ifdef use_xyz
void ZFillFunction(ZFillCallback zFillFunc);
#endif
protected:
virtual bool ExecuteInternal();
private:
JoinList m_Joins;
JoinList m_GhostJoins;
IntersectList m_IntersectList;
ClipType m_ClipType;
typedef std::list<cInt> MaximaList;
MaximaList m_Maxima;
TEdge *m_SortedEdges;
bool m_ExecuteLocked;
PolyFillType m_ClipFillType;
PolyFillType m_SubjFillType;
bool m_ReverseOutput;
bool m_UsingPolyTree;
bool m_StrictSimple;
#ifdef use_xyz
ZFillCallback m_ZFill; //custom callback
#endif
void SetWindingCount(TEdge& edge);
bool IsEvenOddFillType(const TEdge& edge) const;
bool IsEvenOddAltFillType(const TEdge& edge) const;
void InsertLocalMinimaIntoAEL(const cInt botY);
void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
void AddEdgeToSEL(TEdge *edge);
bool PopEdgeFromSEL(TEdge *&edge);
void CopyAELToSEL();
void DeleteFromSEL(TEdge *e);
void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
bool IsContributing(const TEdge& edge) const;
bool IsTopHorz(const cInt XPos);
void DoMaxima(TEdge *e);
void ProcessHorizontals();
void ProcessHorizontal(TEdge *horzEdge);
void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutRec* GetOutRec(int idx);
void AppendPolygon(TEdge *e1, TEdge *e2);
void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
OutPt* GetLastOutPt(TEdge *e);
bool ProcessIntersections(const cInt topY);
void BuildIntersectList(const cInt topY);
void ProcessIntersectList();
void ProcessEdgesAtTopOfScanbeam(const cInt topY);
void BuildResult(Paths& polys);
void BuildResult2(PolyTree& polytree);
void SetHoleState(TEdge *e, OutRec *outrec);
void DisposeIntersectNodes();
bool FixupIntersectionOrder();
void FixupOutPolygon(OutRec &outrec);
void FixupOutPolyline(OutRec &outrec);
bool IsHole(TEdge *e);
bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
void FixHoleLinkage(OutRec &outrec);
void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
void ClearJoins();
void ClearGhostJoins();
void AddGhostJoin(OutPt *op, const IntPoint offPt);
bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
void JoinCommonEdges();
void DoSimplePolygons();
void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
void FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec);
void FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec);
#ifdef use_xyz
void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
#endif
};
//------------------------------------------------------------------------------
class ClipperOffset
{
public:
ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
~ClipperOffset();
void AddPath(const Path& path, JoinType joinType, EndType endType);
void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
void Execute(Paths& solution, double delta);
void Execute(PolyTree& solution, double delta);
void Clear();
double MiterLimit;
double ArcTolerance;
private:
Paths m_destPolys;
Path m_srcPoly;
Path m_destPoly;
std::vector<DoublePoint> m_normals;
double m_delta, m_sinA, m_sin, m_cos;
double m_miterLim, m_StepsPerRad;
IntPoint m_lowest;
PolyNode m_polyNodes;
void FixOrientations();
void DoOffset(double delta);
void OffsetPoint(int j, int& k, JoinType jointype);
void DoSquare(int j, int k);
void DoMiter(int j, int k, double r);
void DoRound(int j, int k);
};
//------------------------------------------------------------------------------
class clipperException : public std::exception
{
public:
clipperException(const char* description): m_descr(description) {}
virtual ~clipperException() throw() {}
virtual const char* what() const throw() {return m_descr.c_str();}
private:
std::string m_descr;
};
//------------------------------------------------------------------------------
} //ClipperLib namespace
#endif //clipper_hpp

View file

@ -0,0 +1,6 @@
http://cairographics.org/
The Windows dynamic linked libraries necessary to run Cairo can be downloaded from
http://www.gtk.org/download/win32.php
All the dlls listed under the heading "Required third party dependencies" are
required except gettext-runtime.dll.

View file

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C++ Express 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cairo", "cairo.vcxproj", "{6AFBCA2B-9262-6D28-7506-E13747347388}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6AFBCA2B-9262-6D28-7506-E13747347388}.Debug|Win32.ActiveCfg = Debug|Win32
{6AFBCA2B-9262-6D28-7506-E13747347388}.Debug|Win32.Build.0 = Debug|Win32
{6AFBCA2B-9262-6D28-7506-E13747347388}.Release|Win32.ActiveCfg = Release|Win32
{6AFBCA2B-9262-6D28-7506-E13747347388}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>C:\Program Files %28x86%29\Borland\Clipper\PreReleaseTesting\cpp\cairo_src;$(IncludePath)</IncludePath>
<SourcePath>C:\Program Files %28x86%29\Borland\Clipper\PreReleaseTesting\cpp\cairo_src;C:\Program Files %28x86%29\Borland\graphics32\Examples\Vcl\Drawing\Clipper\PreReleaseTesting\cpp\cairo_src;$(SourcePath)</SourcePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\Program Files (x86)\Borland\graphics32\Examples\Vcl\Drawing\Clipper\PreReleaseTesting\cpp\cairo_src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
<UseUnicodeForAssemblerListing>
</UseUnicodeForAssemblerListing>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\Program Files (x86)\Borland\graphics32\Examples\Vcl\Drawing\Clipper\PreReleaseTesting\cpp\cairo_src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\clipper.cpp" />
<ClCompile Include="cairo_clipper.cpp" />
<ClCompile Include="main.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\cairo_src\cairo.h" />
<ClInclude Include="..\clipper.hpp" />
<ClInclude Include="cairo_clipper.hpp" />
</ItemGroup>
<ItemGroup>
<Library Include="libcairo-2.lib" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View file

@ -0,0 +1,133 @@
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 1.1 *
* Date : 4 April 2011 *
* Copyright : Angus Johnson 2010-2011 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Modified by Mike Owens to support coordinate transformation *
*******************************************************************************/
#include <stdexcept>
#include <cmath>
#include <iostream>
#include <cairo.h>
#include "clipper.hpp"
#include "cairo_clipper.hpp"
namespace ClipperLib {
namespace cairo {
namespace {
inline cInt Round(double val)
{
if ((val < 0)) return (cInt)(val - 0.5); else return (cInt)(val + 0.5);
}
void transform_point(cairo_t* pen, Transform transform, cInt* x, cInt* y)
{
double _x = (double)*x, _y = (double)*y;
switch (transform)
{
case tDeviceToUser:
cairo_device_to_user(pen, &_x, &_y);
break;
case tUserToDevice:
cairo_user_to_device(pen, &_x, &_y);
break;
default:
;
}
*x = Round(_x); *y = Round(_y);
}
}
void cairo_to_clipper(cairo_t* cr,
Paths &pg,
int scaling_factor,
Transform transform)
{
if (scaling_factor > 8 || scaling_factor < 0)
throw clipperCairoException("cairo_to_clipper: invalid scaling factor");
double scaling = std::pow((double)10, scaling_factor);
pg.clear();
cairo_path_t *path = cairo_copy_path_flat(cr);
int poly_count = 0;
for (int i = 0; i < path->num_data; i += path->data[i].header.length) {
if( path->data[i].header.type == CAIRO_PATH_CLOSE_PATH) poly_count++;
}
pg.resize(poly_count);
int i = 0, pc = 0;
while (pc < poly_count)
{
int vert_count = 1;
int j = i;
while(j < path->num_data && path->data[j].header.type != CAIRO_PATH_CLOSE_PATH)
{
if (path->data[j].header.type == CAIRO_PATH_LINE_TO)
vert_count++;
j += path->data[j].header.length;
}
pg[pc].resize(vert_count);
if (path->data[i].header.type != CAIRO_PATH_MOVE_TO) {
pg.resize(pc);
break;
}
pg[pc][0].X = Round(path->data[i+1].point.x *scaling);
pg[pc][0].Y = Round(path->data[i+1].point.y *scaling);
if (transform != tNone)
transform_point(cr, transform, &pg[pc][0].X, &pg[pc][0].Y);
i += path->data[i].header.length;
j = 1;
while (j < vert_count && i < path->num_data && path->data[i].header.type == CAIRO_PATH_LINE_TO) {
pg[pc][j].X = Round(path->data[i+1].point.x *scaling);
pg[pc][j].Y = Round(path->data[i+1].point.y *scaling);
if (transform != tNone)
transform_point(cr, transform, &pg[pc][j].X, &pg[pc][j].Y);
j++;
i += path->data[i].header.length;
}
pc++;
i += path->data[i].header.length;
}
cairo_path_destroy(path);
}
//--------------------------------------------------------------------------
void clipper_to_cairo(const Paths &pg, cairo_t* cr, int scaling_factor, Transform transform)
{
if (scaling_factor > 8 || scaling_factor < 0)
throw clipperCairoException("clipper_to_cairo: invalid scaling factor");
double scaling = std::pow((double)10, scaling_factor);
for (size_t i = 0; i < pg.size(); ++i)
{
size_t sz = pg[i].size();
if (sz < 3)
continue;
cairo_new_sub_path(cr);
//std::cerr << "sub path";
for (size_t j = 0; j < sz; ++j) {
cInt x = pg[i][j].X, y = pg[i][j].Y;
if (transform != tNone)
transform_point(cr, transform, &x, &y);
//std::cerr << " (" << (double)x / scaling << "," << (double)y / scaling << ")";
cairo_line_to(cr, (double)x / scaling, (double)y / scaling);
}
//std::cerr << std::endl;
cairo_close_path(cr);
}
}
//--------------------------------------------------------------------------
}
}

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 1.1 *
* Date : 4 April 2011 *
* Copyright : Angus Johnson 2010-2011 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Modified by Mike Owens to support coordinate transformation *
*******************************************************************************/
#ifndef CLIPPER_CAIRO_CLIPPER_HPP
#define CLIPPER_CAIRO_CLIPPER_HPP
#include "clipper.hpp"
typedef struct _cairo cairo_t;
namespace ClipperLib {
namespace cairo {
enum Transform {
tNone,
tUserToDevice,
tDeviceToUser
};
//nb: Since Clipper only accepts integer coordinates, fractional values have to
//be scaled up and down when being passed to and from Clipper. This is easily
//accomplished by setting the scaling factor (10^x) in the following functions.
//When scaling, remember that on most platforms, integer is only a 32bit value.
void cairo_to_clipper(cairo_t* cr,
ClipperLib::Paths &pg,
int scaling_factor = 0,
Transform transform = tNone);
void clipper_to_cairo(const ClipperLib::Paths &pg,
cairo_t* cr,
int scaling_factor = 0,
Transform transform = tNone);
}
class clipperCairoException : public std::exception
{
public:
clipperCairoException(const char* description)
throw(): std::exception(), m_description (description) {}
virtual ~clipperCairoException() throw() {}
virtual const char* what() const throw() {return m_description.c_str();}
private:
std::string m_description;
};
}
#endif

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,182 @@
//---------------------------------------------------------------------------
#include <windows.h>
#include <cstring>
#include <cmath>
#include <sstream>
#pragma hdrstop
#include "clipper.hpp"
#include "cairo.h"
#include "cairo-win32.h"
#include "cairo_clipper.hpp"
//---------------------------------------------------------------------------
int offsetVal;
LRESULT CALLBACK WndProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int CALLBACK wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
WCHAR* ClsName = L"CairoApp";
WCHAR* WndName = L"A Simple Cairo Clipper Demo";
offsetVal = 0;
MSG Msg;
HWND hWnd;
WNDCLASSEX WndClsEx;
// Create the application window
WndClsEx.cbSize = sizeof(WNDCLASSEX);
WndClsEx.style = CS_HREDRAW | CS_VREDRAW;
WndClsEx.lpfnWndProc = WndProcedure;
WndClsEx.cbClsExtra = 0;
WndClsEx.cbWndExtra = 0;
WndClsEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW);
WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
WndClsEx.lpszMenuName = NULL;
WndClsEx.lpszClassName = ClsName;
WndClsEx.hInstance = hInstance;
WndClsEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
// Register the application
RegisterClassEx(&WndClsEx);
// Create the window object
hWnd = CreateWindow(ClsName, WndName, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 300,
NULL, NULL, hInstance, NULL);
if( !hWnd ) return 0;
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
while( GetMessage(&Msg, NULL, 0, 0) )
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
//------------------------------------------------------------------------------
void OnPaint(HWND hWnd, HDC dc)
{
RECT rec;
GetClientRect(hWnd, &rec);
cairo_surface_t* surface = cairo_win32_surface_create(dc);
cairo_t* cr = cairo_create(surface);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
cairo_set_line_width (cr, 2.0);
//fill background with white ...
cairo_rectangle(cr, 0, 0, rec.right, rec.bottom);
cairo_set_source_rgba(cr, 1, 1, 1, 1);
cairo_fill(cr);
using namespace ClipperLib;
const int scaling = 2;
Clipper clpr; //clipper class
Paths pg; //std::vector for polygon(s) storage
//create a circular pattern, add the path to clipper and then draw it ...
cairo_arc(cr, 170,110,70,0,2*3.1415926);
cairo_close_path(cr);
cairo::cairo_to_clipper(cr, pg, scaling);
clpr.AddPaths(pg, ptSubject, true);
cairo_set_source_rgba(cr, 0, 0, 1, 0.25);
cairo_fill_preserve (cr);
cairo_set_source_rgba(cr, 0, 0, 0, 0.5);
cairo_stroke (cr);
//draw a star and another circle, add them to clipper and draw ...
cairo_move_to(cr, 60,110);
cairo_line_to (cr, 240,70);
cairo_line_to (cr, 110,210);
cairo_line_to (cr, 140,25);
cairo_line_to (cr, 230,200);
cairo_close_path(cr);
cairo_new_sub_path(cr);
cairo_arc(cr, 190,50,20,0,2*3.1415926);
cairo_close_path(cr);
cairo::cairo_to_clipper(cr, pg, scaling);
clpr.AddPaths(pg, ptClip, true);
cairo_set_source_rgba(cr, 1, 0, 0, 0.25);
cairo_fill_preserve (cr);
cairo_set_source_rgba(cr, 0, 0, 0, 0.5);
cairo_stroke (cr);
clpr.Execute(ctIntersection, pg, pftNonZero, pftNonZero);
//now do something fancy with the returned polygons ...
OffsetPaths(pg, pg, offsetVal * std::pow((double)10,scaling), jtMiter, etClosed);
//finally copy the clipped path back to the cairo context and draw it ...
cairo::clipper_to_cairo(pg, cr, scaling);
cairo_set_source_rgba(cr, 1, 1, 0, 1);
cairo_fill_preserve (cr);
cairo_set_source_rgba(cr, 0, 0, 0, 1);
cairo_stroke (cr);
cairo_text_extents_t extent;
cairo_set_font_size(cr,11);
std::stringstream ss;
ss << "Polygon offset = " << offsetVal << ". (Adjust with arrow keys)";
std::string s = ss.str();
cairo_text_extents(cr, s.c_str(), &extent);
cairo_move_to(cr, 10, rec.bottom - extent.height);
cairo_show_text(cr, s.c_str());
cairo_destroy (cr);
cairo_surface_destroy (surface);
}
//------------------------------------------------------------------------------
LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC Handle;
switch(Msg)
{
case WM_DESTROY:
PostQuitMessage(WM_QUIT);
return 0;
case WM_PAINT:
Handle = BeginPaint(hWnd, &ps);
OnPaint(hWnd, Handle);
EndPaint(hWnd, &ps);
return 0;
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
case VK_RIGHT:
case VK_UP:
if (offsetVal < 20) offsetVal++;
InvalidateRect(hWnd, 0, false);
return 0;
case VK_LEFT:
case VK_DOWN:
if (offsetVal > -20) offsetVal--;
InvalidateRect(hWnd, 0, false);
return 0;
default:
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
default:
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
}
//---------------------------------------------------------------------------

View file

@ -0,0 +1,13 @@
prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=@CMAKE_INSTALL_LIBDIR@
sharedlibdir=@CMAKE_INSTALL_LIBDIR@
includedir=@CMAKE_INSTALL_INCDIR@
Name: polyclipping
Description: polygon clipping library
Version: @VERSION@
Requires:
Libs: -L${libdir} -L${sharedlibdir} -lpolyclipping
Cflags: -I${includedir}