geometry-4.0.0/ 0000755 0000000 0000000 00000000000 13615712371 011542 5 ustar 00 0000000 0000000 geometry-4.0.0/COPYING 0000644 0000000 0000000 00000104513 13615712371 012601 0 ustar 00 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
geometry-4.0.0/DESCRIPTION 0000644 0000000 0000000 00000000711 13615712371 013247 0 ustar 00 0000000 0000000 Name: geometry
Version: 4.0.0
Date: 03-02-2020
Author: Juan Pablo Carbajal ,
Philip Nienhuis ,
Simeon Simeonov ,
Maintainer: Juan Pablo Carbajal
Title: Computational Geometry
Description: Library for extending MatGeom functionality.
Depends: octave (>= 4.2.0), matgeom (>= 1.0.0)
Autoload: no
License: GPLv3+, Boost v1.0
Url: https://octave.sourceforge.io/geometry/
geometry-4.0.0/INDEX 0000644 0000000 0000000 00000001254 13615712371 012336 0 ustar 00 0000000 0000000 geometry >> Computational Geometry
2D Polylines
clipPolyline
clipPolyline_clipper
simplifyPolyline_geometry
2D Ellipses
cov2ellipse
ellipse2cov
2D Polygons
clipPolygon
clipPolygon_clipper
clipPolygon_mrf
drawFilledPolygon
ispolycw
ispolyccw
isPolygonCCW
isPolygonCW_Clipper
joinPolygons
orientPolygon
polygon2patch
polygon2shape
poly2ccw
poly2cw
simplifyPolygon_geometry
2D Piecewise polynomial shapes
curveval
curve2polyline
plotShape
polygon2shape
shape2polygon
shapeCentroid
transformShape
2D Others
beltProblem
Input [broken]
@svg/svg
@svg/plot
@svg/getpath
@svg/path2polygon
@svg/normalize
@svg/pathid
@svg/height
@svg/width
Output
data2geo
geometry-4.0.0/NEWS 0000644 0000000 0000000 00000036235 13615712371 012252 0 ustar 00 0000000 0000000 Summary of important user-visible changes for releases of the geometry package
===============================================================================
geometry-4.0.0 Release Date: 03-02-2020 Release Manager: Juan Pablo Carbajal
===============================================================================
As of this version, geometry does not contain any matgeom functionality.
It contains all the extra functions that we have been adding to geometry,
in particular matlab compatible functionality for the mapping package.
It might need that you do not need geometry anymore and instead you need to
install matgeom to get the functionality you were using.
Geometry was an attempt to port MatGeom (a geometry package developed
for Matlab) to Octave, improving docstrings and updating to octave's special
features when possible.
Over time it became almost impossible to keep geometry in sync with the
upstream developments of MatGeom.
Hence I have decided to separate matgeom from geometry.
My apologize for the troubles caused, this is the way I learn, by doing.
Moreover, the @svg class is not working anymore. I leave it in the package
but it should be considered broken. Will fix in future versions.
** Functions have been modified
clipPolygon:
- Accepts boolean operation as strings or as integer.
- Accepts a box [xmin xmax ymin ymax] as clipping polygon.
** Added Functions
drawFilledPolygon
===============================================================================
geometry-3.0.0 Release Date: 27-03-2017 Release Manager: Juan Pablo Carbajal
===============================================================================
This version of the package is not backward compatible for the following
reasons:
** Functions have changed their name
beltproblem --> beltProblem
closed_path --> closedPath
shapearea --> shapeArea
shapecentroid --> shapeCentroid
shapeplot --> plotShape
shapetransform --> transformShape
simplifypolygon --> simplifyPoligon
simplifyPolyline --> simplifyPolyline
** Functions that are in GNU Octave core since 4.0.1
rad2deg deg2rad
** Added Functions
isAxisHandle isPolygonCCW isPolygonCW_Clipper joinPolygons polygon2patch
orientPolygon boundedVoronoi2d drawGraphEdges clipGraph grAdjacentEdges
grAdjacentNodes grEdgeLengths centroidalVoronoi2d clipGraphPolygon
cvtUpdate intersectEdgePolygon intersectLinePolygon isPointInPolygon
polygonBounds polygonContains convexHull minimumCaliperDiameter
grShortestPath drawNodeLabels nndist createRotation3dLineAngle drawPlane3d
rotation3dAxisAndAngle boxToMesh checkMeshAdjacentFaces
clipConvexPolyhedronHP clipMeshVertices createDodecahedron
createDurerPolyhedron createIcosahedron createMengerSponge createOctahedron
createRhombododecahedron createSoccerBall createTetrahedron
createTetrakaidecahedron cylinderMesh drawFaceNormals drawPolyhedron
ellipsoidMesh faceCentroids faceNormal intersectLineMesh3d intersectPlaneMesh
mergeCoplanarFaces meshAdjacencyMatrix meshDihedralAngles meshEdgeFaces
meshEdgeLength meshEdges meshFace meshFaceAdjacency meshFaceEdges
meshFaceNumber meshFacePolygons meshSurfaceArea meshVolume minConvexHull
polyhedra polyhedronCentroid polyhedronMeanBreadth polyhedronNormalAngle
polyhedronSlice readMesh_off removeMeshVertices smoothMesh sphereMesh
steinerPolytope subdivideMesh surfToMesh tetrahedronVolume torusMesh
triangulateFaces trimMesh trimeshEdgeFaces trimeshMeanBreadth
trimeshSurfaceArea vertexNormal distancePoints clipLine3d
drawLine3d eulerAnglesToRotation3d intersectLineSphere linePosition3d
recenterTransform3d transformLine3d transformVector3d intersectPolylines
clipPolyline clipPolyline_clipper clipPolygon clipPolygon_clipper
** Improved Functions
drawPolygon is more efficent when drawing polygons in cells and now it takes
an axis handle as first argument (optional). Added demo and tests
intersectEdges accepts tolerance as third argument
polygon2patch demo fixed, missing third argument for patch.
===============================================================================
geometry-2.1.1 Release Date: 2016-03-24 Release Manager: Juan Pablo Carbajal
===============================================================================
** Added Functions
fillPolygon rectAsPolygon
** Improved Functions
drawShape was not working due to missing functions. they have all been added
now.
==============================================================================
geometry-2.1.0 Release Date: 2016-02-04 Release Manager: Juan Pablo Carbajal
===============================================================================
** Added Functions
projPointOnPolyline: the function is added for compatibility, but it is just
a wrapper of distancePointPolyline.
findClosestPoint
** Improved Functions
distancePointPolyline is now updated with a spee dup of 100x. It also calculates
the projections, so projPointOnPolyline is obsolete.
===============================================================================
geometry-2.0.0 Release Date: 2015-04-27 Release Manager: Juan Pablo Carbajal
===============================================================================
** Geometry 2.0.0 is not compatible with versions of octave older
than 4.0. Thi si due to inputParser being used in the functions
curve2polyline, cov2ellipse and simplifypolyline. If you do not
need this functions you should no problems using octave > 3.6.0
** Removed functions
oc_polybol is not part of geomtry anymore. This function is part of
the octclip package.
** Added Functions
planePoint
** Bug Fixes:
- polynomialCurveSetFit had debug entries, now removed.
** Other changes:
- closed_path demo code was improved.
===============================================================================
geometry-1.7.0 Release Date: 2013-04-07 Release Manager: Juan Pablo Carbajal
===============================================================================
** Added Functions
box3dVolume cart2cyl circle3dPoint cyl2cart
drawCircle3d drawPoint3d createScaling3d drawCube
createCube drawSphericalTriangle drawTorus revolutionSurface
drawVector3d spheres drawPolyline drawPolynomialCurve
polynomialCurveCentroid polynomialCurveDerivative
polynomialCurveFit polynomialCurvePoint polynomialCurveSetFit
polygonPoint polygonSubcurve
** Bug Fixes:
- cov2ellipse scale and orientation of axis.
===============================================================================
geometry-1.6.0 Release Date: 2012-10-12 Release Manager: Juan Pablo Carbajal
===============================================================================
** geometry doesn't autoloads anymore
** Added Functions
anglePoints3d angles3d boxes3d geom3d_Contents
lines3d planes3d points3d polygons3d vectors3d
graphs_Contents meshes3d_Contents angleSort3d createPlane
intersectLinePlane normalizePlane planeNormal planePosition
projPointOnPlane sph2cart2 vectorAngle3d distancePointLine3d
cart2sph2d createRotationOx createRotationOy createRotationOz
createTranslation3d drawAxis3d drawCylinder drawSphere
polygonArea3d transformPoint3d drawBox3d drawEdge3d drawMesh
createCubeOctahedron boundingBox3d cart2sph2 circle3dOrigin
circle3dPosition drawCircleArc3d drawPolygon3d drawSphericalEdge
drawSphericalPolygon intersectPlaneSphere sph2cart2d
** Updated functions
distancePoints
** Bug Fixes:
- drawArrow was not working due to porting errors.
===============================================================================
geometry-1.5.0 Release Date: 2012-06-05 Release Manager: Juan Pablo Carbajal
===============================================================================
* Added functions:
- cov2ellipse & ellipse2cov: transform between ellipses and covariances matrices.
- beltproblem : Finds the four lines tangent to two circles with given centers and
radii. This is the solution to the belt problem in 2D.
- curveval : Evaluates a polynomial curve defined as a 2-by-N matrix.
- curve2polyline : Converts a polynomial curve into a polyline by the adaptive
sampling method.
- simplifypolyline : Ramer-Douglas-Peucker algorithm to simplify polylines.
- parametrize : Estimate a parametrization of a polygon/line based on the distance
between the points.
- curvature : Estimation of the curvature of a polygon/line based on polynomial
approximation.
- reversePolygon and reversePolyline : reverse the orders of the points in
of polygon/line.
- supportFunction : Compute support function of a polygon.
- distancePointPolygon , distancePointPolyline , distancePolygons ,
expandPolygon , medialAxisConvex , polygonLoops , polygonSelfIntersections
polylineSelfIntersections , splitPolygons
- close_path : given a set of points in the plane calculate a piecewise linear
simple path that passes through all points.
* Changed functions:
- distancePointEdge : Now the function computes the distance between all points
and all edges. A third optional argument provides
backward compatibility.
* Solved bugs:
- simplifypolygon returned empty polygons when points are repeated, i.e when
the polygon is not correctly formed.
- Removed installation warnings.
===============================================================================
geometry-1.4.1 Release Date: 2012-03-24 Release Manager: Juan Pablo Carbajal
===============================================================================
* Renamed functions
- Contents renamed to geom2d_Contents to avoid clashes.
* Deprecated functions
- svgload, svgnormalize, svgpath2polygon: Use the methods in class svg.
* Bug fixes
- @svg/path2polygon
- Fix addpath/rmpath installation warnings
- Fix octclip/src/Makefile
- Fix shapecentriod for piece-wise polynomial shapes.
* Known issues
- simplifypolygon returns empty polygons when points are repeated, i.e when
the polygon is not correctly formed.
===============================================================================
geometry-1.4.0 Release Date: 2012-01-25 Release Manager: Juan Pablo Carbajal
===============================================================================
* Added basic geometric graphs creation and manipulation.
===============================================================================
geometry-1.3.0 Release Date: 2011-11-24 Release Manager: Juan Pablo Carbajal
===============================================================================
* Geometry merged with octCLIP.
* Geometry autoloads.
===============================================================================
geometry-1.2.2 Release Date: 2011-11-04 Release Manager: Juan Pablo Carbajal
===============================================================================
* Improved SVG interface. Thanks to jwe and carandraug.
* Adding files to manipulate and convert 2D shapes defined with smooth
polynomials.
shape2polygon
shapearea
shapecentroid
shapeplot
shapetransform
* Inverted the order in the NEWS file. New entries are on top.
===============================================================================
geometry-1.2.1 Release Date: 2011-11-02 Release Manager: Juan Pablo Carbajal
===============================================================================
* Adding SVG object and demo for data2geom (converting SVG to msh format)
===============================================================================
geometry-1.2.0 Release Date: 2011-10-21 Release Manager: Juan Pablo Carbajal
===============================================================================
* All geom2d added
createCircle
createDirectedCircle
createEdge
medianLine
Contents
bisector
cartesianLine
drawArrow
edges2d
lines2d
orthogonalLine
parallelLine
projPointOnLine
drawCenteredEdge
drawCircle
drawCircleArc
drawEllipse
drawEllipseArc
drawLabels
drawOrientedBox
drawParabola
drawRect
drawShape
circles2d
ellipses2d
createVector
inertiaEllipse
changelog.txt
readme.txt
hexagonalGrid
squareGrid
triangleGrid
intersectCircles
intersectEdges
intersectLineCircle
isLeftOriented
isPointInCircle
isPointInEllipse
isPointOnCircle
isPointOnLine
edgeLength
edgePosition
edgeToLine
circleArcAsCurve
circleAsPolygon
crackPattern
crackPattern2
distancePointEdge
distancePointLine
ellipseAsPolygon
enclosingCircle
radicalAxis
reverseEdge
reverseLine
===============================================================================
geometry-1.1.3 Release Date: 2011-10-13 Release Manager: Juan Pablo Carbajal
===============================================================================
* Continue to add geom2d from matGeom (transforms and points2d)
createBasisTransform
createHomothecy
createLineReflection
createRotation
createScaling
createTranslation
transformPoint
transforms2d
fitAffineTransform2d
transformEdge
transformLine
centroid
distancePoints
midPoint
polarPoint
drawPoint
isCounterClockwise
minDistancePoints
pointOnLine
points2d
intersectLineEdge
isPointOnEdge
===============================================================================
geometry-1.1.2 Release Date: 2011-10-09 Release Manager: Juan Pablo Carbajal
===============================================================================
* Continue to add geom2d from matGeom (rays and vectors)
createRay
drawEdge
drawRay
isParallel
isPerpendicular
isPointOnRay
normalizeVector
rays2d
rotateVector
transformVector
vectorNorm
vectors2d
===============================================================================
geometry-1.1.1 Release Date: 2011-10-06 Release Manager: Juan Pablo Carbajal
===============================================================================
* Continue to add geom2d from matGeom (boxes and clips)
cbezier2poly
boxes2d
clipEdge
clipLine
clipPoints
drawBezierCurve
drawBox
clipRay
intersectBoxes
intersectLines
linePosition
mergeBoxes
randomPointInBox
drawLine
===============================================================================
geometry-1.1.0 Release Date: 2011-10-04 Release Manager: Juan Pablo Carbajal
===============================================================================
* Starting to add geom2d from matGeom
angle2Points
angle3Points
angleAbsDiff
angleDiff
angles2d
angleSort
createLine
deg2rad
edgeAngle
lineAngle
normalizeAngle
rad2deg
vectorAngle
===============================================================================
geometry-1.0.1 Release Date: 2011-09-27 Release Manager: Juan Pablo Carbajal
===============================================================================
Improvements to the docstrings of all functions.
===============================================================================
geometry-1.0.0 Release Date: 2011-09-26 Release Manager: Juan Pablo Carbajal
===============================================================================
** First official release.
===============================================================================
geometry-4.0.0/TODO 0000644 0000000 0000000 00000000174 13615712371 012234 0 ustar 00 0000000 0000000 * Bring back JuanPi's implementation of simplifyPolygon and simplifyPolyline ~ revision 522 or later
* Make svg work again
geometry-4.0.0/inst/ 0000755 0000000 0000000 00000000000 13615712371 012517 5 ustar 00 0000000 0000000 geometry-4.0.0/inst/@svg/ 0000755 0000000 0000000 00000000000 13615712371 013416 5 ustar 00 0000000 0000000 geometry-4.0.0/inst/@svg/display.m 0000644 0000000 0000000 00000001543 13615712371 015244 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
function display (obj)
fields = fieldnames (obj);
for i = 1 : numel(fields)
printf ("#s\n", fields{i});
obj.(fields{i})
end
endfunction
geometry-4.0.0/inst/@svg/getpath.m 0000644 0000000 0000000 00000004056 13615712371 015235 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Created: 2019-05-14
## -*- texinfo -*-
## @deftypefn {Function File} {@var{paths} = } getpath (@var{ids})
## Returns paths in @var{ids}.
##
## @end deftypefn
function paths = getpath(obj, varargin)
if !isempty(varargin)
ids = varargin;
if iscell (ids) && numel(ids) == 1 && iscell(ids{1}) # dealing with ids given as cell
ids = ids{1};
if !all ( cellfun (@ischar, ids) )
print_usage
end
elseif !all ( cellfun (@ischar, ids) )
print_usage
end
else
paths = obj.Path;
return
end
tf = ismember (ids, fieldnames (obj.Path));
cellfun (@(s) printf("'#s' is not a valid path id.\n", s) , {ids{!tf}});
paths = [];
if any (tf)
stuff = {ids{tf}};
for i = 1: numel(stuff)
paths{i} = obj.Path.(ids{i}).data;
endfor
# Variation
# paths = cellfun(@(s) obj.Path.(s).data, stuff,'UniformOutput',false);
# Another variation
# paths = cellfun(@(s) getfield(obj,'Path').(s).data, stuff,'UniformOutput',false);
# Yet another
# paths = cellfun(@(s) getfield(obj.Path,s).data, stuff,'UniformOutput',false);
# Yet yet another
# dummy = @(s) obj.Path.(s).data;
# paths = cellfun(dummy, stuff,'UniformOutput',false);
if numel(paths) == 1
paths = paths{1};
end
end
endfunction
geometry-4.0.0/inst/@svg/height.m 0000644 0000000 0000000 00000001550 13615712371 015045 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {} function_name ()
## @end deftypefn
function o = height(obj,varargin)
o = obj.Data.height;
endfunction
geometry-4.0.0/inst/@svg/inkex.py 0000644 0000000 0000000 00000020045 13615712371 015107 0 ustar 00 0000000 0000000 #!/usr/bin/env python3
"""
inkex.py
A helper module for creating Inkscape extensions
Copyright (C) 2005,2007 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see .
"""
import sys, copy, optparse, random, re
import gettext
from math import *
_ = gettext.gettext
#a dictionary of all of the xmlns prefixes in a standard inkscape doc
NSS = {
u'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
u'cc' :u'http://creativecommons.org/ns#',
u'ccOLD' :u'http://web.resource.org/cc/',
u'svg' :u'http://www.w3.org/2000/svg',
u'dc' :u'http://purl.org/dc/elements/1.1/',
u'rdf' :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
u'inkscape' :u'http://www.inkscape.org/namespaces/inkscape',
u'xlink' :u'http://www.w3.org/1999/xlink',
u'xml' :u'http://www.w3.org/XML/1998/namespace'
}
#a dictionary of unit to user unit conversion factors
uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'm':3543.3070866,
'km':3543307.0866, 'pc':15.0, 'yd':3240 , 'ft':1080}
def unittouu(string):
'''Returns userunits given a string representation of units in another system'''
unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
p = param.match(string)
u = unit.search(string)
if p:
retval = float(p.string[p.start():p.end()])
else:
retval = 0.0
if u:
try:
return retval * uuconv[u.string[u.start():u.end()]]
except KeyError:
pass
return retval
def uutounit(val, unit):
return val/uuconv[unit]
try:
from lxml import etree
except:
sys.exit(_('The fantastic lxml wrapper for libxml2 is required by inkex.py and therefore this extension. Please download and install the latest version from http://cheeseshop.python.org/pypi/lxml/, or install it through your package manager by a command like: sudo apt-get install python-lxml'))
def debug(what):
sys.stderr.write(str(what) + "\n")
return what
def errormsg(msg):
"""Intended for end-user-visible error messages.
(Currently just writes to stderr with an appended newline, but could do
something better in future: e.g. could add markup to distinguish error
messages from status messages or debugging output.)
Note that this should always be combined with translation:
import gettext
_ = gettext.gettext
...
inkex.errormsg(_("This extension requires two selected paths."))
"""
sys.stderr.write((unicode(msg) + "\n").encode("UTF-8"))
def check_inkbool(option, opt, value):
if str(value).capitalize() == 'True':
return True
elif str(value).capitalize() == 'False':
return False
else:
raise optparse.OptionValueError("option %s: invalid inkbool value: %s" % (opt, value))
def addNS(tag, ns=None):
val = tag
if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{':
val = "{%s}%s" % (NSS[ns], tag)
return val
class InkOption(optparse.Option):
TYPES = optparse.Option.TYPES + ("inkbool",)
TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
TYPE_CHECKER["inkbool"] = check_inkbool
class Effect:
"""A class for creating Inkscape SVG Effects"""
def __init__(self, *args, **kwargs):
self.document=None
self.ctx=None
self.selected={}
self.doc_ids={}
self.options=None
self.args=None
self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption)
self.OptionParser.add_option("--id",
action="append", type="string", dest="ids", default=[],
help="id attribute of object to manipulate")
def effect(self):
pass
def getoptions(self,args=sys.argv[1:]):
"""Collect command line arguments"""
self.options, self.args = self.OptionParser.parse_args(args)
def parse(self,file=None):
"""Parse document in specified file or on stdin"""
try:
try:
stream = open(file,'r')
except:
stream = open(self.svg_file,'r')
except:
stream = sys.stdin
self.document = etree.parse(stream)
stream.close()
def getposinlayer(self):
#defaults
self.current_layer = self.document.getroot()
self.view_center = (0.0,0.0)
layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS)
if layerattr:
layername = layerattr[0]
layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS)
if layer:
self.current_layer = layer[0]
xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS)
yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS)
doc_height = unittouu(self.document.getroot().get('height'))
if xattr and yattr:
x = xattr[0]
y = yattr[0]
if x and y:
self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape
def getselected(self):
"""Collect selected nodes"""
for i in self.options.ids:
path = '//*[@id="%s"]' % i
for node in self.document.xpath(path, namespaces=NSS):
self.selected[i] = node
def getElementById(self, id):
path = '//*[@id="%s"]' % id
el_list = self.document.xpath(path, namespaces=NSS)
if el_list:
return el_list[0]
else:
return None
def getParentNode(self, node):
for parent in self.document.getiterator():
if node in parent.getchildren():
return parent
break
def getdocids(self):
docIdNodes = self.document.xpath('//@id', namespaces=NSS)
for m in docIdNodes:
self.doc_ids[m] = 1
def getNamedView(self):
return self.document.xpath('//sodipodi:namedview', namespaces=NSS)[0]
def createGuide(self, posX, posY, angle):
atts = {
'position': str(posX)+','+str(posY),
'orientation': str(sin(radians(angle)))+','+str(-cos(radians(angle)))
}
guide = etree.SubElement(
self.getNamedView(),
addNS('guide','sodipodi'), atts )
return guide
def output(self):
"""Serialize document into XML on stdout"""
self.document.write(sys.stdout)
def affect(self, args=sys.argv[1:], output=True):
"""Affect an SVG document with a callback effect"""
self.svg_file = args[-1]
self.getoptions(args)
self.parse()
self.getposinlayer()
self.getselected()
self.getdocids()
self.effect()
if output: self.output()
def uniqueId(self, old_id, make_new_id = True):
new_id = old_id
if make_new_id:
while new_id in self.doc_ids:
new_id += random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
self.doc_ids[new_id] = 1
return new_id
def xpathSingle(self, path):
try:
retval = self.document.xpath(path, namespaces=NSS)[0]
except:
errormsg(_("No matching node for expression: %s") % path)
retval = None
return retval
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99
geometry-4.0.0/inst/@svg/loadpaths.m 0000644 0000000 0000000 00000005441 13615712371 015557 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
function Paths = loadpaths (obj, svg, varargin)
here = which ("@svg/loadpaths");
here = fileparts (here);
script = fullfile (here, 'parsePath.py');
## Call python script
if exist (svg,'file')
# read from file
[st str]=system (sprintf ('python3 %s %s', script, svg));
else
# inline SVG
[st str]=system (sprintf ('python3 %s < %s', script, svg));
end
## Parse ouput
strpath = strsplit (str(1:end-1), '$', true);
npaths = numel (strpath);
## Convert path data to polynoms
for ip = 1:npaths
eval (strpath{ip});
## FIXME: intialize struct with cell field
svgpath2.cmd = svgpath(1).cmd;
svgpath2.data = {svgpath.data};
nD = length(svgpath2.cmd);
pathdata = cell (nD-1,1);
point_end=[];
## If the path is closed, last command is Z and we set initial point == final
if svgpath2.cmd(end) == 'Z'
nD -= 1;
point_end = svgpath2.data{1};
svgpath2.data(end) = [];
end
## Initial point
points(1,:) = svgpath2.data{1};
for jp = 2:nD
switch svgpath2.cmd(jp)
case 'L'
## Straigth segment to polygon
points(2,:) = svgpath2.data{jp};
pp = [(points(2,:)-points(1,:))' points(1,:)'];
clear points
points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)];
case 'C'
## Cubic bezier to polygon
points(2:4,:) = reshape (svgpath2.data{jp}, 2, 3).';
pp = cubicBezierToPolyline (points);
clear points
points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)];
end
pathdata{jp-1} = pp;
end
if ~isempty(point_end)
## Straight segment to close the path
points(2,:) = point_end;
pp = [(points(2,:)-points(1,:))' points(1,:)'];
if all ( abs(pp(:,1)) < sqrt(eps) )
# Final point of last segment is already initial point
pathdata(end) = [];
else
pathdata{end} = pp;
end
end
## TODO
# pathdata = transformShape(pathdata);
Paths.(svgpathid).data = pathdata;
end
endfunction
geometry-4.0.0/inst/@svg/loadsvgdata.m 0000644 0000000 0000000 00000002260 13615712371 016065 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
function data = loadsvgdata (obj, svg, varargin)
here = which ("@svg/loadsvgdata");
here = fileparts (here);
script = fullfile (here, 'parseSVGData.py');
## Call python script
if exist (svg,'file')
# read from file
[st str]=system (sprintf ('python3 %s %s', script, svg));
else
# inline SVG
[st str]=system (sprintf ('python3 %s < %s', script, svg));
end
## Parse ouput
strdata = strsplit (str(1:end-1), '$', true);
eval (strdata{1});
endfunction
geometry-4.0.0/inst/@svg/normalize.m 0000644 0000000 0000000 00000005671 13615712371 015605 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{SVGn} = normalize (@var{SVG})
## normalizes and SVG.
## @end deftypefn
function [SVGn bb] = normalize (obj)
SVGn = obj;
bb = [];
if ! obj.Data.normalized
ids = fieldnames (obj.Path);
npath = numel(ids);
v = zeros(npath,2);
bb = zeros(1,4);
for ip = 1:npath
v(ip,:) = shapeCentroid(obj.Path.(ids{ip}).data);
p = shape2polygon(obj.Path.(ids{ip}).data);
bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4]));
end
if npath > 1
v = mean(v)(:);
else
v = v.';
end
## check whether document and bounding box agree.
bbHeight = bb(2)-bb(1);
bbWidth = bb(4)-bb(2);
if obj.Data.height != bbHeight
warning("svg:normalize:Sanitycheck",...
["Height of SVG #g and height boundingbox #g don't match.\n" ...
"Using bounding box.\n"],obj.Data.height,bbHeight)
end
if obj.Data.width != bbWidth
warning("svg:normalize:Sanitycheck",...
["Width of SVG #g and width boundingbox #g don't match.\n" ...
"Using bounding box.\n"],obj.Data.width,bbWidth)
end
## Move paths such that center of SVG is at 0,0
## Put coordinates in the usual frame
## Scale such that diagonal of bounding box is 1
Dnorm = sqrt (bbWidth ^ 2 + bbHeight ^ 2);
S = (1 / Dnorm) * eye (2);
bb = zeros(1,4);
for ip = 1:npath
SVGn.Path.(ids{ip}).data = transformShape(obj.Path.(ids{ip}).data,-v);
# Put to middle
SVGn.Path.(ids{ip}).data = ...
transformShape(SVGn.Path.(ids{ip}).data,[0; -bbHeight/2]);
# Reflect y
SVGn.Path.(ids{ip}).data = ...
transformShape(SVGn.Path.(ids{ip}).data,[1 0;0 -1]);
# Put to bottom
SVGn.Path.(ids{ip}).data = ...
transformShape(SVGn.Path.(ids{ip}).data,[0; bbHeight/2]);
# Scale
SVGn.Path.(ids{ip}).data = ...
transformShape(SVGn.Path.(ids{ip}).data,S);
p = shape2polygon(SVGn.Path.(ids{ip}).data);
bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4]));
end
bbHeight = bb(2)-bb(1);
bbWidth = bb(4)-bb(2);
SVGn.Data.height = bbHeight;
SVGn.Data.width = bbWidth;
SVGn.Data.normalized = true;
end
end
geometry-4.0.0/inst/@svg/parsePath.py 0000644 0000000 0000000 00000004220 13615712371 015715 0 ustar 00 0000000 0000000 #!/usr/bin/env python3
## Copyright (c) 2012 Juan Pablo Carbajal
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
import inkex, simplepath
import sys
#import getopt
def parsePaths (filen=None):
svg = inkex.Effect ()
svg.parse (filen)
paths = svg.document.xpath ('//svg:path', namespaces=inkex.NSS)
for path in paths:
D = simplepath.parsePath (path.attrib['d'])
cmdlst = [];
parlst = [];
for cmd,params in D:
cmdlst.append(cmd)
parlst.append(params)
print ('svgpath = struct("cmd","{0}","data",{{{1}}});'
.format(''.join(cmdlst),str(parlst).replace('[[','[').replace(']]',']')))
print ('svgpathid = "{0}"; $'.format(path.attrib['id']))
# ----------------------------
if __name__=="__main__":
'''
try:
optlist,args = getopt.getopt(sys.argv[1:],"thdp")
except getopt.GetoptError:
usage()
sys.exit(2)
doHelp = 0
c = Context()
c.doPrint = 1
for opt in optlist:
if opt[0] == "-d": c.debug = 1
if opt[0] == "-p": c.plot = 1
if opt[0] == "-t": c.triangulate = 1
if opt[0] == "-h": doHelp = 1
if not doHelp:
pts = []
fp = sys.stdin
if len(args) > 0:
fp = open(args[0],'r')
for line in fp:
fld = line.split()
x = float(fld[0])
y = float(fld[1])
pts.append(Site(x,y))
if len(args) > 0: fp.close()
if doHelp or len(pts) == 0:
usage()
sys.exit(2)
'''
svg = sys.argv[1]
parsePaths(svg)
geometry-4.0.0/inst/@svg/parseSVGData.py 0000644 0000000 0000000 00000002326 13615712371 016257 0 ustar 00 0000000 0000000 #!/usr/bin/env python3
## Copyright (c) 2012 Juan Pablo Carbajal
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
import inkex
import sys
#import getopt
def parseSVGData (filen=None):
svg = inkex.Effect ()
svg.parse (filen)
root = svg.document.xpath ('//svg:svg', namespaces=inkex.NSS)
print ('data = struct("height",{0},"width",{1},"id","{2}");'
.format(root[0].attrib['height'],root[0].attrib['width'],
root[0].attrib['id']))
# ----------------------------
if __name__=="__main__":
svg = sys.argv[1]
parseSVGData(svg)
geometry-4.0.0/inst/@svg/path2polygon.m 0000644 0000000 0000000 00000003006 13615712371 016221 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @defun {@var{P} =} path2polygon (@var{id})
## @defunx {@var{P} =} path2polygon (@var{id}, @var{n})
## Converts the SVG path to an array of polygons.
## @end defun
function P = path2polygon (obj, id)
P = shape2polygon (getpath (obj, id));
endfunction
#{
pd = obj.Path.(id).data;
P = cellfun(@(x)convertpath(x,n),pd,'UniformOutput',false);
P = cell2mat(P);
end
function p = convertpath(x,np)
n = size(x,2);
switch n
case 2
p = zeros(2,2);
# Straight segment
p(:,1) = polyval (x(1,:), [0; 1]);
p(:,2) = polyval (x(2,:), [0; 1]);
case 4
p = zeros(np,2);
# Cubic bezier
t = linspace (0, 1, np).';
p(:,1) = polyval (x(1,:),t);
p(:,2) = polyval (x(2,:),t);
end
end
#}
geometry-4.0.0/inst/@svg/pathid.m 0000644 0000000 0000000 00000001562 13615712371 015051 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {} function_name ()
## @end deftypefn
function ids = pathid(obj,varargin)
ids = fieldnames (obj.Path);
endfunction
geometry-4.0.0/inst/@svg/plot.m 0000644 0000000 0000000 00000002601 13615712371 014551 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {@var{h} = } plot ()
## Plots and SVG object.
##
## @end deftypefn
function h = plot(obj, varargin)
# Get path ids
ids = fieldnames(obj.Path);
npath = numel(ids);
t = linspace (0, 1, 64);
args={};
if !isempty (varargin)
args = varargin;
end
holded = false;
if ~ishold(gca)
hold on;
holded = true;
end
for i = 1:npath
x = []; y = [];
data = obj.Path.(ids{i}).data;
for j = 1:numel(data)
x = cat (2, x, polyval (data{j}(1,:),t));
y = cat (2, y, polyval (data{j}(2,:),t));
end
h = plot(x,y,args{:});
end
if holded
hold off
end
axis tight
axis equal
endfunction
geometry-4.0.0/inst/@svg/simplepath.py 0000644 0000000 0000000 00000015467 13615712371 016153 0 ustar 00 0000000 0000000 #!/usr/bin/env python3
"""
simplepath.py
functions for digesting paths into a simple list structure
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see .
"""
import re, math
def lexPath(d):
"""
returns and iterator that breaks path data
identifies command and parameter tokens
"""
offset = 0
length = len(d)
delim = re.compile(r'[ \t\r\n,]+')
command = re.compile(r'[MLHVCSQTAZmlhvcsqtaz]')
parameter = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')
while 1:
m = delim.match(d, offset)
if m:
offset = m.end()
if offset >= length:
break
m = command.match(d, offset)
if m:
yield [d[offset:m.end()], True]
offset = m.end()
continue
m = parameter.match(d, offset)
if m:
yield [d[offset:m.end()], False]
offset = m.end()
continue
#TODO: create new exception
raise Exception ('Invalid path data!')
'''
pathdefs = {commandfamily:
[
implicitnext,
#params,
[casts,cast,cast],
[coord type,x,y,0]
]}
'''
pathdefs = {
'M':['L', 2, [float, float], ['x','y']],
'L':['L', 2, [float, float], ['x','y']],
'H':['H', 1, [float], ['x']],
'V':['V', 1, [float], ['y']],
'C':['C', 6, [float, float, float, float, float, float], ['x','y','x','y','x','y']],
'S':['S', 4, [float, float, float, float], ['x','y','x','y']],
'Q':['Q', 4, [float, float, float, float], ['x','y','x','y']],
'T':['T', 2, [float, float], ['x','y']],
'A':['A', 7, [float, float, float, int, int, float, float], ['r','r','a',0,'s','x','y']],
'Z':['L', 0, [], []]
}
def parsePath(d):
"""
Parse SVG path and return an array of segments.
Removes all shorthand notation.
Converts coordinates to absolute.
"""
retval = []
lexer = lexPath(d)
pen = (0.0,0.0)
subPathStart = pen
lastControl = pen
lastCommand = ''
while 1:
try:
token, isCommand = next (lexer)
except StopIteration:
break
params = []
needParam = True
if isCommand:
if not lastCommand and token.upper() != 'M':
raise Exception ('Invalid path, must begin with moveto.')
else:
command = token
else:
#command was omited
#use last command's implicit next command
needParam = False
if lastCommand:
if lastCommand.isupper():
command = pathdefs[lastCommand][0]
else:
command = pathdefs[lastCommand.upper()][0].lower()
else:
raise Exception ('Invalid path, no initial command.')
numParams = pathdefs[command.upper()][1]
while numParams > 0:
if needParam:
try:
token, isCommand = next (lexer)
if isCommand:
raise Exception ('Invalid number of parameters')
except StopIteration:
raise Exception ('Unexpected end of path')
cast = pathdefs[command.upper()][2][-numParams]
param = cast(token)
if command.islower():
if pathdefs[command.upper()][3][-numParams]=='x':
param += pen[0]
elif pathdefs[command.upper()][3][-numParams]=='y':
param += pen[1]
params.append(param)
needParam = True
numParams -= 1
#segment is now absolute so
outputCommand = command.upper()
#Flesh out shortcut notation
if outputCommand in ('H','V'):
if outputCommand == 'H':
params.append(pen[1])
if outputCommand == 'V':
params.insert(0,pen[0])
outputCommand = 'L'
if outputCommand in ('S','T'):
params.insert(0,pen[1]+(pen[1]-lastControl[1]))
params.insert(0,pen[0]+(pen[0]-lastControl[0]))
if outputCommand == 'S':
outputCommand = 'C'
if outputCommand == 'T':
outputCommand = 'Q'
#current values become "last" values
if outputCommand == 'M':
subPathStart = tuple(params[0:2])
pen = subPathStart
if outputCommand == 'Z':
pen = subPathStart
else:
pen = tuple(params[-2:])
if outputCommand in ('Q','C'):
lastControl = tuple(params[-4:-2])
else:
lastControl = pen
lastCommand = command
retval.append([outputCommand,params])
return retval
def formatPath(a):
"""Format SVG path data from an array"""
return "".join([cmd + " ".join([str(p) for p in params]) for cmd, params in a])
def translatePath(p, x, y):
for cmd,params in p:
defs = pathdefs[cmd]
for i in range(defs[1]):
if defs[3][i] == 'x':
params[i] += x
elif defs[3][i] == 'y':
params[i] += y
def scalePath(p, x, y):
for cmd,params in p:
defs = pathdefs[cmd]
for i in range(defs[1]):
if defs[3][i] == 'x':
params[i] *= x
elif defs[3][i] == 'y':
params[i] *= y
elif defs[3][i] == 'r': # radius parameter
params[i] *= x
elif defs[3][i] == 's': # sweep-flag parameter
if x*y < 0:
params[i] = 1 - params[i]
elif defs[3][i] == 'a': # x-axis-rotation angle
if y < 0:
params[i] = - params[i]
def rotatePath(p, a, cx = 0, cy = 0):
if a == 0:
return p
for cmd,params in p:
defs = pathdefs[cmd]
for i in range(defs[1]):
if defs[3][i] == 'x':
x = params[i] - cx
y = params[i + 1] - cy
r = math.sqrt((x**2) + (y**2))
if r != 0:
theta = math.atan2(y, x) + a
params[i] = (r * math.cos(theta)) + cx
params[i + 1] = (r * math.sin(theta)) + cy
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99
geometry-4.0.0/inst/@svg/subsref.m 0000644 0000000 0000000 00000004717 13615712371 015256 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {} function_name ()
## @end deftypefn
function varargout = subsref (obj, idx)
persistent __method__ method4field typeNotImplemented
if isempty(__method__)
__method__ = struct();
__method__.plot = @(o,varargin) plot (o, varargin{:});
__method__.getpath = @(o,varargin) getpath (o, varargin{:});
__method__.pathid = @(o,varargin) pathid(o,varargin{:});
__method__.path2polygon = @(o,varargin) path2polygon (o, varargin{:});
__method__.normalize = @(o,varargin) normalize (o, varargin{:});
__method__.height = @(o,varargin) height(o, varargin{:});
__method__.width = @(o,varargin) width(o,varargin{:});
# Error strings
method4field = "Class #s has no field #s. Use #s() for the method.";
typeNotImplemented = "#s no implemented for class #s.";
end
if ( !strcmp (class (obj), 'svg') )
error ("Object must be of the svg class but '#s' was used", class (obj) );
elseif ( idx(1).type != '.' )
error ("Invalid index for class #s", class (obj) );
endif
method = idx(1).subs;
if ~isfield(__method__, method)
error('Unknown method #s.',method);
else
fhandle = __method__.(method);
end
if strcmp(method,'normalize')
warning("svg:Devel",["Not returning second output argument of #s" ...
" use method(obj) API to get it"],method);
end
if numel (idx) == 1 # can't access properties, only methods
error (method4field, class (obj), method, method);
end
if strcmp (idx(2).type, '()')
args = idx(2).subs;
if isempty(args)
out = fhandle (obj);
else
out = fhandle (obj, args{:});
end
varargout{1} = out;
else
error (typeNotImplemented,[method idx(2).type], class (obj));
end
endfunction
geometry-4.0.0/inst/@svg/svg.m 0000644 0000000 0000000 00000005051 13615712371 014374 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @deftypefn {Function File} {@var{obj} =} svg ()
## @deftypefnx {Function File} {@var{obj} =} svg (@var{str})
## Create object of the svg class.
##
## If no input argument is provided the object is empty. @var{str} can be a filename
## or a string defining an inline SVG.
##
## @end deftypefn
function svg = svg(name='')
svg = struct;
## SVG data. All the attributes of the node.
## The field unparsed contains all the attributes that are not being parsed.
svg.Data = struct('height',[],'width',[],'id','null','normalized',false);
## SVG metadata. All the attributes of the node.
## The field unparsed contains all the attributes that are not being parsed.
svg.Metadata = struct('unparsed',' ');
## SVG paths. It is a vector of path structs. Maybe path can be a object too?
## Order of Path.Data is important so we store in a cell (could be a matrix padded with zeros).
## All the paths stored in polyval compatible format. Straigth segments are also stored as a polynomial.
svg.Path = struct();
svg = class (svg, 'svg');
if !isempty (name)
if exist(name,"file") == 2
name = file_in_path(path(), name);
else
error("svg:BadArguemnt", "File %s doesn't exist",name);
end
svg.Path = loadpaths(svg, name);
svg.Data = loadsvgdata(svg, name);
svg.Data.normalized = false;
elseif !ischar(name)
print_usage ;
endif
endfunction
%!test
%! dc = svg('drawing5.svg');
%! dc.getpath();
%! dc.pathid();
%! dc.getpath('path3756');
%!
%! dc = svg('drawing.svg');
%! ids = dc.pathid();
%! dc.getpath({ids{[1 3]}});
%!test
%! dc = svg('drawing6.svg');
%! ids = dc.pathid();
%! P = dc.path2polygon(ids{1});
%!test
%! dc = svg('drawing6.svg');
%! dc.plot();
%! dc.plot('color','r','linewidth',2);
geometry-4.0.0/inst/@svg/width.m 0000644 0000000 0000000 00000001546 13615712371 014721 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {} function_name ()
## @end deftypefn
function o = width(obj,varargin)
o = obj.Data.width;
endfunction
geometry-4.0.0/inst/beltProblem.m 0000644 0000000 0000000 00000010405 13615712371 015144 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @deftypefn {Function File} {[@var{tangent},@var{inner}] = } beltProblem (@var{c}, @var{r})
## Finds the four lines tangent to two circles with given centers and radii.
##
## The function solves the belt problem in 2D for circles with center @var{c} and
## radii @var{r}.
##
## @strong{INPUT}
## @table @var
## @item c
## 2-by-2 matrix containig coordinates of the centers of the circles; one row per circle.
## @item r
## 2-by-1 vector with the radii of the circles.
##@end table
##
## @strong{OUPUT}
## @table @var
## @item tangent
## 4-by-4 matrix with the points of tangency. Each row describes a segment(edge).
## @item inner
## 4-by-2 vector with the point of intersection of the inner tangents (crossed belts)
## with the segment that joins the centers of the two circles. If
## the i-th edge is not an inner tangent then @code{inner(i,:)=[NaN,NaN]}.
## @end table
##
## Example:
##
## @example
## c = [0 0;1 3];
## r = [1 0.5];
## [T inner] = beltProblem(c,r)
## @result{} T =
## -0.68516 0.72839 1.34258 2.63581
## 0.98516 0.17161 0.50742 2.91419
## 0.98675 -0.16225 1.49338 2.91888
## -0.88675 0.46225 0.55663 3.23112
##
## @result{} inner =
## 0.66667 2.00000
## 0.66667 2.00000
## NaN NaN
## NaN NaN
##
## @end example
##
## @seealso{edges2d}
## @end deftypefn
function [edgeTan inner] = beltProblem(c,r)
x0 = [c(1,1) c(1,2) c(2,1) c(2,2)];
r0 = r([1 1 2 2]);
middleEdge = createEdge(c(1,:),c(2,:));
ind0 = [1 0 1 0; 0 1 1 0; 1 1 1 0; -1 0 1 0; 0 -1 1 0; -1 -1 1 0;...
1 0 0 1; 0 1 0 1; 1 1 0 1; -1 0 0 1; 0 -1 0 1; -1 -1 0 1;...
1 0 1 1; 0 1 1 1; 1 1 1 1; -1 0 1 1; 0 -1 1 1; -1 -1 1 1;...
1 0 -1 0; 0 1 -1 0; 1 1 -1 0; -1 0 -1 0; 0 -1 -1 0; -1 -1 -1 0;...
1 0 0 -1; 0 1 0 -1; 1 1 0 -1; -1 0 0 -1; 0 -1 0 -1; -1 -1 0 -1;...
1 0 -1 -1; 0 1 -1 -1; 1 1 -1 -1; -1 0 -1 -1; 0 -1 -1 -1; -1 -1 -1 -1];
nInit = size(ind0,1);
ir = randperm(nInit);
edgeTan = zeros(4,4);
inner = zeros(4,2);
nSol = 0;
i=1;
## Solve for 2 different lines
while nSol<4 && i 1e-6);
end
if all(notequal)
nSol = nSol+1;
edgeTan(nSol,:) = createEdge(sol(1:2),sol(3:4));
# Find innerTangent
inner(nSol,:) = intersectEdges(middleEdge,edgeTan(nSol,:));
end
i = i+1;
end
# Sort to avoid random order of results
[~, order] = sort (sumsq (inner, 2));
inner = inner(order,:);
edgeTan = edgeTan(order,:);
endfunction
function res = belt(x,c,r)
res = zeros(4,1);
res(1,1) = (x(3:4) - c(2,1:2))*(x(3:4) - x(1:2))';
res(2,1) = (x(1:2) - c(1,1:2))*(x(3:4) - x(1:2))';
res(3,1) = sumsq(x(1:2) - c(1,1:2)) - r(1)^2;
res(4,1) = sumsq(x(3:4) - c(2,1:2)) - r(2)^2;
end
%!demo
%! c = [0 0;1 3];
%! r = [1 0.5];
%! [T inner] = beltProblem(c,r)
%!
%! figure(1)
%! clf
%! hold on
%! h = drawEdge (T);
%! set(h(find(~isnan(inner(:,1)))),'color','m');
%! set(h,'linewidth',2);
%! hold on
%! drawCircle([c(1,:) r(1); c(2,:) r(2)],'linewidth',2);
%! axis tight
%! axis equal
%!
%! # -------------------------------------------------------------------
%! # The circles with the tangents edges are plotted. The solution with
%! # crossed belts (inner tangets) is shown in red.
geometry-4.0.0/inst/clipPolygon.m 0000644 0000000 0000000 00000014460 13615712371 015201 0 ustar 00 0000000 0000000 ## Copyright (C) 2017 - 2019 Philip Nienhuis
## Copyright (C) 2017 - 2019 Juan Pablo Carbajal
## Copyright (C) 2017 - 2019 Piyush Jain
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op})
## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op}, @var{library})
## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon (@dots{}, @var{args})
## Perform boolean operation on polygon(s) using one of several algorithms.
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s)
## to be clipped (subject polygons). Polygons are separated by [NaN NaN] rows.
##
## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the
## clip polygon(s). @*
## @var{clippol} can also be a vector containing the bottom left and upper right
## coordinates of a clipping rectangle, or bounding box, in the format @*
## [xmin xmax ymin ymax].
##
## The argument @var{op}, the boolean operation, can be either an integer or a
## string. In the case of integer it should be between 0 and 3, correspoding to:
##
## @itemize
## @item 0: difference @var{inpol} - @var{clippol}
##
## @item 1: intersection ('AND') of @var{inpol} and @var{clippol} (= default)
##
## @item 2: exclusiveOR ('XOR') of @var{inpol} and @var{clippol}
##
## @item 3: union ('OR') of @var{inpol} and @var{clippol}
## @end itemize
##
## If @var{op} is a string should be one of @asis{'diff', 'and', 'xor', 'or'},
## the parsing of this option is case insensitive, i.e. @asis{'AND'} is the same
## as @asis{'and'}.
##
## The optional argument @var{library} specifies which library to use for clipping.
## Currently @asis{'clipper'} and @asis{'mrf'} are implemented. Option
## @asis{'clipper'} uses a MEX interface to the Clipper library, option
## @asis{'mrf'} uses the algorithm by Martinez, Rueda and Feito implemented
## with OCT files. @*
## Each library interprets polygons as holes differently, refer to the help
## of the specific function to learn how to pass polygons with holes.
##
## Output array @var{outpol} will be an Nx2 array of polygons resulting from
## the requested boolean operation, or in case of just one input argument an
## Nx1 array indicating winding direction of each subpolygon in input argument
## @var{inpol}.
##
## Optional output argument @var{npol} indicates the number of output polygons.
##
## @seealso{clipPolygon_clipper, clipPolygon_mrf, clipPolyline}
## @end deffn
## Author: Philip Nienhuis
## Created: 2017-03-21
function [opol, npol] = clipPolygon (inpol, clipol, op, library = 'clipper', varargin)
# Check number of required input arguments
if (nargin < 3)
print_usage ()
endif
if (any (size (clipol) == 1))
## Bottom left - upper right corner of clip rectangle input.
## Check if clipol geometry is acceptable.
if (clipol(1) >= clipol(2) || clipol(3) >= clipol(4))
error ('Octave:invalid-input-arg', ...
['clipPolygon: clip rectangle has zero or negative area - ' ...
'check coordinates']);
endif
clipol = reshape (clipol(:)', 2, []);
clipol = [clipol(1, :); clipol(1, :); clipol(2, :); clipol(2, :)];
clipol = [clipol(:, 1) circshift(clipol(:, 2), -1)];
op = 1;
endif
## Very basic input check. Other checks are in called functions.
if (size (inpol, 1) < 3 || size (clipol, 1) < 3)
error ('Octave:invalid-input-arg', ...
'clipPolygon: subject or clip polygons must have at least 3 vertices');
endif
## Parse operations given as strings
if (ischar (op) )
[~, op_] = ismember (tolower (op), {'diff', 'and', 'xor', 'or'});
if (op_ == 0) # wrong operation string
error ('Octave:invalid-input-arg', ...
'clipPolygon: operation "%s" unknown', op);
endif
op = op_ - 1;
endif
switch library
case 'clipper'
[opol, npol] = clipPolygon_clipper (inpol, clipol, op, varargin{:});
case 'mrf'
[opol, npol] = clipPolygon_mrf (inpol, clipol, op, varargin{:});
otherwise
error ('Octave:invalid-fun-call', ...
'clipPolygon: unimplemented polygon clipping library: "%s"', library);
endswitch
endfunction
%!error clipPolygon([],[],[],'abracadabra')
%!error clipPolygon([0 0; 0 1; 0.5 1],[-1 -1; -1 1; 0 1],'no-op')
%!demo
%! pol1 = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3];
%! pol2 = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3];
%!
%! subplot (3, 3, 1)
%! drawFilledPolygon (pol1, 'edgecolor', 'k', 'facecolor', 'c')
%! axis image
%! title ('1. Subject polygon')
%! axis off
%!
%! subplot (3, 3, 2)
%! drawFilledPolygon (pol1, 'linestyle', 'none', 'facecolor', 'c')
%! drawFilledPolygon (pol2, 'edgecolor', 'b', 'facecolor', 'y')
%! axis image
%! title ('2. Clip polygon')
%! axis off
%!
%! algo = {'clipper', 'mrf'};
%! for i = 1:numel (algo)
%! subplot (3, 3, i+2);
%! tic
%! [opol, npol] = clipPolygon (pol1, pol2, 3, 'clipper');
%! printf('%s took: %f seconds (union)\n', algo{i}, toc);
%! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g')
%! axis image
%! title (sprintf('Union - %s', algo{i}));
%! axis off
%!
%! subplot (3, 3, i+4);
%! tic
%! [opol, npol] = clipPolygon (pol1, pol2, 1, 'clipper');
%! printf('%s took: %f seconds (and)\n', algo{i}, toc);
%! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g')
%! axis image
%! title (sprintf('And - %s', algo{i}));
%! axis off
%!
%! subplot (3, 3, i+6);
%! tic
%! [opol, npol] = clipPolygon (pol1, pol2, 2, 'clipper');
%! printf('%s took: %f seconds (xor)\n', algo{i}, toc);
%! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g')
%! axis image
%! title (sprintf('Xor - %s', algo{i}));
%! axis off
%! endfor
geometry-4.0.0/inst/clipPolygon_clipper.m 0000644 0000000 0000000 00000016161 13615712371 016717 0 ustar 00 0000000 0000000 ## Copyright (C) 2015-2019 - Philip Nienhuis
## Copyright (C) 2017 - Juan Pablo Carbajal
## Copyright (C) 2017 - Piyush Jain
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol})
## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op})
## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op}, @var{rules}, @var{rulec})
## Perform boolean operation on polygon(s) using the Clipper library.
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s)
## to be clipped. Polygons are separated by [NaN NaN] rows. @var{clippol} =
## another Nx2 matrix of (X, Y) coordinates representing the clip polygon(s).
##
## Optional argument @var{op}, the boolean operation, can be:
##
## @itemize
## @item 0: difference @var{inpol} - @var{clippol}
##
## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default)
##
## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol}
##
## @item 3: union ("OR") of @var{inpol} and @var{clippol}
## @end itemize
##
## In addition a rule can be specified to instruct polyclip how to assess
## holes, or rather, how to assess polygon fill. This works as follows: start
## with a winding number of zero (0). From a point outside all polygons
## specified in @var{INPOL}, go to the center of the innermost polygon and note
## which polygons are crossed. For each polygon boundary crossing from right
## to left, increase the winding number, while for each polygon crossing from
## left to right, decrement it, and then assign it to the crossed polygon.
## @var{rules} and @var{rulec} can be set individually for subject and clip
## polygons, respectively, as follows:
##
## @itemize
## @item 0 Even-Odd, also called Alternate (= default):
## The first polygon crossed specifies the outer boundary of a filled polygon,
## the next polygon (if present) specifies the inner boundary of that filled
## polygon, and so on. Winding direction (clockwise or counterclockwise) is
## irrelevant here.
##
## @item 1 Non-Zero:
## All polygons with a non-zero winding number are filled.
##
## @item 2 Positive:
## All polygons with a winding number > 0 are filled. This is the usual setting
## for counterclockwise polygons to be the outer, and clockwise polygons to be
## the inner boundary ("holes") of complex polygons.
##
## @item 3 Negative:
## All polygons with a winding number < 0 are filled.
## @end itemize
## (for details see [1])
##
## Output array @var{outpol} will be an Nx2 array of polygons resulting from
## the requested boolean operation, or in case of just one input argument an
## Nx1 array indicating winding direction of each subpolygon in input argument
## @var{inpol}.
##
## [1]: @uref{http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm}
##
## @seealso{clipPolygon_mrf,clipPolygon}
## @end deffn
## Author: Philip Nienhuis
## Created: 2015-05-03
## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab
function [outpoly, npol] = clipPolygon_clipper (inpoly, clippoly, method=1, rules=0, rulec=0)
## Input validation
if (nargin < 3)
print_usage ();
endif
if (! isnumeric (inpoly) || size (inpoly, 2) < 2)
error ("Octave:invalid-input-arg", ...
"clipPolygon: inpoly should be a numeric Nx2 array");
endif
if (! isnumeric (clippoly) || size (clippoly, 2) < 2)
error ("Octave:invalid-input-arg", ...
"clipPolygon: clippoly should be a numeric Nx2 array");
elseif (! isnumeric (method) || method < 0 || method > 3)
error ("Octave:invalid-input-arg", ...
"clipPolygon: operation must be a number in the range [0..3]");
elseif (! isnumeric (rules) || ! isnumeric (rulec) || rules < 0 || rulec < 0)
error ("Octave:invalid-input-arg", ...
"clipPolygon: fill type rules must be nummbers in range [0..3]");
endif
[inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly);
clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn);
## Perform boolean operation
outpol = clipper (inpol, clpol, method, rules, rulec);
npol = numel (outpol);
if (! isempty (outpol))
## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X:
[tmp(1:2:2*npol, 1)] = deal ({outpol.x});
[tmp(2:2:2*npol, 1)] = ...
cellfun (@(x) [x(1); NaN], tmp(1:2:2*npol, 1), "uni", 0);
## Convert back from in64 into double, wipe trailing NaN
X = double (cell2mat (tmp))(1:end-1);
## Y-coordinates:
[tmp(1:2:2*npol, 1)] = deal ({outpol.y});
[tmp(2:2:2*npol, 1)] = ...
cellfun (@(y) [y(1); NaN], tmp(1:2:2*npol, 1), "uni", 0);
Y = double (cell2mat (tmp))(1:end-1);
outpoly = ([X Y] / xy_magn) + xy_mean;
else
outpoly = zeros (0, 2);
endif
endfunction
%!demo
%! pol1 = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3];
%! pol2 = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3];
%! lw = 2;
%!
%! subplot (2, 7, [1 2])
%! pol1a = polygon2patch (pol1);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw);
%! axis image
%! title ("1. Subject polygon")
%! axis off
%!
%! subplot (2, 7, [3 4])
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! pol2a = polygon2patch (pol2);
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw);
%! axis image
%! title "2. Clip polygon"
%! axis off
%!
%! op = {"Sub - clip", "AND / Intersection", "Exclusive OR", "OR / Union"};
%! for i=1:numel(op)
%! subplot (6, 4, [12 16]+i);
%! [opol, npol] = clipPolygon_clipper (pol1, pol2, i-1);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! title (sprintf("%d. %s", i+3, op{i}));
%! axis off
%! endfor
%!
%! subplot (2, 7, [6 7]);
%! [opol, npol] = clipPolygon_clipper (pol2, pol1, 0);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! axis off
%! title "3. Clip - sub";
geometry-4.0.0/inst/clipPolygon_mrf.m 0000644 0000000 0000000 00000021146 13615712371 016044 0 ustar 00 0000000 0000000 ## Copyright (C) 2017 - Piyush Jain
## Copyright (C) 2017 - Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon_mrf (@var{inpol}, @var{clippol})
## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_mrf (@var{inpol}, @var{clippol}, @var{op})
## Perform boolean operation on polygon(s) using the algorithm by Martinez, Rueda and Feito.
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s)
## to be clipped (subject polygon).
## @var{clippol} = Nx2 matrix of (X, Y) coordinates representing the clip polygon(s).
##
## Polygons may have multiple non-intersecting regions. The contours are separated by [Nan NaN] rows.
## Polygons may also contain holes. Holes are defined as the region enclosed within the boundaries of polygon which are not part of the polygon region. Here again, the inner and outer contours are separated by [Nan NaN] rows. Specifically, if a contour is lying inside another contour, it is automatically treated as a hole.
##
## The following features are allowed in input polygons:
##
## @itemize
## @item 0: Contours can be described in clockwise or counterclockwise order.
##
## @item 1: Holes.
##
## @item 2: A vertex of a polygon can touch (in a point) a vertex or edge of the same polygon.
##
## @item 3: Self-intersecting polygons.
## @end itemize
##
## The following features are not allowed in input polygons:
##
## @itemize
## The intersection of two edges of the same polygon can be a point, but cannot be a segment.
## @end itemize
##
## The argument @var{op}, the boolean operation, can be:
##
## @itemize
## @item 0: difference @var{inpol} - @var{clippol}
##
## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default)
##
## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol}
##
## @item 3: union ("OR") of @var{inpol} and @var{clippol}
## @end itemize
##
## Output array @var{outpol} will be an Nx2 array of polygons resulting from
## the requested boolean operation
##
## Optional output argument @var{npol} indicates the number of output polygons.
##
## Know more about the algorithm by Martinez, Rueda and Feito[1].
##
## [1]: @uref{http://www4.ujaen.es/~fmartin/bool_op.html}
##
## @seealso{clipPolygon_clipper,clipPolygon}
## @end deffn
## Created: 2017-06-09
function [outpol, npol] = clipPolygon_mrf (inpoly, clippoly=[], method=1)
## Input validation
if (nargin < 2 || nargin > 3)
print_usage ();
endif
if(isempty(inpoly) || isempty(clippoly))
error ('Octave:invalid-input-arg', ...
"clipPolygon_mrf: Empty polygon");
endif
if (! isnumeric (inpoly) || size (inpoly, 2) < 2)
error ('Octave:invalid-input-arg', ...
"clipPolygon_mrf: inpoly should be a numeric Nx2 array");
endif
if (! isnumeric (clippoly) || size (clippoly, 2) < 2)
error ('Octave:invalid-input-arg', ...
"clipPolygon_mrf: clippoly should be a numeric Nx2 array");
elseif (! isnumeric (method) || method < 0 || method > 3)
error ('Octave:invalid-input-arg', ...
"clipPolygon_mrf: operation must be a number in the range [0..3]");
endif
inpol = __polytostruct__ (inpoly);
clpol = __polytostruct__ (clippoly);
## Perform boolean operation
[X, Y, npol] = polybool_mrf(inpol, clpol, method);
if(npol == 0)
outpol = [ , ];
else
outpol = [X Y];
endif
endfunction
%!test
%! pol1 = [-0.15 -0.15; 0.45 -0.15; 0.15 0.45];
%! pol2 = [-0.05 -0.05; 0.15 0.35; 0.35 -0.05; NaN NaN;
%! 0.05 0.05; 0.25 0.05; 0.15 0.25];
%! opol_0 = [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN;
%! 0.15 0.35; -0.05 -0.05; 0.35 -0.05; NaN NaN;
%! 0.15 0.45; -0.15 -0.15; 0.45 -0.15];
%! npol_0 = 3;
%! opol_1= [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN;
%! 0.15 0.35; -0.05 -0.05; 0.35 -0.05];
%! npol_1 = 2;
%! opol_2 = [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN;
%! 0.15 0.35; -0.05 -0.05; 0.35 -0.05; NaN NaN;
%! 0.15 0.45; -0.15 -0.15; 0.45 -0.15];
%! npol_2 = 3;
%! opol_3 = [0.15 0.45; -0.15 -0.15; 0.45 -0.15];
%! npol_3 = 1;
%! [opol npol] = clipPolygon_mrf (pol1, pol2, 0);
%! assert(opol, opol_0);
%! assert(npol, npol_0);
%! [opol npol] = clipPolygon_mrf (pol1, pol2, 1);
%! assert(opol, opol_1);
%! assert(npol, npol_1);
%! [opol npol] = clipPolygon_mrf (pol1, pol2, 2);
%! assert(opol, opol_2);
%! assert(npol, npol_2);
%! [opol npol] = clipPolygon_mrf (pol1, pol2, 3);
%! assert(opol, opol_3);
%! assert(npol, npol_3);
%!error clipPolygon_mrf([], [], 0);
%!error
%! pol1 = [0.15 0.15; 0.55 0.45; 0.15 0.75];
%! pol2 = [0.35 0.45; 0.75 0.15; 0.75 0.75];
%! clipPolygon_mrf(pol1, pol2, 4);
%!test ## Bug #56506
%! subpol = [0 0; 5 5; 2.5 4;0 0];
%! clppol2 = [10 1; 16 6; 13.5 5; 10 1];
%! [a, b] = clipPolygon_mrf (subpol, clppol2, 1);
%! assert (a, []);
%! assert (b, 0);
%!demo
%! pol1 = [0.15 0.15; 0.55 0.45; 0.15 0.75];
%! pol2 = [0.35 0.45; 0.75 0.15; 0.75 0.75];
%! pol1a = polygon2patch(pol1);
%! pol2a = polygon2patch(pol2);
%! lw = 2;
%! subplot (2, 6, [2 3])
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw);
%! axis image
%! grid on
%! title ("1. Subject polygon")
%!
%! subplot (2, 6, [4 5])
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw);
%! axis image
%! grid on
%! title "2. Clip polygon"
%!
%! op = {"Sub -clip", "AND / Intersection", "Exclusive OR", "OR / Union"};
%! for i=1:numel(op)
%! subplot (6, 4, [12 16]+i);
%! [opol, npol] = clipPolygon_mrf (pol1, pol2, i-1);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! title (sprintf("%d. %s", i+2, op{i}));
%! axis off
%! endfor
%!
%! subplot (10, 4, 37);
%! [opol, npol] = clipPolygon_mrf (pol2, pol1, 0);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! axis off
%! title "7. Clip - sub";
%!demo
%! pol1 = [1 1; 5 1; 3 7; NaN NaN; 2 2; 3 5; 4 2];
%! pol2 = [3 1; 5 6; 1 6];
%! pol1a = polygon2patch(pol1);
%! pol2a = polygon2patch(pol2);
%! lw = 2;
%! subplot (2, 6, [2 3])
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw);
%! axis image
%! grid on
%! title ("1. Subject polygon")
%!
%! subplot (2, 6, [4 5])
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw);
%! axis image
%! grid on
%! title "2. Clip polygon"
%!
%! op = {"Sub -clip", "AND / Intersection", "Exclusive OR", "OR / Union"};
%! for i=1:numel(op)
%! subplot (6, 4, [12 16]+i);
%! [opol, npol] = clipPolygon_mrf (pol1, pol2, i-1);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! title (sprintf("%d. %s", i+2, op{i}));
%! axis off
%! endfor
%!
%! subplot (10, 4, 37);
%! [opol, npol] = clipPolygon_mrf (pol2, pol1, 0);
%! opol = polygon2patch (opol);
%! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none');
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none');
%! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ...
%! 'linewidth', lw);
%! axis image
%! grid on
%! axis off
%! title "7. Clip - sub"; geometry-4.0.0/inst/clipPolyline.m 0000644 0000000 0000000 00000005461 13615712371 015346 0 ustar 00 0000000 0000000 ## Copyright (C) 2017-2019 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {} {@var{oline}} = clipPolyline (@var{inpol}, @var{clippol}, @var{op})
## Clip (possibly composite) polylines with polygon(s) using one of boolean
## methods.
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s)
## to be clipped. Polyline sections are separated by [NaN NaN] rows.
## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the
## clip polygon(s). @var{clippol} may comprise separate and/or concentric
## polygons (the latter with holes).
##
## The argument @var{op}, the boolean operation, can be:
##
## @itemize
## @item 0: difference @var{inpol} - @var{clippol}
##
## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default)
## @end itemize
##
## Output array @var{oline} will be an Nx2 array of polyline sections
## resulting from the requested boolean operation.
##
## The optional argument @var{library} specifies which library to use for clipping.
## Currently only @asis{"clipper"} is implemented.
##
## @seealso{clipPolygon}
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2017-03-21
function [olin, nlin] = clipPolyline (p1, p2, op, library = "clipper")
if ~(ismember (tolower (library), {"clipper"}))
error ('Octave:invalid-fun-call', "clipPolyline: unimplemented polygon clipping library: '%s'", library);
endif
[olin, nlin] = clipPolyline_clipper (p1, p2, op);
endfunction
%!demo
%! sline = [0, 6.5; 1.25, 4; 1.25, 0; NaN, NaN; 0.25, 7; 1.75, 4; 1.75, 0];
%! for ii=1:10
%! sline = [sline; [NaN NaN]; [ii/2+0.25, 7; ii/2+1.75, 4; ii/2+1.75, 0]];
%! endfor
%! pol2a = [1 2; 7 4; 4 7; 1 2; 2.5 3; 4 5.5; 5.5 4; 2.5 3; 1 2];
%! figure ();
%! hold on
%! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', 2);
%! [olin, nlin] = clipPolyline_clipper (sline, pol2a, 1);
%! plot (olin(:, 1), olin(:, 2), 'r', 'linewidth', 3);
%! [olin, nlin] = clipPolyline (sline, pol2a, 0);
%! plot (olin(:, 1), olin(:, 2), 'g', 'linewidth', 3);
%! grid on;
%! box on;
%! axis equal;
%! legend ({"Clip polygon", "AND", "OR"});
%! title ("Demo: clipping polylines with polygons");
geometry-4.0.0/inst/clipPolyline_clipper.m 0000644 0000000 0000000 00000006103 13615712371 017056 0 ustar 00 0000000 0000000 ## Copyright (C) 2017 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol})
## @deftypefnx {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol}, @var{op})
## Clip (possibly composite) polylines with polygon(s) using one of boolean
## methods.
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s)
## to be clipped. Polyline sections are separated by [NaN NaN] rows.
## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the
## clip polygon(s). @var{clippol} may comprise separate and/or concentric
## polygons (the latter with holes).
##
## Optional argument @var{op}, the boolean operation, can be:
##
## @itemize
## @item 0: difference @var{inpol} - @var{clippol}
##
## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default)
## @end itemize
##
## Output array @var{oline} will be an Nx2 array of polyline sections
## resulting from the requested boolean operation.
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2017-03-21
## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab
function [olin, nlin] = clipPolyline_clipper (inpoly, clippoly, method=1)
## Input validation
if (nargin < 2)
print_usage ();
endif
if (! isnumeric (inpoly) || size (inpoly, 2) < 2)
error (" clipPolyline: inpoly should be a numeric Nx2 array");
endif
if (! isnumeric (clippoly) || size (clippoly, 2) < 2)
error (" clipPolyline: clippoly should be a numeric Nx2 array");
elseif (! isnumeric (method) || method < 0 || method > 3)
error (" clipPolyline: operation must be a numeric 0 or 1");
endif
[inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly);
clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn);
## Perform boolean operation
olin = clipper (inpol, clpol, method, -1);
nlin = numel (olin);
if (! isempty (olin))
## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X:
[tmp(1:2:2*nlin, 1)] = deal ({olin.x});
[tmp(2:2:2*nlin-1, 1)] = NaN;
## Convert back from in64 into double, wipe trailing NaN
X = double (cell2mat (tmp));
## Y-coordinates:
[tmp(1:2:2*nlin, 1)] = deal ({olin.y});
[tmp(2:2:2*nlin-1, 1)] = NaN;
Y = double (cell2mat (tmp));
olin = ([X Y] / xy_magn) + xy_mean;
else
olin = zeros (0, 2);
endif
endfunction
geometry-4.0.0/inst/cov2ellipse.m 0000644 0000000 0000000 00000006146 13615712371 015133 0 ustar 00 0000000 0000000 ## Copyright (C) 2004-2011 David Legland
## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)
## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## 1 Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## 2 Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS''
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## -*- texinfo -*-
## @deftypefn {Function File} {@var{ellipse} = } cov2ellipse (@var{K})
## @deftypefnx {Function File} {[@var{ra} @var{rb} @var{theta}] = } cov2ellipse (@var{K})
## @deftypefnx {Function File} {@dots{} = } cov2ellipse (@dots{}, @samp{tol},@var{tol})
## Calculates ellipse parameters from covariance matrix.
##
## @var{K} must be symmetric positive (semi)definite. The optional argument
## @samp{tol} sets the tolerance for the verification of the
## positive-(semi)definiteness of the matrix @var{K} (see @command{isdefinite}).
##
## If only one output argument is supplied a vector defining a ellipse is returned
## as defined in @command{ellipses2d}. Otherwise the angle @var{theta} is given
## in radians.
##
## Run @code{demo cov2ellipse} to see an example.
##
## @seealso{ellipses2d, cov2ellipse, drawEllipse}
## @end deftypefn
function varargout = cov2ellipse (K, varargin);
parser = inputParser ();
parser.FunctionName = "cov2ellipse";
parser.addParamValue ('Tol', 100*eps*norm (K, "fro"), @(x)x>0);
parser.parse(varargin{:});
if isdefinite (K,parser.Results.Tol) == -1
print_usage
end
[R S W] = svd (K);
theta = atan2 (R(2,1), R(1,1));
v = sqrt (diag(S))';
if nargout == 1
varargout{1} = [0 0 v theta*180/pi];
elseif nargout == 3
varargout{1} = v(1);
varargout{2} = v(2);
varargout{3} = theta;
end
endfunction
%!demo
%! K = [2 1; 1 2];
%! L = chol(K,'lower');
%! u = randn(1e3,2)*L';
%!
%! elli = cov2ellipse (K)
%!
%! figure(1)
%! plot(u(:,1),u(:,2),'.r');
%! hold on;
%! drawEllipse(elli,'linewidth',2);
%! hold off
%! axis tight
geometry-4.0.0/inst/curve2polyline.m 0000644 0000000 0000000 00000010403 13615712371 015655 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @defun {@var{polyline} = } curve2polyline (@var{curve})
## @defunx {@var{polyline} = } curve2polyline (@dots{},@var{property},@var{value},@dots{})
## Adaptive sampling of a parametric curve.
##
## The @var{curve} is described as a 2-by-N matrix. Rows correspond to the
## polynomial (compatible with @code{polyval}) describing the respective component
## of the curve. The curve must be parametrized in the interval [0,1].
## The vertices of the polyline are accumulated in regions of the curve where
## the curvature is higher.
##
## @strong{Parameters}
## @table @samp
## @item 'Nmax'
## Maximum number of vertices. Not used.
## @item 'Tol'
## Tolerance for the error criteria. Default value @code{1e-4}.
##
## Currently the area of the smaller triangle formed by three consecutive points
## on the curve is considered. When this area is smaller than tolerance the
## points are colinear, and hence no more sampling between these points is
## needed.
##
## @item 'MaxIter'
## Maximum number of iterations. Default value @code{10}.
## @item 'Method'
## Not implemented.
## @end table
##
## This function is based on the algorithm described in
## L. H. de Figueiredo (1993). "Adaptive Sampling of Parametric Curves". Graphic Gems III.
## @seealso{shape2polygon, curveval}
## @end defun
## I had to remove the recursion so this version could be improved.
## Thursday, April 12 2012 -- JuanPi
function [polyline t bump]= curve2polyline (curve, varargin)
## TODO make tolerance relative to the "diameter" of the curve.
# --- Parse arguments --- #
parser = inputParser ();
parser.FunctionName = "curve2polyline";
parser.addParamValue ('Nmax', 32, @(x)x>0);
parser.addParamValue ('Tol', 1e-4, @(x)x>0);
parser.addParamValue ('MaxIter', 10, @(x)x>0);
parser.parse(varargin{:});
Nmax = parser.Results.Nmax;
tol = parser.Results.Tol;
MaxIter = parser.Results.MaxIter;
clear parser toldef
# ------ #
t = [0; 1];
tf = 1;
points = 1;
for iter = 1:MaxIter
# Add parameter values where error is still bigger than tol.
t = interleave(t, tf);
nt = length (t);
# Update error
polyline = curveval (curve,t);
bump = bumpyness (polyline);
# Check which intervals must be subdivided
idx = find (bump > tol);
# The position of the bumps maps into intervals
# 1 -> 1 2
# 2 -> 3 4
# 3 -> 5 6
# and so on
idx = [2*(idx-1)+1; 2*idx](:);
tf = false (nt-1,1);
tf(idx) = true;
if all (!tf)
break;
end
end
endfunction
function f = bumpyness (p)
## Check for co-linearity
## TODO implement various method for this
## -- Area of the triangle close to zero (used currently).
## -- Angle close to pi.
## -- abs(p0-pt) + abs(pt-p1) - abs(p0-p1) almost zero.
## -- Curve's tange at 0,t,1 are almost parallel.
## -- pt is in chord p0 -> p1.
## Do this in isParallel.m and remove this function
PL = p(1:2:end-2,:);
PC = p(2:2:end-1,:);
PR = p(3:2:end,:);
a = PL - PC;
b = PR - PC;
f = (a(:,1).*b(:,2) - a(:,2).*b(:,1)).^2;
endfunction
function tt = interleave (t,varargin)
nt = length (t);
ntt = 2 * nt -1;
tt = zeros (ntt,1);
tt(1:2:ntt) = t;
beta = 0.4 + 0.2 * rand (nt-1, 1);
tt(2:2:ntt) = t(1:end-1) + beta .* (t(2:end)-t(1:end-1));
if nargin > 1
tf = true (ntt,1);
tf(2:2:ntt) = varargin{1};
tt(!tf) = [];
end
endfunction
%!demo
%! curve = [0 0 1 0;1 -0.3-1 0.3 0];
%! polyline = curve2polyline(curve,'tol',1e-8);
%!
%! t = linspace(0,1,100)';
%! pc = curveval(curve,t);
%!
%! plot(polyline(:,1),polyline(:,2),'-o',pc(:,1),pc(:,2),'-r')
geometry-4.0.0/inst/curveval.m 0000644 0000000 0000000 00000002003 13615712371 014517 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {@var{p} = } curveval (@var{curve}, @var{t})
## Evaluates parametric @var{curve} at @var{t}.
##
## @end deftypefn
function p = curveval (curve, t)
dim = size (curve,1);
p = zeros (length(t), dim);
for i = 1:dim
p(:,i) = polyval (curve(i,:), t);
end
endfunction
geometry-4.0.0/inst/data2geo.m 0000644 0000000 0000000 00000007200 13615712371 014362 0 ustar 00 0000000 0000000 ## Copyright (C) 2016-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @deftypefn {Function File} {@var{fileStr} =} data2geo (@var{data}, @var{lc})
## @deftypefnx {Function File} {@var{fileStr} =} data2geo (@dots{}, @var{param}, @var{value})
## Uses data to build a file compatible with Gmsh.
##
## @var{data} is assumed to describe a polygon in @code{polygon2d} format.
## The argument @var{lc} specifies the edge size.
##
## The optional parameters can be 'output' followed with a string specifying a file
## to write, and 'spherical' followed by a real number @var{r} indicating that the
## polygon describes a spherical surface of radious @var{r}.
##
## @seealso{polygon2d}
## @end deftypefn
function strFile = data2geo(data, lc, varargin)
nl = @()sprintf('\n');
## Parse options
filegiven = [];
spherical = [];
if nargin > 2
filegiven = find(cellfun(@(x)strcmpi(x,'output'),varargin));
spherical = find(cellfun(@(x)strcmpi(x,'spherical'),varargin));
end
[n dim] = size(data);
if dim == 2
data(:,3) = zeros(n,1);
end
header = ' // File created with Octave';
strFile = [header nl()];
# Points
strFile = [strFile '// Points' nl()];
for i=1:n
strFile = [strFile pointGeo(i,data(i,:),lc)];
end
# Lines
strFile = [strFile '// Lines' nl()];
for i=1:n-1
strFile = [strFile lineGeo(i,i,i+1)];
end
strFile = [strFile lineGeo(n,n,1)];
# Loop
strFile = [strFile lineLoopGeo(n+1,n,1:n)];
# Surface
if spherical
sphr = varargin{spherical+1};
if dim ==2
sphr(1,3) = 0;
end
strFile = [strFile pointGeo(n+1,sphr,lc)];
strFile = [strFile ruledSurfGeo(n+3,1,n+1,n+1)];
else
strFile = [strFile planeSurfGeo(n+2,1,n+1)];
end
if filegiven
outfile = varargin{filegiven+1};
fid = fopen(outfile,'w');
fprintf(fid,'%s',strFile);
fclose(fid);
disp(['DATA2GEO: Geometry file saved to ' outfile])
end
endfunction
%!demo
%! points = [0 0 0; 0.1 0 0; 0.1 .3 0; 0 0.3 0];
%! strFile = data2geo(points,0.009);
%! disp(strFile)
# This demo doesn't work because the svg class is broken as of geometry 4.0.0
#%!demo
#%! dc = svg('drawing6.svg');
#%! ids = dc.pathid();
#%! P = dc.path2polygon(ids{1},12)(1:end-1,:);
#%! P = bsxfun(@minus, P, centroid(P));
#%! P = simplifyPolygon_geometry(P,'tol',5e-1);
#%! filename = tmpnam ();
#%! meshsize = sqrt(mean(sumsq(diff(P,1,1),2)))/2;
#%! data2geo (P, meshsize, 'output', [filename '.geo']);
#%!
#%! pkg load msh fpl
#%! T = msh2m_gmsh(filename);
#%! pdemesh(T.p,T.e,T.t)
#%! view(2)
#%! axis tight
#%! # --------------------------------------------------------------------------
#%! # We load the drawing6.svg file into Octave and transform it into a polygon.
#%! # Then we create a temporary file where the .geo mesh will be written.
#%! # If the packages msh and fpl are available, a mesh is created from the .geo
#%! # file.
geometry-4.0.0/inst/drawFilledPolygon.m 0000644 0000000 0000000 00000012261 13615712371 016324 0 ustar 00 0000000 0000000 ## Copyright (C) 2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @defun {} drawFilledPolygon (@var{p})
## @defunx {} drawFilledPolygon (@var{hax}, @var{p})
## @defunx {} clipPolygon (@dots{}, @var{prop}, @var{value}, @dots{})
## @defunx {@var{h} =} drawFilledPolygon (@dots{})
## Draw a filled polygon.
##
## Add a patch representing the polygon(s) @var{p} in the current axes.
##
## Multiple property-value pairs may be specified, but they must
## appear in pairs. These arguments are passed to the function @code{patch}.
##
## If the first argument @var{hax} is an axes handle, then plot into this
## axes, rather than the current axes returned by @code{gca}.
##
## If @var{p} is a cell, each element of the cell is processed in sequence.
##
## The optional return value @var{h} is a vector of graphics handles to the
## created patch objects.
##
## For example:
##
## Draw a polygon with default filling color and red edges.
##
## @example
## @group
## pol = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3];
## h = drawFilledPolygon (pol, 'edgecolor', 'r');
## @end group
## @end example
##
## @seealso{drawPolygon, polygon2patch, patch}
## @end defun
## Author: Juan Pablo Carbajal
## Created: 2019-12-15
function h = drawFilledPolygon (px, varargin)
# Check input
if (nargin < 1)
print_usage ();
endif
# Check for empty polygons
if (isempty (px))
return
endif
# Store hold state
state = ishold (gca);
hold on;
# Extract handle of axis to draw on
ax = gca;
if (isAxisHandle (px))
ax = px;
px = varargin{1};
varargin(1) = [];
end
## Manage cell arrays of polygons
# Case of a set of polygons stored in a cell array
if (iscell (px))
np = numel (px);
h_ = zeros(1, np);
for i = 1:np
h_(np - i + 1) = drawFilledPolygon (px{i}, varargin{:});
endfor
else
# Check size vs number of arguments
if (size (px, 2) == 1)
# Case of polygon specified as two N-by-1 arrays with same length
if (nargin < 2 || nargin == 2 && ~isnumeric (varargin{1}))
error('Octave:invalid-input-arg', ...
['drawFilledPolygon: Should specify either a N-by-2 array,' ...
' or 2 N-by-1 vectors']);
endif
# Merge coordinates of polygon vertices
py = varargin{1};
varargin(1) = [];
if (length (py) ~= length (px))
error('Octave:invalid-input-arg', ...
['drawFilledPolygon: X and Y coordinate arrays should have' ...
' same lengths (%d,%d)'], length (px), length (py))
endif
px = [px py];
elseif (size (px, 2) > 2 || size (px, 2) < 1)
error ('Octave:invalid-input-arg', ...
'drawFilledPolygon: Should specify a N-by-2 array');
endif
# Set default format
fmtdef = {'facecolor', [0.7 0.7 0.7], ...
'edgecolor', 'k', ...
'linewidth', 2};
varargin = {fmtdef{:}, varargin{:}};
# if (isempty (varargin))
# varargin = formatdef;
# else # set missing with defaults
# [tfdef, idxarg] = ismember (formatdef(1:2:end), ...
# tolower (varargin(1:2:end)));
# if (any (tfdef))
# idxdef = find (tfdef);
# idxarg = idxarg(idxarg > 0);
# varargin(2 * idxarg) = formatdef(2 * idxdef);
# endif
# endif
pxpatch = polygon2patch (px);
h_ = patch (ax, pxpatch(:,1), pxpatch(:,2), varargin{:});
endif # whether input arg was a cell
if (~state)
hold off
endif
# Avoid returning argument if not required
if (nargout > 0)
h = h_;
endif
endfunction
%!demo
%! figure (1)
%! clf;
%! pol = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3];
%! subplot(131)
%! drawFilledPolygon(pol)
%! axis tight equal off
%! subplot(132)
%! drawFilledPolygon(pol, 'facecolor', 'c', 'linestyle', '--', 'edgecolor', 'r')
%! axis tight equal off
%! subplot(133)
%! R = createRotation (polygonCentroid (splitPolygons(pol){1}), pi/6);
%! pol2 = transformPoint (pol, R);
%! drawFilledPolygon(pol, 'linestyle', 'none')
%! drawFilledPolygon(gca, pol2, 'facealpha', 0.5)
%! axis tight equal off
%!demo
%! pol = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3];
%! n = 5;
%! alpha = linspace(0.1, 1, n);
%! theta = linspace(pi / 3, 0, n);
%!
%! cpol = cell(n, 1);
%! for i = 1:n
%! cpol{i} = transformPoint (pol, createRotation (theta(i)));
%! endfor
%! h = drawFilledPolygon(cpol, 'linestyle', 'none');
%! for i = 1:n-1
%! set(h(i), 'facealpha', alpha(i))
%! endfor
%! axis tight equal off
geometry-4.0.0/inst/drawing.svg 0000644 0000000 0000000 00000003401 13615712371 014671 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/drawing2.svg 0000644 0000000 0000000 00000003717 13615712371 014765 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/drawing3.svg 0000644 0000000 0000000 00000002052 13615712371 014755 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/drawing4.svg 0000644 0000000 0000000 00000004070 13615712371 014760 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/drawing5.svg 0000644 0000000 0000000 00000003746 13615712371 014772 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/drawing6.svg 0000644 0000000 0000000 00000002604 13615712371 014763 0 ustar 00 0000000 0000000
image/svg+xml
geometry-4.0.0/inst/ellipse2cov.m 0000644 0000000 0000000 00000006527 13615712371 015136 0 ustar 00 0000000 0000000 ## Copyright (C) 2004-2011 David Legland
## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)
## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## 1 Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## 2 Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS''
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## -*- texinfo -*-
## @deftypefn {Function File} {@var{K} = } ellipse2cov (@var{elli})
## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@var{ra}, @var{rb})
## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@dots{}, @var{theta})
## Calculates covariance matrix from ellipse.
##
## If only one input is given, @var{elli} must define an ellipse as described in
## @command{ellipses2d}.
## If two inputs are given, @var{ra} and @var{rb} define the half-lenght of the
## axes.
## If a third input is given, @var{theta} must be the angle of rotation of the
## ellipse in radians, and in counter-clockwise direction.
##
## The output @var{K} contains the covariance matrix define by the ellipse.
##
## Run @code{demo ellipse2cov} to see an example.
##
## @seealso{ellipses2d, cov2ellipse, drawEllipse}
## @end deftypefn
function K = ellipse2cov (elli, varargin);
ra = 1;
rb = 1;
theta = 0;
switch numel (varargin)
case 0
## ellipse format
if numel (elli) != 5
print_usage ();
end
ra = elli(1,3);
rb = elli(1,4);
theta = elli(1,5)*pi/180;
case 1
## ra,rb
if numel (elli) != 1
print_usage ();
end
ra = elli;
rb = varargin{1};
case 2
## ra,rb, theta
if numel (elli) != 1
print_usage ();
end
ra = elli;
rb = varargin{1};
theta = varargin{2};
otherwise
print_usage ();
end
T = createRotation (theta)(1:2,1:2);
K = T*diag([ra rb])*T';
endfunction
%!demo
%! elli = [0 0 1 3 -45];
%!
%! # Create 2D normal random variables with covarinace defined by elli.
%! K = ellipse2cov (elli)
%! L = chol(K,'lower');
%! u = randn(1e3,2)*L';
%!
%! Kn = cov (u)
%!
%! figure(1)
%! plot(u(:,1),u(:,2),'.r');
%! hold on;
%! drawEllipse(elli,'linewidth',2);
%! hold off
%! axis tight
geometry-4.0.0/inst/isPolygonCCW.m 0000644 0000000 0000000 00000010206 13615712371 015214 0 ustar 00 0000000 0000000 ## Copyright (C) 2016-2017 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {} {@var{ccw} =} isPolygonCCW (@var{p})
## @deftypefnx {} {@var{ccw} =} isPolygonCCW (@var{px}, @var{py})
## Returns true if the polygon @var{p} are oriented Counter-Clockwise.
##
## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates
## of the vertices of the polygon can also be given as two N-by-1 arrays
## @var{px}, @var{py}.
##
## Optional third argument @var{library} can be one of "geometry" or
## "clipper". In the latter case the potentially faster Clipper polygon
## library will be invoked to assess winding directions. The default is
## "geometry".
##
## If any polygon is self-crossing, the result is undefined.
##
## If @var{p} is a cell, each element is considered a polygon, the
## resulting @var{cww} is a cell of the same size.
##
## @seealso{polygonArea}
## @end deftypefn
## Author: Juan Pablo Carbajal
function ccw = isPolygonCCW (px, py=[], lib="geometry")
## case of wrong number of input arguments
if (nargin > 3 || nargin < 1)
print_usage ();
endif
if (ischar (py))
py = lower (py);
if (ismember (py, {"geometry", "clipper"}))
lib = py;
py = [];
else
error ('Octave:invalid-fun-call', "use of '%s' not implemented", lib);
endif
endif
if (! isempty (py))
if (! strcmp (typeinfo (px), typeinfo (py)))
error ('Octave:invalid-input-arg', 'X and Y should be of the same type');
endif
if (any (size (px) != size (py)) )
error ('Octave:invalid-input-arg', 'X and Y should be of the same size');
endif
endif
if (iscell (px))
## Cell Array Format
## Call this function on each cell
if (isempty (py))
py = cell (size (px));
endif
ccw = cellfun (@(u,v) isPolygonCCW (u,v,lib), px, py, "unif", 0);
else
## Input are matrices
## merge them to one
px = [px py];
if (isempty (px))
error ("isPolygonCW: empty input polygon encountered");
elseif (strcmpi (lib, "clipper"))
## Clipper can do all of them in one call
ccw = logical (isPolygonCW_Clipper (px));
return
endif
if (any (isnan (px(:))))
## Inputs are many polygons separated with NaN
## Split them and call this function on each of them
px = splitPolygons (px);
ccw = cellfun (@(u) isPolygonCCW (u,[],lib), px);
else ## Here do the actual work
ccw = polygonArea (px) > 0;
endif
endif
endfunction
%!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan
%! pccw = [0 0; 1 0; 1 1; 0 1];
%! pcw = reversePolygon (pccw);
%! pxccw = pccw(:,1);
%! pyccw = pccw(:,2);
%! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2];
%! pynan = [0; 2; 2; 0; NaN; 0; 3; 0];
%! pnan = [pxnan pynan];
## Native testing
%!assert (isPolygonCCW (pccw));
%!assert (isPolygonCCW (pxccw, pyccw));
%!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw}), {true, true});
%!assert (~isPolygonCCW (pcw));
%!assert (isPolygonCCW ({pccw;pcw}), {true;false});
%!assert (isPolygonCCW(pnan), [true; false]);
%!assert (isPolygonCCW({pnan,pcw}),{[true;false], false});
## Clipper testing
%!assert (isPolygonCCW (pccw,[],"clipper"));
%!assert (isPolygonCCW (pxccw, pyccw,"clipper"));
%!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw},"clipper"), {true, true});
%!assert (~isPolygonCCW (pcw,[],"clipper"));
%!assert (isPolygonCCW ({pccw;pcw},[],"clipper"), {true;false});
%!xtest assert (isPolygonCCW(pnan,[],"clipper"), [true; false]);
%!xtest assert (isPolygonCCW({pnan,pcw},[],"clipper"),{[true; false], false});
geometry-4.0.0/inst/isPolygonCW_Clipper.m 0000644 0000000 0000000 00000003250 13615712371 016570 0 ustar 00 0000000 0000000 ## Copyright (C) 2015-2017 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{orientation}] = isPolygonCW_Clipper (@var{inpol})
## Inspect winding direction of polygon(s).
##
## Based on Clipper library (polyclipping.sf.net / 3rd Party / Matlab)
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s)
## whose winding direction should be assessed. Subpolygons are separated by
## [NaN NaN] rows.
##
## Output argument @var{orientation} contains the winding direction(s) of
## each subpolygon: 0 for clockwise, 1 for counterclockwise.
##
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2015-05-03
function [orientation] = isPolygonCW_Clipper (inpoly)
## Input validation
if (nargin < 1)
print_usage ();
endif
if (! isnumeric (inpoly) || size (inpoly, 2) < 2)
error ("ispolycw: inpoly should be a numeric Nx2 array");
endif
inpol = __dbl2int64__ (inpoly);
## Just find out orientation of polygons
orientation = clipper (inpol);
endfunction
geometry-4.0.0/inst/ispolyccw.m 0000644 0000000 0000000 00000004506 13615712371 014716 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 - Juan Pablo Carbajal
## Copyright (C) 2017 - Piyush Jain
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @deftypefn {} {@var{ccw} =} ispolyccw (@var{p})
## @deftypefnx {} {@var{ccw} =} ispolyccw (@var{px}, @var{py})
## Returns true if the polygon @var{p} are oriented Counter-Clockwise.
##
## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates
## of the vertices of the polygon can also be given as two N-by-1 arrways
## @var{px}, @var{py}.
##
## If polygon is self-crossing, the result is undefined.
##
## If x and y contain multiple contours, either in NaN-separated vector form or in cell array form, ispolyccw returns a logical array containing one true or false value per contour.
##
## If @var{points} is a cell, each element is considered a polygon, the
## resulting @var{cww} array has the same shape as the cell.
##
## @seealso{polygonArea}
## @end deftypefn
function ccw = ispolyccw (px, py)
if (nargin > 3 || nargin < 1)
print_usage ();
endif
if(nargin == 1)
px = reshape(px, numel(px)/2, 2);
else
px = reshape(px, numel(px), 1);
py = reshape(py, numel(py), 1);
px = [px py];
endif
ccw = isPolygonCCW(px);
end
%!shared pccw, pcw, ph
%! pccw = pcw = [0 0; 1 0; 1 1; 0 1];
%! pcw([2 4],:) = pcw([4 2], :);
%! ph = [pccw; nan(1,2); 0.5*pcw+[0.25 0.25]];
%!assert (ispolyccw (pccw));
%!assert (~ispolyccw (pcw));
%!assert (ispolyccw ({pccw;pcw}), {true false});
%!assert (ispolyccw(ph),[true;false]);
%!test
%! phcw = [pcw; nan(1,2); 0.5*pccw+[0.25 0.25]];
%! assert (ispolyccw(phcw),[false;true]);
%!test
%! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3];
%! assert(ispolyccw(x,y),[false;true]);
geometry-4.0.0/inst/ispolycw.m 0000644 0000000 0000000 00000005023 13615712371 014546 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 - Juan Pablo Carbajal
## Copyright (C) 2017 - Piyush Jain
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {} {@var{ccw} =} ispolycw (@var{p})
## @deftypefnx {} {@var{ccw} =} ispolycw (@var{px}, @var{py})
## Returns true if the polygon @var{p} are oriented Clockwise.
##
## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates
## of the vertices of the polygon can also be given as two N-by-1 arrways
## @var{px}, @var{py}.
##
## If polygon is self-crossing, the result is undefined.
##
## If x and y contain multiple contours, either in NaN-separated vector form or in cell array form, ispolycw returns a logical array containing one true or false value per contour.
##
## If a contour contains two or fewer vertices, ispolycw returns true.
##
## If @var{points} is a cell, each element is considered a polygon, the
## resulting @var{cw} array has the same shape as the cell.
##
## @seealso{polygonArea}
## @end deftypefn
function cw = ispolycw (px, py)
if iscell (px)
cw = cellfun (@ispolycw, px);
else
if nargin == 2;
px = [px py];
end
px = reshape(px, numel(px)/2, 2);
px = splitPolygons (px);
for i=1:size(px)(1)
pol = px{i};
## if contour contains two or fewer vertices
if size(pol)(1) < 3
cw(i,1) = true;
else
cw(i,1) = polygonArea (pol) < 0;
endif
endfor
end
end
%!shared pccw, pcw, ph
%! pccw = pcw = [0 0; 1 0; 1 1; 0 1];
%! pcw([2 4],:) = pcw([4 2], :);
%! ph = [pccw; nan(1,2); 0.5*pcw+[0.25 0.25]];
%!assert (~ispolycw (pccw));
%!assert (ispolycw (pcw));
%!assert (ispolycw ({pccw;pcw}), [false;true]);
%!assert (ispolycw ({pccw,pcw}), [false,true]);
%!assert (ispolycw(ph),[false;true]);
%!test
%! phcw = [pcw; nan(1,2); 0.5*pccw+[0.25 0.25]];
%! assert (ispolycw(phcw),[true;false]);
%!test
%! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3];
%! assert(ispolycw(x,y),[true;false]);
geometry-4.0.0/inst/joinPolygons.m 0000644 0000000 0000000 00000004153 13615712371 015372 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {} {@var{outpol} =} joinPolygons (@var{inpol})
## Convert a cell style set of polygons into an array of subpolygons
## separated by NaN rows.
##
## @var{inpol} is expected to be an Nx1 (column) cell array with each cell
## containing either a matrix of Mx1 (X), Mx2 (X,Y), or Mx3 (X,Y,Z) coordinates.
##
## @var{outpol} is a numeric Px1, Px2 or Px3 array os subpolygons each
## separated by a row of NaN values.
##
## @seealso{splitPolygons}
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2016-05-10
function [polys] = joinPolygons (poly)
if (! iscell (poly))
error ('Octave:invalid-input-arg', 'joinPolygons: cell array expected');
elseif (isempty (poly))
polys = [];
return
elseif (isvector (poly) && any (cellfun (@(p)isrow(p) && numel(p) != 1, poly)))
error ('Octave:invalid-input-arg', 'joinPolygons: column vectors expected');
endif
XY(1:2:2*size (poly, 1), :) = [{poly{:}}'];
XY(2:2:2*size (poly, 1) - 1, :) = NaN (1, size (poly{1}, 2));
polys = cell2mat (XY);
endfunction
%!test
%! assert (joinPolygons ({1,2}), [1 2]);
%!test
%! assert (joinPolygons ({}), []);
%!test
%! XY = joinPolygons ({[1 6; 2 5; 3 4]; [4 3; 5 2; 6 1]});
%! assert (XY, [1 6; 2 5; 3 4; NaN NaN; 4 3; 5 2; 6 1]);
%!error joinPolygons ([1 2 NaN 3 4], [56 NaN 78])
%!error joinPolygons ({[1,0], [0,2]});
geometry-4.0.0/inst/orientPolygon.m 0000644 0000000 0000000 00000010100 13615712371 015535 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 - Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @deftypefn {} {@var{q} =} orientPolygon (@var{p})
## @deftypefnx {} {@dots{} =} orientPolygon (@var{p}, [], @var{dir})
## @deftypefnx {} {[@var{qx} @var{qy}] =} orientPolygon (@var{px}, @var{py})
## @deftypefnx {} {@dots{} =} orientPolygon (@var{px}, @var{py}, @var{dir})
## Orient polygon counterclockwise or clockwise.
##
## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates
## of the vertices of the polygon can also be given as two N-by-1 arrways
## @var{px}, @var{py}. It can also be cells of polygons or NaN separated polygons.
## The output has the same format as the input.
##
## The optional argument @var{dir} can be @asis{"ccw"} or @asis{"cw"}.
## By default it orients polygon counterclockwise (@code{@var{dir} == "ccw"}).
## To orient the polygon clockwise, use @code{@var{dir} == "cw"}.
##
## Holes are treated as independet polygons, that is a cw polygon with a cw hole
## will be seen as two cw polygons.
##
## If polygon is self-crossing, the result is undefined.
##
## @seealso{isPolygonCCW}
## @end deftypefn
function [x y] = orientPolygon (x, y=[], d = "ccw");
#case of wrong number of input arguments
if (nargin > 3 || nargin < 1)
print_usage ();
endif
if (!isempty (y))
if (!strcmp (typeinfo (x), typeinfo (y)))
error ('Octave:invalid-input-arg', 'X and Y should be of the same type');
endif
if(any (size (x) != size (y)) )
error ('Octave:invalid-input-arg', 'X and Y should be of the same size');
endif
endif
# define orientation mode
mode_ccw = strcmpi (d, "ccw");
if (iscell (x))
# Cell Array Format
# Call this function on each cell
if (isempty (y))
y = cell (size (x));
endif
[x y] = cellfun (@(u,v) orientPolygon (u,v,d), x, y, "unif", 0);
else
# Input are matrices
# merge them to one
x = [x y];
if any (isnan (x(:)))
# Inputs are many polygons separated with NaN
# Split them and call this function on each of them
x = splitPolygons (x);
x = cellfun (@(u) orientPolygon (u,[],d), x, "unif", 0);
x = joinPolygons (x);
else ## Here do the actual work
#Check the orientation of the polygons
if ( (!isPolygonCCW (x) && mode_ccw) || (isPolygonCCW (x) && !mode_ccw) );
x = reversePolygon (x);
endif
endif
if (!isempty (y))
y = x(:,2);
x = x(:,1);
endif
endif
endfunction
%!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan
%! pccw = [0 0; 1 0; 1 1; 0 1];
%! pcw = reversePolygon (pccw);
%! pxccw = pccw(:,1);
%! pyccw = pccw(:,2);
%! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2];
%! pynan = [0; 2; 2; 0; NaN; 0; 3; 0];
%! pnan = [pxnan pynan];
%!test
%! x = orientPolygon (pccw,[],"ccw");
%! assert (x, pccw);
%!test
%! x = orientPolygon (pccw,[],"cw");
%! assert (x, pcw);
%!test
%! x = orientPolygon (pcw,[],"ccw");
%! assert (x, pccw);
%!test
%! x = orientPolygon (pcw,[],"cw");
%! assert (x, pcw);
%!test
%! x = orientPolygon (pnan,[],"cw");
%! y = splitPolygons (pnan);
%! y = joinPolygons ({reversePolygon(y{1}); y{2}});
%! assert (x, y);
%!test
%! x = orientPolygon (pnan,[],"ccw");
%! y = splitPolygons (pnan);
%! y = joinPolygons ({y{1}; reversePolygon(y{2})});
%! assert (x, y);
%!test
%! [x y] = orientPolygon (pxccw,pyccw,"ccw");
%! assert ([x y], pccw);
%!test
%! [x y] = orientPolygon (pxccw,pyccw,"cw");
%! assert ([x y], pcw);
geometry-4.0.0/inst/plotShape.m 0000644 0000000 0000000 00000006247 13615712371 014645 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 (C) Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @defun {} {@var{h} = } plotShape (@var{shape})
## @defunx {} {@var{h} = } plotShape (@dots{}, @asis{'tol'}, @var{value})
## @defunx {} {@var{h} = } plotShape (@dots{}, @var{prop}, @var{value})
## Plots a 2D shape defined by piecewise smooth polynomials in the current axis.
##
## @var{shape} is a cell where each elements is a 2-by-(poly_degree+1) matrix
## containing a pair of polynomials.
##
## The property @asis{'Tol'} sets the tolerance for the quality
## of the polygon as explained in @command{shape2polygon}.
## Additional property value pairs are passed to @code{drawPolygon}.
##
## @seealso{drawPolygon, shape2polygon, polygon2shape}
## @end defun
function h = plotShape(shape, varargin)
# Parse arguments
# consume tolerance option
# use last one given, erase all
tol = 1e-4;
if ~isempty (varargin)
istol = cellfun (@(x)strcmp (tolower (x), 'tol'), varargin);
if any (istol)
idx = find (istol);
# use last
tol = varargin{idx(end) + 1};
# erase all
varargin([idx(:); idx(:)+1]) = [];
endif
endif
# Estimate step for discretization using random samples to get area range
pts = cell2mat (cellfun (@(x)curveval (x, rand (1, 11)), shape, 'unif', 0));
bb = boundingBox (pts);
mxrange = ( (bb(2) - bb(1)) * (bb(4) - bb(3)) ) * 0.5;
dr = tol * mxrange;
p = shape2polygon (shape, 'tol', dr);
h = drawPolygon (p, varargin{:});
endfunction
%!demo
%! # Taylor series of cos(pi*x),sin(pi*x)
%! n = 5; N = 0:5;
%! s{1}(1,2:2:2*n+2) = fliplr ( (-1).^N .* (pi).^(2*N) ./ factorial (2*N));
%! s{1}(2,1:2:2*n+1) = fliplr ( (-1).^N .* (pi).^(2*N+1) ./ factorial (2*N+1));
%!
%! h(1) = plotShape (s, 'tol', 1e-1, 'color','b');
%! h(2) = plotShape (s, 'tol', 1e-3, 'color', 'm');
%! h(3) = plotShape (s, 'tol', 1e-9, 'color', 'g');
%! legend (h, {'1e-1','1e-3','1e-9'})
%! axis image
%!shared s
%! s = {[0.1 1; 1 0]};
%!test
%! plotShape (s); close;
%!test
%! plotShape (s,'tol', 1e-4);close;
%!test
%! plotShape (s,'color', 'm', 'tol', 1e-4);close;
%!test
%! plotShape (s,'color', 'm', 'linewidth', 2, 'tol', 1e-4);close;
%!test
%! plotShape (s,'color', 'm', 'tol', 1e-4, 'linewidth', 2);close;
%!test
%! plotShape (s,'-om', 'tol', 1e-4, 'linewidth', 2);close;
%! plotShape (s,'tol', 1e-4, '-om', 'linewidth', 2);close;
%! plotShape (s,'-om', 'linewidth', 2, 'tol', 1e-4);close;
%!test
%! plotShape (s,'-om', 'tol', 1e-4, 'tol', 1e-2);close;
geometry-4.0.0/inst/poly2ccw.m 0000644 0000000 0000000 00000004255 13615712371 014445 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 - Amr Mohamed
## Copyright (C) 2017 - Piyush Jain
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING. If not,
## see .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{xccw},@var{yccw}] = poly2ccw (@var{x},@var{y})
## Convert Polygons to counterclockwise contours(polygons).
##
## @var{x}/@var{y} is a cell array or NaN delimited vector of polygons, representing the x/y coordinates of the points. If x1 and y1 can contain multiple contours, represented either as NaN-separated vectors or as cell arrays, then each contour is converted to counter-clockwise ordering.
## @var{xccw}/@var{yccw} has the same format of the input.
##
## @seealso{poly2cw,ispolycw}
## @end deftypefn
## Created: 2017-07-18
function [xccw, yccw]=poly2ccw(x,y);
if (nargin != 2)
#case of wrong number of input arguments
print_usage();
endif
if(isempty(x) || isempty(y))
error ('Octave:invalid-input-arg', ...
"poly2ccw: Empty arguments");
endif
x = reshape(x, numel(x), 1);
y = reshape(y, numel(y), 1);
[xccw, yccw] = orientPolygon(x,y,"ccw");
if(xccw(1) == xccw(2) && yccw(1) == yccw(2))
xccw = circshift(xccw,-1);
yccw = circshift(yccw,-1);
endif
endfunction
%!test
%! x = [0 0 1 1 0]; y = [0 1 1 0 0];
%! [xccw,yccw] = poly2ccw(x,y);
%! xexp = [0; 1; 1; 0; 0]; yexp = [0; 0; 1; 1; 0];
%! assert (xccw,xexp);
%! assert (yccw,yexp);
%!test
%! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3];
%! [xccw,yccw]=poly2ccw(x,y);
%! xexp=[0; 2; 2; 0; NaN; 0; 2; 0];
%! yexp=[0; 0; 2; 2; NaN; 0; 0; 3];
%! assert (xccw,xexp);
%! assert (yccw,yexp);
geometry-4.0.0/inst/poly2cw.m 0000644 0000000 0000000 00000004226 13615712371 014300 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 - Amr Mohamed
## Copyright (C) 2017 - Piyush Jain
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING. If not,
## see .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{xcw},@var{ycw}] = poly2cw (@var{x},@var{y})
## Convert Polygons to clockwise contours(polygons).
##
## @var{x}/@var{y} is a cell array or NaN delimited vector of polygons, representing the x/y coordinates of the points. If x1 and y1 can contain multiple contours, represented either as NaN-separated vectors or as cell arrays, then each contour is converted to counter-clockwise ordering.
## @var{xccw}/@var{yccw} has the same format of the input.
##
## @seealso{poly2ccw,ispolycw}
## @end deftypefn
## Created: 2017-07-18
function [xcw, ycw]=poly2cw(x,y);
if (nargin != 2)
#case of wrong number of input arguments
print_usage();
endif
if(isempty(x) || isempty(y))
error ('Octave:invalid-input-arg', ...
"poly2ccw: Empty arguments");
endif
x = reshape(x, numel(x), 1);
y = reshape(y, numel(y), 1);
[xcw, ycw] = orientPolygon(x,y,"cw");
if(xcw(1) == xcw(2) && ycw(1) == ycw(2))
xcw = circshift(xcw,-1);
ycw = circshift(ycw,-1);
endif
endfunction
%!test
%! x = [0; 1; 1; 0; 0]; y = [0; 0; 1; 1; 0];
%! [xcw,ycw] = poly2cw(x,y);
%! xexp = [0; 0; 1; 1; 0]; yexp = [0; 1; 1; 0; 0];
%! assert (xcw,xexp);
%! assert (ycw,yexp);
%!test
%! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3];
%! [xcw,ycw]=poly2cw(x,y);
%! xexp=[0; 0; 2; 2; NaN; 0; 0; 2];
%! yexp=[0; 2; 2; 0; NaN; 0; 3; 0];
%! assert (xcw,xexp);
%! assert (ycw,yexp);
geometry-4.0.0/inst/polybool.m 0000644 0000000 0000000 00000026754 13615712371 014552 0 ustar 00 0000000 0000000 ## Copyright (C) 2017-2019 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see
## .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{VXo}, @var{VYo}] = polybool (@var{op}, @var{VX1}, @var{VY1}, @var{VX2}, @var{VY2})
## @deftypefnx {Function File} [@var{MXYZ}] = polybool (@var{op}, @var{MSP}, @var{MCP})
## @deftypefnx {Function File} [@var{MXYZ}] = polybool (@dots{}, @var{library})
## Perform boolean operation(s) on polygons.
##
## The subject and clip polygons can each be represented by two separate
## input vectors. The subject polygon X and Y coordinates would be @var{VX1}
## and @var{VY1}, resp., and the clip polygon(s) X and Y coordinates would be
## @var{VX2} and @var{VY2}. All these vectors can be row or column vectors,
## numeric or cell, and the output format will match that of @var{VX1} and
## @var{VY1}.
##
## Alternatively, the subject and clip polygons can be represented by 2D or
## 3D matrices (@var{MSP} and @var{MCP}, respectively) of X, Y, and
## -optionally- Z values, where each row constitues the coordinates of one
## vertex. The Z values of clip polygon(s) are ignored. Z-values of newly
## created vertices in the output polygon(s) are copied from the nearest
## vertex in the subject polygon(s).
##
## In any case the input polygons can be multipart, where subpolygons are
## separated by NaN values (or NaN rows in case of matrix input). By
## convention, in case of nested polygons the outer polygon should have a
## clockwise winding direction, inner polygons constituting "holes" should
## have a counterclockwise winding direction; polygons nested in holes
## should again be clockwise, and so on.
##
## Every polygon part should comprise at least different 3 vertices. As
## polygons are implicitly assumed to be closed, no need to repeat the first
## vertex as last closing vertex.
##
## Likewise, output polygons returned in @var{VXo} and @var{VYo} (in case
## of vector input) or @var{MXYZ} (in case of matrix input) can be multipart
## and if so also have NaNs or NaN row(s) separating subpolygons.
##
## @var{op} is the requested operation and can be one of the following (for
## character values only the first letter is required, case-independent):
##
## @table @asis
## @item 0 (numeric)
## @itemx "subtraction"
## @itemx "minus" @*
## Subtract the clip polygon(s) from the subject polygon(s).
##
## @item 1 (numeric)
## @itemx "intersection"
## @itemx "and" @*
## Return intersection(s) of subject and clip polygon(s).
##
## @item 2 (numeric)
## @itemx "exclusiveor"
## @itemx "xor" @*
## Return ExclusiveOr(s) of subject and clip polygon(s); this is the
## complement of the 'and' operation or the result of subtracting the output
## of 'and' from 'or' operations on both polygons.
##
## @item 3 (numeric)
## @itemx "union"
## @itemx "or" @*
## Return the union of both input polygons.
## @end table
##
## @seealso{ispolycw,isShapeMultiPart}
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2017-11-12
function [xo, yo] = polybool (op, varargin)
## Input checks
if (nargin < 3)
## For matrices we need at least 3 args. For vectors we'll check later.
print_usage ();
elseif (! ischar (op) && (isnumeric (op) && (op < 0 || op > 3)))
error ("Octave:invalid-input-arg", ...
"polybool: char value or numeric value [0-3] expected for arg. #1");
endif
## Check subject polygon class and type.
## itype = 1 (column vectors), 2 (row vectors), -1 (matrix),
## 3 (cell column vectors), 4 (cell row vectors)
if (isnumeric (varargin{1}) && isnumeric (varargin{2}))
sza1 = size (varargin{1});
if (isvector (varargin{1}))
## Separate numeric vector input (ML compatible). Make it a Nx2 matrix
itype = 1;
X1 = varargin{1};
Y1 = varargin{2};
elseif (numel (sza1) == 2 && prod (sza1) > max (sza1) && ...
sza1(1) >= 3 && sza1(1) >= sza1(2))
## Matrix input (makes Z-values possible), X,Y{,Z] in columns
itype = -1;
inpol = varargin{1};
else
error ("Octave:invalid-input-arg", ...
"polybool: Nx2 or Nx3 (with N > 2) numeric input expected for arg #2");
endif
elseif (iscell (varargin{1}) && iscell (varargin{2}))
## Always assume (ML-compatible) vector input
itype = 3;
[X1, Y1] = polyjoin (varargin{1}, varargin{2});
else
error ("Octave:invalid-input-arg", ...
"polybool: X1, Y1 input vectors must be same class");
endif
if (itype != -1)
## X1 and X2 are assumed numeric vectors now
if (numel (X1) != numel (Y1))
error ("Octave:invalid-input-arg", ...
"polybool: X1, Y1 input vectors must be same length");
endif
if (isrow (X1) != isrow (Y1))
error ("Octave:invalid-input-arg", ...
"polybool: X1 and Y1 should have same dimension");
endif ## Convert vector input into a Nx2 matrix
if (isrow (X1))
++itype;
inpol = [X1; Y1]';
else
inpol = [X1 Y1];
endif
endif
if (size (inpol, 1) < 3)
## Not a polygon
error ("Octave:invalid-input-arg", ...,
"polybool: input 'polygon' has less than 3 vertices");
endif
## Check clip polygon class and type.
## ctype = 1 (column vectors), 2 (row vectors), -1 (matrix),
## 3 (cell column vectors), 4 (cell row vectors)
if (itype == -1)
## Matrix input
sza2 = size (varargin{2});
if (numel (sza2) == 2 && prod (sza2) > max (sza2) && ...
sza2(1) >= 3 && sza2(1) >= sza2(2))
ctype = -1;
clpol = varargin{2};
else
error ("Octave:invalid-input-arg", ...,
"polybool: Nx3 matrix input (with N > 2) expected for arg #3");
endif
elseif (nargin < 5)
# For vector input we need at least 5 args
print_usage ();
else
if (isnumeric (varargin{3}) && isnumeric (varargin{4}))
ctype = 1;
X2 = varargin{3};
Y2 = varargin{4};
elseif (iscell (varargin{3}) && iscell (varargin{4}))
ctype = 3;
[X2, Y2] = polyjoin (varargin{3}, varargin{4});
else
error ("Octave:invalid-input-arg", ...
"polybool: X2, Y2 input vectors must be same class");
endif
if (isrow (X2) != isrow (Y2))
error ("Octave:invalid-input-arg", ...
"polybool: X2 and Y2 should have same dimension");
endif
if (numel (X2) != numel (Y2))
error ("Octave:invalid-input-arg", ...
"polybool: X2, Y2 input vectors must be same length");
endif
## Turn clip poygon into matrix
if (isrow (X2))
++ctype;
clpol = [X2; Y2]';
else
clpol = [X2 Y2];
endif
endif
if (size (inpol, 1) < 3)
## Not a polygon
error ("Octave:invalid-input-arg", ...,
"polybool: clip 'polygon' has less than 3 vertices");
endif
## Boolean operation library
ichar = 0;
blib = "clipper";
## Find out arg no. of library name
if (itype == -1 && nargin > 3)
ichar = 3;
elseif (nargin > 5)
ichar = 5;
endif
if (ichar)
if (ischar (varargin{ichar}))
blib = lower (varargin{ichar});
if (! ismember (blib, {"clipper", "mrf"}))
error ("Octave:invalid-input-arg", ...,
"polybool: unknown polygon library - %s", blib);
endif
elseif (! ischar (varargin{ichar}))
print_usage ();
endif
endif
if (ischar (op))
switch (lower (op(1)))
case {"s", "m", "-"}
## Subtraction
op = 0;
case {"i", "a", "&"}
## Intersection / And
op = 1;
case {"e", "x"}
## ExclusiveOR
op = 2;
case {"u", "o", "|", "+", "p"}
## Union / Or
op = 3;
otherwise
error ("Octave:invalid-input-arg", ...
"polybool: unknown operation '%s'", op);
endswitch
endif
## Call clipPolygon (geometry pkg) to do the work
try
if (strcmp (blib, "clipper"))
[outpol, npol] = clipPolygon_clipper (inpol, clpol, op);
else
[outpol, npol] = clipPolygon_mrf (inpol, clpol, op);
endif
catch
error ("polybool: internal error, possibly invalid geometric input");
end_try_catch
## Postprocess output to match input formats
switch itype
case 1
## Numeric column input
xo = outpol(:, 1);
yo = outpol(:, 2);
case 2
## Numeric row input
xo = outpol(:, 1)';
yo = outpol(:, 2)';
case 3
## cell column input
xo = {outpol(:, 1)};
yo = {outpol(:, 2)};
case 4
## Cell row input
xo = {outpol(:, 1)'};
yo = {outpol(:, 2)'};
case -1
## Matrix input
xo = outpol;
yo = [];
otherwise
endswitch
endfunction
%!shared ipol, cpol, ix, iy, cx, cy, xi, yi, xc, yc
%! ipol = [0 0; 3 0; 3 3; 0 3; 0 0];
%! cpol = [2, 1; 5, 1; 5, 4; 2, 4; 2, 1];
%! ix = {ipol(:, 1)'};
%! iy = {ipol(:, 2)'};
%! cx = {cpol(:, 1)'};
%! cy = {cpol(:, 2)'};
%! xi = {ipol(:, 1)};
%! yi = {ipol(:, 2)};
%! xc = {cpol(:, 1)};
%! yc = {cpol(:, 2)};
%% Subtraction - matrix input
%!test
%! opol = polybool (0, ipol, cpol);
%! assert (size (opol), [7, 2]);
%! assert (polygonArea (opol), 7);
%% Subtraction - row vector input input
%!test
%! [ox, oy] = polybool (0, ix, iy, cx, cy);
%! opol = [ox{1}', oy{1}'];
%! assert (size (opol), [7, 2]);
%! assert (polygonArea (opol), 7);
%% Subtraction - column vector input input
%!test
%! [ox, oy] = polybool (0, xi, yi, xc, yc);
%! opol = [ox{1}, oy{1}];
%! assert (size (opol), [7, 2]);
%! assert (polygonArea (opol), 7);
%!test
%! opol = polybool (1, cpol, ipol);
%! assert (size (opol), [5, 2]);
%! assert (polygonArea (opol), 2);
%!test
%! [ox, oy] = polybool (1, ix, iy, cx, cy);
%! opol = [ox{1}', oy{1}'];
%! assert (size (opol), [5, 2]);
%! assert (polygonArea (opol), 2);
%!test
%! opol = polybool (2, cpol, ipol);
%! assert (size (opol), [15, 2]);
%! assert (polygonArea (opol), 14);
%!test
%! [ox, oy] = polybool (2, ix, iy, cx, cy);
%! opol = [ox{1}', oy{1}'];
%! assert (size (opol), [15, 2]);
%! assert (polygonArea (opol), 14);
%!test
%! opol = polybool (3, cpol, ipol);
%! assert (size (opol), [9, 2]);
%! assert (polygonArea (opol), 16);
%!test
%! [ox, oy] = polybool (3, ix, iy, cx, cy);
%! opol = [ox{1}', oy{1}'];
%! assert (size (opol), [9, 2]);
%! assert (polygonArea (opol), 16);
%!error polybool ("a", 1, 2, 3 ,4);
%!error polybool (-1, 1, 2);
%!error polybool (-1, [1 1; 2 2; 3 3], [2 2; 3 3; 4 4]);
%!error polybool (1, [0 0 0; 2 2 2; 5 5 5], [1 1 1; 3 3 3]);
%!error polybool (1, [0 0 0; 2 2 2; 5 5 5], [1 1 1; 3 3 3; 6 6 7]);
%!error polybool (1, {1, 2}, [1, 2]);
%!error polybool (1, {[1, 2, 3]}, {[1, 2, 3, 4]});
%!error polybool (1, {[1, 2, 3]}, {[1, 2, 3]}, {[1, 2, 3]}, {[1, 2, 4, 5]});
%!error polybool ('z', {[1, 2, 3]}, {[1, 2, 3]}, {[1, 2, 3]}, {[1, 2, 4]});
%!error polybool (1, [1 1; 2 2; 3 3], [2 2; 3 3; 4 4], "abc") geometry-4.0.0/inst/polygon2patch.m 0000644 0000000 0000000 00000015661 13615712371 015477 0 ustar 00 0000000 0000000 ## Copyright (C) 2015-2017 Philip Nienhuis
## Copyright (C) 2016 - Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {} { @var{XYo} =} polygon2patch (@var{XYi})
## @deftypefnx {} [@var{Xo}, @var{Yo} ] = polygon2patch (@var{Xi}, @var{Yi})
## @deftypefnx {} [@var{Xo}, @var{Yo}, @var{Zo} ] = polygon2patch (@var{Xi}, @var{Yi}, @var{Zi})
## Connect outer (filled) polygon and inner (hole) polygons using branch cuts
## such that all polygons are connected as one string of vertices, for
## subsequent plotting polygons with holes using the function @command{patch}.
##
## @var{XYi} can be a 2 or 3 dimensional array; only the X and Y coordinates
## will be optmized and Z-values will be kept with their original vertices.
## Alternatively separate X, Y and optionally Z-vectors can be specified.
## The outer polygon should appear as a first subvector, bounded by a row of
## NaN values, and have a counterclockwise winding direction. All subsequent
## inner hole polygons should also be bounded by rows of NaN values and have
## clockwise winding directions.
##
## This function expects and returns column vectors or matrices where
## each row contains coordinates of a vertex.
##
## @seealso{drawPolygon, patch}
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2016-04-30
function [X, Y, Z] = polygon2patch (XX, YY=[], ZZ=[]);
matinp = 0;
XYsz = size (XX, 2);
## Check args
if (nargin == 1)
if (ismatrix (XX) && XYsz >= 2)
## apparently matrix input rather than two separate X,Y[,Z] vectors
matinp = 1;
XY = XX;
endif
elseif (nargin >= 2)
## Separate vector input
XY = [XX YY ZZ];
elseif (nargin < 1)
error ("Octave:invalid-input-arg", ...
"polygon2patch: not enough input arguments");
endif
## Also keep track of Z.
## Z isn't (yet) in the branch cut optimization
## (but that could be done easily)
if (isempty (ZZ) || XYsz == 2)
## At least provide pointers where Z coordinates have gone
## in output arrays
ZZ = [1:size(XY, 1)]';
XY = [ XY ZZ ];
endif
Z = [];
## Find NAN separators
idx = find (isnan (XY(:, 1)));
if (isempty (idx))
## No NaN separators => no subfeatures. Return
if (!matinp)
X = XX; Y = YY;
if (nargin == 3)
Z = ZZ;
endif
else
X = XX;
Y = [];
endif
return
endif
ipt = [0; idx; numel(XY(:, 1))+1];
for ii=1:numel (ipt) - 1
## Check for closed polygon
if (any (abs (XY(ipt(ii)+1, 1:2) - XY(ipt(ii+1)-1, 1:2)) > eps))
## Duplicate first vertex as last vertex of subpolygon
## First shift all subpolys down
XY(ipt(ii+1)+1:end+1, :) = XY(ipt(ii+1):end, :);
ipt(ii+1:end) += 1;
XY(ipt(ii+1)-1, :) = XY(ipt(ii)+1, :);
endif
XY(ipt(ii)+1:ipt(ii+1)-1, 4) = [ ipt(ii)+1:ipt(ii+1)-1 ]';
endfor
## Compute all interdistances
XY(ipt(2:end-1), :) = [];
dists = distancePoints (XY(:, 1:2), XY(:, 1:2));
szdst = size (dists);
dists = dists + tril (Inf (szdst(1)));
X_Y = XY(1:ipt(2)-1, :);
## Keep track of which holes are still unconnected
processed = [0 (ones (1, numel (ipt) - 2))];
tt = cumsum (diff (ipt) - 1);
idx = [tt(1:end-1)+1 tt(2:end)];
odx = 1:(ipt(2) - 1);
ody = 1:size (dists, 2);
## Find hole polygon with smallest distance to an outer vertex; afterwards
## assign that to outer vertex + restart search until all holes are processed.
## FIXME Although Octave doesn't draw the branch cuts, it may be better to
## also check that branch cuts do not cross polygons between two
## vertices belonging to other polygons (or self-intersect polygons)
while (any (processed))
## Get slice of dists with outer vertices + vertices connected to it, excl.
## columns already processed
odz = setdiff (ody, odx);
[~, indx] = min (dists(odx, odz)(:));
## Get subscripts into sliced dists matrix
[r, c] = ind2sub ([numel(odx),numel(odz)], indx);
## Recompute subscripts into full dists matrix
rr = odx(r); ## Needed to insert new hole into place
cc = odz(c); ## To rotate hole such that this vertex has
## smallest distance to outer polygon vertex
## Find hole polygon corresponding to these subscripts
ii = find (cc >= idx(:, 1) & cc < idx(:, 2));
shft = idx(ii, 1) - cc;
tmpXY = XY(idx(ii, 1):idx(ii, 2), :);
if (shft)
tmpXY(1:end-1, :) = circshift (tmpXY(1:end-1, :), [shft, 0]);
## tmpXY is always shifted upward here. Copy toprow coordinates to bottom
tmpXY(end, :) = tmpXY(1, :);
endif
X_Y = [X_Y(1:r, :); tmpXY; X_Y(r:end, :)];
odx = [odx idx(ii, 1):idx(ii, 2)];
processed(ii+1) = 0;
endwhile
if (!matinp)
X = X_Y(:, 1);
Y = X_Y(:, 2);
if (nargin == 3)
Z = X_Y(:, 3);
endif
else
X = X_Y(:, 1:XYsz);
Y = [];
endif
endfunction
%!demo
%! figure()
%! p = [0 0; 0 1; 1 1; 1 0]; %ccw
%! pp = [0 0; 1 0; 1 1; 0 1]; %cw
%! ph = p + [1.2 0];
%! # add hole
%! ph(end+1,:) = nan;
%! ph = [ph; (pp-[0.5 0.5])*0.5+[1.7 0.5]];
%! po = polygon2patch (ph);
%! patch (po(:,1), po(:,2), 'b', 'facecolor', 'c');
%! axis image
%!demo
%! holes = [0 0; 35 0; 35 25; 0 25; 0 0; NaN NaN; 7 1; 2 1; 3 5; 6 6; 7 1; ...
%! NaN NaN; 9 2; 8 5; 18 7; 28 5; 30 2; 9 2; NaN NaN; 19 11; 18 14; 21 13; ...
%! 19 11; NaN NaN; 24 24; 34 24; 34 6; 24 24; NaN NaN; 9 6; 7 14; 9 18; 9 6; ...
%! NaN NaN; 27 6; 27 12; 31 9; 27 6; NaN NaN; 2 24; 23 24; 22 21; 23 19; ...
%! 1 23; 2 24; NaN NaN; 18 8; 26 13; 26 7; 18 8; NaN NaN; 8 18; 6 14; 8 7; ...
%! 2 9; 1 18; 5 19; 8 18; NaN NaN; 13 16; 17 8; 10 6; 13 16; NaN NaN; 34 1; ...
%! 28 6; 31 8; 34 1; NaN NaN; 9 20; 26 17; 31 10; 24 15; 8 19; 9 20];
%! subplot (2, 2, 1);
%! p1 = plot (holes(:, 1), holes(:, 2), 'b'); box off; axis off
%! title ("Plot of array 'holes'");
%! subplot (2, 2, 2);
%! p2 = patch (holes(:, 1), holes(:, 2), 'b', 'facecolor', 'c'); box off; axis off
%! title ("Patch of array 'holes'\nbefore processing");
%! subplot (2, 2, 3);
%! pt = polygon2patch (holes);
%! p3 = plot (pt(:, 1), pt(:, 2), 'b'); box off; axis off
%! title ("Plot of array 'holes'\nafter polygon2patch");
%! subplot (2, 2, 4);
%! p4 = patch (pt(:, 1), pt(:, 2), 'b', 'facecolor', 'c'); box off; axis off
%! title ("Patch of array 'holes'\nafter polygon2patch");
geometry-4.0.0/inst/polygon2shape.m 0000644 0000000 0000000 00000003633 13615712371 015474 0 ustar 00 0000000 0000000 ## Copyright (C) 2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @deftypefn {Function File} {@var{shape} = } polygon2shape (@var{polygon})
## Converts a polygon to a shape with edges defined by smooth polynomials.
##
## @var{polygon} is a N-by-2 matrix, each row representing a vertex.
## @var{shape} is a N-by-1 cell, where each element is a pair of polynomials
## compatible with polyval.
##
## In its current state, the shape is formed by polynomials of degree 1. Therefore
## the shape representation costs more memory except for colinear points in the
## polygon.
##
## @seealso{shape2polygon, simplifyPolygon, polyval}
## @end deftypefn
function shape = polygon2shape (polygon)
# Filter colinear points
polygon = simplifyPolygon_geometry (polygon);
np = size(polygon,1);
# polygonal shapes are memory inefficient!!
# TODO filter the regions where edge angles are canging slowly and fit
# polynomial of degree 3;
pp = nan (2*np,2);
# Transform edges into polynomials of degree 1;
# pp = [(p1-p0) p0];
pp(:,1) = diff(polygon([1:end 1],:)).'(:);
pp(:,2) = polygon.'(:);
shape = mat2cell(pp, 2*ones (1,np), 2);
endfunction
%!test
%! pp = [0 0; 1 0; 1 1; 0 1];
%! s = polygon2shape (pp);
geometry-4.0.0/inst/polyjoin.m 0000644 0000000 0000000 00000011637 13615712371 014550 0 ustar 00 0000000 0000000 ## Copyright (C) 2016 Amr Mohamed
## Copyright (C) 2017 Piyush Jain
## Copyright (C) 2017-2018 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see
## .
## -*- texinfo -*-
## @deftypefn {} [@var{xo}, @var{yo}] = polyjoin (@var{xi}, @var{yi})
## @deftypefnx {} {@var{xyo} =} polyjoin (@var{xi})
## Convert cell arrays of multipart polygon coordinates to numeric
## vectors with polygon parts separated by NaNs.
##
## @var{xi} and @var{yi} are cell vectors where each cell contains a
## numeric vector of X and Y coordinates, resp. Alternatively, @var{xi}
## can be a cell array wih each cell containing Nx2 or Nx3 matrices
## constituting XY or XYZ coordinates of polygon part vertices and yi
## can be omitted.
##
## @var{xo} and @var{yo} are vectors of X and Y coordinates of polygon
## vertices where polygon parts are separated by NaNs. If @var{xi} and
## @var{yi} either were row vectors or contained row vectors, @var{xo}
## and @var{yo} will be returned as row vectors, otherwise as column
## vectors.
##
## If @var{xi} contained Nx2 or Nx3 matrices, @var{xo} will be a Nx2
## or Nx3 matrix where polygon parts are separetd by NaN rows. @var{yo}
## will be empty.
##
## polyjoin ultimately calls function joinPolygons in the Geometry package.
##
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2017-11-19
function [xo, yo] = polyjoin (xi, yi)
## Input checks
if (nargin < 1)
print_usage ();
elseif (! iscell (xi))
error ("Octave:invalid-input-arg", ...
"polyjoin: input cell array or vectors expected");
elseif (nargin == 1 && (! iscell (xi) ||
(isnumeric (xi{1}) && size (xi{1}, 2) < 2)))
error ("Octave:invalid-input-arg", ...
"polyjoin: Nx2 or Nx3 matrix expected for arg. #1");
elseif (nargin > 1 && ! iscell (yi))
error ("Octave:invalid-input-arg", ...
"polyjoin: expected 2 cell arrays of coordinate vectors");
elseif (nargin > 1 && nargout < 2)
warning ("Octave:invalid-input-arg", ...
["polyjoin: nr. of input arguments doesn't match nr. of output" ...
" arguments"]);
endif
## Remember input vector orientation; does not apply to input matrices
ir = 0;
if (isvector (xi{1}))
if (nargin == 1)
yi = {};
endif
if (isrow (xi{1}))
## Transpose
ir = 1;
xi = cellfun (@transpose, xi, "uni", 0);
yi = cellfun (@transpose, yi, "uni", 0);
endif
if (isrow (xi) && ! isscalar (xi))
ir = 1;
xi = xi';
yi = yi';
endif
yo = joinPolygons (yi);
else
yo = [];
endif
## if (numel (xi) > 1)
xo = joinPolygons (xi);
## else
## xo = cell2mat (xi);
## endif
if (ir)
## Convert back to row vectors
xo = xo';
yo = yo';
endif
endfunction
%!demo
%! x = {[1 2]'; [3 4]'}
%! y = {[10 20]'; [30 40]'}
%! [vecx, vecy] = polyjoin (x, y)
%!test
%! x = {[1 2]'; [3 4]'}; y = {[10 20]'; [30 40]'};
%! [vecx, vecy] = polyjoin (x, y);
%! assert (vecx, [1; 2; NaN; 3; 4]);
%! assert (vecy, [10; 20; NaN; 30; 40]);
%!test
%! x = {[1;2]; [3;4]; [3]}; y = {[10;20]; [30;40]; [10]};
%! [vecx, vecy] = polyjoin (x, y);
%! assert (vecx, [1; 2; NaN; 3; 4; NaN; 3]);
%! assert (vecy, [10; 20; NaN; 30; 40; NaN; 10]);
%!test
%! x = {[1 2 3]'; 4; [5 6 7 8 NaN 9]'};
%! y = {[9 8 7]'; 6; [5 4 3 2 NaN 1]'};
%! [vecx, vecy] = polyjoin (x, y);
%! assert (vecx, [1; 2; 3; NaN; 4; NaN; 5; 6; 7; 8; NaN; 9]);
%! assert (vecy, [9; 8; 7; NaN; 6; NaN; 5; 4; 3; 2; NaN; 1]);
## Test 2D input matrices
%!test
%! xyi = {[0 0; 0 10; 10, 10; 10, 0; 0, 0]; [1 5; 2 5; 2 6; 1 6; 1 5]};
%! xyo = polyjoin (xyi);
%! assert (polyjoin (xyi), [0 0; 0 10; 10 10; 10 0; 0 0; NaN, NaN; 1 5; 2 5; 2 6; 1 6; 1 5], eps);
## Test 3D input matrices
%!test
%! xyi = {[0 0 1; 0 10 2; 10, 10 3; 10, 0 2; 0, 0 1]; [1 5 1.5; 2 5 2; 2 6 2.5; 1 6 2; 1 5 1.5]};
%! xyo = polyjoin (xyi);
%! assert (polyjoin (xyi), [0 0 1; 0 10 2; 10 10 3; 10 0 2; 0 0 1; NaN, NaN NaN; 1 5 1.5; 2 5 2; 2 6 2.5; 1 6 2; 1 5 1.5], eps);
## Corner case of just one point
%!test
%! assert (polyjoin ({[2, 3]}), [2, 3], eps);
%!error polyjoin (1);
%!error polyjoin ({2});
%!error polyjoin ({2, 3});
%!error polyjoin ({1; 2}, [3 4]);
%!warning polyjoin ({1; 2}, {3 4});
geometry-4.0.0/inst/polysplit.m 0000644 0000000 0000000 00000006207 13615712371 014741 0 ustar 00 0000000 0000000 ## Copyright (C) 2017 - Piyush Jain
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING. If not,
## see .
## -*- texinfo -*-
## @deftypefn {Function File}[@var{cellx},@var{celly}] = polysplit(@var{vecx},@var{vecy})
## Convert NaN separated polygon vectors to cell arrays of polygons.
##
## @var{vecx}/@var{vecy} is a row/column vector of points, with possibly couples of NaN values.
##
## The function separates each component separated by NaN values, and
## returns a cell array of polygons.
##
## @seealso{polyjoin,ispolycw}
## @end deftypefn
## Created: 2017-07-19
function [cellx,celly] = polysplit(vecx,vecy)
if (nargin != 2)
#case wrong number of input arguments
print_usage();
endif
if (iscell (vecx))
if (iscell (vecy))
# case of having two cell array
cellx = vecx;
celly = vecy;
else
error ('Octave:invalid-input-arg', ...
"polysplit: vecx and vecy have different forms");
endif
elseif (length (vecx)!=length (vecy))
# case of having two vectors of different lengthes
error ('Octave:invalid-input-arg', ...
"polysplit: vecx and vecy are of different lengths");
elseif (sum (isnan (vecx(:))) != sum (isnan (vecy(:))))
error ('Octave:invalid-input-arg', ...
"polysplit: vecx and vecy should have the same number of polygon segments");
else
##column vector
if(size(vecx)(2) == 1 && size(vecy)(2) == 1)
#split the cell arrays of x coordinates and y coordinates
cellx = splitPolygons(vecx);
celly = splitPolygons(vecy);
##row vector
elseif(size(vecx)(1) == 1 && size(vecy)(1) == 1)
vecx = vecx';
vecy = vecy';
cellx = splitPolygons(vecx);
celly = splitPolygons(vecy);
cellx = cellfun(@transpose,cellx,'UniformOutput',false);
celly = cellfun(@transpose,celly,'UniformOutput',false);
endif
#Check and remove if there are any empty cells
emptyCells = cellfun(@isempty,cellx);
emptyCells = cellfun(@isempty,celly);
cellx(emptyCells) = [];
celly(emptyCells) = [];
endif
endfunction
%!test
%! x=[1 ;2 ;NaN ;3 ;4]; y=[4 ;3 ;NaN ;2 ;1];
%! [cellx,celly]=polysplit(x,y);
%! assert (cellx, {[1; 2];[3; 4]});
%! assert (celly, {[4; 3];[2; 1]});
%!test
%! x=[1 2 NaN 3 4]; y=[4 3 NaN 2 1];
%! [cellx,celly]=polysplit(x,y);
%! assert (cellx, {[1 2];[3 4]});
%! assert (celly, {[4 3];[2 1]});
%!test
%! x=[0 ;2 ;2 ;0 ;0 ;NaN ;NaN]; y=[0 ;0 ;3 ;3 ;0 ;NaN ;NaN];
%! [cellx,celly]=polysplit(x,y);
%! assert (cellx, {[0 ;2 ;2 ;0 ;0]});
%! assert (celly, {[0 ;0 ;3 ;3 ;0]}); geometry-4.0.0/inst/private/ 0000755 0000000 0000000 00000000000 13615712371 014171 5 ustar 00 0000000 0000000 geometry-4.0.0/inst/private/__dbl2int64__.m 0000644 0000000 0000000 00000003766 13615712371 016667 0 ustar 00 0000000 0000000 ## Copyright (C) 2017-2019 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
function [opol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly=[], xy_mean=[], xy_magn=[])
if (isempty (clippoly))
clippoly = zeros (0, size (inpoly, 2));
endif
if (isempty (xy_mean))
## Convert & scale to int64 (that's what Clipper works with)
## Find (X, Y) translation
xy_mean = mean ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :));
## Find (X, Y) magnitude
xy_magn = max ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :)) ...
- min ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :));
## Apply (X,Y) multiplication (floor (log10 (intmax ("int64"))) = 18)
xy_magn = 10^(17 - ceil (max (log10 (xy_magn))));
endif
## Scale inpoly coordinates to optimally use int64
inpoly(:, 1:2) -= xy_mean;
inpoly *= xy_magn;
idin = [ 0 find(isnan (inpoly (:, 1)))' numel(inpoly (:, 1))+1 ];
## Provisional preallocation. npolx is average nr. of vertices per polygon
npolx = fix (size (inpoly, 1) / numel (idin)-1);
npoly = size (inpoly, 2);
opol = repmat (struct ("x", zeros (npolx, npoly), "y", zeros (npolx, npoly)), ...
1, numel(idin) - 1);
for ii=1:numel (idin) - 1
opol(ii).x = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 1));
opol(ii).y = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 2));
endfor
endfunction
geometry-4.0.0/inst/private/__polytostruct__.m 0000644 0000000 0000000 00000002460 13615712371 017740 0 ustar 00 0000000 0000000 ## Copyright (C) 2017 - Piyush Jain
## Copyright (C) 2017 - Juan Pablo Carbajal
## Copyright (C) 2017-2019 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
function [opol] = __polytostruct__ (inpoly)
idin = [ 0 find(isnan (inpoly (:, 1)))' numel(inpoly (:, 1))+1 ];
## Provisional preallocation. npolx is average nr. of vertices per polygon
npolx = fix (size (inpoly, 1) / numel (idin) - 1);
npoly = size (inpoly, 2);
opol = repmat (struct ("x", zeros (npolx, npoly), "y", zeros (npolx, npoly)), ...
1, numel(idin) - 1);
for ii=1:numel (idin) - 1
opol(ii).x = inpoly(idin(ii)+1:idin(ii+1)-1, 1);
opol(ii).y = inpoly(idin(ii)+1:idin(ii+1)-1, 2);
endfor
endfunction
geometry-4.0.0/inst/private/lineGeo.m 0000644 0000000 0000000 00000002320 13615712371 015726 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{str} = lineGeo (@var{n}, @var{pi}, @var{pj})
## Generates a string for Gmsh Line format.
##
## Curves are Gmsh's second type of elementery entities, and,
## amongst curves, straight lines are the simplest. A straight line is
## defined by a list of point numbers. The initial point @var{pi}, the final
## point @var{pj}. @var{n} is an indetifier for the line.
##
## @end deftypefn
function str = lineGeo(n,i,j)
str = sprintf('Line(%d) = {%d,%d};\n',n,i,j);
end
geometry-4.0.0/inst/private/lineLoopGeo.m 0000644 0000000 0000000 00000002644 13615712371 016571 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{str} = lineLoopGeo (@var{id}, @var{nl}, @var{lns})
## Generates a string for Gmsh Line Loop format.
##
## The third elementary entity is the surface. In order to define a
## simple rectangular surface from defined lines, a
## line loop has first to be defined. A line loop is a list of
## connected lines, a sign being associated with each line (depending
## on the orientation of the line). @var{id} is an indentifier for the loop.
## @var{nl} is the number of lines in the loop. @var{lns} is the list of lines.
##
## @end deftypefn
function str = lineLoopGeo(id,nl,lns)
substr = repmat(',%d',1,nl-1);
str = sprintf(['Line Loop(%d) = {%d' substr '};\n'],id,lns);
end
geometry-4.0.0/inst/private/planeSurfGeo.m 0000644 0000000 0000000 00000003354 13615712371 016746 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{str} = planeSurfGeo (@var{id}, @var{nloop},@var{loops})
## Generates a string for Gmsh Plane Surface format.
##
## @var{id} is the plane surface's identification number.
## @var{nloop} is the number of loops defining the surface.
## @var{loops} contain the identification numbers of all the line loops defining
## the surface. The first line loop defines the exterior boundary of the surface;
## all other line loops define holes in the surface. A line loop defining a hole
## should not have any lines in common with the exterior line loop (in which case
## it is not a hole, and the two surfaces should be defined separately).
## Likewise, a line loop defining a hole should not have any lines in common with
## another line loop defining a hole in the same surface (in which case the two
## line loops should be combined).
##
## @end deftypefn
function str = planeSurfGeo(id,nloop,loops)
substr = repmat(',%d',1,nloop-1);
str = sprintf(['Plane Surface(%d) = {%d' substr '};\n'],id,loops);
end
geometry-4.0.0/inst/private/pointGeo.m 0000644 0000000 0000000 00000002562 13615712371 016140 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{str} = poointGeo (@var{n}, @var{xyz}, @var{l})
## Generates a string for Gmsh Point format.
##
## Gmsh's simplest `elementary entity', a `Point'. A Point is defined by a list
## of five numbers: @var{n} the identificator, @var{xyz} three coordinates (X, Y
## and Z), and a characteristic length @var{l} that sets the target element size
## at the point:
## The distribution of the mesh element sizes is then obtained by
## interpolation of these characteristic lengths throughout the
## geometry.
##
## @end deftypefn
function str = pointGeo(n,xyz,l)
str = sprintf('Point(%d) = {%.16g,%.16g,%.16g,%.16g};\n',n,xyz,l);
end
geometry-4.0.0/inst/private/ruledSurfGeo.m 0000644 0000000 0000000 00000003331 13615712371 016755 0 ustar 00 0000000 0000000 ## Copyright (C) 2012 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} @var{str} = ruledSurfGeo (@var{id}, @var{nloop}, @var{loops}, @var{centerid})
## Generates a string for Gmsh Ruled Surface format.
##
## Creates a ruled surface with identifier @var{id}, i.e., a surface that can be
## interpolated using transfinite interpolation. @var{nloop} indicates the number
## of loops that define the surface. @var{loops} should contain the identification
## number of a line loop composed of either three or four elementary lines.
## @var{centerid} is the identification number of the center of the sphere, this
## forces the surface to be a spherical patch.
##
## @end deftypefn
function str = ruledSurfGeo(id,nloop,loops,centerid)
substr = repmat(',%d',1,nloop-1);
if ~isempty(centerid)
str = sprintf(['Ruled Surface(%d) = {%d' substr '} In Sphere {%d};\n'], ...
id,loops,centerid);
else
error('data2geo:Error',"The id of the centers shouldn't be empty");
end
end
geometry-4.0.0/inst/shape2polygon.m 0000644 0000000 0000000 00000005210 13615712371 015465 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @defun {@var{polygon} = } shape2polygon (@var{shape})
## @defunx {@var{polygon} = } shape2polygon (@dots{},@var{property},@var{value},@dots{})
## Transforms a 2D shape described by piecewise smooth polynomials into a polygon.
##
## @var{shape} is a n-by-1 cell where each element is a pair of polynomials
## compatible with polyval.
## @var{polygon} is a k-by-2 matrix, where each row represents a vertex.
## The property-value pairs are passed to @code{curve2polyline}.
##
## @seealso{polygon2shape, curve2poyline}
## @end defun
function polygon = shape2polygon (shape, varargin)
polygon = cell2mat (cellfun ( ...
@(x) curve2polyline (x, varargin{:}), shape, 'UniformOutput', false));
polygon = simplifyPolygon_geometry (polygon);
if size (polygon, 1) == 1
polygon(2,1) = polyval (shape{1}(1,:), 1);
polygon(2,2) = polyval (shape{1}(2,:), 1);
end
endfunction
%!demo
%! shape = {[-93.172 606.368 -476.054 291.429; ...
%! -431.196 637.253 11.085 163.791]; ...
%! [-75.3626 -253.2337 457.1678 328.5714; ...
%! 438.7659 -653.6278 -7.9953 380.9336]; ...
%! [-89.5841 344.9716 -275.3876 457.1429; ...
%! -170.3613 237.8858 1.0469 158.0765];...
%! [32.900 -298.704 145.804 437.143; ...
%! -243.903 369.597 -34.265 226.648]; ...
%! [-99.081 409.127 -352.903 317.143; ...
%! 55.289 -114.223 -26.781 318.076]; ...
%! [-342.231 191.266 168.108 274.286; ...
%! 58.870 -38.083 -89.358 232.362]};
%!
%! # Estimate a good tolerance
%! n = cell2mat(cellfun(@(x)curveval(x,rand(1,10)), shape, 'uniformoutput',false));
%! dr = (max(n(:,1))-min(n(:,1)))*(max(n(:,2))-min(n(:,2)))*40;
%! p = shape2polygon (shape,'tol',dr);
%!
%! figure(1)
%! plotShape(shape,'-b');
%! hold on;
%! drawPolygon (p,'-or');
%! hold off
geometry-4.0.0/inst/shapeArea.m 0000644 0000000 0000000 00000005553 13615712371 014576 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @deftypefn {Function File} { [@var{a}, @var{ccw}]=} shapeArea (@var{pp})
## Calculate the area of a 2D shape defined with piecewise smooth polynomials.
##
## Shape is defined with piecewise smooth polynomials. @var{pp} is a
## cell where each elements is a 2-by-(poly_degree+1) array containing a pair of
## polynomials.
##
## @code{px(i,:) = pp@{i@}(1,:)} and @code{py(i,:) = pp@{i@}(2,:)}.
##
## The returned area is always positive even if the shape is parametrized
## in a clockwise direction. If the case of a clockwise parametrized shape
## @code{@var{ccw} == -1} otherwise @code{@var{ccw} == 1}.
##
## @seealso{shapeCentroid, shape2polygon, plotShape}
## @end deftypefn
function [A ccw] = shapeArea (shape)
A = sum (cellfun (@Aint, shape));
ccw = sign (A);
if (A < 0)
warning ('geom2d:cw-shape', ...
['Shape has negative area. ' ...
'Assuming this is due to a clockwise parametrization of the boundary']);
A = ccw * A;
end
endfunction
function dA = Aint (x)
px = x(1,:);
py = x(2,:);
P = polyint (conv (px, polyder(py)));
dA = diff (polyval (P,[0 1]));
end
%!demo # non-convex piece-wise polynomial shape
%! boomerang = {[ 0 -2 1; ...
%! -4 4 0]; ...
%! [0.25 -1; ...
%! 0 0]; ...
%! [ 0 1.5 -0.75; ...
%! -3 3 0];
%! [0.25 0.75; ...
%! 0 0]};
%! A = shapeArea (boomerang)
%!test
%! warning('off', 'geom2d:cw-shape', 'local');
%! triangle = {[1 0; 0 0]; [-0.5 1; 1 0]; [-0.5 0.5; -1 1]};
%! A = shapeArea (triangle);
%! assert (0.5, A);
%!test
%! warning('off', 'geom2d:cw-shape', 'local');
%! circle = {[1.715729 -6.715729 0 5; ...
%! -1.715729 -1.568542 8.284271 0]; ...
%! [1.715729 1.568542 -8.284271 0; ...
%! 1.715729 -6.715729 0 5]; ...
%! [-1.715729 6.715729 0 -5; ...
%! 1.715729 1.568542 -8.284271 0]; ...
%! [-1.715729 -1.568542 8.284271 0; ...
%! -1.715729 6.715729 0 -5]};
%! A = shapeArea (circle);
%! assert (pi*5^2, A, 5e-2);
geometry-4.0.0/inst/shapeCentroid.m 0000644 0000000 0000000 00000012523 13615712371 015470 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## Author: Juan Pablo Carbajal
## -*- texinfo -*-
## @deftypefn {Function File} { @var{cm} =} shapeCentroid (@var{pp})
## Centroid of a simple plane shape defined with piecewise smooth polynomials.
##
## The shape is defined with piecewise smooth polynomials. @var{pp} is a
## cell where each elements is a 2-by-(poly_degree+1) matrix containing a pair
## of polynomials.
## @code{px(i,:) = pp@{i@}(1,:)} and @code{py(i,:) = pp@{i@}(2,:)}.
##
## The edges of the shape should not self-intersect. This function does not check for the
## sanity of the shape.
##
## @seealso{shapearea, shape2polygon}
## @end deftypefn
function cm = shapeCentroid (shape)
cm = sum( cell2mat ( cellfun (@CMint, shape, 'UniformOutput', false)), 1);
[A ccw] = shapeArea (shape);
cm = cm / A;
if (ccw < 0)
warning ('geom2d:cw-shape', ...
'Clockwise parametrized shape, inverting centroid.');
cm = -cm;
end
endfunction
function dcm = CMint (x)
px = x(1,:);
py = x(2,:);
Px = polyint (conv(conv (-px , py) , polyder (px)));
Py = polyint (conv(conv (px , py) , polyder (py)));
dcm = zeros (1,2);
dcm(1) = diff(polyval(Px,[0 1]));
dcm(2) = diff(polyval(Py,[0 1]));
endfunction
%!demo # non-convex bezier shape
%! boomerang = {[ 0 -2 1; ...
%! -4 4 0]; ...
%! [0.25 -1; ...
%! 0 0]; ...
%! [ 0 1.5 -0.75; ...
%! -3 3 0];
%! [0.25 0.75; ...
%! 0 0]};
%! CoM = shapeCentroid (boomerang)
%! Gcentroid = centroid(shape2polygon(boomerang))
%! figure(1); clf;
%! plotShape(boomerang,'-o');
%! hold on
%! drawPoint(CoM,'xk;shape centroid;');
%! drawPoint(Gcentroid,'xr;point centroid;');
%! hold off
%! axis equal
%!demo
%! Lshape = {[0.00000 0.76635; -0.67579 -0.24067]; ...
%! [0.77976 0.76635; 0.00000 -0.91646]; ...
%! [0.00000 1.54611; 0.38614 -0.91646]; ...
%! [-0.43813 1.54611; 0.00000 -0.53032]; ...
%! [0.00000 1.10798; 0.28965 -0.53032]; ...
%! [-0.34163 1.10798; 0.00000 -0.24067]};...
%! CoM = shapeCentroid (Lshape)
%! Gcentroid = centroid (shape2polygon (Lshape))
%!
%! plotShape(Lshape,'-o');
%! hold on
%! drawPoint(CoM,'xk;shape centroid;');
%! drawPoint(Gcentroid,'xr;point centroid;');
%! hold off
%! axis equal
%!test
%! warning('off', 'geom2d:cw-shape', 'local');
%! square = {[1 -0.5; 0 -0.5]; [0 0.5; 1 -0.5]; [-1 0.5; 0 0.5]; [0 -0.5; -1 0.5]};
%! CoM = shapeCentroid (square);
%! assert (CoM, [0 0], sqrt(eps));
%!test
%! warning('off', 'geom2d:cw-shape', 'local');
%! square = {[1 -0.5; 0 -0.5]; [0 0.5; 1 -0.5]; [-1 0.5; 0 0.5]; [0 -0.5; -1 0.5]};
%! square_t = transformShape (square,[1;1]);
%! CoM = shapeCentroid (square_t);
%! assert (CoM, [1 1], sqrt(eps));
%!test
%! warning('off', 'geom2d:cw-shape', 'local');
%! circle = {[1.715729 -6.715729 0 5; ...
%! -1.715729 -1.568542 8.284271 0]; ...
%! [1.715729 1.568542 -8.284271 0; ...
%! 1.715729 -6.715729 0 5]; ...
%! [-1.715729 6.715729 0 -5; ...
%! 1.715729 1.568542 -8.284271 0]; ...
%! [-1.715729 -1.568542 8.284271 0; ...
%! -1.715729 6.715729 0 -5]};
%! CoM = shapeCentroid (circle);
%! assert (CoM , [0 0], 5e-3);
%!shared shape
%! shape = {[-93.172 606.368 -476.054 291.429; ...
%! -431.196 637.253 11.085 163.791]; ...
%! [-75.3626 -253.2337 457.1678 328.5714; ...
%! 438.7659 -653.6278 -7.9953 380.9336]; ...
%! [-89.5841 344.9716 -275.3876 457.1429; ...
%! -170.3613 237.8858 1.0469 158.0765];...
%! [32.900 -298.704 145.804 437.143; ...
%! -243.903 369.597 -34.265 226.648]; ...
%! [-99.081 409.127 -352.903 317.143; ...
%! 55.289 -114.223 -26.781 318.076]; ...
%! [-342.231 191.266 168.108 274.286; ...
%! 58.870 -38.083 -89.358 232.362]};
%!test # x-Reflection
%! warning('off', 'geom2d:cw-shape', 'local');
%! v = shapeCentroid (shape)(:);
%! T = createLineReflection([0 0 1 0]);
%! nshape = transformShape (shape, T);
%! vn = shapeCentroid (nshape)(:);
%! assert(vn,T(1:2,1:2)*v);
%!test # Rotation
%! warning('off', 'geom2d:cw-shape', 'local');
%! v = shapeCentroid (shape)(:);
%! T = createRotation(v.',pi/2);
%! nshape = transformShape (shape, T);
%! vn = shapeCentroid (nshape)(:);
%! assert(vn,v,1e-2);
%!test # Translation
%! warning('off', 'geom2d:cw-shape', 'local');
%! v = shapeCentroid (shape)(:);
%! nshape = transformShape (shape, -v);
%! vn = shapeCentroid (nshape)(:);
%! assert(vn,[0; 0],1e-2);
geometry-4.0.0/inst/simplifyPolygon_geometry.m 0000644 0000000 0000000 00000004115 13615712371 020015 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2019 Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @deftypefn {Function File} {@var{spoly} = } simplifyPolygon_geometry (@var{poly})
## Simplify a polygon using the Ramer-Douglas-Peucker algorithm.
##
## @var{poly} is a N-by-2 matrix, each row representing a vertex.
##
## @seealso{simplifyPolyline_geometry, shape2polygon}
## @end deftypefn
function polygonsimp = simplifyPolygon_geometry (polygon, varargin)
polygonsimp = simplifyPolyline_geometry (polygon,varargin{:});
# Remove parrallel consecutive edges
PL = polygonsimp(1:end-1,:);
PC = polygonsimp(2:end,:);
PR = polygonsimp([3:end 1],:);
a = PL - PC;
b = PR - PC;
tf = find (isParallel(a,b))+1;
polygonsimp (tf,:) = [];
endfunction
%!test
%! P = [0 0; 1 0; 0 1];
%! P2 = [0 0; 0.1 0; 0.2 0; 0.25 0; 1 0; 0 1; 0 0.7; 0 0.6; 0 0.3; 0 0.1];
%! assert(simplifyPolygon_geometry (P2),P,min(P2(:))*eps)
%!demo
%!
%! P = [0 0; 1 0; 0 1];
%! P2 = [0 0; 0.1 0; 0.2 0; 0.25 0; 1 0; 0 1; 0 0.7; 0 0.6; 0 0.3; 0 0.1];
%! Pr = simplifyPolygon_geometry (P2);
%!
%! cla
%! drawPolygon(P,'or;Reference;');
%! hold on
%! drawPolygon(P2,'x-b;Redundant;');
%! drawPolygon(Pr,'*g;Simplified;');
%! hold off
%!
%! # --------------------------------------------------------------------------
%! # The two polygons describe the same figure, a triangle. Extra points are
%! # removed from the redundant one.
geometry-4.0.0/inst/simplifyPolyline_geometry.m 0000644 0000000 0000000 00000012032 13615712371 020156 0 ustar 00 0000000 0000000 ## Copyright (C) 2015-2019 - Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## Author: Juan Pablo Carbajal
## Updated: 2019-05-14
## -*- texinfo -*-
## @deftypefn {} {[@var{pline2} @var{idx}] = } simplifyPolyline_geometry (@var{pline})
## @deftypefnx {} {@dots{} = } simplifyPolyline_geometry (@dots{},@var{property},@var{value},@dots{})
## Simplify or subsample a polyline using the Ramer-Douglas-Peucker algorithm,
## a.k.a. the iterative end-point fit algorithm or the split-and-merge algorithm.
##
## The @var{pline} as a N-by-2 matrix. Rows correspond to the
## verices (compatible with @code{polygons2d}). The vector @var{idx} constains
## the indexes on vetices in @var{pline} that generates @var{pline2}, i.e.
## @code{pline2 = pline(idx,:)}.
##
## @strong{Parameters}
## @table @samp
## @item 'Nmax'
## Maximum number of vertices. Default value @code{1e3}.
## @item 'Tol'
## Tolerance for the error criteria. Default value @code{1e-4}.
## @item 'MaxIter'
## Maximum number of iterations. Default value @code{10}.
## @item 'Method'
## Not implemented.
## @end table
##
## Run @code{demo simplifyPolyline_geometry} to see an example.
##
## @seealso{curve2polyline, curveval, simplifyPolygon_geometry}
## @end deftypefn
function [pline idx] = simplifyPolyline_geometry (pline_o, varargin)
## TODO do not print warnings if user provided Nmax or MaxIter.
# --- Parse arguments --- #
parser = inputParser ();
parser.FunctionName = "simplifyPolyline_geometry";
toldef = 1e-4;#max(sumsq(diff(pline_o),2))*2;
parser.addParamValue ('Tol', toldef, @(x)x>0);
parser.addParamValue ('Nmax', 1e3, @(x)x>0);
parser.addParamValue ('MaxIter', 100, @(x)x>0);
parser.parse(varargin{:});
Nmax = parser.Results.Nmax;
tol = parser.Results.Tol;
MaxIter = parser.Results.MaxIter;
clear parser toldef
msg = ["simplifyPolyline_geometry: Maximum number of points reached with maximum error %g." ...
" Increase %s if the result is not satisfactory."];
# ------ #
[N dim] = size (pline_o);
idx = [1 N];
for iter = 1:MaxIter
# Find the point with the maximum distance.
[dist ii] = maxdistance (pline_o, idx);
tf = dist > tol;
n = sum (tf);
if ( all (!tf) );
break;
end
idx(end+1:end+n) = ii(tf);
idx = sort (idx);
if length(idx) >= Nmax
## TODO remove extra points
warning ('geometry:MayBeWrongOutput', sprintf (msg, max (dist),'Nmax'));
break;
end
end
if iter == MaxIter
warning ('geometry:MayBeWrongOutput', sprintf (msg ,max (dist), 'MaxIter'));
end
pline = pline_o(idx,:);
endfunction
function [dist ii] = maxdistance (p, idx)
## Separate the groups of points according to the edge they can divide.
idxc = arrayfun (@colon, idx(1:end-1), idx(2:end), "UniformOutput",false);
points = cellfun (@(x)p(x,:), idxc, "UniformOutput",false);
## Build the edges
edges = [p(idx(1:end-1),:) p(idx(2:end),:)];
edges = mat2cell (edges, ones (1,size (edges,1)), 4)';
## Calculate distance between the points and the corresponding edge
[dist ii] = cellfun (@dd, points, edges, idxc);
endfunction
function [dist ii] = dd (p,e,idx)
[d pos] = distancePointEdge (p, e);
[dist ii] = max (d);
ii = idx(ii);
endfunction
%!demo
%! t = linspace(0,1,100).';
%! y = polyval([1 -1.5 0.5 0],t);
%! pline = [t y];
%!
%! figure(1)
%! clf
%! plot (t,y,'-r;Original;','linewidth',2);
%! hold on
%!
%! tol = [8 2 1 0.5]*1e-2;
%! colors = jet(4);
%!
%! for i=1:4
%! pline_ = simplifyPolyline_geometry(pline,'tol',tol(i));
%! msg = sprintf('-;%g;',tol(i));
%! h = plot (pline_(:,1),pline_(:,2),msg);
%! set(h,'color',colors(i,:),'linewidth',2,'markersize',4);
%! end
%! hold off
%!
%! # ---------------------------------------------------------
%! # Four approximations of the initial polyline with decreasing tolerances.
%!demo
%! P = [0 0; 3 1; 3 4; 1 3; 2 2; 1 1];
%! func = @(x,y) linspace(x,y,5);
%! P2(:,1) = cell2mat( ...
%! arrayfun (func, P(1:end-1,1),P(2:end,1), ...
%! 'uniformoutput',false))'(:);
%! P2(:,2) = cell2mat( ...
%! arrayfun (func, P(1:end-1,2),P(2:end,2), ...
%! 'uniformoutput',false))'(:);
%!
%! P2s = simplifyPolyline_geometry (P2);
%!
%! plot(P(:,1),P(:,2),'s',P2(:,1),P2(:,2),'o',P2s(:,1),P2s(:,2),'-ok');
%!
%! # ---------------------------------------------------------
%! # Simplification of a polyline in the plane.
geometry-4.0.0/inst/transformShape.m 0000644 0000000 0000000 00000006223 13615712371 015674 0 ustar 00 0000000 0000000 ## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see .
## -*- texinfo -*-
## @deftypefn {Function File} {@var{nshape} = } transformShape (@var{shape}, @var{T})
## Applies transformation to a shape defined by piecewise smooth polynomials.
##
## @var{shape} is a cell where each elements is a 2-by-(poly_degree+1) matrix
## containing a pair of polynomials.
##
## Format of @var{T} can be one of :
## @example
## @group
## [c] , [a b] , [a b c] or [a b c]
## [f] [d e] [d e f] [d e f]
## [0 0 1]
## @end group
## @end example
##
## @seealso{shape2polygon, plotShape}
## @end deftypefn
function nshape = transformShape (shape, Trans)
if size(Trans,1) < 2
error("geometry:invalid-input-arg", ...
"Transformation can be 2x1, 2x2, 2x3 or 3x3. See help.");
end
if ~iscell(shape)
error("geometry:invalid-input-arg", "Shape must be a cell of 2D polynomials.");
end
A =[];
v = [];
switch size(Trans,2)
case 1
# Just translation
v = Trans;
case 2
# Just linear transformation
A = Trans;
case 3
# Affine transform
A = Trans(1:2,1:2);
v = Trans(1:2,3);
end
nshape = cellfun (@(x)polytransform (x,A,v), shape, 'UniformOutput',false);
endfunction
function np = polytransform(p,A,v)
np = p;
if ~isempty (A)
np = A*np;
end
if ~isempty (v)
np(:,end) = np(:,end) + v;
end
endfunction
%!demo
%! shape = {[-93.172 606.368 -476.054 291.429; ...
%! -431.196 637.253 11.085 163.791]; ...
%! [-75.3626 -253.2337 457.1678 328.5714; ...
%! 438.7659 -653.6278 -7.9953 380.9336]; ...
%! [-89.5841 344.9716 -275.3876 457.1429; ...
%! -170.3613 237.8858 1.0469 158.0765];...
%! [32.900 -298.704 145.804 437.143; ...
%! -243.903 369.597 -34.265 226.648]; ...
%! [-99.081 409.127 -352.903 317.143; ...
%! 55.289 -114.223 -26.781 318.076]; ...
%! [-342.231 191.266 168.108 274.286; ...
%! 58.870 -38.083 -89.358 232.362]};
%! warning ("off", 'geom2d:cw-shape',"local");
%! A = shapeArea (shape);
%! T = eye(2)/sqrt(A);
%! shape = transformShape (shape,T);
%! T = shapeCentroid (shape)(:);
%! shape = transformShape (shape,-T + [2; 0]);
%!
%! close
%! plotShape (shape,'-r','linewidth',2);
%! hold on
%! for i = 1:9
%! T = createRotation (i*pi/5)(1:2,1:2)/exp(0.3*i);
%! plotShape (transformShape(shape, T), 'color',rand(1,3),'linewidth',2);
%! end
%! hold off
%! axis image
geometry-4.0.0/src/ 0000755 0000000 0000000 00000000000 13615712371 012331 5 ustar 00 0000000 0000000 geometry-4.0.0/src/Makefile 0000644 0000000 0000000 00000000673 13615712371 013777 0 ustar 00 0000000 0000000 all: clipper.mex polybool_mrf.oct
MKOCTFILE ?= mkoctfile
OBJS = \
connector.o \
martinez.o \
polygon.o \
utilities.o
%.mex: %.cpp
$(MKOCTFILE) -Wall -mex -g clipper.cpp mexclipper.cpp
%.o: %.cpp
$(MKOCTFILE) -c $< -o $@
%.oct: %.cc
$(MKOCTFILE) $< -o $@
polybool_mrf.oct: $(OBJS) polybool_mrf.cc
$(MKOCTFILE) $(OBJS) polybool_mrf.cc -o $@
clean:
rm -f *.o *.oct PKG_* *.o octave-core core *.oct *.mex *~
.PHONY: all clean
geometry-4.0.0/src/clipper.cpp 0000644 0000000 0000000 00000416773 13615712371 014515 0 ustar 00 0000000 0000000 /*
(C) 2012-2017 Angus Johnson
Boost Software License - Version 1.0 - August 17th, 2003
http://www.boost.org/LICENSE_1_0.txt
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/*******************************************************************************
* *
* 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 *
* *
*******************************************************************************/
/*******************************************************************************
* *
* This is a translation of the Delphi Clipper library and the naming style *
* used has retained a Delphi flavour. *
* *
*******************************************************************************/
#include "clipper.hpp"
#include
#include
#include
#include
#include
#include
#include
#include
namespace ClipperLib {
static double const pi = 3.141592653589793238;
static double const two_pi = pi *2;
static double const def_arc_tolerance = 0.25;
enum Direction { dRightToLeft, dLeftToRight };
static int const Unassigned = -1; //edge not currently 'owning' a solution
static int const Skip = -2; //edge that would otherwise close a path
#define HORIZONTAL (-1.0E+40)
#define TOLERANCE (1.0e-20)
#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
struct TEdge {
IntPoint Bot;
IntPoint Curr; //current (updated for every new scanbeam)
IntPoint Top;
double Dx;
PolyType PolyTyp;
EdgeSide Side; //side only refers to current side of solution poly
int WindDelta; //1 or -1 depending on winding direction
int WindCnt;
int WindCnt2; //winding count of the opposite polytype
int OutIdx;
TEdge *Next;
TEdge *Prev;
TEdge *NextInLML;
TEdge *NextInAEL;
TEdge *PrevInAEL;
TEdge *NextInSEL;
TEdge *PrevInSEL;
};
struct IntersectNode {
TEdge *Edge1;
TEdge *Edge2;
IntPoint Pt;
};
struct LocalMinimum {
cInt Y;
TEdge *LeftBound;
TEdge *RightBound;
};
struct OutPt;
//OutRec: contains a path in the clipping solution. Edges in the AEL will
//carry a pointer to an OutRec when they are part of the clipping solution.
struct OutRec {
int Idx;
bool IsHole;
bool IsOpen;
OutRec *FirstLeft; //see comments in clipper.pas
PolyNode *PolyNd;
OutPt *Pts;
OutPt *BottomPt;
};
struct OutPt {
int Idx;
IntPoint Pt;
OutPt *Next;
OutPt *Prev;
};
struct Join {
OutPt *OutPt1;
OutPt *OutPt2;
IntPoint OffPt;
};
struct LocMinSorter
{
inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
{
return locMin2.Y < locMin1.Y;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
inline cInt Round(double val)
{
if ((val < 0)) return static_cast(val - 0.5);
else return static_cast(val + 0.5);
}
//------------------------------------------------------------------------------
inline cInt Abs(cInt val)
{
return val < 0 ? -val : val;
}
//------------------------------------------------------------------------------
// PolyTree methods ...
//------------------------------------------------------------------------------
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
//------------------------------------------------------------------------------
PolyNode* PolyTree::GetFirst() const
{
if (!Childs.empty())
return Childs[0];
else
return 0;
}
//------------------------------------------------------------------------------
int PolyTree::Total() const
{
int result = (int)AllNodes.size();
//with negative offsets, ignore the hidden outer polygon ...
if (result > 0 && Childs[0] != AllNodes[0]) result--;
return result;
}
//------------------------------------------------------------------------------
// PolyNode methods ...
//------------------------------------------------------------------------------
PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
{
}
//------------------------------------------------------------------------------
int PolyNode::ChildCount() const
{
return (int)Childs.size();
}
//------------------------------------------------------------------------------
void PolyNode::AddChild(PolyNode& child)
{
unsigned cnt = (unsigned)Childs.size();
Childs.push_back(&child);
child.Parent = this;
child.Index = cnt;
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNext() const
{
if (!Childs.empty())
return Childs[0];
else
return GetNextSiblingUp();
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNextSiblingUp() const
{
if (!Parent) //protects against PolyTree.GetNextSiblingUp()
return 0;
else if (Index == Parent->Childs.size() - 1)
return Parent->GetNextSiblingUp();
else
return Parent->Childs[Index + 1];
}
//------------------------------------------------------------------------------
bool PolyNode::IsHole() const
{
bool result = true;
PolyNode* node = Parent;
while (node)
{
result = !result;
node = node->Parent;
}
return result;
}
//------------------------------------------------------------------------------
bool PolyNode::IsOpen() const
{
return m_IsOpen;
}
//------------------------------------------------------------------------------
#ifndef use_int32
//------------------------------------------------------------------------------
// Int128 class (enables safe math on signed 64bit integers)
// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
// Int128 val2((long64)9223372036854775807);
// Int128 val3 = val1 * val2;
// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
//------------------------------------------------------------------------------
class Int128
{
public:
ulong64 lo;
long64 hi;
Int128(long64 _lo = 0)
{
lo = (ulong64)_lo;
if (_lo < 0) hi = -1; else hi = 0;
}
Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
Int128& operator = (const long64 &val)
{
lo = (ulong64)val;
if (val < 0) hi = -1; else hi = 0;
return *this;
}
bool operator == (const Int128 &val) const
{return (hi == val.hi && lo == val.lo);}
bool operator != (const Int128 &val) const
{ return !(*this == val);}
bool operator > (const Int128 &val) const
{
if (hi != val.hi)
return hi > val.hi;
else
return lo > val.lo;
}
bool operator < (const Int128 &val) const
{
if (hi != val.hi)
return hi < val.hi;
else
return lo < val.lo;
}
bool operator >= (const Int128 &val) const
{ return !(*this < val);}
bool operator <= (const Int128 &val) const
{ return !(*this > val);}
Int128& operator += (const Int128 &rhs)
{
hi += rhs.hi;
lo += rhs.lo;
if (lo < rhs.lo) hi++;
return *this;
}
Int128 operator + (const Int128 &rhs) const
{
Int128 result(*this);
result+= rhs;
return result;
}
Int128& operator -= (const Int128 &rhs)
{
*this += -rhs;
return *this;
}
Int128 operator - (const Int128 &rhs) const
{
Int128 result(*this);
result -= rhs;
return result;
}
Int128 operator-() const //unary negation
{
if (lo == 0)
return Int128(-hi, 0);
else
return Int128(~hi, ~lo + 1);
}
operator double() const
{
const double shift64 = 18446744073709551616.0; //2^64
if (hi < 0)
{
if (lo == 0) return (double)hi * shift64;
else return -(double)(~lo + ~hi * shift64);
}
else
return (double)(lo + hi * shift64);
}
};
//------------------------------------------------------------------------------
Int128 Int128Mul (long64 lhs, long64 rhs)
{
bool negate = (lhs < 0) != (rhs < 0);
if (lhs < 0) lhs = -lhs;
ulong64 int1Hi = ulong64(lhs) >> 32;
ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
if (rhs < 0) rhs = -rhs;
ulong64 int2Hi = ulong64(rhs) >> 32;
ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
//nb: see comments in clipper.pas
ulong64 a = int1Hi * int2Hi;
ulong64 b = int1Lo * int2Lo;
ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
Int128 tmp;
tmp.hi = long64(a + (c >> 32));
tmp.lo = long64(c << 32);
tmp.lo += long64(b);
if (tmp.lo < b) tmp.hi++;
if (negate) tmp = -tmp;
return tmp;
};
#endif
//------------------------------------------------------------------------------
// Miscellaneous global functions
//------------------------------------------------------------------------------
bool Orientation(const Path &poly)
{
return Area(poly) >= 0;
}
//------------------------------------------------------------------------------
double Area(const Path &poly)
{
int size = (int)poly.size();
if (size < 3) return 0;
double a = 0;
for (int i = 0, j = size -1; i < size; ++i)
{
a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
j = i;
}
return -a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutPt *op)
{
const OutPt *startOp = op;
if (!op) return 0;
double a = 0;
do {
a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
op = op->Next;
} while (op != startOp);
return a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutRec &outRec)
{
return Area(outRec.Pts);
}
//------------------------------------------------------------------------------
bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
{
OutPt *pp2 = pp;
do
{
if (pp2->Pt == Pt) return true;
pp2 = pp2->Next;
}
while (pp2 != pp);
return false;
}
//------------------------------------------------------------------------------
//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
int PointInPolygon(const IntPoint &pt, const Path &path)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
size_t cnt = path.size();
if (cnt < 3) return 0;
IntPoint ip = path[0];
for(size_t i = 1; i <= cnt; ++i)
{
IntPoint ipNext = (i == cnt ? path[0] : path[i]);
if (ipNext.Y == pt.Y)
{
if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
}
if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
{
if (ip.X >= pt.X)
{
if (ipNext.X > pt.X) result = 1 - result;
else
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
} else
{
if (ipNext.X > pt.X)
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
}
}
ip = ipNext;
}
return result;
}
//------------------------------------------------------------------------------
int PointInPolygon (const IntPoint &pt, OutPt *op)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
OutPt* startOp = op;
for(;;)
{
if (op->Next->Pt.Y == pt.Y)
{
if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
}
if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
{
if (op->Pt.X >= pt.X)
{
if (op->Next->Pt.X > pt.X) result = 1 - result;
else
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
} else
{
if (op->Next->Pt.X > pt.X)
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
}
}
op = op->Next;
if (startOp == op) break;
}
return result;
}
//------------------------------------------------------------------------------
bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
{
OutPt* op = OutPt1;
do
{
//nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
int res = PointInPolygon(op->Pt, OutPt2);
if (res >= 0) return res > 0;
op = op->Next;
}
while (op != OutPt1);
return true;
}
//----------------------------------------------------------------------
bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==
Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);
else
#endif
return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==
(e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
}
//------------------------------------------------------------------------------
inline bool IsHorizontal(TEdge &e)
{
return e.Dx == HORIZONTAL;
}
//------------------------------------------------------------------------------
inline double GetDx(const IntPoint pt1, const IntPoint pt2)
{
return (pt1.Y == pt2.Y) ?
HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
}
//---------------------------------------------------------------------------
inline void SetDx(TEdge &e)
{
cInt dy = (e.Top.Y - e.Bot.Y);
if (dy == 0) e.Dx = HORIZONTAL;
else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;
}
//---------------------------------------------------------------------------
inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
{
EdgeSide Side = Edge1.Side;
Edge1.Side = Edge2.Side;
Edge2.Side = Side;
}
//------------------------------------------------------------------------------
inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
{
int OutIdx = Edge1.OutIdx;
Edge1.OutIdx = Edge2.OutIdx;
Edge2.OutIdx = OutIdx;
}
//------------------------------------------------------------------------------
inline cInt TopX(TEdge &edge, const cInt currentY)
{
return ( currentY == edge.Top.Y ) ?
edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
}
//------------------------------------------------------------------------------
void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
{
#ifdef use_xyz
ip.Z = 0;
#endif
double b1, b2;
if (Edge1.Dx == Edge2.Dx)
{
ip.Y = Edge1.Curr.Y;
ip.X = TopX(Edge1, ip.Y);
return;
}
else if (Edge1.Dx == 0)
{
ip.X = Edge1.Bot.X;
if (IsHorizontal(Edge2))
ip.Y = Edge2.Bot.Y;
else
{
b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
ip.Y = Round(ip.X / Edge2.Dx + b2);
}
}
else if (Edge2.Dx == 0)
{
ip.X = Edge2.Bot.X;
if (IsHorizontal(Edge1))
ip.Y = Edge1.Bot.Y;
else
{
b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
ip.Y = Round(ip.X / Edge1.Dx + b1);
}
}
else
{
b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
ip.Y = Round(q);
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = Round(Edge1.Dx * q + b1);
else
ip.X = Round(Edge2.Dx * q + b2);
}
if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
{
if (Edge1.Top.Y > Edge2.Top.Y)
ip.Y = Edge1.Top.Y;
else
ip.Y = Edge2.Top.Y;
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = TopX(Edge1, ip.Y);
else
ip.X = TopX(Edge2, ip.Y);
}
//finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
if (ip.Y > Edge1.Curr.Y)
{
ip.Y = Edge1.Curr.Y;
//use the more vertical edge to derive X ...
if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
ip.X = TopX(Edge2, ip.Y); else
ip.X = TopX(Edge1, ip.Y);
}
}
//------------------------------------------------------------------------------
void ReversePolyPtLinks(OutPt *pp)
{
if (!pp) return;
OutPt *pp1, *pp2;
pp1 = pp;
do {
pp2 = pp1->Next;
pp1->Next = pp1->Prev;
pp1->Prev = pp2;
pp1 = pp2;
} while( pp1 != pp );
}
//------------------------------------------------------------------------------
void DisposeOutPts(OutPt*& pp)
{
if (pp == 0) return;
pp->Prev->Next = 0;
while( pp )
{
OutPt *tmpPp = pp;
pp = pp->Next;
delete tmpPp;
}
}
//------------------------------------------------------------------------------
inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
{
std::memset(e, 0, sizeof(TEdge));
e->Next = eNext;
e->Prev = ePrev;
e->Curr = Pt;
e->OutIdx = Unassigned;
}
//------------------------------------------------------------------------------
void InitEdge2(TEdge& e, PolyType Pt)
{
if (e.Curr.Y >= e.Next->Curr.Y)
{
e.Bot = e.Curr;
e.Top = e.Next->Curr;
} else
{
e.Top = e.Curr;
e.Bot = e.Next->Curr;
}
SetDx(e);
e.PolyTyp = Pt;
}
//------------------------------------------------------------------------------
TEdge* RemoveEdge(TEdge* e)
{
//removes e from double_linked_list (but without removing from memory)
e->Prev->Next = e->Next;
e->Next->Prev = e->Prev;
TEdge* result = e->Next;
e->Prev = 0; //flag as removed (see ClipperBase.Clear)
return result;
}
//------------------------------------------------------------------------------
inline void ReverseHorizontal(TEdge &e)
{
//swap horizontal edges' Top and Bottom x's so they follow the natural
//progression of the bounds - ie so their xbots will align with the
//adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
std::swap(e.Top.X, e.Bot.X);
#ifdef use_xyz
std::swap(e.Top.Z, e.Bot.Z);
#endif
}
//------------------------------------------------------------------------------
void SwapPoints(IntPoint &pt1, IntPoint &pt2)
{
IntPoint tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
//------------------------------------------------------------------------------
bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
{
//precondition: segments are Collinear.
if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
{
if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
return pt1.X < pt2.X;
} else
{
if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
return pt1.Y > pt2.Y;
}
}
//------------------------------------------------------------------------------
bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
{
OutPt *p = btmPt1->Prev;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt1->Next;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt2->Prev;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
p = btmPt2->Next;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&
std::min(dx1p, dx1n) == std::min(dx2p, dx2n))
return Area(btmPt1) > 0; //if otherwise identical use orientation
else
return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
}
//------------------------------------------------------------------------------
OutPt* GetBottomPt(OutPt *pp)
{
OutPt* dups = 0;
OutPt* p = pp->Next;
while (p != pp)
{
if (p->Pt.Y > pp->Pt.Y)
{
pp = p;
dups = 0;
}
else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
{
if (p->Pt.X < pp->Pt.X)
{
dups = 0;
pp = p;
} else
{
if (p->Next != pp && p->Prev != pp) dups = p;
}
}
p = p->Next;
}
if (dups)
{
//there appears to be at least 2 vertices at BottomPt so ...
while (dups != p)
{
if (!FirstIsBottomPt(p, dups)) pp = dups;
dups = dups->Next;
while (dups->Pt != pp->Pt) dups = dups->Next;
}
}
return pp;
}
//------------------------------------------------------------------------------
bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
const IntPoint pt2, const IntPoint pt3)
{
if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
return false;
else if (pt1.X != pt3.X)
return (pt2.X > pt1.X) == (pt2.X < pt3.X);
else
return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
}
//------------------------------------------------------------------------------
bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
{
if (seg1a > seg1b) std::swap(seg1a, seg1b);
if (seg2a > seg2b) std::swap(seg2a, seg2b);
return (seg1a < seg2b) && (seg2a < seg1b);
}
//------------------------------------------------------------------------------
// ClipperBase class methods ...
//------------------------------------------------------------------------------
ClipperBase::ClipperBase() //constructor
{
m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
m_UseFullRange = false;
}
//------------------------------------------------------------------------------
ClipperBase::~ClipperBase() //destructor
{
Clear();
}
//------------------------------------------------------------------------------
void RangeTest(const IntPoint& Pt, bool& useFullRange)
{
if (useFullRange)
{
if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
throw clipperException("Coordinate outside allowed range");
}
else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
{
useFullRange = true;
RangeTest(Pt, useFullRange);
}
}
//------------------------------------------------------------------------------
TEdge* FindNextLocMin(TEdge* E)
{
for (;;)
{
while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
while (IsHorizontal(*E->Prev)) E = E->Prev;
TEdge* E2 = E;
while (IsHorizontal(*E)) E = E->Next;
if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
if (E2->Prev->Bot.X < E->Bot.X) E = E2;
break;
}
return E;
}
//------------------------------------------------------------------------------
TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
{
TEdge *Result = E;
TEdge *Horz = 0;
if (E->OutIdx == Skip)
{
//if edges still remain in the current bound beyond the skip edge then
//create another LocMin and call ProcessBound once more
if (NextIsForward)
{
while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
//don't include top horizontals when parsing a bound a second time,
//they will be contained in the opposite bound ...
while (E != Result && IsHorizontal(*E)) E = E->Prev;
}
else
{
while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
while (E != Result && IsHorizontal(*E)) E = E->Next;
}
if (E == Result)
{
if (NextIsForward) Result = E->Next;
else Result = E->Prev;
}
else
{
//there are more edges in the bound beyond result starting with E
if (NextIsForward)
E = Result->Next;
else
E = Result->Prev;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
E->WindDelta = 0;
Result = ProcessBound(E, NextIsForward);
m_MinimaList.push_back(locMin);
}
return Result;
}
TEdge *EStart;
if (IsHorizontal(*E))
{
//We need to be careful with open paths because this may not be a
//true local minima (ie E may be following a skip edge).
//Also, consecutive horz. edges may start heading left before going right.
if (NextIsForward)
EStart = E->Prev;
else
EStart = E->Next;
if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
{
if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
ReverseHorizontal(*E);
}
else if (EStart->Bot.X != E->Bot.X)
ReverseHorizontal(*E);
}
EStart = E;
if (NextIsForward)
{
while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
Result = Result->Next;
if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
{
//nb: at the top of a bound, horizontals are added to the bound
//only when the preceding edge attaches to the horizontal's left vertex
//unless a Skip edge is encountered when that becomes the top divide
Horz = Result;
while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
}
while (E != Result)
{
E->NextInLML = E->Next;
if (IsHorizontal(*E) && E != EStart &&
E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
E = E->Next;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
ReverseHorizontal(*E);
Result = Result->Next; //move to the edge just beyond current bound
} else
{
while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
Result = Result->Prev;
if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
{
Horz = Result;
while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
if (Horz->Next->Top.X == Result->Prev->Top.X ||
Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
}
while (E != Result)
{
E->NextInLML = E->Prev;
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
E = E->Prev;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
Result = Result->Prev; //move to the edge just beyond current bound
}
return Result;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
{
#ifdef use_lines
if (!Closed && PolyTyp == ptClip)
throw clipperException("AddPath: Open paths must be subject.");
#else
if (!Closed)
throw clipperException("AddPath: Open paths have been disabled.");
#endif
int highI = (int)pg.size() -1;
if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
//create a new edge array ...
TEdge *edges = new TEdge [highI +1];
bool IsFlat = true;
//1. Basic (first) edge initialization ...
try
{
edges[1].Curr = pg[1];
RangeTest(pg[0], m_UseFullRange);
RangeTest(pg[highI], m_UseFullRange);
InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
for (int i = highI - 1; i >= 1; --i)
{
RangeTest(pg[i], m_UseFullRange);
InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
}
}
catch(...)
{
delete [] edges;
throw; //range test fails
}
TEdge *eStart = &edges[0];
//2. Remove duplicate vertices, and (when closed) collinear edges ...
TEdge *E = eStart, *eLoopStop = eStart;
for (;;)
{
//nb: allows matching start and end points when not Closed ...
if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
{
if (E == E->Next) break;
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
eLoopStop = E;
continue;
}
if (E->Prev == E->Next)
break; //only two vertices
else if (Closed &&
SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
(!m_PreserveCollinear ||
!Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
{
//Collinear edges are allowed for open paths but in closed paths
//the default is to merge adjacent collinear edges into a single edge.
//However, if the PreserveCollinear property is enabled, only overlapping
//collinear edges (ie spikes) will be removed from closed paths.
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
E = E->Prev;
eLoopStop = E;
continue;
}
E = E->Next;
if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
}
if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
{
delete [] edges;
return false;
}
if (!Closed)
{
m_HasOpenPaths = true;
eStart->Prev->OutIdx = Skip;
}
//3. Do second stage of edge initialization ...
E = eStart;
do
{
InitEdge2(*E, PolyTyp);
E = E->Next;
if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
}
while (E != eStart);
//4. Finally, add edge bounds to LocalMinima list ...
//Totally flat paths must be handled differently when adding them
//to LocalMinima list to avoid endless loops etc ...
if (IsFlat)
{
if (Closed)
{
delete [] edges;
return false;
}
E->Prev->OutIdx = Skip;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
locMin.RightBound->Side = esRight;
locMin.RightBound->WindDelta = 0;
for (;;)
{
if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
if (E->Next->OutIdx == Skip) break;
E->NextInLML = E->Next;
E = E->Next;
}
m_MinimaList.push_back(locMin);
m_edges.push_back(edges);
return true;
}
m_edges.push_back(edges);
bool leftBoundIsForward;
TEdge* EMin = 0;
//workaround to avoid an endless loop in the while loop below when
//open paths have matching start and end points ...
if (E->Prev->Bot == E->Prev->Top) E = E->Next;
for (;;)
{
E = FindNextLocMin(E);
if (E == EMin) break;
else if (!EMin) EMin = E;
//E and E.Prev now share a local minima (left aligned if horizontal).
//Compare their slopes to find which starts which bound ...
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
if (E->Dx < E->Prev->Dx)
{
locMin.LeftBound = E->Prev;
locMin.RightBound = E;
leftBoundIsForward = false; //Q.nextInLML = Q.prev
} else
{
locMin.LeftBound = E;
locMin.RightBound = E->Prev;
leftBoundIsForward = true; //Q.nextInLML = Q.next
}
if (!Closed) locMin.LeftBound->WindDelta = 0;
else if (locMin.LeftBound->Next == locMin.RightBound)
locMin.LeftBound->WindDelta = -1;
else locMin.LeftBound->WindDelta = 1;
locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
if (locMin.LeftBound->OutIdx == Skip)
locMin.LeftBound = 0;
else if (locMin.RightBound->OutIdx == Skip)
locMin.RightBound = 0;
m_MinimaList.push_back(locMin);
if (!leftBoundIsForward) E = E2;
}
return true;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
{
bool result = false;
for (Paths::size_type i = 0; i < ppg.size(); ++i)
if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::Clear()
{
DisposeLocalMinimaList();
for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
{
TEdge* edges = m_edges[i];
delete [] edges;
}
m_edges.clear();
m_UseFullRange = false;
m_HasOpenPaths = false;
}
//------------------------------------------------------------------------------
void ClipperBase::Reset()
{
m_CurrentLM = m_MinimaList.begin();
if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
m_Scanbeam = ScanbeamList(); //clears/resets priority_queue
//reset all edges ...
for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
{
InsertScanbeam(lm->Y);
TEdge* e = lm->LeftBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esLeft;
e->OutIdx = Unassigned;
}
e = lm->RightBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esRight;
e->OutIdx = Unassigned;
}
}
m_ActiveEdges = 0;
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeLocalMinimaList()
{
m_MinimaList.clear();
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)
{
if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;
locMin = &(*m_CurrentLM);
++m_CurrentLM;
return true;
}
//------------------------------------------------------------------------------
IntRect ClipperBase::GetBounds()
{
IntRect result;
MinimaList::iterator lm = m_MinimaList.begin();
if (lm == m_MinimaList.end())
{
result.left = result.top = result.right = result.bottom = 0;
return result;
}
result.left = lm->LeftBound->Bot.X;
result.top = lm->LeftBound->Bot.Y;
result.right = lm->LeftBound->Bot.X;
result.bottom = lm->LeftBound->Bot.Y;
while (lm != m_MinimaList.end())
{
//todo - needs fixing for open paths
result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
TEdge* e = lm->LeftBound;
for (;;) {
TEdge* bottomE = e;
while (e->NextInLML)
{
if (e->Bot.X < result.left) result.left = e->Bot.X;
if (e->Bot.X > result.right) result.right = e->Bot.X;
e = e->NextInLML;
}
result.left = std::min(result.left, e->Bot.X);
result.right = std::max(result.right, e->Bot.X);
result.left = std::min(result.left, e->Top.X);
result.right = std::max(result.right, e->Top.X);
result.top = std::min(result.top, e->Top.Y);
if (bottomE == lm->LeftBound) e = lm->RightBound;
else break;
}
++lm;
}
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::InsertScanbeam(const cInt Y)
{
m_Scanbeam.push(Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::PopScanbeam(cInt &Y)
{
if (m_Scanbeam.empty()) return false;
Y = m_Scanbeam.top();
m_Scanbeam.pop();
while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
return true;
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeAllOutRecs(){
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
DisposeOutRec(i);
m_PolyOuts.clear();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeOutRec(PolyOutList::size_type index)
{
OutRec *outRec = m_PolyOuts[index];
if (outRec->Pts) DisposeOutPts(outRec->Pts);
delete outRec;
m_PolyOuts[index] = 0;
}
//------------------------------------------------------------------------------
void ClipperBase::DeleteFromAEL(TEdge *e)
{
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted
if (AelPrev) AelPrev->NextInAEL = AelNext;
else m_ActiveEdges = AelNext;
if (AelNext) AelNext->PrevInAEL = AelPrev;
e->NextInAEL = 0;
e->PrevInAEL = 0;
}
//------------------------------------------------------------------------------
OutRec* ClipperBase::CreateOutRec()
{
OutRec* result = new OutRec;
result->IsHole = false;
result->IsOpen = false;
result->FirstLeft = 0;
result->Pts = 0;
result->BottomPt = 0;
result->PolyNd = 0;
m_PolyOuts.push_back(result);
result->Idx = (int)m_PolyOuts.size() - 1;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
{
//check that one or other edge hasn't already been removed from AEL ...
if (Edge1->NextInAEL == Edge1->PrevInAEL ||
Edge2->NextInAEL == Edge2->PrevInAEL) return;
if (Edge1->NextInAEL == Edge2)
{
TEdge* Next = Edge2->NextInAEL;
if (Next) Next->PrevInAEL = Edge1;
TEdge* Prev = Edge1->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge2;
Edge2->PrevInAEL = Prev;
Edge2->NextInAEL = Edge1;
Edge1->PrevInAEL = Edge2;
Edge1->NextInAEL = Next;
}
else if (Edge2->NextInAEL == Edge1)
{
TEdge* Next = Edge1->NextInAEL;
if (Next) Next->PrevInAEL = Edge2;
TEdge* Prev = Edge2->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge1;
Edge1->PrevInAEL = Prev;
Edge1->NextInAEL = Edge2;
Edge2->PrevInAEL = Edge1;
Edge2->NextInAEL = Next;
}
else
{
TEdge* Next = Edge1->NextInAEL;
TEdge* Prev = Edge1->PrevInAEL;
Edge1->NextInAEL = Edge2->NextInAEL;
if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;
Edge1->PrevInAEL = Edge2->PrevInAEL;
if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;
Edge2->NextInAEL = Next;
if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;
Edge2->PrevInAEL = Prev;
if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;
}
if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;
else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;
}
//------------------------------------------------------------------------------
void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)
{
if (!e->NextInLML)
throw clipperException("UpdateEdgeIntoAEL: invalid call");
e->NextInLML->OutIdx = e->OutIdx;
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
else m_ActiveEdges = e->NextInLML;
if (AelNext) AelNext->PrevInAEL = e->NextInLML;
e->NextInLML->Side = e->Side;
e->NextInLML->WindDelta = e->WindDelta;
e->NextInLML->WindCnt = e->WindCnt;
e->NextInLML->WindCnt2 = e->WindCnt2;
e = e->NextInLML;
e->Curr = e->Bot;
e->PrevInAEL = AelPrev;
e->NextInAEL = AelNext;
if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::LocalMinimaPending()
{
return (m_CurrentLM != m_MinimaList.end());
}
//------------------------------------------------------------------------------
// TClipper methods ...
//------------------------------------------------------------------------------
Clipper::Clipper(int initOptions) : ClipperBase() //constructor
{
m_ExecuteLocked = false;
m_UseFullRange = false;
m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
m_HasOpenPaths = false;
#ifdef use_xyz
m_ZFill = 0;
#endif
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::ZFillFunction(ZFillCallback zFillFunc)
{
m_ZFill = zFillFunc;
}
//------------------------------------------------------------------------------
#endif
bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
{
return Execute(clipType, solution, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
{
return Execute(clipType, polytree, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, Paths &solution,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
if (m_HasOpenPaths)
throw clipperException("Error: PolyTree struct is needed for open path clipping.");
m_ExecuteLocked = true;
solution.resize(0);
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = false;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult(solution);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
m_ExecuteLocked = true;
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = true;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult2(polytree);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::FixHoleLinkage(OutRec &outrec)
{
//skip OutRecs that (a) contain outermost polygons or
//(b) already have the correct owner/child linkage ...
if (!outrec.FirstLeft ||
(outrec.IsHole != outrec.FirstLeft->IsHole &&
outrec.FirstLeft->Pts)) return;
OutRec* orfl = outrec.FirstLeft;
while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
orfl = orfl->FirstLeft;
outrec.FirstLeft = orfl;
}
//------------------------------------------------------------------------------
bool Clipper::ExecuteInternal()
{
bool succeeded = true;
try {
Reset();
m_Maxima = MaximaList();
m_SortedEdges = 0;
succeeded = true;
cInt botY, topY;
if (!PopScanbeam(botY)) return false;
InsertLocalMinimaIntoAEL(botY);
while (PopScanbeam(topY) || LocalMinimaPending())
{
ProcessHorizontals();
ClearGhostJoins();
if (!ProcessIntersections(topY))
{
succeeded = false;
break;
}
ProcessEdgesAtTopOfScanbeam(topY);
botY = topY;
InsertLocalMinimaIntoAEL(botY);
}
}
catch(...)
{
succeeded = false;
}
if (succeeded)
{
//fix orientations ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec->IsOpen) continue;
if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
ReversePolyPtLinks(outRec->Pts);
}
if (!m_Joins.empty()) JoinCommonEdges();
//unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts) continue;
if (outRec->IsOpen)
FixupOutPolyline(*outRec);
else
FixupOutPolygon(*outRec);
}
if (m_StrictSimple) DoSimplePolygons();
}
ClearJoins();
ClearGhostJoins();
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::SetWindingCount(TEdge &edge)
{
TEdge *e = edge.PrevInAEL;
//find the edge of the same polytype that immediately preceeds 'edge' in AEL
while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
if (!e)
{
if (edge.WindDelta == 0)
{
PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);
edge.WindCnt = (pft == pftNegative ? -1 : 1);
}
else
edge.WindCnt = edge.WindDelta;
edge.WindCnt2 = 0;
e = m_ActiveEdges; //ie get ready to calc WindCnt2
}
else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
{
edge.WindCnt = 1;
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else if (IsEvenOddFillType(edge))
{
//EvenOdd filling ...
if (edge.WindDelta == 0)
{
//are we inside a subj polygon ...
bool Inside = true;
TEdge *e2 = e->PrevInAEL;
while (e2)
{
if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
Inside = !Inside;
e2 = e2->PrevInAEL;
}
edge.WindCnt = (Inside ? 0 : 1);
}
else
{
edge.WindCnt = edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else
{
//nonZero, Positive or Negative filling ...
if (e->WindCnt * e->WindDelta < 0)
{
//prev edge is 'decreasing' WindCount (WC) toward zero
//so we're outside the previous polygon ...
if (Abs(e->WindCnt) > 1)
{
//outside prev poly but still inside another.
//when reversing direction of prev poly use the same WC
if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise continue to 'decrease' WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
else
//now outside all polys of same polytype so set own WC ...
edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
} else
{
//prev edge is 'increasing' WindCount (WC) away from zero
//so we're inside the previous polygon ...
if (edge.WindDelta == 0)
edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
//if wind direction is reversing prev then use same WC
else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise add to WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
//update WindCnt2 ...
if (IsEvenOddAltFillType(edge))
{
//EvenOdd filling ...
while (e != &edge)
{
if (e->WindDelta != 0)
edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
e = e->NextInAEL;
}
} else
{
//nonZero, Positive or Negative filling ...
while ( e != &edge )
{
edge.WindCnt2 += e->WindDelta;
e = e->NextInAEL;
}
}
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_SubjFillType == pftEvenOdd; else
return m_ClipFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_ClipFillType == pftEvenOdd; else
return m_SubjFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsContributing(const TEdge& edge) const
{
PolyFillType pft, pft2;
if (edge.PolyTyp == ptSubject)
{
pft = m_SubjFillType;
pft2 = m_ClipFillType;
} else
{
pft = m_ClipFillType;
pft2 = m_SubjFillType;
}
switch(pft)
{
case pftEvenOdd:
//return false if a subj line has been flagged as inside a subj polygon
if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
break;
case pftNonZero:
if (Abs(edge.WindCnt) != 1) return false;
break;
case pftPositive:
if (edge.WindCnt != 1) return false;
break;
default: //pftNegative
if (edge.WindCnt != -1) return false;
}
switch(m_ClipType)
{
case ctIntersection:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctUnion:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
break;
case ctDifference:
if (edge.PolyTyp == ptSubject)
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctXor:
if (edge.WindDelta == 0) //XOr always contributing unless open
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
return true;
break;
default:
return true;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
OutPt* result;
TEdge *e, *prevE;
if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
{
result = AddOutPt(e1, Pt);
e2->OutIdx = e1->OutIdx;
e1->Side = esLeft;
e2->Side = esRight;
e = e1;
if (e->PrevInAEL == e2)
prevE = e2->PrevInAEL;
else
prevE = e->PrevInAEL;
} else
{
result = AddOutPt(e2, Pt);
e1->OutIdx = e2->OutIdx;
e1->Side = esRight;
e2->Side = esLeft;
e = e2;
if (e->PrevInAEL == e1)
prevE = e1->PrevInAEL;
else
prevE = e->PrevInAEL;
}
if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)
{
cInt xPrev = TopX(*prevE, Pt.Y);
cInt xE = TopX(*e, Pt.Y);
if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&
SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))
{
OutPt* outPt = AddOutPt(prevE, Pt);
AddJoin(result, outPt, e->Top);
}
}
return result;
}
//------------------------------------------------------------------------------
void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
AddOutPt( e1, Pt );
if (e2->WindDelta == 0) AddOutPt(e2, Pt);
if( e1->OutIdx == e2->OutIdx )
{
e1->OutIdx = Unassigned;
e2->OutIdx = Unassigned;
}
else if (e1->OutIdx < e2->OutIdx)
AppendPolygon(e1, e2);
else
AppendPolygon(e2, e1);
}
//------------------------------------------------------------------------------
void Clipper::AddEdgeToSEL(TEdge *edge)
{
//SEL pointers in PEdge are reused to build a list of horizontal edges.
//However, we don't need to worry about order with horizontal edge processing.
if( !m_SortedEdges )
{
m_SortedEdges = edge;
edge->PrevInSEL = 0;
edge->NextInSEL = 0;
}
else
{
edge->NextInSEL = m_SortedEdges;
edge->PrevInSEL = 0;
m_SortedEdges->PrevInSEL = edge;
m_SortedEdges = edge;
}
}
//------------------------------------------------------------------------------
bool Clipper::PopEdgeFromSEL(TEdge *&edge)
{
if (!m_SortedEdges) return false;
edge = m_SortedEdges;
DeleteFromSEL(m_SortedEdges);
return true;
}
//------------------------------------------------------------------------------
void Clipper::CopyAELToSEL()
{
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while ( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op1;
j->OutPt2 = op2;
j->OffPt = OffPt;
m_Joins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::ClearJoins()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
delete m_Joins[i];
m_Joins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::ClearGhostJoins()
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
delete m_GhostJoins[i];
m_GhostJoins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op;
j->OutPt2 = 0;
j->OffPt = OffPt;
m_GhostJoins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
{
const LocalMinimum *lm;
while (PopLocalMinima(botY, lm))
{
TEdge* lb = lm->LeftBound;
TEdge* rb = lm->RightBound;
OutPt *Op1 = 0;
if (!lb)
{
//nb: don't insert LB into either AEL or SEL
InsertEdgeIntoAEL(rb, 0);
SetWindingCount(*rb);
if (IsContributing(*rb))
Op1 = AddOutPt(rb, rb->Bot);
}
else if (!rb)
{
InsertEdgeIntoAEL(lb, 0);
SetWindingCount(*lb);
if (IsContributing(*lb))
Op1 = AddOutPt(lb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
else
{
InsertEdgeIntoAEL(lb, 0);
InsertEdgeIntoAEL(rb, lb);
SetWindingCount( *lb );
rb->WindCnt = lb->WindCnt;
rb->WindCnt2 = lb->WindCnt2;
if (IsContributing(*lb))
Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
if (rb)
{
if (IsHorizontal(*rb))
{
AddEdgeToSEL(rb);
if (rb->NextInLML)
InsertScanbeam(rb->NextInLML->Top.Y);
}
else InsertScanbeam( rb->Top.Y );
}
if (!lb || !rb) continue;
//if any output polygons share an edge, they'll need joining later ...
if (Op1 && IsHorizontal(*rb) &&
m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
{
Join* jr = m_GhostJoins[i];
//if the horizontal Rb and a 'ghost' horizontal overlap, then convert
//the 'ghost' join to a real join ready for later ...
if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
AddJoin(jr->OutPt1, Op1, jr->OffPt);
}
}
if (lb->OutIdx >= 0 && lb->PrevInAEL &&
lb->PrevInAEL->Curr.X == lb->Bot.X &&
lb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&
(lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
AddJoin(Op1, Op2, lb->Top);
}
if(lb->NextInAEL != rb)
{
if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&
(rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
AddJoin(Op1, Op2, rb->Top);
}
TEdge* e = lb->NextInAEL;
if (e)
{
while( e != rb )
{
//nb: For calculating winding counts etc, IntersectEdges() assumes
//that param1 will be to the Right of param2 ABOVE the intersection ...
IntersectEdges(rb , e , lb->Curr); //order important here
e = e->NextInAEL;
}
}
}
}
}
//------------------------------------------------------------------------------
void Clipper::DeleteFromSEL(TEdge *e)
{
TEdge* SelPrev = e->PrevInSEL;
TEdge* SelNext = e->NextInSEL;
if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
if( SelPrev ) SelPrev->NextInSEL = SelNext;
else m_SortedEdges = SelNext;
if( SelNext ) SelNext->PrevInSEL = SelPrev;
e->NextInSEL = 0;
e->PrevInSEL = 0;
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
{
if (pt.Z != 0 || !m_ZFill) return;
else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
else if (pt == e1.Top) pt.Z = e1.Top.Z;
else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
else if (pt == e2.Top) pt.Z = e2.Top.Z;
else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
}
//------------------------------------------------------------------------------
#endif
void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
{
bool e1Contributing = ( e1->OutIdx >= 0 );
bool e2Contributing = ( e2->OutIdx >= 0 );
#ifdef use_xyz
SetZ(Pt, *e1, *e2);
#endif
#ifdef use_lines
//if either edge is on an OPEN path ...
if (e1->WindDelta == 0 || e2->WindDelta == 0)
{
//ignore subject-subject open path intersections UNLESS they
//are both open paths, AND they are both 'contributing maximas' ...
if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
//if intersecting a subj line with a subj poly ...
else if (e1->PolyTyp == e2->PolyTyp &&
e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
{
if (e1->WindDelta == 0)
{
if (e2Contributing)
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
}
else
{
if (e1Contributing)
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
}
else if (e1->PolyTyp != e2->PolyTyp)
{
//toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
(m_ClipType != ctUnion || e2->WindCnt2 == 0))
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
(m_ClipType != ctUnion || e1->WindCnt2 == 0))
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
return;
}
#endif
//update winding counts...
//assumes that e1 will be to the Right of e2 ABOVE the intersection
if ( e1->PolyTyp == e2->PolyTyp )
{
if ( IsEvenOddFillType( *e1) )
{
int oldE1WindCnt = e1->WindCnt;
e1->WindCnt = e2->WindCnt;
e2->WindCnt = oldE1WindCnt;
} else
{
if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
else e1->WindCnt += e2->WindDelta;
if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
else e2->WindCnt -= e1->WindDelta;
}
} else
{
if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
}
PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
if (e1->PolyTyp == ptSubject)
{
e1FillType = m_SubjFillType;
e1FillType2 = m_ClipFillType;
} else
{
e1FillType = m_ClipFillType;
e1FillType2 = m_SubjFillType;
}
if (e2->PolyTyp == ptSubject)
{
e2FillType = m_SubjFillType;
e2FillType2 = m_ClipFillType;
} else
{
e2FillType = m_ClipFillType;
e2FillType2 = m_SubjFillType;
}
cInt e1Wc, e2Wc;
switch (e1FillType)
{
case pftPositive: e1Wc = e1->WindCnt; break;
case pftNegative: e1Wc = -e1->WindCnt; break;
default: e1Wc = Abs(e1->WindCnt);
}
switch(e2FillType)
{
case pftPositive: e2Wc = e2->WindCnt; break;
case pftNegative: e2Wc = -e2->WindCnt; break;
default: e2Wc = Abs(e2->WindCnt);
}
if ( e1Contributing && e2Contributing )
{
if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
(e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
{
AddLocalMaxPoly(e1, e2, Pt);
}
else
{
AddOutPt(e1, Pt);
AddOutPt(e2, Pt);
SwapSides( *e1 , *e2 );
SwapPolyIndexes( *e1 , *e2 );
}
}
else if ( e1Contributing )
{
if (e2Wc == 0 || e2Wc == 1)
{
AddOutPt(e1, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( e2Contributing )
{
if (e1Wc == 0 || e1Wc == 1)
{
AddOutPt(e2, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
{
//neither edge is currently contributing ...
cInt e1Wc2, e2Wc2;
switch (e1FillType2)
{
case pftPositive: e1Wc2 = e1->WindCnt2; break;
case pftNegative : e1Wc2 = -e1->WindCnt2; break;
default: e1Wc2 = Abs(e1->WindCnt2);
}
switch (e2FillType2)
{
case pftPositive: e2Wc2 = e2->WindCnt2; break;
case pftNegative: e2Wc2 = -e2->WindCnt2; break;
default: e2Wc2 = Abs(e2->WindCnt2);
}
if (e1->PolyTyp != e2->PolyTyp)
{
AddLocalMinPoly(e1, e2, Pt);
}
else if (e1Wc == 1 && e2Wc == 1)
switch( m_ClipType ) {
case ctIntersection:
if (e1Wc2 > 0 && e2Wc2 > 0)
AddLocalMinPoly(e1, e2, Pt);
break;
case ctUnion:
if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
AddLocalMinPoly(e1, e2, Pt);
break;
case ctDifference:
if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
AddLocalMinPoly(e1, e2, Pt);
break;
case ctXor:
AddLocalMinPoly(e1, e2, Pt);
}
else
SwapSides( *e1, *e2 );
}
}
//------------------------------------------------------------------------------
void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
{
TEdge *e2 = e->PrevInAEL;
TEdge *eTmp = 0;
while (e2)
{
if (e2->OutIdx >= 0 && e2->WindDelta != 0)
{
if (!eTmp) eTmp = e2;
else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;
}
e2 = e2->PrevInAEL;
}
if (!eTmp)
{
outrec->FirstLeft = 0;
outrec->IsHole = false;
}
else
{
outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];
outrec->IsHole = !outrec->FirstLeft->IsHole;
}
}
//------------------------------------------------------------------------------
OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
{
//work out which polygon fragment has the correct hole state ...
if (!outRec1->BottomPt)
outRec1->BottomPt = GetBottomPt(outRec1->Pts);
if (!outRec2->BottomPt)
outRec2->BottomPt = GetBottomPt(outRec2->Pts);
OutPt *OutPt1 = outRec1->BottomPt;
OutPt *OutPt2 = outRec2->BottomPt;
if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
else if (OutPt1->Next == OutPt1) return outRec2;
else if (OutPt2->Next == OutPt2) return outRec1;
else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
else return outRec2;
}
//------------------------------------------------------------------------------
bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)
{
do
{
outRec1 = outRec1->FirstLeft;
if (outRec1 == outRec2) return true;
} while (outRec1);
return false;
}
//------------------------------------------------------------------------------
OutRec* Clipper::GetOutRec(int Idx)
{
OutRec* outrec = m_PolyOuts[Idx];
while (outrec != m_PolyOuts[outrec->Idx])
outrec = m_PolyOuts[outrec->Idx];
return outrec;
}
//------------------------------------------------------------------------------
void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
{
//get the start and ends of both output polygons ...
OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
OutRec *holeStateRec;
if (OutRec1RightOfOutRec2(outRec1, outRec2))
holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1))
holeStateRec = outRec1;
else
holeStateRec = GetLowermostRec(outRec1, outRec2);
//get the start and ends of both output polygons and
//join e2 poly onto e1 poly and delete pointers to e2 ...
OutPt* p1_lft = outRec1->Pts;
OutPt* p1_rt = p1_lft->Prev;
OutPt* p2_lft = outRec2->Pts;
OutPt* p2_rt = p2_lft->Prev;
//join e2 poly onto e1 poly and delete pointers to e2 ...
if( e1->Side == esLeft )
{
if( e2->Side == esLeft )
{
//z y x a b c
ReversePolyPtLinks(p2_lft);
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
outRec1->Pts = p2_rt;
} else
{
//x y z a b c
p2_rt->Next = p1_lft;
p1_lft->Prev = p2_rt;
p2_lft->Prev = p1_rt;
p1_rt->Next = p2_lft;
outRec1->Pts = p2_lft;
}
} else
{
if( e2->Side == esRight )
{
//a b c z y x
ReversePolyPtLinks(p2_lft);
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
} else
{
//a b c x y z
p1_rt->Next = p2_lft;
p2_lft->Prev = p1_rt;
p1_lft->Prev = p2_rt;
p2_rt->Next = p1_lft;
}
}
outRec1->BottomPt = 0;
if (holeStateRec == outRec2)
{
if (outRec2->FirstLeft != outRec1)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec1->IsHole = outRec2->IsHole;
}
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->FirstLeft = outRec1;
int OKIdx = e1->OutIdx;
int ObsoleteIdx = e2->OutIdx;
e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
e2->OutIdx = Unassigned;
TEdge* e = m_ActiveEdges;
while( e )
{
if( e->OutIdx == ObsoleteIdx )
{
e->OutIdx = OKIdx;
e->Side = e1->Side;
break;
}
e = e->NextInAEL;
}
outRec2->Idx = outRec1->Idx;
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
{
if( e->OutIdx < 0 )
{
OutRec *outRec = CreateOutRec();
outRec->IsOpen = (e->WindDelta == 0);
OutPt* newOp = new OutPt;
outRec->Pts = newOp;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = newOp;
newOp->Prev = newOp;
if (!outRec->IsOpen)
SetHoleState(e, outRec);
e->OutIdx = outRec->Idx;
return newOp;
} else
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
//OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
OutPt* op = outRec->Pts;
bool ToFront = (e->Side == esLeft);
if (ToFront && (pt == op->Pt)) return op;
else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
OutPt* newOp = new OutPt;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = op;
newOp->Prev = op->Prev;
newOp->Prev->Next = newOp;
op->Prev = newOp;
if (ToFront) outRec->Pts = newOp;
return newOp;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::GetLastOutPt(TEdge *e)
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
if (e->Side == esLeft)
return outRec->Pts;
else
return outRec->Pts->Prev;
}
//------------------------------------------------------------------------------
void Clipper::ProcessHorizontals()
{
TEdge* horzEdge;
while (PopEdgeFromSEL(horzEdge))
ProcessHorizontal(horzEdge);
}
//------------------------------------------------------------------------------
inline bool IsMinima(TEdge *e)
{
return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
}
//------------------------------------------------------------------------------
inline bool IsMaxima(TEdge *e, const cInt Y)
{
return e && e->Top.Y == Y && !e->NextInLML;
}
//------------------------------------------------------------------------------
inline bool IsIntermediate(TEdge *e, const cInt Y)
{
return e->Top.Y == Y && e->NextInLML;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPair(TEdge *e)
{
if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
return e->Next;
else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
return e->Prev;
else return 0;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPairEx(TEdge *e)
{
//as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)
TEdge* result = GetMaximaPair(e);
if (result && (result->OutIdx == Skip ||
(result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;
return result;
}
//------------------------------------------------------------------------------
void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
{
if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
if( Edge1->NextInSEL == Edge2 )
{
TEdge* Next = Edge2->NextInSEL;
if( Next ) Next->PrevInSEL = Edge1;
TEdge* Prev = Edge1->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge2;
Edge2->PrevInSEL = Prev;
Edge2->NextInSEL = Edge1;
Edge1->PrevInSEL = Edge2;
Edge1->NextInSEL = Next;
}
else if( Edge2->NextInSEL == Edge1 )
{
TEdge* Next = Edge1->NextInSEL;
if( Next ) Next->PrevInSEL = Edge2;
TEdge* Prev = Edge2->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge1;
Edge1->PrevInSEL = Prev;
Edge1->NextInSEL = Edge2;
Edge2->PrevInSEL = Edge1;
Edge2->NextInSEL = Next;
}
else
{
TEdge* Next = Edge1->NextInSEL;
TEdge* Prev = Edge1->PrevInSEL;
Edge1->NextInSEL = Edge2->NextInSEL;
if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
Edge1->PrevInSEL = Edge2->PrevInSEL;
if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
Edge2->NextInSEL = Next;
if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
Edge2->PrevInSEL = Prev;
if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
}
if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
}
//------------------------------------------------------------------------------
TEdge* GetNextInAEL(TEdge *e, Direction dir)
{
return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
}
//------------------------------------------------------------------------------
void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
{
if (HorzEdge.Bot.X < HorzEdge.Top.X)
{
Left = HorzEdge.Bot.X;
Right = HorzEdge.Top.X;
Dir = dLeftToRight;
} else
{
Left = HorzEdge.Top.X;
Right = HorzEdge.Bot.X;
Dir = dRightToLeft;
}
}
//------------------------------------------------------------------------
/*******************************************************************************
* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
* Bottom of a scanbeam) are processed as if layered. The order in which HEs *
* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
* and with other non-horizontal edges [*]. Once these intersections are *
* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
*******************************************************************************/
void Clipper::ProcessHorizontal(TEdge *horzEdge)
{
Direction dir;
cInt horzLeft, horzRight;
bool IsOpen = (horzEdge->WindDelta == 0);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
eLastHorz = eLastHorz->NextInLML;
if (!eLastHorz->NextInLML)
eMaxPair = GetMaximaPair(eLastHorz);
MaximaList::const_iterator maxIt;
MaximaList::const_reverse_iterator maxRit;
if (m_Maxima.size() > 0)
{
//get the first maxima in range (X) ...
if (dir == dLeftToRight)
{
maxIt = m_Maxima.begin();
while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
maxIt = m_Maxima.end();
}
else
{
maxRit = m_Maxima.rbegin();
while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
maxRit = m_Maxima.rend();
}
}
OutPt* op1 = 0;
for (;;) //loop through consec. horizontal edges
{
bool IsLastHorz = (horzEdge == eLastHorz);
TEdge* e = GetNextInAEL(horzEdge, dir);
while(e)
{
//this code block inserts extra coords into horizontal edges (in output
//polygons) whereever maxima touch these horizontal edges. This helps
//'simplifying' polygons (ie if the Simplify property is set).
if (m_Maxima.size() > 0)
{
if (dir == dLeftToRight)
{
while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
maxIt++;
}
}
else
{
while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
maxRit++;
}
}
};
if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
(dir == dRightToLeft && e->Curr.X < horzLeft)) break;
//Also break if we've got to the end of an intermediate horizontal edge ...
//nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
e->Dx < horzEdge->NextInLML->Dx) break;
if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
{
#ifdef use_xyz
if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);
else SetZ(e->Curr, *e, *horzEdge);
#endif
op1 = AddOutPt(horzEdge, e->Curr);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Bot);
}
//OK, so far we're still in range of the horizontal Edge but make sure
//we're at the last of consec. horizontals when matching with eMaxPair
if(e == eMaxPair && IsLastHorz)
{
if (horzEdge->OutIdx >= 0)
AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
DeleteFromAEL(horzEdge);
DeleteFromAEL(eMaxPair);
return;
}
if(dir == dLeftToRight)
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges(horzEdge, e, Pt);
}
else
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges( e, horzEdge, Pt);
}
TEdge* eNext = GetNextInAEL(e, dir);
SwapPositionsInAEL( horzEdge, e );
e = eNext;
} //end while(e)
//Break out of loop if HorzEdge.NextInLML is not also horizontal ...
if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
} //end for (;;)
if (horzEdge->OutIdx >= 0 && !op1)
{
op1 = GetLastOutPt(horzEdge);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Top);
}
if (horzEdge->NextInLML)
{
if(horzEdge->OutIdx >= 0)
{
op1 = AddOutPt( horzEdge, horzEdge->Top);
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->WindDelta == 0) return;
//nb: HorzEdge is no longer horizontal here
TEdge* ePrev = horzEdge->PrevInAEL;
TEdge* eNext = horzEdge->NextInAEL;
if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
(ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
{
OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
{
OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
}
else
UpdateEdgeIntoAEL(horzEdge);
}
else
{
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
DeleteFromAEL(horzEdge);
}
}
//------------------------------------------------------------------------------
bool Clipper::ProcessIntersections(const cInt topY)
{
if( !m_ActiveEdges ) return true;
try {
BuildIntersectList(topY);
size_t IlSize = m_IntersectList.size();
if (IlSize == 0) return true;
if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
else return false;
}
catch(...)
{
m_SortedEdges = 0;
DisposeIntersectNodes();
throw clipperException("ProcessIntersections error");
}
m_SortedEdges = 0;
return true;
}
//------------------------------------------------------------------------------
void Clipper::DisposeIntersectNodes()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i )
delete m_IntersectList[i];
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
void Clipper::BuildIntersectList(const cInt topY)
{
if ( !m_ActiveEdges ) return;
//prepare for sorting ...
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e->Curr.X = TopX( *e, topY );
e = e->NextInAEL;
}
//bubblesort ...
bool isModified;
do
{
isModified = false;
e = m_SortedEdges;
while( e->NextInSEL )
{
TEdge *eNext = e->NextInSEL;
IntPoint Pt;
if(e->Curr.X > eNext->Curr.X)
{
IntersectPoint(*e, *eNext, Pt);
if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);
IntersectNode * newNode = new IntersectNode;
newNode->Edge1 = e;
newNode->Edge2 = eNext;
newNode->Pt = Pt;
m_IntersectList.push_back(newNode);
SwapPositionsInSEL(e, eNext);
isModified = true;
}
else
e = eNext;
}
if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
else break;
}
while ( isModified );
m_SortedEdges = 0; //important
}
//------------------------------------------------------------------------------
void Clipper::ProcessIntersectList()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i)
{
IntersectNode* iNode = m_IntersectList[i];
{
IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
}
delete iNode;
}
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
{
return node2->Pt.Y < node1->Pt.Y;
}
//------------------------------------------------------------------------------
inline bool EdgesAdjacent(const IntersectNode &inode)
{
return (inode.Edge1->NextInSEL == inode.Edge2) ||
(inode.Edge1->PrevInSEL == inode.Edge2);
}
//------------------------------------------------------------------------------
bool Clipper::FixupIntersectionOrder()
{
//pre-condition: intersections are sorted Bottom-most first.
//Now it's crucial that intersections are made only between adjacent edges,
//so to ensure this the order of intersections may need adjusting ...
CopyAELToSEL();
std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
size_t cnt = m_IntersectList.size();
for (size_t i = 0; i < cnt; ++i)
{
if (!EdgesAdjacent(*m_IntersectList[i]))
{
size_t j = i + 1;
while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
if (j == cnt) return false;
std::swap(m_IntersectList[i], m_IntersectList[j]);
}
SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
}
return true;
}
//------------------------------------------------------------------------------
void Clipper::DoMaxima(TEdge *e)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
if (!eMaxPair)
{
if (e->OutIdx >= 0)
AddOutPt(e, e->Top);
DeleteFromAEL(e);
return;
}
TEdge* eNext = e->NextInAEL;
while(eNext && eNext != eMaxPair)
{
IntersectEdges(e, eNext, e->Top);
SwapPositionsInAEL(e, eNext);
eNext = e->NextInAEL;
}
if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
{
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
{
if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
#ifdef use_lines
else if (e->WindDelta == 0)
{
if (e->OutIdx >= 0)
{
AddOutPt(e, e->Top);
e->OutIdx = Unassigned;
}
DeleteFromAEL(e);
if (eMaxPair->OutIdx >= 0)
{
AddOutPt(eMaxPair, e->Top);
eMaxPair->OutIdx = Unassigned;
}
DeleteFromAEL(eMaxPair);
}
#endif
else throw clipperException("DoMaxima error");
}
//------------------------------------------------------------------------------
void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
{
TEdge* e = m_ActiveEdges;
while( e )
{
//1. process maxima, treating them as if they're 'bent' horizontal edges,
// but exclude maxima with horizontal edges. nb: e can't be a horizontal.
bool IsMaximaEdge = IsMaxima(e, topY);
if(IsMaximaEdge)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
}
if(IsMaximaEdge)
{
if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
TEdge* ePrev = e->PrevInAEL;
DoMaxima(e);
if( !ePrev ) e = m_ActiveEdges;
else e = ePrev->NextInAEL;
}
else
{
//2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
{
UpdateEdgeIntoAEL(e);
if (e->OutIdx >= 0)
AddOutPt(e, e->Bot);
AddEdgeToSEL(e);
}
else
{
e->Curr.X = TopX( *e, topY );
e->Curr.Y = topY;
#ifdef use_xyz
e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);
#endif
}
//When StrictlySimple and 'e' is being touched by another edge, then
//make sure both edges have a vertex here ...
if (m_StrictSimple)
{
TEdge* ePrev = e->PrevInAEL;
if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
(ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
{
IntPoint pt = e->Curr;
#ifdef use_xyz
SetZ(pt, *ePrev, *e);
#endif
OutPt* op = AddOutPt(ePrev, pt);
OutPt* op2 = AddOutPt(e, pt);
AddJoin(op, op2, pt); //StrictlySimple (type-3) join
}
}
e = e->NextInAEL;
}
}
//3. Process horizontals at the Top of the scanbeam ...
m_Maxima.sort();
ProcessHorizontals();
m_Maxima.clear();
//4. Promote intermediate vertices ...
e = m_ActiveEdges;
while(e)
{
if(IsIntermediate(e, topY))
{
OutPt* op = 0;
if( e->OutIdx >= 0 )
op = AddOutPt(e, e->Top);
UpdateEdgeIntoAEL(e);
//if output polygons share an edge, they'll need joining later ...
TEdge* ePrev = e->PrevInAEL;
TEdge* eNext = e->NextInAEL;
if (ePrev && ePrev->Curr.X == e->Bot.X &&
ePrev->Curr.Y == e->Bot.Y && op &&
ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (ePrev->WindDelta != 0))
{
OutPt* op2 = AddOutPt(ePrev, e->Bot);
AddJoin(op, op2, e->Top);
}
else if (eNext && eNext->Curr.X == e->Bot.X &&
eNext->Curr.Y == e->Bot.Y && op &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (eNext->WindDelta != 0))
{
OutPt* op2 = AddOutPt(eNext, e->Bot);
AddJoin(op, op2, e->Top);
}
}
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolyline(OutRec &outrec)
{
OutPt *pp = outrec.Pts;
OutPt *lastPP = pp->Prev;
while (pp != lastPP)
{
pp = pp->Next;
if (pp->Pt == pp->Prev->Pt)
{
if (pp == lastPP) lastPP = pp->Prev;
OutPt *tmpPP = pp->Prev;
tmpPP->Next = pp->Next;
pp->Next->Prev = tmpPP;
delete pp;
pp = tmpPP;
}
}
if (pp == pp->Prev)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolygon(OutRec &outrec)
{
//FixupOutPolygon() - removes duplicate points and simplifies consecutive
//parallel edges by removing the middle vertex.
OutPt *lastOK = 0;
outrec.BottomPt = 0;
OutPt *pp = outrec.Pts;
bool preserveCol = m_PreserveCollinear || m_StrictSimple;
for (;;)
{
if (pp->Prev == pp || pp->Prev == pp->Next)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
//test for duplicate points and collinear edges ...
if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
(SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
(!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
{
lastOK = 0;
OutPt *tmp = pp;
pp->Prev->Next = pp->Next;
pp->Next->Prev = pp->Prev;
pp = pp->Prev;
delete tmp;
}
else if (pp == lastOK) break;
else
{
if (!lastOK) lastOK = pp;
pp = pp->Next;
}
}
outrec.Pts = pp;
}
//------------------------------------------------------------------------------
int PointCount(OutPt *Pts)
{
if (!Pts) return 0;
int result = 0;
OutPt* p = Pts;
do
{
result++;
p = p->Next;
}
while (p != Pts);
return result;
}
//------------------------------------------------------------------------------
void Clipper::BuildResult(Paths &polys)
{
polys.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
if (!m_PolyOuts[i]->Pts) continue;
Path pg;
OutPt* p = m_PolyOuts[i]->Pts->Prev;
int cnt = PointCount(p);
if (cnt < 2) continue;
pg.reserve(cnt);
for (int i = 0; i < cnt; ++i)
{
pg.push_back(p->Pt);
p = p->Prev;
}
polys.push_back(pg);
}
}
//------------------------------------------------------------------------------
void Clipper::BuildResult2(PolyTree& polytree)
{
polytree.Clear();
polytree.AllNodes.reserve(m_PolyOuts.size());
//add each output polygon/contour to polytree ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
int cnt = PointCount(outRec->Pts);
if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
FixHoleLinkage(*outRec);
PolyNode* pn = new PolyNode();
//nb: polytree takes ownership of all the PolyNodes
polytree.AllNodes.push_back(pn);
outRec->PolyNd = pn;
pn->Parent = 0;
pn->Index = 0;
pn->Contour.reserve(cnt);
OutPt *op = outRec->Pts->Prev;
for (int j = 0; j < cnt; j++)
{
pn->Contour.push_back(op->Pt);
op = op->Prev;
}
}
//fixup PolyNode links etc ...
polytree.Childs.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->PolyNd) continue;
if (outRec->IsOpen)
{
outRec->PolyNd->m_IsOpen = true;
polytree.AddChild(*outRec->PolyNd);
}
else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
else
polytree.AddChild(*outRec->PolyNd);
}
}
//------------------------------------------------------------------------------
void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
{
//just swap the contents (because fIntersectNodes is a single-linked-list)
IntersectNode inode = int1; //gets a copy of Int1
int1.Edge1 = int2.Edge1;
int1.Edge2 = int2.Edge2;
int1.Pt = int2.Pt;
int2.Edge1 = inode.Edge1;
int2.Edge2 = inode.Edge2;
int2.Pt = inode.Pt;
}
//------------------------------------------------------------------------------
inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
{
if (e2.Curr.X == e1.Curr.X)
{
if (e2.Top.Y > e1.Top.Y)
return e2.Top.X < TopX(e1, e2.Top.Y);
else return e1.Top.X > TopX(e2, e1.Top.Y);
}
else return e2.Curr.X < e1.Curr.X;
}
//------------------------------------------------------------------------------
bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
cInt& Left, cInt& Right)
{
if (a1 < a2)
{
if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
}
else
{
if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
}
return Left < Right;
}
//------------------------------------------------------------------------------
inline void UpdateOutPtIdxs(OutRec& outrec)
{
OutPt* op = outrec.Pts;
do
{
op->Idx = outrec.Idx;
op = op->Prev;
}
while(op != outrec.Pts);
}
//------------------------------------------------------------------------------
void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
{
if(!m_ActiveEdges)
{
edge->PrevInAEL = 0;
edge->NextInAEL = 0;
m_ActiveEdges = edge;
}
else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
{
edge->PrevInAEL = 0;
edge->NextInAEL = m_ActiveEdges;
m_ActiveEdges->PrevInAEL = edge;
m_ActiveEdges = edge;
}
else
{
if(!startEdge) startEdge = m_ActiveEdges;
while(startEdge->NextInAEL &&
!E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
startEdge = startEdge->NextInAEL;
edge->NextInAEL = startEdge->NextInAEL;
if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
edge->PrevInAEL = startEdge;
startEdge->NextInAEL = edge;
}
}
//----------------------------------------------------------------------
OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
{
OutPt* result = new OutPt;
result->Pt = outPt->Pt;
result->Idx = outPt->Idx;
if (InsertAfter)
{
result->Next = outPt->Next;
result->Prev = outPt;
outPt->Next->Prev = result;
outPt->Next = result;
}
else
{
result->Prev = outPt->Prev;
result->Next = outPt;
outPt->Prev->Next = result;
outPt->Prev = result;
}
return result;
}
//------------------------------------------------------------------------------
bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
const IntPoint Pt, bool DiscardLeft)
{
Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
if (Dir1 == Dir2) return false;
//When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
//want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
//So, to facilitate this while inserting Op1b and Op2b ...
//when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
//otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
if (Dir1 == dLeftToRight)
{
while (op1->Next->Pt.X <= Pt.X &&
op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, !DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, !DiscardLeft);
}
}
else
{
while (op1->Next->Pt.X >= Pt.X &&
op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, DiscardLeft);
}
}
if (Dir2 == dLeftToRight)
{
while (op2->Next->Pt.X <= Pt.X &&
op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, !DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, !DiscardLeft);
};
} else
{
while (op2->Next->Pt.X >= Pt.X &&
op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, DiscardLeft);
};
};
if ((Dir1 == dLeftToRight) == DiscardLeft)
{
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
}
else
{
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
}
return true;
}
//------------------------------------------------------------------------------
bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
{
OutPt *op1 = j->OutPt1, *op1b;
OutPt *op2 = j->OutPt2, *op2b;
//There are 3 kinds of joins for output polygons ...
//1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
//along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
//2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
//location at the Bottom of the overlapping segment (& Join.OffPt is above).
//3. StrictSimple joins where edges touch but are not collinear and where
//Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
(j->OffPt == j->OutPt2->Pt))
{
//Strictly Simple join ...
if (outRec1 != outRec2) return false;
op1b = j->OutPt1->Next;
while (op1b != op1 && (op1b->Pt == j->OffPt))
op1b = op1b->Next;
bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
op2b = j->OutPt2->Next;
while (op2b != op2 && (op2b->Pt == j->OffPt))
op2b = op2b->Next;
bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
if (reverse1 == reverse2) return false;
if (reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
else if (isHorizontal)
{
//treat horizontal joins differently to non-horizontal joins since with
//them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
//may be anywhere along the horizontal edge.
op1b = op1;
while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
op1 = op1->Prev;
while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
op1b = op1b->Next;
if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
op2b = op2;
while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
op2 = op2->Prev;
while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
op2b = op2b->Next;
if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
cInt Left, Right;
//Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
return false;
//DiscardLeftSide: when overlapping edges are joined, a spike will created
//which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
//on the discard Side as either may still be needed for other joins ...
IntPoint Pt;
bool DiscardLeftSide;
if (op1->Pt.X >= Left && op1->Pt.X <= Right)
{
Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
}
else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
{
Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
}
else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
{
Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
}
else
{
Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
}
j->OutPt1 = op1; j->OutPt2 = op2;
return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
} else
{
//nb: For non-horizontal joins ...
// 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
// 2. Jr.OutPt1.Pt > Jr.OffPt.Y
//make sure the polygons are correctly oriented ...
op1b = op1->Next;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
if (Reverse1)
{
op1b = op1->Prev;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
if ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
};
op2b = op2->Next;
while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
if (Reverse2)
{
op2b = op2->Prev;
while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
if ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
}
if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
if (Reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
}
//----------------------------------------------------------------------
static OutRec* ParseFirstLeft(OutRec* FirstLeft)
{
while (FirstLeft && !FirstLeft->Pts)
FirstLeft = FirstLeft->FirstLeft;
return FirstLeft;
}
//------------------------------------------------------------------------------
void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
{
//tests if NewOutRec contains the polygon before reassigning FirstLeft
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
{
if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
outRec->FirstLeft = NewOutRec;
}
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)
{
//A polygon has split into two such that one is now the inner of the other.
//It's possible that these polygons now wrap around other polygons, so check
//every polygon that's also contained by OuterOutRec's FirstLeft container
//(including 0) to see if they've become inner to the new inner polygon ...
OutRec* orfl = OuterOutRec->FirstLeft;
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)
continue;
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)
continue;
if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))
outRec->FirstLeft = InnerOutRec;
else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))
outRec->FirstLeft = OuterOutRec;
else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)
outRec->FirstLeft = orfl;
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)
{
//reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
outRec->FirstLeft = NewOutRec;
}
}
//----------------------------------------------------------------------
void Clipper::JoinCommonEdges()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
{
Join* join = m_Joins[i];
OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
if (!outRec1->Pts || !outRec2->Pts) continue;
if (outRec1->IsOpen || outRec2->IsOpen) continue;
//get the polygon fragment with the correct hole state (FirstLeft)
//before calling JoinPoints() ...
OutRec *holeStateRec;
if (outRec1 == outRec2) holeStateRec = outRec1;
else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;
else holeStateRec = GetLowermostRec(outRec1, outRec2);
if (!JoinPoints(join, outRec1, outRec2)) continue;
if (outRec1 == outRec2)
{
//instead of joining two polygons, we've just created a new one by
//splitting one polygon into two.
outRec1->Pts = join->OutPt1;
outRec1->BottomPt = 0;
outRec2 = CreateOutRec();
outRec2->Pts = join->OutPt2;
//update all OutRec2.Pts Idx's ...
UpdateOutPtIdxs(*outRec2);
if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
{
//outRec1 contains outRec2 ...
outRec2->IsHole = !outRec1->IsHole;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
ReversePolyPtLinks(outRec2->Pts);
} else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
{
//outRec2 contains outRec1 ...
outRec2->IsHole = outRec1->IsHole;
outRec1->IsHole = !outRec2->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
outRec1->FirstLeft = outRec2;
if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
ReversePolyPtLinks(outRec1->Pts);
}
else
{
//the 2 polygons are completely separate ...
outRec2->IsHole = outRec1->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
//fixup FirstLeft pointers that may need reassigning to OutRec2
if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
}
} else
{
//joined 2 polygons together ...
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->Idx = outRec1->Idx;
outRec1->IsHole = holeStateRec->IsHole;
if (holeStateRec == outRec2)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);
}
}
}
//------------------------------------------------------------------------------
// ClipperOffset support functions ...
//------------------------------------------------------------------------------
DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
{
if(pt2.X == pt1.X && pt2.Y == pt1.Y)
return DoublePoint(0, 0);
double Dx = (double)(pt2.X - pt1.X);
double dy = (double)(pt2.Y - pt1.Y);
double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
Dx *= f;
dy *= f;
return DoublePoint(dy, -Dx);
}
//------------------------------------------------------------------------------
// ClipperOffset class
//------------------------------------------------------------------------------
ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
{
this->MiterLimit = miterLimit;
this->ArcTolerance = arcTolerance;
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
ClipperOffset::~ClipperOffset()
{
Clear();
}
//------------------------------------------------------------------------------
void ClipperOffset::Clear()
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
delete m_polyNodes.Childs[i];
m_polyNodes.Childs.clear();
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
{
int highI = (int)path.size() - 1;
if (highI < 0) return;
PolyNode* newNode = new PolyNode();
newNode->m_jointype = joinType;
newNode->m_endtype = endType;
//strip duplicate points from path and also get index to the lowest point ...
if (endType == etClosedLine || endType == etClosedPolygon)
while (highI > 0 && path[0] == path[highI]) highI--;
newNode->Contour.reserve(highI + 1);
newNode->Contour.push_back(path[0]);
int j = 0, k = 0;
for (int i = 1; i <= highI; i++)
if (newNode->Contour[j] != path[i])
{
j++;
newNode->Contour.push_back(path[i]);
if (path[i].Y > newNode->Contour[k].Y ||
(path[i].Y == newNode->Contour[k].Y &&
path[i].X < newNode->Contour[k].X)) k = j;
}
if (endType == etClosedPolygon && j < 2)
{
delete newNode;
return;
}
m_polyNodes.AddChild(*newNode);
//if this path's lowest pt is lower than all the others then update m_lowest
if (endType != etClosedPolygon) return;
if (m_lowest.X < 0)
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
else
{
IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
if (newNode->Contour[k].Y > ip.Y ||
(newNode->Contour[k].Y == ip.Y &&
newNode->Contour[k].X < ip.X))
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
}
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
{
for (Paths::size_type i = 0; i < paths.size(); ++i)
AddPath(paths[i], joinType, endType);
}
//------------------------------------------------------------------------------
void ClipperOffset::FixOrientations()
{
//fixup orientations of all closed paths if the orientation of the
//closed path with the lowermost vertex is wrong ...
if (m_lowest.X >= 0 &&
!Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon ||
(node.m_endtype == etClosedLine && Orientation(node.Contour)))
ReversePath(node.Contour);
}
} else
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
ReversePath(node.Contour);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(Paths& solution, double delta)
{
solution.clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
if (solution.size() > 0) solution.erase(solution.begin());
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(PolyTree& solution, double delta)
{
solution.Clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
//remove the outer PolyNode rectangle ...
if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
{
PolyNode* outerNode = solution.Childs[0];
solution.Childs.reserve(outerNode->ChildCount());
solution.Childs[0] = outerNode->Childs[0];
solution.Childs[0]->Parent = outerNode->Parent;
for (int i = 1; i < outerNode->ChildCount(); ++i)
solution.AddChild(*outerNode->Childs[i]);
}
else
solution.Clear();
}
}
//------------------------------------------------------------------------------
void ClipperOffset::DoOffset(double delta)
{
m_destPolys.clear();
m_delta = delta;
//if Zero offset, just copy any CLOSED polygons to m_p and return ...
if (NEAR_ZERO(delta))
{
m_destPolys.reserve(m_polyNodes.ChildCount());
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon)
m_destPolys.push_back(node.Contour);
}
return;
}
//see offset_triginometry3.svg in the documentation folder ...
if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
else m_miterLim = 0.5;
double y;
if (ArcTolerance <= 0.0) y = def_arc_tolerance;
else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
y = std::fabs(delta) * def_arc_tolerance;
else y = ArcTolerance;
//see offset_triginometry2.svg in the documentation folder ...
double steps = pi / std::acos(1 - y / std::fabs(delta));
if (steps > std::fabs(delta) * pi)
steps = std::fabs(delta) * pi; //ie excessive precision check
m_sin = std::sin(two_pi / steps);
m_cos = std::cos(two_pi / steps);
m_StepsPerRad = steps / two_pi;
if (delta < 0.0) m_sin = -m_sin;
m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
m_srcPoly = node.Contour;
int len = (int)m_srcPoly.size();
if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
continue;
m_destPoly.clear();
if (len == 1)
{
if (node.m_jointype == jtRound)
{
double X = 1.0, Y = 0.0;
for (cInt j = 1; j <= steps; j++)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
double X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
}
else
{
double X = -1.0, Y = -1.0;
for (int j = 0; j < 4; ++j)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
if (X < 0) X = 1;
else if (Y < 0) Y = 1;
else X = -1;
}
}
m_destPolys.push_back(m_destPoly);
continue;
}
//build m_normals ...
m_normals.clear();
m_normals.reserve(len);
for (int j = 0; j < len - 1; ++j)
m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
else
m_normals.push_back(DoublePoint(m_normals[len - 2]));
if (node.m_endtype == etClosedPolygon)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else if (node.m_endtype == etClosedLine)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
m_destPoly.clear();
//re-build m_normals ...
DoublePoint n = m_normals[len -1];
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-n.X, -n.Y);
k = 0;
for (int j = len - 1; j >= 0; j--)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else
{
int k = 0;
for (int j = 1; j < len - 1; ++j)
OffsetPoint(j, k, node.m_jointype);
IntPoint pt1;
if (node.m_endtype == etOpenButt)
{
int j = len - 1;
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
int j = len - 1;
k = len - 2;
m_sinA = 0;
m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
if (node.m_endtype == etOpenSquare)
DoSquare(j, k);
else
DoRound(j, k);
}
//re-build m_normals ...
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
k = len - 1;
for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
if (node.m_endtype == etOpenButt)
{
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
k = 1;
m_sinA = 0;
if (node.m_endtype == etOpenSquare)
DoSquare(0, 1);
else
DoRound(0, 1);
}
m_destPolys.push_back(m_destPoly);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
{
//cross product ...
m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
if (std::fabs(m_sinA * m_delta) < 1.0)
{
//dot product ...
double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
if (cosA > 0) // angle => 0 degrees
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
return;
}
//else angle => 180 degrees
}
else if (m_sinA > 1.0) m_sinA = 1.0;
else if (m_sinA < -1.0) m_sinA = -1.0;
if (m_sinA * m_delta < 0)
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
m_destPoly.push_back(m_srcPoly[j]);
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
else
switch (jointype)
{
case jtMiter:
{
double r = 1 + (m_normals[j].X * m_normals[k].X +
m_normals[j].Y * m_normals[k].Y);
if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
break;
}
case jtSquare: DoSquare(j, k); break;
case jtRound: DoRound(j, k); break;
}
k = j;
}
//------------------------------------------------------------------------------
void ClipperOffset::DoSquare(int j, int k)
{
double dx = std::tan(std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoMiter(int j, int k, double r)
{
double q = m_delta / r;
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoRound(int j, int k)
{
double a = std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
double X = m_normals[k].X, Y = m_normals[k].Y, X2;
for (int i = 0; i < steps; ++i)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + X * m_delta),
Round(m_srcPoly[j].Y + Y * m_delta)));
X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
//------------------------------------------------------------------------------
// Miscellaneous public functions
//------------------------------------------------------------------------------
void Clipper::DoSimplePolygons()
{
PolyOutList::size_type i = 0;
while (i < m_PolyOuts.size())
{
OutRec* outrec = m_PolyOuts[i++];
OutPt* op = outrec->Pts;
if (!op || outrec->IsOpen) continue;
do //for each Pt in Polygon until duplicate found do ...
{
OutPt* op2 = op->Next;
while (op2 != outrec->Pts)
{
if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
{
//split the polygon into two ...
OutPt* op3 = op->Prev;
OutPt* op4 = op2->Prev;
op->Prev = op4;
op4->Next = op;
op2->Prev = op3;
op3->Next = op2;
outrec->Pts = op;
OutRec* outrec2 = CreateOutRec();
outrec2->Pts = op2;
UpdateOutPtIdxs(*outrec2);
if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
{
//OutRec2 is contained by OutRec1 ...
outrec2->IsHole = !outrec->IsHole;
outrec2->FirstLeft = outrec;
if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
}
else
if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
{
//OutRec1 is contained by OutRec2 ...
outrec2->IsHole = outrec->IsHole;
outrec->IsHole = !outrec2->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
outrec->FirstLeft = outrec2;
if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
}
else
{
//the 2 polygons are separate ...
outrec2->IsHole = outrec->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
}
op2 = op; //ie get ready for the Next iteration
}
op2 = op2->Next;
}
op = op->Next;
}
while (op != outrec->Pts);
}
}
//------------------------------------------------------------------------------
void ReversePath(Path& p)
{
std::reverse(p.begin(), p.end());
}
//------------------------------------------------------------------------------
void ReversePaths(Paths& p)
{
for (Paths::size_type i = 0; i < p.size(); ++i)
ReversePath(p[i]);
}
//------------------------------------------------------------------------------
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPath(in_poly, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPaths(in_polys, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(Paths &polys, PolyFillType fillType)
{
SimplifyPolygons(polys, polys, fillType);
}
//------------------------------------------------------------------------------
inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
{
double Dx = ((double)pt1.X - pt2.X);
double dy = ((double)pt1.Y - pt2.Y);
return (Dx*Dx + dy*dy);
}
//------------------------------------------------------------------------------
double DistanceFromLineSqrd(
const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
{
//The equation of a line in general form (Ax + By + C = 0)
//given 2 points (x�,y�) & (x�,y�) is ...
//(y� - y�)x + (x� - x�)y + (y� - y�)x� - (x� - x�)y� = 0
//A = (y� - y�); B = (x� - x�); C = (y� - y�)x� - (x� - x�)y�
//perpendicular distance of point (x�,y�) = (Ax� + By� + C)/Sqrt(A� + B�)
//see http://en.wikipedia.org/wiki/Perpendicular_distance
double A = double(ln1.Y - ln2.Y);
double B = double(ln2.X - ln1.X);
double C = A * ln1.X + B * ln1.Y;
C = A * pt.X + B * pt.Y - C;
return (C * C) / (A * A + B * B);
}
//---------------------------------------------------------------------------
bool SlopesNearCollinear(const IntPoint& pt1,
const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
{
//this function is more accurate when the point that's geometrically
//between the other 2 points is the one that's tested for distance.
//ie makes it more likely to pick up 'spikes' ...
if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
{
if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
else
{
if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
}
//------------------------------------------------------------------------------
bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
{
double Dx = (double)pt1.X - pt2.X;
double dy = (double)pt1.Y - pt2.Y;
return ((Dx * Dx) + (dy * dy) <= distSqrd);
}
//------------------------------------------------------------------------------
OutPt* ExcludeOp(OutPt* op)
{
OutPt* result = op->Prev;
result->Next = op->Next;
op->Next->Prev = result;
result->Idx = 0;
return result;
}
//------------------------------------------------------------------------------
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
{
//distance = proximity in units/pixels below which vertices
//will be stripped. Default ~= sqrt(2).
size_t size = in_poly.size();
if (size == 0)
{
out_poly.clear();
return;
}
OutPt* outPts = new OutPt[size];
for (size_t i = 0; i < size; ++i)
{
outPts[i].Pt = in_poly[i];
outPts[i].Next = &outPts[(i + 1) % size];
outPts[i].Next->Prev = &outPts[i];
outPts[i].Idx = 0;
}
double distSqrd = distance * distance;
OutPt* op = &outPts[0];
while (op->Idx == 0 && op->Next != op->Prev)
{
if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
{
ExcludeOp(op->Next);
op = ExcludeOp(op);
size -= 2;
}
else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else
{
op->Idx = 1;
op = op->Next;
}
}
if (size < 3) size = 0;
out_poly.resize(size);
for (size_t i = 0; i < size; ++i)
{
out_poly[i] = op->Pt;
op = op->Next;
}
delete [] outPts;
}
//------------------------------------------------------------------------------
void CleanPolygon(Path& poly, double distance)
{
CleanPolygon(poly, poly, distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
{
out_polys.resize(in_polys.size());
for (Paths::size_type i = 0; i < in_polys.size(); ++i)
CleanPolygon(in_polys[i], out_polys[i], distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(Paths& polys, double distance)
{
CleanPolygons(polys, polys, distance);
}
//------------------------------------------------------------------------------
void Minkowski(const Path& poly, const Path& path,
Paths& solution, bool isSum, bool isClosed)
{
int delta = (isClosed ? 1 : 0);
size_t polyCnt = poly.size();
size_t pathCnt = path.size();
Paths pp;
pp.reserve(pathCnt);
if (isSum)
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
pp.push_back(p);
}
else
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
pp.push_back(p);
}
solution.clear();
solution.reserve((pathCnt + delta) * (polyCnt + 1));
for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
for (size_t j = 0; j < polyCnt; ++j)
{
Path quad;
quad.reserve(4);
quad.push_back(pp[i % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
if (!Orientation(quad)) ReversePath(quad);
solution.push_back(quad);
}
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
{
Minkowski(pattern, path, solution, true, pathIsClosed);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void TranslatePath(const Path& input, Path& output, const IntPoint delta)
{
//precondition: input != output
output.resize(input.size());
for (size_t i = 0; i < input.size(); ++i)
output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
{
Clipper c;
for (size_t i = 0; i < paths.size(); ++i)
{
Paths tmp;
Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
c.AddPaths(tmp, ptSubject, true);
if (pathIsClosed)
{
Path tmp2;
TranslatePath(paths[i], tmp2, pattern[0]);
c.AddPath(tmp2, ptClip, true);
}
}
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
{
Minkowski(poly1, poly2, solution, false, true);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
enum NodeType {ntAny, ntOpen, ntClosed};
void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
{
bool match = true;
if (nodetype == ntClosed) match = !polynode.IsOpen();
else if (nodetype == ntOpen) return;
if (!polynode.Contour.empty() && match)
paths.push_back(polynode.Contour);
for (int i = 0; i < polynode.ChildCount(); ++i)
AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
}
//------------------------------------------------------------------------------
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntAny, paths);
}
//------------------------------------------------------------------------------
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntClosed, paths);
}
//------------------------------------------------------------------------------
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
//Open paths are top level only, so ...
for (int i = 0; i < polytree.ChildCount(); ++i)
if (polytree.Childs[i]->IsOpen())
paths.push_back(polytree.Childs[i]->Contour);
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const IntPoint &p)
{
s << "(" << p.X << "," << p.Y << ")";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Path &p)
{
if (p.empty()) return s;
Path::size_type last = p.size() -1;
for (Path::size_type i = 0; i < last; i++)
s << "(" << p[i].X << "," << p[i].Y << "), ";
s << "(" << p[last].X << "," << p[last].Y << ")\n";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Paths &p)
{
for (Paths::size_type i = 0; i < p.size(); i++)
s << p[i];
s << "\n";
return s;
}
//------------------------------------------------------------------------------
} //ClipperLib namespace
geometry-4.0.0/src/clipper.hpp 0000644 0000000 0000000 00000040033 13615712371 014500 0 ustar 00 0000000 0000000 /*
(C) 2012-2017 Angus Johnson
Boost Software License - Version 1.0 - August 17th, 2003
http://www.boost.org/LICENSE_1_0.txt
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/*******************************************************************************
* *
* 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
#include
#include
#include
#include
#include
#include
#include
#include
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 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 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 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 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
geometry-4.0.0/src/connector.cpp 0000644 0000000 0000000 00000005250 13615712371 015031 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#include "connector.h"
#include
void PointChain::init (const Segment& s)
{
l.push_back (s.begin ());
l.push_back (s.end ());
}
bool PointChain::LinkSegment (const Segment& s)
{
if (s.begin () == l.front ()) {
if (s.end () == l.back ())
_closed = true;
else
l.push_front (s.end ());
return true;
}
if (s.end () == l.back ()) {
if (s.begin () == l.front ())
_closed = true;
else
l.push_back (s.begin ());
return true;
}
if (s.end () == l.front ()) {
if (s.begin () == l.back ())
_closed = true;
else
l.push_front (s.begin ());
return true;
}
if (s.begin () == l.back ()) {
if (s.end () == l.front ())
_closed = true;
else
l.push_back (s.end ());
return true;
}
return false;
}
bool PointChain::LinkPointChain (PointChain& chain)
{
if (chain.l.front () == l.back ()) {
chain.l.pop_front ();
l.splice (l.end (), chain.l);
return true;
}
if (chain.l.back () == l.front ()) {
l.pop_front ();
l.splice (l.begin (), chain.l);
return true;
}
if (chain.l.front () == l.front ()) {
l.pop_front ();
reverse (chain.l.begin (), chain.l.end ());
l.splice (l.begin (), chain.l);
return true;
}
if (chain.l.back () == l.back ()) {
l.pop_back ();
reverse (chain.l.begin (), chain.l.end ());
l.splice (l.end (), chain.l);
return true;
}
return false;
}
void Connector::add(const Segment& s)
{
iterator j = openPolygons.begin ();
while (j != openPolygons.end ()) {
if (j->LinkSegment (s)) {
if (j->closed ())
closedPolygons.splice (closedPolygons.end (), openPolygons, j);
else {
list::iterator k = j;
for (++k; k != openPolygons.end (); k++) {
if (j->LinkPointChain (*k)) {
openPolygons.erase (k);
break;
}
}
}
return;
}
j++;
}
// The segment cannot be connected with any open polygon
openPolygons.push_back (PointChain ());
openPolygons.back ().init (s);
}
void Connector::toPolygon (Polygon& p)
{
for (iterator it = begin (); it != end (); it++) {
p.push_back (Contour ());
Contour& contour = p.back ();
for (PointChain::iterator it2 = it->begin (); it2 != it->end (); it2++)
contour.add (*it2);
}
}
geometry-4.0.0/src/connector.h 0000644 0000000 0000000 00000003327 13615712371 014501 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#ifndef CONNECTOR_H
#define CONNECTOR_H
#include "segment.h"
#include "martinez.h"
#include
class PointChain {
public:
typedef list::iterator iterator;
PointChain () : l (), _closed (false) {}
void init (const Segment& s);
bool LinkSegment (const Segment& s);
bool LinkPointChain (PointChain& chain);
bool closed () const { return _closed; }
iterator begin () { return l.begin (); }
iterator end () { return l.end (); }
void clear () { l.clear (); }
unsigned int size () const { return l.size (); }
private:
/** Linked point chain */
list l;
bool _closed; // is the chain closed, that is, is the first point is linked with the last one?
};
class Connector {
public:
typedef list::iterator iterator;
Connector () : openPolygons (), closedPolygons () {}
~Connector () {}
void add (const Segment& s);
iterator begin () { return closedPolygons.begin (); }
iterator end () { return closedPolygons.end (); }
void clear () { closedPolygons.clear (); openPolygons.clear (); }
unsigned int size () const { return closedPolygons.size (); }
void toPolygon (Polygon& p);
private:
list openPolygons;
list closedPolygons;
};
#endif
geometry-4.0.0/src/martinez.cpp 0000644 0000000 0000000 00000032266 13615712371 014677 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#include "martinez.h"
#include "connector.h"
#include
#include
#include
#include
// #define _DEBUG_ // uncomment this line if you want to debug the computation of the boolean operation
// This function is intended for debugging purposes
void Martinez::print (SweepEvent& e)
{
const char* namesEventTypes[] = { " (NORMAL) ", " (NON_CONTRIBUTING) ", " (SAME_TRANSITION) ", " (DIFFERENT_TRANSITION) " };
cout << " Point: " << e.p << " Other point: " << e.other->p << (e.left ? " (Left) " : " (Right) ")
<< (e.inside ? " (Inside) " : " (Outside) ") << (e.inOut ? " (In-Out) " : " (Out-In) ") << "Type: "
<< namesEventTypes[e.type] << " Polygon: " << (e.pl == SUBJECT ? " (SUBJECT)" : " (CLIPPING)") << endl;
}
// Compare two sweep events
// Return true means that e1 is placed at the event queue after e2, i.e,, e1 is processed by the algorithm after e2
bool Martinez::SweepEventComp::operator() (SweepEvent* e1, SweepEvent* e2) {
if (e1->p.x > e2->p.x) // Different x-coordinate
return true;
if (e2->p.x > e1->p.x) // Different x-coordinate
return false;
if (e1->p != e2->p) // Different points, but same x-coordinate. The event with lower y-coordinate is processed first
return e1->p.y > e2->p.y;
if (e1->left != e2->left) // Same point, but one is a left endpoint and the other a right endpoint. The right endpoint is processed first
return e1->left;
// Same point, both events are left endpoints or both are right endpoints. The event associate to the bottom segment is processed first
return e1->above (e2->other->p);
}
// e1 and a2 are the left events of line segments (e1->p, e1->other->p) and (e2->p, e2->other->p)
bool Martinez::SegmentComp::operator() (SweepEvent* e1, SweepEvent* e2) {
if (e1 == e2)
return false;
if (signedArea (e1->p, e1->other->p, e2->p) != 0 || signedArea (e1->p, e1->other->p, e2->other->p) != 0) {
// Segments are not collinear
// If they share their left endpoint use the right endpoint to sort
if (e1->p == e2->p)
return e1->below (e2->other->p);
// Different points
SweepEventComp comp;
if (comp (e1, e2)) // has the line segment associated to e1 been inserted into S after the line segment associated to e2 ?
return e2->above (e1->p);
// The line segment associated to e2 has been inserted into S after the line segment associated to e1
return e1->below (e2->p);
}
// Segments are collinear. Just a consistent criterion is used
if (e1->p == e2->p)
return e1 < e2;
SweepEventComp comp;
return comp (e1, e2);
}
void Martinez::compute (BoolOpType op, Polygon& result)
{
// Test 1 for trivial result case
if (subject.ncontours () * clipping.ncontours () == 0) { // At least one of the polygons is empty
if (op == DIFFERENCE)
result = subject;
if (op == UNION || op == XOR)
result = (subject.ncontours () == 0) ? clipping : subject;
return;
}
// Test 2 for trivial result case
Point minsubj, maxsubj, minclip, maxclip;
subject.boundingbox (minsubj, maxsubj);
clipping.boundingbox (minclip, maxclip);
if (minsubj.x > maxclip.x || minclip.x > maxsubj.x || minsubj.y > maxclip.y || minclip.y > maxsubj.y) {
// the bounding boxes do not overlap
if (op == DIFFERENCE)
result = subject;
if (op == UNION || op == XOR) {
result = subject;
for (unsigned int i = 0; i < clipping.ncontours (); i++) {
result.push_back (Contour ());
result.back () = clipping.contour (i);
}
}
return;
}
// Boolean operation is not trivial
// Insert all the endpoints associated to the line segments into the event queue
for (unsigned int i = 0; i < subject.ncontours (); i++)
for (unsigned int j = 0; j < subject.contour (i).nvertices (); j++)
processSegment(subject.contour (i).segment (j), SUBJECT);
for (unsigned int i = 0; i < clipping.ncontours (); i++)
for (unsigned int j = 0; j < clipping.contour (i).nvertices (); j++)
processSegment(clipping.contour (i).segment (j), CLIPPING);
Connector connector; // to connect the edge solutions
set S; // Status line
set::iterator it, sli, prev, next;
SweepEvent* e;
const double MINMAXX = std::min (maxsubj.x, maxclip.x); // for optimization 1
while (!eq.empty()) {
e = eq.top ();
eq.pop ();
#ifdef _DEBUG_
cout << "Process event: "; print (*e);
#endif
// optimization 1
if ((op == INTERSECTION && (e->p.x > MINMAXX)) || (op == DIFFERENCE && e->p.x > maxsubj.x)) {
connector.toPolygon (result);
return;
}
if ((op == UNION && (e->p.x > MINMAXX))) {
// add all the non-processed line segments to the result
if (!e->left)
connector.add (e->segment ());
while (!eq.empty()) {
e = eq.top();
eq.pop();
if (!e->left)
connector.add (e->segment ());
}
connector.toPolygon (result);
return;
}
// end of optimization 1
if (e->left) { // the line segment must be inserted into S
e->poss = it = S.insert(e).first;
next = prev = it;
(prev != S.begin()) ? --prev : prev = S.end();
// Compute the inside and inOut flags
if (prev == S.end ()) { // there is not a previous line segment in S?
e->inside = e->inOut = false;
} else if ((*prev)->type != NORMAL) {
if (prev == S.begin ()) { // e overlaps with prev
e->inside = true; // it is not relevant to set true or false
e->inOut = false;
} else { // the previous two line segments in S are overlapping line segments
sli = prev;
sli--;
if ((*prev)->pl == e->pl) {
e->inOut = !(*prev)->inOut;
e->inside = !(*sli)->inOut;
} else {
e->inOut = !(*sli)->inOut;
e->inside = !(*prev)->inOut;
}
}
} else if (e->pl == (*prev)->pl) { // previous line segment in S belongs to the same polygon that "e" belongs to
e->inside = (*prev)->inside;
e->inOut = ! (*prev)->inOut;
} else { // previous line segment in S belongs to a different polygon that "e" belongs to
e->inside = ! (*prev)->inOut;
e->inOut = (*prev)->inside;
}
#ifdef _DEBUG_
cout << "Status line after insertion: " << endl;
for (set::const_iterator it2 = S.begin(); it2 != S.end(); it2++)
print (**it2);
#endif
// Process a possible intersection between "e" and its next neighbor in S
if ((++next) != S.end())
possibleIntersection(e, *next);
// Process a possible intersection between "e" and its previous neighbor in S
if (prev != S.end ())
possibleIntersection(*prev, e);
} else { // the line segment must be removed from S
next = prev = sli = e->other->poss; // S.find (e->other);
// Get the next and previous line segments to "e" in S
++next;
(prev != S.begin()) ? --prev : prev = S.end();
// Check if the line segment belongs to the Boolean operation
switch (e->type) {
case (NORMAL):
switch (op) {
case (INTERSECTION):
if (e->other->inside)
connector.add (e->segment ());
break;
case (UNION):
if (!e->other->inside)
connector.add (e->segment ());
break;
case (DIFFERENCE):
if (((e->pl == SUBJECT) && (!e->other->inside)) || (e->pl == CLIPPING && e->other->inside))
connector.add (e->segment ());
break;
case (XOR):
connector.add (e->segment ());
break;
}
break;
case (SAME_TRANSITION):
if (op == INTERSECTION || op == UNION)
connector.add (e->segment ());
break;
case (DIFFERENT_TRANSITION):
if (op == DIFFERENCE)
connector.add (e->segment ());
break;
}
// delete line segment associated to e from S and check for intersection between the neighbors of "e" in S
S.erase (sli);
if (next != S.end() && prev != S.end())
possibleIntersection (*prev, *next);
}
#ifdef _DEBUG_
cout << "Status line after processing intersections: " << endl;
for (set::const_iterator it2 = S.begin(); it2 != S.end(); it2++)
print (**it2);
cout << endl;
#endif
}
connector.toPolygon (result);
}
void Martinez::processSegment (const Segment& s, PolygonType pl)
{
if (s.begin () == s.end ()) // if the two edge endpoints are equal the segment is dicarded
return; // in the future this can be done as preprocessing to avoid "polygons" with less than 3 edges
SweepEvent* e1 = storeSweepEvent (SweepEvent(s.begin(), true, pl, 0));
SweepEvent* e2 = storeSweepEvent (SweepEvent(s.end(), true, pl, e1));
e1->other = e2;
if (e1->p.x < e2->p.x) {
e2->left = false;
} else if (e1->p.x > e2->p.x) {
e1->left = false;
} else if (e1->p.y < e2->p.y) { // the line segment is vertical. The bottom endpoint is the left endpoint
e2->left = false;
} else {
e1->left = false;
}
eq.push (e1);
eq.push (e2);
}
void Martinez::possibleIntersection (SweepEvent* e1, SweepEvent* e2)
{
// if ((e1->pl == e2->pl) ) // you can uncomment these two lines if self-intersecting polygons are not allowed
// return false;
Point ip1, ip2; // intersection points
int nintersections;
if (!(nintersections = findIntersection(e1->segment (), e2->segment (), ip1, ip2)))
return;
if ((nintersections == 1) && ((e1->p == e2->p) || (e1->other->p == e2->other->p)))
return; // the line segments intersect at an endpoint of both line segments
if (nintersections == 2 && e1->pl == e2->pl) { // the line segments overlap, but they belong to the same polygon
std::cerr << "A polygon has overlapping edges. Sorry, but the program does not work yet with this kind of polygon\n";
exit (1);
}
// The line segments associated to e1 and e2 intersect
nint += nintersections;
if (nintersections == 1) {
if (e1->p != ip1 && e1->other->p != ip1) // if ip1 is not an endpoint of the line segment associated to e1 then divide "e1"
divideSegment (e1, ip1);
if (e2->p != ip1 && e2->other->p != ip1) // if ip1 is not an endpoint of the line segment associated to e2 then divide "e2"
divideSegment (e2, ip1);
return;
}
// The line segments overlap
vector sortedEvents;
if (e1->p == e2->p) {
sortedEvents.push_back (0);
} else if (sec (e1, e2)) {
sortedEvents.push_back (e2);
sortedEvents.push_back (e1);
} else {
sortedEvents.push_back (e1);
sortedEvents.push_back (e2);
}
if (e1->other->p == e2->other->p) {
sortedEvents.push_back (0);
} else if (sec (e1->other, e2->other)) {
sortedEvents.push_back (e2->other);
sortedEvents.push_back (e1->other);
} else {
sortedEvents.push_back (e1->other);
sortedEvents.push_back (e2->other);
}
if (sortedEvents.size () == 2) { // are both line segments equal?
e1->type = e1->other->type = NON_CONTRIBUTING;
e2->type = e2->other->type = (e1->inOut == e2->inOut) ? SAME_TRANSITION : DIFFERENT_TRANSITION;
return;
}
if (sortedEvents.size () == 3) { // the line segments share an endpoint
sortedEvents[1]->type = sortedEvents[1]->other->type = NON_CONTRIBUTING;
if (sortedEvents[0]) // is the right endpoint the shared point?
sortedEvents[0]->other->type = (e1->inOut == e2->inOut) ? SAME_TRANSITION : DIFFERENT_TRANSITION;
else // the shared point is the left endpoint
sortedEvents[2]->other->type = (e1->inOut == e2->inOut) ? SAME_TRANSITION : DIFFERENT_TRANSITION;
divideSegment (sortedEvents[0] ? sortedEvents[0] : sortedEvents[2]->other, sortedEvents[1]->p);
return;
}
if (sortedEvents[0] != sortedEvents[3]->other) { // no line segment includes totally the other one
sortedEvents[1]->type = NON_CONTRIBUTING;
sortedEvents[2]->type = (e1->inOut == e2->inOut) ? SAME_TRANSITION : DIFFERENT_TRANSITION;
divideSegment (sortedEvents[0], sortedEvents[1]->p);
divideSegment (sortedEvents[1], sortedEvents[2]->p);
return;
}
// one line segment includes the other one
sortedEvents[1]->type = sortedEvents[1]->other->type = NON_CONTRIBUTING;
divideSegment (sortedEvents[0], sortedEvents[1]->p);
sortedEvents[3]->other->type = (e1->inOut == e2->inOut) ? SAME_TRANSITION : DIFFERENT_TRANSITION;
divideSegment (sortedEvents[3]->other, sortedEvents[2]->p);
}
void Martinez::divideSegment (SweepEvent* e, const Point& p)
{
// "Right event" of the "left line segment" resulting from dividing e (the line segment associated to e)
SweepEvent *r = storeSweepEvent(SweepEvent(p, false, e->pl, e, e->type));
// "Left event" of the "right line segment" resulting from dividing e (the line segment associated to e)
SweepEvent *l = storeSweepEvent(SweepEvent(p, true, e->pl, e->other, e->other->type));
if (sec (l, e->other)) { // avoid a rounding error. The left event would be processed after the right event
cout << "Oops" << endl;
e->other->left = true;
l->left = false;
}
if (sec (e, r)) { // avoid a rounding error. The left event would be processed after the right event
cout << "Oops2" << endl;
// cout << *e << endl;
}
e->other->other = l;
e->other = r;
eq.push(l);
eq.push(r);
}
geometry-4.0.0/src/martinez.h 0000644 0000000 0000000 00000010140 13615712371 014327 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#ifndef MARTINEZ_H
#define MARTINEZ_H
#include "polygon.h"
#include "point.h"
#include "segment.h"
#include "utilities.h"
#include
#include
#include
#include
using namespace std;
class Connector;
class Martinez {
public:
enum BoolOpType { INTERSECTION, UNION, DIFFERENCE, XOR };
/** Class constructor */
Martinez (Polygon& sp, Polygon& cp) : eq (), eventHolder (), subject (sp), clipping (cp), sec (), nint (0) {}
/** Compute the boolean operation */
void compute (BoolOpType op, Polygon& result);
/** Number of intersections found (for statistics) */
int nInt () const { return nint; }
private:
enum EdgeType { NORMAL, NON_CONTRIBUTING, SAME_TRANSITION, DIFFERENT_TRANSITION };
enum PolygonType { SUBJECT, CLIPPING };
struct SweepEvent;
struct SegmentComp : public binary_function { // for sorting edges in the sweep line
bool operator() (SweepEvent* e1, SweepEvent* e2);
};
struct SweepEvent {
Point p; // point associated with the event
bool left; // is the point the left endpoint of the segment (p, other->p)?
PolygonType pl; // Polygon to which the associated segment belongs to
SweepEvent *other; // Event associated to the other endpoint of the segment
/** Does the segment (p, other->p) represent an inside-outside transition in the polygon for a vertical ray from (p.x, -infinite) that crosses the segment? */
bool inOut;
EdgeType type;
bool inside; // Only used in "left" events. Is the segment (p, other->p) inside the other polygon?
set::iterator poss; // Only used in "left" events. Position of the event (line segment) in S
/** Class constructor */
SweepEvent (const Point& pp, bool b, PolygonType apl, SweepEvent* o, EdgeType t = NORMAL) : p (pp), left (b), pl (apl), other (o), type (t) {}
/** Return the line segment associated to the SweepEvent */
Segment segment () { return Segment (p, other->p); }
/** Is the line segment (p, other->p) below point x */
bool below (const Point& x) const { return (left) ? signedArea (p, other->p, x) > 0 : signedArea (other->p, p, x) > 0; }
/** Is the line segment (p, other->p) above point x */
bool above (const Point& x) const { return !below (x); }
};
static void print (SweepEvent& e); // This function is intended for debugging purposes
struct SweepEventComp : public binary_function { // for sortening events
bool operator() (SweepEvent* e1, SweepEvent* e2);
};
/** @brief Event Queue */
priority_queue, SweepEventComp> eq;
/** @brief It holds the events generated during the computation of the boolean operation */
deque eventHolder;
/** @brief Polygon 1 */
Polygon& subject;
/** @brief Polygon 2 */
Polygon& clipping;
/** To compare events */
SweepEventComp sec;
/** @brief Number of intersections (for statistics) */
int nint;
/** @brief Compute the events associated to segment s, and insert them into pq and eq */
void processSegment (const Segment& s, PolygonType pl);
/** @brief Process a posible intersection between the segment associated to the left events e1 and e2 */
void possibleIntersection (SweepEvent *e1, SweepEvent *e2);
/** @brief Divide the segment associated to left event e, updating pq and (implicitly) the status line */
void divideSegment (SweepEvent *e, const Point& p);
/** @brief Store the SweepEvent e into the event holder, returning the address of e */
SweepEvent *storeSweepEvent(const SweepEvent& e) { eventHolder.push_back (e); return &eventHolder.back (); }
};
#endif
geometry-4.0.0/src/mexclipper.cpp 0000644 0000000 0000000 00000027041 13615712371 015211 0 ustar 00 0000000 0000000 /*
(C) 2012-2017 Angus Johnson
Boost Software License - Version 1.0 - August 17th, 2003
http://www.boost.org/LICENSE_1_0.txt
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// mex clipper.cpp mexclipper.cpp
//
// Modified 2014-10-24, Jari Repo (JR), University West, jari.repo@hv.se
// replaced "Polygons" to "Paths"
// replaced "AddPolygons" by "AddPaths"
// replaced the call to "OffsetPolygons" by use of the "ClipperOffset" class
// Adapted 2017-01-24 Philip Nienhuis
// allow clipping polylines
#include "mex.h"
#include "clipper.hpp"
using namespace ClipperLib;
//void read_polygons_MATLAB(const mxArray *prhs, Polygons &poly)
void read_polygons_MATLAB(const mxArray *prhs, Paths &poly)
{
int id_x, id_y;
unsigned int num_contours;
unsigned int nx, ny;
long64 *x, *y;
const mxArray *x_in, *y_in;
/* Checking if input is non empty Matlab-structure */
if (!mxIsStruct(prhs))
mexErrMsgTxt("Input needs to be structure.");
if (!mxGetM(prhs) || !mxGetN(prhs))
mexErrMsgTxt("Empty structure.");
/* Checking field names and data type */
id_x = mxGetFieldNumber(prhs,"x");
if (id_x==-1)
mexErrMsgTxt("Input structure must contain a field 'x'.");
x_in = mxGetFieldByNumber(prhs, 0, id_x);
if (!mxIsInt64(x_in))
mexErrMsgTxt("Structure field 'x' must be of type INT64.");
id_y = mxGetFieldNumber(prhs,"y");
if (id_y==-1)
mexErrMsgTxt("Input structure must contain a field 'y'.");
y_in = mxGetFieldByNumber(prhs, 0, id_y);
if (!mxIsInt64(y_in))
mexErrMsgTxt("Structure field 'y' must be of type INT64.");
num_contours = mxGetNumberOfElements(prhs);
poly.resize(num_contours);
for (unsigned i = 0; i < num_contours; i++){
x_in = mxGetFieldByNumber(prhs, i, id_x);
y_in = mxGetFieldByNumber(prhs, i, id_y);
nx = mxGetNumberOfElements(x_in);
ny = mxGetNumberOfElements(y_in);
if (nx!=ny)
mexErrMsgTxt("Structure fields x and y must be the same length.");
poly[i].resize(nx);
x = (long64*)mxGetData(x_in);
y = (long64*)mxGetData(y_in);
for (unsigned j = 0; j < nx; j++){
poly[i][j].X = x[j];
poly[i][j].Y = y[j];
}
}
}
//void write_polygons_MATLAB(mxArray *plhs, Polygons &solution)
void write_polygons_MATLAB(mxArray *plhs, Paths &solution)
{
mxArray *x_out, *y_out;
for (unsigned i = 0; i < solution.size(); ++i)
{
x_out = mxCreateDoubleMatrix(solution[i].size(), 1, mxREAL);
y_out = mxCreateDoubleMatrix(solution[i].size(), 1, mxREAL);
for (unsigned j = 0; j < solution[i].size(); ++j)
{
((double*)mxGetPr(x_out))[j]=solution[i][j].X;
((double*)mxGetPr(y_out))[j]=solution[i][j].Y;
}
mxSetFieldByNumber(plhs,i,0,x_out);
mxSetFieldByNumber(plhs,i,1,y_out);
}
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
//Polygons subj, clip, solution;
Paths subj, clip, solution;
PolyTree solutionL;
const char *field_names[] = {"x","y"};
mwSize dims[2];
if (nrhs == 0) {
mexPrintf("OutPol = clipper(RefPol, ClipPol, Method, [RefF], [ClipF]);\n");
mexPrintf(" Clips polygons or polylines by Method:\n");
mexPrintf(" 0 - Difference (RefPol - ClipPol)\n");
mexPrintf(" 1 - Intersection\n");
mexPrintf(" 2 - Xor (polygons only)\n");
mexPrintf(" 3 - Union (polygons only)\n");
mexPrintf(" Optionally specifying Fill Types for the polygons (polygons only):\n");
mexPrintf(" 0 - Even-Odd (default)\n");
mexPrintf(" 1 - Non-Zero\n");
mexPrintf(" 2 - Positive\n");
mexPrintf(" 3 - Negative\n\n");
mexPrintf("Or:\n\n");
mexPrintf("OutPol = clipper(RefPol, Delta, MiterLimit);\n");
mexPrintf(" Offsets RefPol by Delta (+: outset, -: inset).\n");
mexPrintf(" MiterLimit * Delta = max distance of new vertex.\n");
mexPrintf(" MiterLimit = 1 for square corners.\n");
mexPrintf(" MiterLimit = 0 for round corners.\n\n");
mexPrintf("Or:\n\n");
mexPrintf("Orientation = clipper(RefPol);\n");
mexPrintf(" Returns boolean orientations of polygons.\n\n");
mexPrintf("All polygons are structures with the fields ...\n");
mexPrintf(" .x: x-coordinates of contour\n");
mexPrintf(" .y: y-coordinates of contour\n");
mexPrintf("All polygons may contain several contours.\n");
mexPrintf("\nPolygon Clipping Routine based on clipper v4.7.5.\n");
mexPrintf(" Credit goes to Angus Johnson\n");
mexPrintf(" http://www.angusj.com/delphi/clipper.php\n\n");
return;}
/* Check number of arguments */
if (nlhs != 1)
mexErrMsgTxt("One output required.");
if (nrhs == 1)
{
// Find the orientation of input polygons
bool orient;
read_polygons_MATLAB(prhs[0], subj);
plhs[0] = mxCreateDoubleMatrix(subj.size(), 1, mxREAL);
for (unsigned i = 0; i < subj.size(); ++i)
{
orient = Orientation(subj[i]);
((double*)mxGetPr(plhs[0]))[i] = (double)orient;
}
}
else if (nrhs >= 3)
{
if (!mxIsDouble(prhs[2]) || mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=1)
mexErrMsgTxt("Third input must be scalar.");
if (mxIsStruct(prhs[1]))
{
// Clip two input polygons
int ct, clpl;
clpl = 0;
ct = mxGetScalar(prhs[2]);
ClipType CT = ctDifference;
switch (ct){
case 0:
CT=ctDifference;
break;
case 1:
CT=ctIntersection;
break;
case 2:
CT=ctXor;
break;
case 3:
CT=ctUnion;
break;
default:
mexErrMsgTxt("Third input must be 0, 1, 2, or 3.");
}
PolyFillType SFT = pftEvenOdd;
if (nrhs >= 4)
{
if (!mxIsDouble(prhs[3]) || mxGetM(prhs[3])!=1 || mxGetN(prhs[3])!=1)
mexErrMsgTxt("Fourth input must be scalar if specified.");
int sft;
sft = mxGetScalar(prhs[3]);
switch (sft){
case 0:
SFT = pftEvenOdd;
break;
case 1:
SFT = pftNonZero;
break;
case 2:
SFT = pftPositive;
break;
case 3:
SFT = pftNegative;
break;
case -1:
clpl = 1;
SFT=pftEvenOdd;
break;
default:
mexErrMsgTxt("Fourth input must be 0, 1, 2, 3, or -1.");
}
}
PolyFillType CFT = pftEvenOdd;
if (nrhs >= 5)
{
if (!mxIsDouble(prhs[4]) || mxGetM(prhs[4])!=1 || mxGetN(prhs[4])!=1)
mexErrMsgTxt("Fifth input must be scalar if specified.");
int cft;
cft=mxGetScalar(prhs[4]);
switch (cft){
case 0:
CFT = pftEvenOdd;
break;
case 1:
CFT = pftNonZero;
break;
case 2:
CFT = pftPositive;
break;
case 3:
CFT = pftNegative;
break;
default:
mexErrMsgTxt("Fifth input must be 0, 1, 2, or 3.");
}
}
/* Import polygons to structures */
read_polygons_MATLAB(prhs[0], subj);
read_polygons_MATLAB(prhs[1], clip);
Clipper c;
if (clpl) {
c.AddPaths(subj, ptSubject, false); //assume polylines
c.AddPaths(clip, ptClip, true);
if (c.Execute(CT, solutionL, SFT, CFT)){
dims[0] = 1;
OpenPathsFromPolyTree(solutionL, solution);
dims[1] = solution.size();
plhs[0] = mxCreateStructArray(2, dims, 2, field_names);
write_polygons_MATLAB(plhs[0], solution);
} else
mexErrMsgTxt("Clipper Error.");
}
else {
c.AddPaths(subj, ptSubject, true); //assume closed polygons
c.AddPaths(clip, ptClip, true);
if (c.Execute(CT, solution, SFT, CFT)){
dims[0] = 1;
dims[1] = solution.size();
plhs[0] = mxCreateStructArray(2, dims, 2, field_names);
write_polygons_MATLAB(plhs[0], solution);
} else
mexErrMsgTxt("Clipper Error.");
}
}
else
{
// Offset single input polygon
if (!mxIsDouble(prhs[1]) || mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=1)
mexErrMsgTxt("Second input must be either a structure or a scalar double.");
if (nrhs > 3)
mexPrintf("Ignoring fill type arguments for offsetting.\n");
/* Import polygons to structures */
read_polygons_MATLAB(prhs[0], subj);
JoinType jt;
double delta, ml;
delta = mxGetScalar(prhs[1]);
ml = mxGetScalar(prhs[2]);
if (ml==0)
jt = jtRound;
else if (ml==1)
jt = jtSquare;
else
jt = jtMiter;
ClipperOffset offs( ml );
//enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
offs.AddPaths(subj,jt,etClosedPolygon);
offs.Execute(solution, delta);
dims[0] = 1;
dims[1] = solution.size();
plhs[0] = mxCreateStructArray(2, dims, 2, field_names);
write_polygons_MATLAB(plhs[0], solution);
offs.Clear();
}
}
else
mexErrMsgTxt("One or three inputs required.");
}
geometry-4.0.0/src/point.h 0000644 0000000 0000000 00000002656 13615712371 013644 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
// ------------------------------------------------------------------
// Clase Point - Punto en el plano
// ------------------------------------------------------------------
#ifndef POINT_H
#define POINT_H
#include
#include
#include
using namespace std;
class Point {
public:
/** coordinates */
double x, y;
Point (): x(0), y (0) {}
Point (double ax, double ay): x (ax), y (ay) {}
/** Distance to other point */
float dist(const Point& p) const
{
float dx = x - p.x;
float dy = y - p.y;
return sqrt (dx * dx + dy * dy);
}
bool operator== (const Point& p) const { return (x == p.x) && (y == p.y); }
bool operator!= (const Point& p) const { return !(*this == p); }
};
inline ostream& operator<< (ostream& o, const Point& p) { return o << "(" << p.x << "," << p.y << ")"; }
inline istream& operator>> (istream& i, Point& p) { return i >> p.x >> p.y; }
#endif
geometry-4.0.0/src/polybool_mrf.cc 0000644 0000000 0000000 00000012514 13615712371 015346 0 ustar 00 0000000 0000000 /*
Copyright (C) 2017 - Piyush Jain
Copyright (C) 2017 - Juan Pablo Carbajal
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
#include "polygon.h"
#include "utilities.h"
#include "martinez.h"
#include "connector.h"
#include
#include
DEFUN_DLD(polybool_mrf, args, ,
"\
-*- texinfo -*-\n\
@deftypefn {Loadable Function} {} polybool_mrf (@var{subj} ,@var{clip}, @var{operation}\n\
Perform Boolean Operations on polygons\n\n\
@var{subj}-@var{clip} are NaN Delimited Column/Row Vectors\n\n\
@var{Operation} is a string representing the operation to perform. \n\
Valid Operations are: 0 (DIFFERENCE), 1 (INTERSECTION), 2 (XOR) , 3 (UNION).\n\
It is an optional argument. If not provided, INTERSECTION is the default operation.\n\n\
@end deftypefn")
{
int nargin = args.length();
if(nargin < 2 || nargin > 3)
print_usage();
else
{
Polygon subj, clip;
octave_map subpoly = args(0).map_value ();
octave_map clippoly = args(1).map_value ();
// Subject polygon
octave_idx_type ncontours = subpoly.numel();
double px, py;
octave_map::const_iterator px_iter = subpoly.seek ("x");
octave_map::const_iterator py_iter = subpoly.seek ("y");
for (octave_idx_type i = 0; i < ncontours; i++) {
Array X = subpoly.contents(px_iter)(i).array_value();
Array Y = subpoly.contents(py_iter)(i).array_value();
octave_idx_type npoints = X.numel();
subj.push_back (Contour ());
Contour& contour = subj.back ();
for (octave_idx_type j = 0; j < npoints; j++) {
px = X(j);
py = Y(j);
if (j > 0 && px == contour.back ().x && py == contour.back ().y)
continue;
if (j == npoints-1 && px == contour.vertex (0).x && py == contour.vertex (0).y)
continue;
contour.add (Point (px, py));
}
if (contour.nvertices () < 3) {
subj.pop_back ();
continue;
}
}
// Clipping polygon
ncontours = clippoly.numel();
px_iter = clippoly.seek ("x");
py_iter = clippoly.seek ("y");
for (octave_idx_type i = 0; i < ncontours; i++) {
Array X = clippoly.contents(px_iter)(i).array_value();
Array Y = clippoly.contents(py_iter)(i).array_value();
octave_idx_type npoints = X.numel();
clip.push_back (Contour ());
Contour& contour = clip.back ();
for (octave_idx_type j = 0; j < npoints; j++) {
px = X(j);
py = Y(j);
if (j > 0 && px == contour.back ().x && py == contour.back ().y)
continue;
if (j == npoints-1 && px == contour.vertex (0).x && py == contour.vertex (0).y)
continue;
contour.add (Point (px, py));
}
if (contour.nvertices () < 3) {
clip.pop_back ();
continue;
}
}
// Selecting operation
Martinez::BoolOpType op = Martinez::INTERSECTION;
if (nargin > 2) {
int opcode = args(2).scalar_value();
switch (opcode) {
case 0:
op = Martinez::DIFFERENCE;
break;
case 1:
op = Martinez::INTERSECTION;
break;
case 2:
op = Martinez::XOR;
break;
case 3:
op = Martinez::UNION;
break;
}
}
// Perform boolean operation
Polygon martinezResult;
martinezResult.clear ();
Martinez mr (subj, clip);
mr.compute (op, martinezResult);
// Passing the result into matrix
octave_value_list result;
octave_idx_type size = martinezResult.nvertices() + martinezResult.ncontours();
if(size > 0)
{
--size;
Matrix tempx(dim_vector(size,1));
Matrix tempy(dim_vector(size,1));
octave_idx_type k = 0;
for (octave_idx_type i = 0; i < martinezResult.ncontours (); i++)
{
Contour::iterator c = martinezResult.contour (i).begin();
while (c != martinezResult.contour (i).end()) {
tempx(k,0) = c->x;
tempy(k,0) = c->y;
k++;
++c;
}
if(i != martinezResult.ncontours()-1){
tempx(k,0) = std::numeric_limits::quiet_NaN();
tempy(k,0) = std::numeric_limits::quiet_NaN();
k++;
}
}
result(0) = tempx;
result(1) = tempy;
result(2) = martinezResult.ncontours();
}
else
{
result(0) = std::numeric_limits::quiet_NaN();
result(1) = std::numeric_limits::quiet_NaN();
result(2) = 0;
}
return result;
}
return octave_value_list();
}
geometry-4.0.0/src/polygon.cpp 0000644 0000000 0000000 00000017577 13615712371 014545 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#include "polygon.h"
#include "utilities.h"
#include
#include
#include
#include
void Contour::boundingbox (Point& min, Point& max)
{
min.x = min.y = numeric_limits::max ();
max.x = max.y = -numeric_limits::max ();
Contour::iterator i = begin();
while (i != end()) {
if (i->x < min.x)
min.x = i->x;
if (i->x > max.x)
max.x = i->x;
if (i->y < min.y)
min.y = i->y;
if (i->y > max.y)
max.y = i->y;
++i;
}
}
bool Contour::counterclockwise ()
{
if (_precomputedCC)
return _CC;
_precomputedCC = true;
double area = 0.0;
for (unsigned int c = 0; c < nvertices () - 1; c++)
area += vertex (c).x * vertex (c+1).y - vertex (c+1).x * vertex (c).y;
area += vertex (nvertices ()-1).x * vertex (0).y - vertex (0).x * vertex (nvertices ()-1).y;
return _CC = area >= 0.0;
}
void Contour::move (double x, double y)
{
for (unsigned int i = 0; i < points.size (); i++) {
points[i].x += x;
points[i].y += y;
}
}
unsigned Polygon::nvertices () const
{
unsigned int nv = 0;
for (unsigned int i = 0; i < ncontours (); i++)
nv += contours[i].nvertices ();
return nv;
}
void Polygon::boundingbox (Point& min, Point& max)
{
min.x = min.y = numeric_limits::max ();
max.x = max.y = -numeric_limits::max ();
Point mintmp;
Point maxtmp;
for (unsigned int i = 0; i < ncontours (); i++) {
contours[i].boundingbox (mintmp, maxtmp);
if (mintmp.x < min.x)
min.x = mintmp.x;
if (maxtmp.x > max.x)
max.x = maxtmp.x;
if (mintmp.y < min.y)
min.y = mintmp.y;
if (maxtmp.y > max.y)
max.y = maxtmp.y;
}
}
void Polygon::move (double x, double y)
{
for (unsigned int i = 0; i < contours.size (); i++)
contours[i].move (x, y);
}
/*
* The following code is necessary for implementing the computeHoles member function
*
*/
namespace { // start of anonymous namespace
struct SweepEvent;
struct SegmentComp : public binary_function {
bool operator() (SweepEvent* e1, SweepEvent* e2);
};
struct SweepEvent {
Point p; // point associated with the event
bool left; // is the point the left endpoint of the segment (p, other->p)?
int pl; // Polygon to which the associated segment belongs to
SweepEvent* other; // Event associated to the other endpoint of the segment
/** Does the segment (p, other->p) represent an inside-outside transition in the polygon for a vertical ray from (p.x, -infinite) that crosses the segment? */
bool inOut;
set::iterator poss; // Only used in "left" events. Position of the event (segment) in S
/** Class constructor */
SweepEvent (const Point& pp, bool b, int apl) : p (pp), left (b), pl (apl) {}
/** Return the segment associated to the SweepEvent */
Segment segment () { return Segment (p, other->p); }
/** Is the segment (p, other->p) below point x */
bool below (const Point& x) const { return (left) ? signedArea (p, other->p, x) > 0 : signedArea (other->p, p, x) > 0; }
/** Is the segment (p, other->p) above point x */
bool above (const Point& x) const { return !below (x); }
};
struct SweepEventComp : public binary_function {
bool operator() (SweepEvent* e1, SweepEvent* e2) {
if (e1->p.x < e2->p.x) // Different x coordinate
return true;
if (e2->p.x < e1->p.x) // Different x coordinate
return false;
if (e1->p != e2->p) // Different points, but same x coordinate. The event with lower y coordinate is processed first
return e1->p.y < e2->p.y;
if (e1->left != e2->left) // Same point, but one is a left endpoint and the other a right endpoint. The right endpoint is processed first
return !e1->left;
// Same point, both events are left endpoints or both are right endpoints. The event associate to the bottom segment is processed first
return e1->below (e2->other->p);
}
};
} // end of anonymous namespace
bool SegmentComp::operator() (SweepEvent* e1, SweepEvent* e2) {
if (e1 == e2)
return false;
if (signedArea (e1->p, e1->other->p, e2->p) != 0 || signedArea (e1->p, e1->other->p, e2->other->p) != 0) {
// Segments are not collinear
// If they share their left endpoint use the right endpoint to sort
if (e1->p == e2->p)
return e1->below (e2->other->p);
// Different points
SweepEventComp comp;
if (comp (e1, e2)) // has the segment associated to e1 been sorted in evp before the segment associated to e2?
return e1->below (e2->p);
// The segment associated to e2 has been sorted in evp before the segment associated to e1
return e2->above (e1->p);
}
// Segments are collinear. Just a consistent criterion is used
if (e1->p == e2->p)
return e1 < e2;
SweepEventComp comp;
return comp (e1, e2);
}
//#define _DEBUG_
void Polygon::computeHoles ()
{
if (ncontours () < 2) {
if (ncontours () == 1 && contour (0).clockwise ())
contour (0).changeOrientation ();
return;
}
vector ev;
vector evp;
ev.reserve (nvertices ()*2);
evp.reserve (nvertices ()*2);
for (unsigned i = 0; i < ncontours (); i++) {
// cout << contour (i);
contour (i).setCounterClockwise ();
// cout << contour (i);
for (unsigned j = 0; j < contour (i).nedges (); j++) {
Segment s = contour(i).segment (j);
if (s.begin ().x == s.end ().x) // vertical segments are not processed
continue;
ev.push_back (SweepEvent (s.begin (), true, i));
ev.push_back (SweepEvent (s.end (), true, i));
SweepEvent* se1 = &ev[ev.size ()-2];
SweepEvent* se2 = &ev[ev.size ()-1];
se1->other = se2;
se2->other = se1;
if (se1->p.x < se2->p.x) {
se2->left = false;
se1->inOut = false;
} else {
se1->left = false;
se2->inOut = true;
}
evp.push_back (se1);
evp.push_back (se2);
}
}
sort (evp.begin (), evp.end (), SweepEventComp ());
set S; // Status line
vector processed (ncontours (), false);
vector holeOf (ncontours (), -1);
int nprocessed = 0;
for (unsigned i = 0; i < evp.size () && nprocessed < ncontours (); i++) {
SweepEvent* e = evp[i];
#ifdef _DEBUG_
cout << "Process event: " << *e << endl;
#endif
if (e->left) { // the segment must be inserted into S
e->poss = S.insert(e).first;
if (!processed[e->pl]) {
processed[e->pl] = true;
nprocessed++;
set::iterator prev = e->poss;
if (prev == S.begin()) {
contour (e->pl).setCounterClockwise ();
} else {
prev--;
if (!(*prev)->inOut) {
holeOf[e->pl] = (*prev)->pl;
contour (e->pl).setExternal (false);
contour ((*prev)->pl).addHole (e->pl);
if (contour((*prev)->pl).counterclockwise ())
contour (e->pl).setClockwise ();
else
contour (e->pl).setCounterClockwise ();
} else if (holeOf[(*prev)->pl] != -1) {
holeOf[e->pl] = holeOf[(*prev)->pl];
contour (e->pl).setExternal (false);
contour (holeOf[e->pl]).addHole (e->pl);
if (contour(holeOf[e->pl]).counterclockwise ())
contour (e->pl).setClockwise ();
else
contour (e->pl).setCounterClockwise ();
} else {
contour (e->pl).setCounterClockwise ();
}
}
}
} else { // the segment must be removed from S
S.erase (e->other->poss);
}
#ifdef _DEBUG_
cout << "Tras ajuste: " << endl;
for (set::const_iterator it2 = S.begin(); it2 != S.end(); it2++)
cout << **it2 << endl;
cout << endl;
string st;
getline (cin, st);
#endif
}
}
geometry-4.0.0/src/polygon.h 0000644 0000000 0000000 00000007372 13615712371 014202 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#ifndef POLYGON_H
#define POLYGON_H
#include
#include
#include "segment.h"
using namespace std;
class Contour {
public:
typedef vector::iterator iterator;
Contour () : points (), holes (), _external (true), _precomputedCC (false) {}
/** Get the p-th vertex of the external contour */
Point& vertex (unsigned p) { return points[p]; }
Segment segment (unsigned p) const { return (p == nvertices () - 1) ? Segment (points.back (), points.front ()) : Segment (points[p], points[p+1]); }
/** Number of vertices and edges */
unsigned nvertices () const { return points.size (); }
unsigned nedges () const { return points.size (); }
/** Get the bounding box */
void boundingbox (Point& min, Point& max);
/** Return if the contour is counterclockwise oriented */
bool counterclockwise ();
/** Return if the contour is clockwise oriented */
bool clockwise () { return !counterclockwise (); }
void changeOrientation () { reverse (points.begin (), points.end ()); _CC = !_CC; }
void setClockwise () { if (counterclockwise ()) changeOrientation (); }
void setCounterClockwise () { if (clockwise ()) changeOrientation (); }
void move (double x, double y);
void add (const Point& s) { points.push_back (s); }
void erase (iterator i) { points.erase (i); }
void clear () { points.clear (); holes.clear (); }
iterator begin () { return points.begin (); }
iterator end () { return points.end (); }
Point& back () { return points.back (); }
const Point& back () const { return points.back (); }
void addHole (unsigned ind) { holes.push_back (ind); }
unsigned nholes () const { return holes.size (); }
unsigned hole (unsigned p) const { return holes[p]; }
bool external () const { return _external; }
void setExternal (bool e) { _external = e; }
private:
/** Set of points conforming the external contour */
vector points;
/** Holes of the contour. They are stored as the indexes of the holes in a polygon class */
vector holes;
bool _external; // is the contour an external contour? (i.e., is it not a hole?)
bool _precomputedCC;
bool _CC;
};
ostream& operator<< (ostream& o, Contour& c);
class Polygon {
public:
typedef vector::iterator iterator;
Polygon () : contours () {}
Polygon (const string& filename);
/** Get the p-th contour */
Contour& contour (unsigned p) { return contours[p]; }
Contour& operator[] (unsigned int p) { return contours[p]; }
/** Number of contours */
unsigned ncontours () const { return contours.size (); }
/** Number of vertices */
unsigned nvertices () const;
/** Get the bounding box */
void boundingbox (Point& min, Point& max);
void move (double x, double y);
void push_back (const Contour& c) { contours.push_back (c); }
Contour& back () { return contours.back (); }
const Contour& back () const { return contours.back (); }
void pop_back () { contours.pop_back (); }
void erase (iterator i) { contours.erase (i); }
void clear () { contours.clear (); }
iterator begin () { return contours.begin (); }
iterator end () { return contours.end (); }
void computeHoles ();
private:
/** Set of contours conforming the polygon */
vector contours;
};
ostream& operator<< (ostream& o, Polygon& p);
istream& operator>> (istream& i, Polygon& p);
#endif
geometry-4.0.0/src/segment.h 0000644 0000000 0000000 00000003035 13615712371 014145 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
// ------------------------------------------------------------------
// Clase Segment - Segmentos en el plano
// ------------------------------------------------------------------
#ifndef SEGMENT_H
#define SEGMENT_H
#include "point.h"
class Polygon;
class Segment {
public:
/** Segment endpoints */
Point p1, p2;
public:
/** Default constructor */
Segment () {}
~Segment () {}
/** Constructor from two points **/
Segment(const Point& ap1, const Point& ap2) : p1 (ap1), p2 (ap2) {}
/** Set the beginning point */
void setbegin(const Point& p) { p1 = p; }
/** Set the end point */
void setend(const Point& p) { p2 = p; }
/** Get the beginning point */
const Point& begin() const { return p1; }
/** Get the end point */
const Point& end() const { return p2; }
/** Change the segment orientation */
Segment& changeOrientation () { Point tmp = p1; p1 = p2; p2 = tmp; return *this; }
};
inline ostream& operator<< (ostream& o, const Segment& p) { return o << p.begin () << "-" << p.end (); }
#endif
geometry-4.0.0/src/utilities.cpp 0000644 0000000 0000000 00000006377 13615712371 015065 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include "utilities.h"
#include "segment.h"
static int findIntersection (double u0, double u1, double v0, double v1, double w[2])
{
if ((u1 < v0) || (u0 > v1))
return 0;
if (u1 > v0) {
if (u0 < v1) {
w[0] = (u0 < v0) ? v0 : u0;
w[1] = (u1 > v1) ? v1 : u1;
return 2;
} else {
// u0 == v1
w[0] = u0;
return 1;
}
} else {
// u1 == v0
w[0] = u1;
return 1;
}
}
int findIntersection (const Segment& seg0, const Segment& seg1, Point& pi0, Point& pi1)
{
const Point& p0 = seg0.begin ();
Point d0 (seg0.end ().x - p0.x, seg0.end ().y - p0.y);
const Point& p1 = seg1.begin ();
Point d1 (seg1.end ().x - p1.x, seg1.end ().y - p1.y);
double sqrEpsilon = 0.0000001; // it was 0.001 before
Point E (p1.x - p0.x, p1.y - p0.y);
double kross = d0.x * d1.y - d0.y * d1.x;
double sqrKross = kross * kross;
double sqrLen0 = d0.x * d0.x + d0.y * d0.y;
double sqrLen1 = d1.x * d1.x + d1.y * d1.y;
if (sqrKross > sqrEpsilon * sqrLen0 * sqrLen1) {
// lines of the segments are not parallel
double s = (E.x * d1.y - E.y * d1.x) / kross;
if ((s < 0) || (s > 1)) {
return 0;
}
double t = (E.x * d0.y - E.y * d0.x) / kross;
if ((t < 0) || (t > 1)) {
return 0;
}
// intersection of lines is a point an each segment
pi0.x = p0.x + s * d0.x;
pi0.y = p0.y + s * d0.y;
if (pi0.dist (seg0.begin ()) < 0.00000001) pi0 = seg0.begin ();
if (pi0.dist (seg0.end ()) < 0.00000001) pi0 = seg0.end ();
if (pi0.dist (seg1.begin ()) < 0.00000001) pi0 = seg1.begin ();
if (pi0.dist (seg1.end ()) < 0.00000001) pi0 = seg1.end ();
return 1;
}
// lines of the segments are parallel
double sqrLenE = E.x * E.x + E.y * E.y;
kross = E.x * d0.y - E.y * d0.x;
sqrKross = kross * kross;
if (sqrKross > sqrEpsilon * sqrLen0 * sqrLenE) {
// lines of the segment are different
return 0;
}
// Lines of the segments are the same. Need to test for overlap of segments.
double s0 = (d0.x * E.x + d0.y * E.y) / sqrLen0; // so = Dot (D0, E) * sqrLen0
double s1 = s0 + (d0.x * d1.x + d0.y * d1.y) / sqrLen0; // s1 = s0 + Dot (D0, D1) * sqrLen0
double smin = min (s0, s1);
double smax = max (s0, s1);
double w[2];
int imax = findIntersection (0.0, 1.0, smin, smax, w);
if (imax > 0) {
pi0.x = p0.x + w[0] * d0.x;
pi0.y = p0.y + w[0] * d0.y;
if (pi0.dist (seg0.begin ()) < 0.00000001) pi0 = seg0.begin ();
if (pi0.dist (seg0.end ()) < 0.00000001) pi0 = seg0.end ();
if (pi0.dist (seg1.begin ()) < 0.00000001) pi0 = seg1.begin ();
if (pi0.dist (seg1.end ()) < 0.00000001) pi0 = seg1.end ();
if (imax > 1) {
pi1.x = p0.x + w[1] * d0.x;
pi1.y = p0.y + w[1] * d0.y;
}
}
return imax;
}
geometry-4.0.0/src/utilities.h 0000644 0000000 0000000 00000002736 13615712371 014525 0 ustar 00 0000000 0000000 /***************************************************************************
* Developer: Francisco Martínez del Río (2011) *
* fmartin@ujaen.es *
* Version: 1.4.1 *
* *
* This is a public domain program *
***************************************************************************/
// Utility functions
#ifndef UTILITIES_H
#define UTILITIES_H
#include "polygon.h"
int findIntersection (const Segment& seg0, const Segment& seg1, Point& ip0, Point& ip1);
/** Signed area of the triangle (p0, p1, p2) */
inline float signedArea (const Point& p0, const Point& p1, const Point& p2)
{
return (p0.x - p2.x)*(p1.y - p2.y) - (p1.x - p2.x) * (p0.y - p2.y);
}
/** Signed area of the triangle ( (0,0), p1, p2) */
inline float signedArea (const Point& p1, const Point& p2)
{
return -p2.x*(p1.y - p2.y) - -p2.y*(p1.x - p2.x);
}
/** Sign of triangle (p1, p2, o) */
inline int sign (const Point& p1, const Point& p2, const Point& o)
{
float det = (p1.x - o.x) * (p2.y - o.y) - (p2.x - o.x) * (p1.y - o.y);
return (det < 0 ? -1 : (det > 0 ? +1 : 0));
}
inline bool pointInTriangle (const Segment& s, Point& o, Point& p)
{
int x = sign (s.begin (), s.end (), p);
return ((x == sign (s.end (), o, p)) && (x == sign (o, s.begin (), p)));
}
#endif