Ported adaptive slicing to C++

and merge branch 'slice_xs' into adaptive-slicing-spline to call adaptive slicing algorithm from _slice
This commit is contained in:
Florens Wasserfall 2017-03-28 08:44:11 +02:00
commit f6616329a2
108 changed files with 4001 additions and 1847 deletions

View File

@ -10,6 +10,7 @@ my %prereqs = qw(
Devel::CheckLib 0
Encode 0
Encode::Locale 1.05
ExtUtils::CppGuess 0
ExtUtils::MakeMaker 6.80
ExtUtils::ParseXS 3.22
File::Basename 0
@ -128,7 +129,7 @@ EOF
# temporary workaround for upstream bug in test
push @cmd, '--notest'
if $module =~ /^(?:OpenGL|Math::PlanePath|Test::Harness)$/;
if $module =~ /^(?:OpenGL|Math::PlanePath|Test::Harness|IO::Scalar)$/;
push @cmd, "$module~$version";
my $res = system @cmd;

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<http://www.gnu.org/licenses/>.

View File

@ -5,7 +5,7 @@ A: Yes.
Slic3r [![Build Status](https://travis-ci.org/alexrj/Slic3r.svg?branch=master)](https://travis-ci.org/alexrj/Slic3r) [![Build status](https://ci.appveyor.com/api/projects/status/8iqmeat6cj158vo6?svg=true)](https://ci.appveyor.com/project/lordofhyphens/slic3r) [![Build Status](http://osx-build.slic3r.org:8080/buildStatus/icon?job=Slic3r)](http://osx-build.slic3r.org:8080/job/Slic3r)
======
Prebuilt Windows (64-bit) and OSX (>10.7) builds:
* https://bintray.com/lordofhyphens/Slic3r/slic3r_dev/view (from build server)
* http://dl.slic3r.org/dev/
<img width=256 src=https://cloud.githubusercontent.com/assets/31754/22719818/09998c92-ed6d-11e6-9fa0-09de638f3a36.png />

View File

@ -57,7 +57,6 @@ use Slic3r::GCode::ArcFitting;
use Slic3r::GCode::MotionPlanner;
use Slic3r::GCode::PressureRegulator;
use Slic3r::GCode::Reader;
use Slic3r::GCode::SpiralVase;
use Slic3r::GCode::VibrationLimit;
use Slic3r::Geometry qw(PI);
use Slic3r::Geometry::Clipper;

View File

@ -1,230 +0,0 @@
package Slic3r::AdaptiveSlicing;
use Moo;
use List::Util qw(min max);
use Math::Trig qw(asin acos deg2rad rad2deg);
use Slic3r::Geometry qw(X Y Z triangle_normal scale unscale);
# This constant essentially describes the volumetric error at the surface which is induced
# by stacking "elliptic" extrusion threads.
# It is empirically determined by
# 1. measuring the surface profile of printed parts to find
# the ratio between layer height and profile height and then
# 2. computing the geometric difference between the model-surface and the elliptic profile.
# [Link to detailed description follows]
use constant SURFACE_CONST => 0.18403;
# public
has 'mesh' => (is => 'ro', required => 1);
has 'size' => (is => 'ro', required => 1);
#private
has 'normal_z' => (is => 'ro', default => sub { [] }); # facet_id => [normal];
has 'ordered_facets' => (is => 'ro', default => sub { [] }); # id => [facet_id, min_z, max_z];
has 'current_facet' => (is => 'rw');
sub BUILD {
my $self = shift;
my $facet_id = 0;
$self->mesh->repair;
my $facets = $self->mesh->facets;
my $vertices = $self->mesh->vertices;
my $normals = $self->mesh->normals;
# generate facet normals
for ($facet_id = 0; $facet_id <= $#{$facets}; $facet_id++) {
my $normal = $normals->[$facet_id];
my $normal_length = sqrt($normal->[0]**2 + $normal->[1]**2 + $normal->[2]**2);
if($normal_length > 0) {
$self->normal_z->[$facet_id] = $normal->[Z]/$normal_length;
}else{ # facet with area = 0
$self->normal_z->[$facet_id] = 0.01;#[0 ,0 ,0];
#print "facet with normal 0. p1: " . $vertices->[$facets->[$facet_id]->[0]]->[Z] . " p2: " . $vertices->[$facets->[$facet_id]->[1]]->[Z] . " p3: " . $vertices->[$facets->[$facet_id]->[2]]->[Z] . "\n";
#print "normal: " . $normal->[0] . ", " . $normal->[1] . ", " . $normal->[2] . "\n";
}
}
# generate a list of facet_ids, containing maximum and minimum Z-Value of the facet, ordered by minimum Z
my @sort_facets;
for ($facet_id = 0; $facet_id <= $#{$facets}; $facet_id++) {
my $a = $vertices->[$facets->[$facet_id]->[0]]->[Z];
my $b = $vertices->[$facets->[$facet_id]->[1]]->[Z];
my $c = $vertices->[$facets->[$facet_id]->[2]]->[Z];
my $min_z = min($a, $b, $c);
my $max_z = max($a, $b, $c);
push @sort_facets, [$facet_id, scale $min_z, scale $max_z];
}
@sort_facets = sort {$a->[1] <=> $b->[1]} @sort_facets;
for (my $i = 0; $i <= $#sort_facets; $i++) {
$self->ordered_facets->[$i] = $sort_facets[$i];
}
# initialize pointer to iterate over the object
$self->current_facet(0);
}
# find height of the next layer by analyzing the angle of all facets intersecting the new layer
sub next_layer_height {
my $self = shift;
my ($z, $quality_factor, $min_height, $max_height) = @_;
# factor must be between 0-1, 0 is highest quality, 1 highest print speed
if($quality_factor < 0 or $quality_factor > 1) {
die "Speed / Quality factor must be in the interval [0:1]";
}
my $delta_min = SURFACE_CONST * $min_height;
my $delta_max = SURFACE_CONST * $max_height + 0.5*$max_height;
my $scaled_quality_factor = $quality_factor * ($delta_max-$delta_min) + $delta_min;
my $height = $max_height;
my $first_hit = 0;
# find all facets intersecting the slice-layer
my $ordered_id = $self->current_facet;
while ($ordered_id <= $#{$self->ordered_facets}) {
# facet's minimum is higher than slice_z -> end loop
if($self->ordered_facets->[$ordered_id]->[1] >= $z) {
last;
}
# facet's maximum is higher than slice_z -> store the first event for next layer_height call to begin at this point
if($self->ordered_facets->[$ordered_id]->[2] > $z) {
# first event?
if(!$first_hit) {
$first_hit = 1;
$self->current_facet($ordered_id);
}
#skip touching facets which could otherwise cause small height values
if($self->ordered_facets->[$ordered_id]->[2] <= $z+1)
{
$ordered_id++;
next;
}
# compute layer-height for this facet and store minimum of all heights
$height = min($height, $self->_facet_height($ordered_id, $scaled_quality_factor));
}
$ordered_id++;
}
# lower height limit due to printer capabilities
$height = max($min_height, $height);
# check for sloped facets inside the determined layer and correct height if necessary
if($height > $min_height){
while ($ordered_id <= $#{$self->ordered_facets}) {
# facet's minimum is higher than slice_z + height -> end loop
if($self->ordered_facets->[$ordered_id]->[1] >= ($z + scale $height)) {
last;
}
#skip touching facets which could otherwise cause small height values
if($self->ordered_facets->[$ordered_id]->[2] <= $z+1)
{
$ordered_id++;
next;
}
# Compute new height for this facet and check against height.
my $reduced_height = $self->_facet_height($ordered_id, $scaled_quality_factor);
#$area_h = max($min_height, min($max_height, $area_h));
my $z_diff = unscale ($self->ordered_facets->[$ordered_id]->[1] - $z);
# # handle horizontal facets
# if ($self->normal_z->[$self->ordered_facets->[$ordered_id]->[0]] > 0.999) {
# Slic3r::debugf "cusp computation, height is reduced from %f", $height;
# $height = $z_diff;
# Slic3r::debugf "to %f due to near horizontal facet\n", $height;
# }else{
if( $reduced_height > $z_diff) {
if($reduced_height < $height) {
Slic3r::debugf "adaptive layer computation: height is reduced from %f", $height;
$height = $reduced_height;
Slic3r::debugf "to %f due to higher facet\n", $height;
}
}else{
Slic3r::debugf "adaptive layer computation: height is reduced from %f", $height;
$height = $z_diff;
Slic3r::debugf "to z-diff: %f\n", $height;
}
# }
$ordered_id++;
}
# lower height limit due to printer capabilities again
$height = max($min_height, $height);
}
Slic3r::debugf "adaptive layer computation, layer-bottom at z:%f, quality_factor:%f, resulting layer height:%f\n", unscale $z, $quality_factor, $height;
return $height;
}
# computes the cusp height from a given facets normal and the cusp_value
sub _facet_cusp_height {
my $self = shift;
my ($ordered_id, $cusp_value) = @_;
my $normal_z = $self->normal_z->[$self->ordered_facets->[$ordered_id]->[0]];
my $cusp = ($normal_z == 0) ? 9999 : abs($cusp_value/$normal_z);
return $cusp;
}
sub _facet_height {
my ($self, $ordered_id, $scaled_quality_factor) = @_;
my $normal_z = abs($self->normal_z->[$self->ordered_facets->[$ordered_id]->[0]]);
my $height = $scaled_quality_factor/(SURFACE_CONST + $normal_z/2);
return ($normal_z == 0) ? 9999 : $height;
}
# Returns the distance to the next horizontal facet in Z-dir
# to consider horizontal object features in slice thickness
sub horizontal_facet_distance {
my $self = shift;
my ($z, $max_height) = @_;
$max_height = scale $max_height;
my $ordered_id = $self->current_facet;
while ($ordered_id <= $#{$self->ordered_facets}) {
# facet's minimum is higher than max forward distance -> end loop
if($self->ordered_facets->[$ordered_id]->[1] > $z+$max_height) {
last;
}
# min_z == max_z -> horizontal facet
if($self->ordered_facets->[$ordered_id]->[1] > $z) {
if($self->ordered_facets->[$ordered_id]->[1] == $self->ordered_facets->[$ordered_id]->[2]) {
return unscale($self->ordered_facets->[$ordered_id]->[1] - $z);
}
}
$ordered_id++;
}
# objects maximum?
if($z + $max_height > scale($self->size)) {
return max($self->size - unscale($z), 0);
}
return unscale $max_height;
}
1;

View File

@ -8,12 +8,6 @@ use utf8;
use List::Util qw(first max);
# cemetery of old config settings
our @Ignore = qw(duplicate_x duplicate_y multiply_x multiply_y support_material_tool acceleration
adjust_overhang_flow standby_temperature scale rotate duplicate duplicate_grid
rotate scale duplicate_grid start_perimeters_at_concave_points start_perimeters_at_non_overhang
randomize_start seal_position bed_size print_center g0);
# C++ Slic3r::PrintConfigDef exported as a Perl hash of hashes.
# The C++ counterpart is a constant singleton.
our $Options = print_config_def();
@ -120,11 +114,7 @@ sub load_ini_hash {
my ($ini_hash) = @_;
my $config = $class->new;
foreach my $opt_key (keys %$ini_hash) {
($opt_key, my $value) = _handle_legacy($opt_key, $ini_hash->{$opt_key});
next if !defined $opt_key;
$config->set_deserialize($opt_key, $value);
}
$config->set_deserialize($_, $ini_hash->{$_}) for keys %$ini_hash;
return $config;
}
@ -145,60 +135,6 @@ sub get_value {
: $self->get($opt_key);
}
sub _handle_legacy {
my ($opt_key, $value) = @_;
# handle legacy options
if ($opt_key =~ /^(extrusion_width|bottom_layer_speed|first_layer_height)_ratio$/) {
$opt_key = $1;
$opt_key =~ s/^bottom_layer_speed$/first_layer_speed/;
$value = $value =~ /^\d+(?:\.\d+)?$/ && $value != 0 ? ($value*100) . "%" : 0;
}
if ($opt_key eq 'threads' && !$Slic3r::have_threads) {
$value = 1;
}
if ($opt_key eq 'gcode_flavor' && $value eq 'makerbot') {
$value = 'makerware';
}
if ($opt_key eq 'fill_density' && defined($value) && $value !~ /%/ && $value <= 1) {
# fill_density was turned into a percent value
$value *= 100;
$value = "$value"; # force update of the PV value, workaround for bug https://rt.cpan.org/Ticket/Display.html?id=94110
}
if ($opt_key eq 'randomize_start' && $value) {
$opt_key = 'seam_position';
$value = 'random';
}
if ($opt_key eq 'bed_size' && $value) {
$opt_key = 'bed_shape';
my ($x, $y) = split /,/, $value;
$value = "0x0,${x}x0,${x}x${y},0x${y}";
}
return () if first { $_ eq $opt_key } @Ignore;
# For historical reasons, the world's full of configs having these very low values;
# to avoid unexpected behavior we need to ignore them. Banning these two hard-coded
# values is a dirty hack and will need to be removed sometime in the future, but it
# will avoid lots of complaints for now.
if ($opt_key eq 'perimeter_acceleration' && $value == '25') {
$value = 0;
}
if ($opt_key eq 'infill_acceleration' && $value == '50') {
$value = 0;
}
if (!exists $Options->{$opt_key}) {
my @keys = grep { $Options->{$_}{aliases} && grep $_ eq $opt_key, @{$Options->{$_}{aliases}} } keys %$Options;
if (!@keys) {
warn "Unknown option $opt_key\n";
return ();
}
$opt_key = $keys[0];
}
return ($opt_key, $value);
}
# Create a hash of hashes from the underlying C++ Slic3r::DynamicPrintConfig.
# The first hash key is '_' meaning no category.
sub as_ini {
@ -265,8 +201,10 @@ sub validate {
if !first { $_ eq $self->fill_pattern } @{$Options->{fill_pattern}{values}};
# --external-fill-pattern
die "Invalid value for --external-fill-pattern\n"
if !first { $_ eq $self->external_fill_pattern } @{$Options->{external_fill_pattern}{values}};
die "Invalid value for --top-infill-pattern\n"
if !first { $_ eq $self->top_infill_pattern } @{$Options->{top_infill_pattern}{values}};
die "Invalid value for --bottom-infill-pattern\n"
if !first { $_ eq $self->bottom_infill_pattern } @{$Options->{bottom_infill_pattern}{values}};
# --fill-density
die "The selected fill pattern is not supposed to work at 100% density\n"

View File

@ -1,86 +0,0 @@
package Slic3r::GCode::SpiralVase;
use Moo;
has 'config' => (is => 'ro', required => 1);
has 'enable' => (is => 'rw', default => sub { 0 });
has 'reader' => (is => 'ro', default => sub { Slic3r::GCode::Reader->new });
use Slic3r::Geometry qw(unscale);
sub BUILD {
my ($self) = @_;
$self->reader->apply_print_config($self->config);
}
sub process_layer {
my $self = shift;
my ($gcode) = @_;
# This post-processor relies on several assumptions:
# - all layers are processed through it, including those that are not supposed
# to be transformed, in order to update the reader with the XY positions
# - each call to this method includes a full layer, with a single Z move
# at the beginning
# - each layer is composed by suitable geometry (i.e. a single complete loop)
# - loops were not clipped before calling this method
# if we're not going to modify G-code, just feed it to the reader
# in order to update positions
if (!$self->enable) {
$self->reader->parse($gcode, sub {});
return $gcode;
}
# get total XY length for this layer by summing all extrusion moves
my $total_layer_length = 0;
my $layer_height = 0;
my $z = undef;
$self->reader->clone->parse($gcode, sub {
my ($reader, $cmd, $args, $info) = @_;
if ($cmd eq 'G1') {
if ($info->{extruding}) {
$total_layer_length += $info->{dist_XY};
} elsif (exists $args->{Z}) {
$layer_height += $info->{dist_Z};
$z //= $args->{Z};
}
}
});
#use XXX; XXX [ $gcode, $layer_height, $z, $total_layer_length ];
# remove layer height from initial Z
$z -= $layer_height;
my $new_gcode = "";
$self->reader->parse($gcode, sub {
my ($reader, $cmd, $args, $info) = @_;
if ($cmd eq 'G1' && exists $args->{Z}) {
# if this is the initial Z move of the layer, replace it with a
# (redundant) move to the last Z of previous layer
my $line = $info->{raw};
$line =~ s/ Z[.0-9]+/ Z$z/;
$new_gcode .= "$line\n";
} elsif ($cmd eq 'G1' && !exists($args->{Z}) && $info->{dist_XY}) {
# horizontal move
my $line = $info->{raw};
if ($info->{extruding}) {
$z += $info->{dist_XY} * $layer_height / $total_layer_length;
$line =~ s/^G1 /sprintf 'G1 Z%.3f ', $z/e;
$new_gcode .= "$line\n";
}
# skip travel moves: the move to first perimeter point will
# cause a visible seam when loops are not aligned in XY; by skipping
# it we blend the first loop move in the XY plane (although the smoothness
# of such blend depend on how long the first segment is; maybe we should
# enforce some minimum length?)
} else {
$new_gcode .= "$info->{raw}\n";
}
});
return $new_gcode;
}
1;

View File

@ -55,6 +55,8 @@ use constant FILE_WILDCARDS => {
svg => 'SVG files *.svg|*.svg;*.SVG',
};
use constant MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(known stl obj amf)};
use constant STL_MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(stl)};
use constant AMF_MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(amf)};
our $datadir;
# If set, the "Controller" tab for the control of the printer over serial line and the serial port settings are hidden.
@ -62,6 +64,7 @@ our $no_controller;
our $no_plater;
our $mode;
our $autosave;
our $threads;
our @cb;
our $Settings = {
@ -69,10 +72,12 @@ our $Settings = {
mode => 'simple',
version_check => 1,
autocenter => 1,
invert_zoom => 0,
background_processing => 0,
# If set, the "Controller" tab for the control of the printer over serial line and the serial port settings are hidden.
# By default, Prusa has the controller hidden.
no_controller => 1,
no_controller => 0,
threads => $Slic3r::Config::Options->{threads}{default},
color_toolpaths_by => 'role',
},
};
@ -122,15 +127,15 @@ sub OnInit {
my $last_version;
if (-f "$enc_datadir/slic3r.ini") {
my $ini = eval { Slic3r::Config->read_ini("$datadir/slic3r.ini") };
$Settings = $ini if $ini;
$last_version = $Settings->{_}{version};
$Settings->{_}{mode} ||= 'expert';
$Settings->{_}{autocenter} //= 1;
$Settings->{_}{background_processing} //= 1;
# If set, the "Controller" tab for the control of the printer over serial line and the serial port settings are hidden.
$Settings->{_}{no_controller} //= 1;
if ($ini) {
$last_version = $ini->{_}{version};
$ini->{_}{$_} = $Settings->{_}{$_}
for grep !exists $ini->{_}{$_}, keys %{$Settings->{_}};
$Settings = $ini;
}
}
$Settings->{_}{version} = $Slic3r::VERSION;
$Settings->{_}{threads} = $threads if $threads;
$self->save_settings;
# application frame
@ -297,7 +302,7 @@ sub have_version_check {
my ($self) = @_;
# return an explicit 0
return ($Slic3r::have_threads && $Slic3r::build && $have_LWP) || 0;
return ($Slic3r::have_threads && $Slic3r::VERSION !~ /-dev$/ && $have_LWP) || 0;
}
sub check_version {

View File

@ -50,7 +50,7 @@ use constant PI => 3.1415927;
# Constant to determine if Vertex Buffer objects are used to draw
# bed grid and the cut plane for object separation.
use constant HAS_VBO => 1;
use constant HAS_VBO => eval { glGenBuffersARB_p(0); 1 };
# phi / theta angles to orient the camera.
@ -127,6 +127,9 @@ sub new {
# Calculate the zoom delta and apply it to the current zoom factor
my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
if ($Slic3r::GUI::Settings->{_}{invert_zoom}) {
$zoom *= -1;
}
$zoom = max(min($zoom, 4), -4);
$zoom /= 10;
$self->_zoom($self->_zoom / (1-$zoom));
@ -745,10 +748,10 @@ sub InitGL {
# Enables Smooth Color Shading; try GL_FLAT for (lack of) fun.
glShadeModel(GL_SMOOTH);
glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.5, 0.3, 0.3, 1);
glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.3, 0.3, 0.3, 1);
glMaterialfv_p(GL_FRONT_AND_BACK, GL_SPECULAR, 1, 1, 1, 1);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0, 0, 0.9);
glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0.1, 0.1, 0.9);
# A handy trick -- have surface material mirror the color.
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
@ -1149,21 +1152,25 @@ use List::Util qw(first min max);
use Slic3r::Geometry qw(scale unscale epsilon);
use Slic3r::Print::State ':steps';
use constant COLORS => [ [1,1,0,1], [1,0.5,0.5,1], [0.5,1,0.5,1], [0.5,0.5,1,1] ];
__PACKAGE__->mk_accessors(qw(
colors
color_by
color_toolpaths_by
select_by
drag_by
volumes_by_object
_objects_by_volumes
));
sub default_colors { [1,0.95,0.2,1], [1,0.45,0.45,1], [0.5,1,0.5,1], [0.5,0.5,1,1] }
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
$self->colors([ $self->default_colors ]);
$self->color_by('volume'); # object | volume
$self->color_toolpaths_by('role'); # role | extruder
$self->select_by('object'); # object | volume | instance
$self->drag_by('instance'); # object | instance
$self->volumes_by_object({}); # obj_idx => [ volume_idx, volume_idx ... ]
@ -1201,7 +1208,7 @@ sub load_object {
$color_idx = $obj_idx;
}
my $color = [ @{COLORS->[ $color_idx % scalar(@{&COLORS}) ]} ];
my $color = [ @{$self->colors->[ $color_idx % scalar(@{$self->colors}) ]} ];
$color->[3] = $volume->modifier ? 0.5 : 1;
push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
bounding_box => $mesh->bounding_box,
@ -1278,7 +1285,7 @@ sub load_print_object_slices {
push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[0],
color => $self->colors->[0],
verts => OpenGL::Array->new_list(GL_FLOAT, @verts),
norms => OpenGL::Array->new_list(GL_FLOAT, @norms),
quad_verts => OpenGL::Array->new_list(GL_FLOAT, @quad_verts),
@ -1293,68 +1300,78 @@ sub load_print_toolpaths {
return if !$print->step_done(STEP_BRIM);
return if !$print->has_skirt
&& $print->config->brim_width == 0
&& $print->config->interior_brim_width == 0
&& $print->config->brim_connections_width == 0;
my $qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my %offsets = (); # print_z => [ qverts, tverts ]
my $skirt_height = 0; # number of layers
if ($print->has_infinite_skirt) {
$skirt_height = $print->total_layer_count;
} else {
$skirt_height = min($print->config->skirt_height, $print->total_layer_count);
}
$skirt_height ||= 1 if $print->config->brim_width > 0;
# get first $skirt_height layers (maybe this should be moved to a PrintObject method?)
my $object0 = $print->get_object(0);
my @layers = ();
push @layers, map $object0->get_layer($_-1), 1..min($skirt_height, $object0->layer_count);
push @layers, map $object0->get_support_layer($_-1), 1..min($skirt_height, $object0->support_layer_count);
@layers = sort { $a->print_z <=> $b->print_z } @layers;
@layers = @layers[0..($skirt_height-1)];
foreach my $i (0..($skirt_height-1)) {
my $top_z = $layers[$i]->print_z;
$offsets{$top_z} = [$qverts->size, $tverts->size];
if ($i == 0) {
$self->_extrusionentity_to_verts($print->brim, $top_z, Slic3r::Point->new(0,0), $qverts, $tverts);
}
$self->_extrusionentity_to_verts($print->skirt, $top_z, Slic3r::Point->new(0,0), $qverts, $tverts);
}
my $bb = Slic3r::Geometry::BoundingBoxf3->new;
{
my $pbb = $print->bounding_box;
$bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->min_point}));
$bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->max_point}));
}
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[2],
qverts => $qverts,
tverts => $tverts,
offsets => { %offsets },
);
my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
if (!$print->brim->empty) {
my $color = $color_by_extruder
? $self->colors->[ ($print->brim_extruder-1) % @{$self->colors} ]
: $self->colors->[2];
push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => $color,
qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
offsets => {}, # print_z => [ qverts, tverts ]
);
my $top_z = $print->get_object(0)->get_layer(0)->print_z;
$volume->offsets->{$top_z} = [0, 0];
$self->_extrusionentity_to_verts($print->brim, $top_z, Slic3r::Point->new(0,0),
$volume->qverts, $volume->tverts);
}
if (!$print->skirt->empty) {
# TODO: it's a bit difficult to predict skirt extruders with the current skirt logic.
# We need to rewrite it anyway.
my $color = +($self->default_colors)[0];
push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => $color,
qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
offsets => {}, # print_z => [ qverts, tverts ]
);
my $skirt_height = 0; # number of layers
if ($print->has_infinite_skirt) {
$skirt_height = $print->total_layer_count;
} else {
$skirt_height = min($print->config->skirt_height, $print->total_layer_count);
}
$skirt_height ||= 1 if $print->config->brim_width > 0 || $print->config->interior_brim_width;
# get first $skirt_height layers (maybe this should be moved to a PrintObject method?)
my $object0 = $print->get_object(0);
my @layers = ();
push @layers, map $object0->get_layer($_-1), 1..min($skirt_height, $object0->layer_count);
push @layers, map $object0->get_support_layer($_-1), 1..min($skirt_height, $object0->support_layer_count);
@layers = sort { $a->print_z <=> $b->print_z } @layers;
@layers = @layers[0..($skirt_height-1)];
foreach my $i (0..($skirt_height-1)) {
my $top_z = $layers[$i]->print_z;
$volume->offsets->{$top_z} = [$volume->qverts->size, $volume->tverts->size];
$self->_extrusionentity_to_verts($print->skirt, $top_z, Slic3r::Point->new(0,0),
$volume->qverts, $volume->tverts);
}
}
}
sub load_print_object_toolpaths {
my ($self, $object) = @_;
my $perim_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $perim_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $infill_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $infill_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $support_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my $support_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
my %perim_offsets = (); # print_z => [ qverts, tverts ]
my %infill_offsets = ();
my %support_offsets = ();
# order layers by print_z
my @layers = sort { $a->print_z <=> $b->print_z }
@{$object->layers}, @{$object->support_layers};
@ -1370,122 +1387,91 @@ sub load_print_object_toolpaths {
$bb->merge_point(Slic3r::Pointf3->new_unscale(@{$cbb->max_point}, $object->size->z));
}
}
my %volumes = (); # color => Volume
# Maximum size of an allocation block: 32MB / sizeof(float)
my $alloc_size_max = 32 * 1048576 / 4;
my $add = sub {
my ($coll, $top_z, $copy, $color) = @_;
my $volume = $volumes{$color};
if (!$volume) {
push @{$self->volumes}, $volumes{$color} = $volume = Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => $color,
qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
offsets => {}, # print_z => [ qverts, tverts ]
);
}
$volume->offsets->{$top_z} //= [ $volume->qverts->size, $volume->tverts->size ];
$self->_extrusionentity_to_verts($coll, $top_z, $copy, $volume->qverts, $volume->tverts);
};
my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
foreach my $layer (@layers) {
my $top_z = $layer->print_z;
if (!exists $perim_offsets{$top_z}) {
$perim_offsets{$top_z} = [
$perim_qverts->size, $perim_tverts->size,
];
}
if (!exists $infill_offsets{$top_z}) {
$infill_offsets{$top_z} = [
$infill_qverts->size, $infill_tverts->size,
];
}
if (!exists $support_offsets{$top_z}) {
$support_offsets{$top_z} = [
$support_qverts->size, $support_tverts->size,
];
}
foreach my $copy (@{ $object->_shifted_copies }) {
foreach my $layerm (@{$layer->regions}) {
if ($object->step_done(STEP_PERIMETERS)) {
$self->_extrusionentity_to_verts($layerm->perimeters, $top_z, $copy,
$perim_qverts, $perim_tverts);
my $color = $color_by_extruder
? $self->colors->[ ($layerm->region->config->perimeter_extruder-1) % @{$self->colors} ]
: $self->colors->[0];
$add->($layerm->perimeters, $top_z, $copy, $color);
}
if ($object->step_done(STEP_INFILL)) {
$self->_extrusionentity_to_verts($layerm->fills, $top_z, $copy,
$infill_qverts, $infill_tverts);
my $color = $color_by_extruder
? $self->colors->[ ($layerm->region->config->infill_extruder-1) % @{$self->colors} ]
: $self->colors->[1];
if ($color_by_extruder && $layerm->region->config->infill_extruder != $layerm->region->config->solid_infill_extruder) {
# divide solid and non-solid infill
my $solid = Slic3r::ExtrusionPath::Collection->new;
my $non_solid = Slic3r::ExtrusionPath::Collection->new;
foreach my $fill (@{$layerm->fills}) {
if ($fill->[0]->is_solid_infill) {
$solid->append($fill);
} else {
$non_solid->append($fill);
}
}
$add->($non_solid, $top_z, $copy, $color);
$color = $self->colors->[ ($layerm->region->config->solid_infill_extruder-1) % @{&COLORS} ];
$add->($solid, $top_z, $copy, $color);
} else {
$add->($layerm->fills, $top_z, $copy, $color);
}
}
}
if ($layer->isa('Slic3r::Layer::Support') && $object->step_done(STEP_SUPPORTMATERIAL)) {
$self->_extrusionentity_to_verts($layer->support_fills, $top_z, $copy,
$support_qverts, $support_tverts);
$self->_extrusionentity_to_verts($layer->support_interface_fills, $top_z, $copy,
$support_qverts, $support_tverts);
{
my $color = $color_by_extruder
? $self->colors->[ ($layer->object->config->support_material_extruder-1) % @{$self->colors} ]
: $self->colors->[2];
$add->($layer->support_fills, $top_z, $copy, $color);
}
{
my $color = ($color_by_extruder)
? $self->colors->[ ($layer->object->config->support_material_interface_extruder-1) % @{$self->colors} ]
: $self->colors->[2];
$add->($layer->support_interface_fills, $top_z, $copy, $color);
}
}
}
if ($perim_qverts->size() > $alloc_size_max || $perim_tverts->size() > $alloc_size_max) {
# Store the vertex arrays and restart their containers.
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[0],
qverts => $perim_qverts,
tverts => $perim_tverts,
offsets => { %perim_offsets },
);
$perim_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
$perim_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
%perim_offsets = ();
foreach my $color (keys %volumes) {
my $volume = $volumes{$color};
if ($volume->qverts->size() > $alloc_size_max || $volume->tverts->size() > $alloc_size_max) {
# stop appending to this volume; create a new one next time
delete $volumes{$color};
}
}
if ($infill_qverts->size() > $alloc_size_max || $infill_tverts->size() > $alloc_size_max) {
# Store the vertex arrays and restart their containers.
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[1],
qverts => $infill_qverts,
tverts => $infill_tverts,
offsets => { %infill_offsets },
);
$infill_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
$infill_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
%infill_offsets = ();
}
if ($support_qverts->size() > $alloc_size_max || $support_tverts->size() > $alloc_size_max) {
# Store the vertex arrays and restart their containers.
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[2],
qverts => $support_qverts,
tverts => $support_tverts,
offsets => { %support_offsets },
);
$support_qverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
$support_tverts = Slic3r::GUI::_3DScene::GLVertexArray->new;
%support_offsets = ();
}
}
if ($perim_qverts->size() > 0 || $perim_tverts->size() > 0) {
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[0],
qverts => $perim_qverts,
tverts => $perim_tverts,
offsets => { %perim_offsets },
);
}
if ($infill_qverts->size() > 0 || $infill_tverts->size() > 0) {
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[1],
qverts => $infill_qverts,
tverts => $infill_tverts,
offsets => { %infill_offsets },
);
}
if ($support_qverts->size() > 0 || $support_tverts->size() > 0) {
push @{$self->volumes}, Slic3r::GUI::3DScene::Volume->new(
bounding_box => $bb,
color => COLORS->[2],
qverts => $support_qverts,
tverts => $support_tverts,
offsets => { %support_offsets },
);
}
}

View File

@ -5,25 +5,25 @@ use strict;
use warnings;
use utf8;
use Scalar::Util qw(looks_like_number);
use Slic3r::Geometry qw(PI X Y unscale);
use Wx qw(:dialog :id :misc :sizer :choicebook :button :bitmap
use Wx qw(:dialog :id :misc :sizer :choicebook :button :bitmap :textctrl
wxBORDER_NONE wxTAB_TRAVERSAL);
use Wx::Event qw(EVT_CLOSE EVT_BUTTON);
use base qw(Wx::Dialog Class::Accessor);
__PACKAGE__->mk_accessors(qw(sender config2 x_homed y_homed));
__PACKAGE__->mk_accessors(qw(sender writer config2 x_homed y_homed));
sub new {
my ($class, $parent, $config, $sender) = @_;
my ($class, $parent, $config, $sender, $manual_control_config) = @_;
my $self = $class->SUPER::new($parent, -1, "Manual Control", wxDefaultPosition,
[500,380], wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
[500,400], wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
$self->sender($sender);
$self->writer(Slic3r::GCode::Writer->new);
$self->writer->config->apply_dynamic($config);
$self->config2({
xy_travel_speed => 130,
z_travel_speed => 10,
});
$self->config2($manual_control_config);
my $bed_sizer = Wx::FlexGridSizer->new(2, 3, 1, 1);
$bed_sizer->AddGrowableCol(1, 1);
@ -107,7 +107,7 @@ sub new {
my $optgroup = Slic3r::GUI::OptionsGroup->new(
parent => $self,
title => 'Settings',
title => 'Manual motion settings',
on_change => sub {
my ($opt_id, $value) = @_;
$self->config2->{$opt_id} = $value;
@ -133,16 +133,101 @@ sub new {
));
$optgroup->append_line($line);
}
my $left_sizer = Wx::BoxSizer->new(wxVERTICAL);
$left_sizer->Add($bed_sizer, 1, wxEXPAND | wxALL, 10);
$left_sizer->Add($optgroup->sizer, 0, wxEXPAND | wxALL, 10);
my $main_sizer = Wx::BoxSizer->new(wxVERTICAL);
$main_sizer->Add($bed_sizer, 1, wxEXPAND | wxALL, 10);
$main_sizer->Add($optgroup->sizer, 0, wxEXPAND | wxALL, 10);
#$main_sizer->Add($self->CreateButtonSizer(wxCLOSE), 0, wxEXPAND);
#EVT_BUTTON($self, wxID_CLOSE, sub { $self->Close });
my $right_sizer = Wx::BoxSizer->new(wxVERTICAL);
{
my $optgroup = Slic3r::GUI::OptionsGroup->new(
parent => $self,
title => 'Temperature',
on_change => sub {
my ($opt_id, $value) = @_;
$self->config2->{$opt_id} = $value;
},
);
$right_sizer->Add($optgroup->sizer, 0, wxEXPAND | wxALL, 10);
{
my $line = $optgroup->create_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'temperature',
type => 's',
label => 'Extruder',
default => '',
sidetext => '°C',
default => $self->config2->{temperature},
));
$line->append_button("Set", "tick.png", sub {
if (!looks_like_number($self->config2->{temperature})) {
Slic3r::GUI::show_error($self, "Invalid temperature.");
return;
}
my $cmd = $self->writer->set_temperature($self->config2->{temperature});
$self->sender->send($cmd, 1);
});
$optgroup->append_line($line);
}
{
my $line = $optgroup->create_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'bed_temperature',
type => 's',
label => 'Bed',
default => '',
sidetext => '°C',
default => $self->config2->{bed_temperature},
));
$line->append_button("Set", "tick.png", sub {
if (!looks_like_number($self->config2->{bed_temperature})) {
Slic3r::GUI::show_error($self, "Invalid bed temperature.");
return;
}
my $cmd = $self->writer->set_bed_temperature($self->config2->{bed_temperature});
$self->sender->send($cmd, 1);
});
$optgroup->append_line($line);
}
}
{
my $box = Wx::StaticBox->new($self, -1, "Console");
my $sbsizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
$right_sizer->Add($sbsizer, 1, wxEXPAND, 0);
my $log = $self->{log_textctrl} = Wx::TextCtrl->new($self, -1, "", wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxBORDER_NONE);
$log->SetBackgroundColour($self->GetBackgroundColour);
$log->SetFont($Slic3r::GUI::small_font);
$log->SetEditable(0);
$sbsizer->Add($self->{log_textctrl}, 1, wxEXPAND, 0);
my $cmd_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
my $cmd_textctrl = Wx::TextCtrl->new($self, -1, '');
$cmd_sizer->Add($cmd_textctrl, 1, wxEXPAND, 0);
my $btn = Wx::Button->new($self, -1,
"Send", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("cog_go.png"), wxBITMAP_TYPE_PNG));
}
$cmd_sizer->Add($btn, 0, wxEXPAND | wxLEFT, 5);
EVT_BUTTON($self, $btn, sub {
return if $cmd_textctrl->GetValue eq '';
$self->sender->send($cmd_textctrl->GetValue, 1);
$cmd_textctrl->SetValue('');
});
$sbsizer->Add($cmd_sizer, 0, wxEXPAND | wxTOP, 2);
}
my $main_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$main_sizer->Add($left_sizer, 1, wxEXPAND | wxRIGHT, 10);
$main_sizer->Add($right_sizer, 0, wxEXPAND, 0);
$self->SetSizer($main_sizer);
$self->SetMinSize($self->GetSize);
#$main_sizer->SetSizeHints($self);
$main_sizer->SetSizeHints($self);
$self->Layout;
# needed to actually free memory
@ -154,6 +239,12 @@ sub new {
return $self;
}
sub update_log {
my ($self, $log) = @_;
$self->{log_textctrl}->SetValue($log);
}
sub abs_xy_move {
my ($self, $pos) = @_;

View File

@ -9,7 +9,7 @@ use Wx::Event qw(EVT_BUTTON EVT_MOUSEWHEEL EVT_TIMER EVT_SCROLLWIN);
use base qw(Wx::Panel Class::Accessor);
__PACKAGE__->mk_accessors(qw(printer_name config sender jobs
printing status_timer temp_timer));
printing status_timer temp_timer manual_control_config));
use constant CONNECTION_TIMEOUT => 3; # seconds
use constant STATUS_TIMER_INTERVAL => 1000; # milliseconds
@ -21,6 +21,12 @@ sub new {
$self->printer_name($printer_name || 'Printer');
$self->config($config);
$self->manual_control_config({
xy_travel_speed => 130,
z_travel_speed => 10,
temperature => '',
bed_temperature => '',
});
$self->jobs([]);
# set up the timer that polls for updates
@ -38,6 +44,8 @@ sub new {
}
}
$self->{log_textctrl}->AppendText("$_\n") for @{$self->sender->purge_log};
$self->{manual_control_dialog}->update_log($self->{log_textctrl}->GetValue)
if $self->{manual_control_dialog};
{
my $temp = $self->sender->getT;
if ($temp eq '') {
@ -77,7 +85,7 @@ sub new {
# printer name
{
my $text = Wx::StaticText->new($box, -1, $self->printer_name, wxDefaultPosition, [220,-1]);
my $text = Wx::StaticText->new($self, -1, $self->printer_name, wxDefaultPosition, [220,-1]);
my $font = $text->GetFont;
$font->SetPointSize(20);
$text->SetFont($font);
@ -91,19 +99,19 @@ sub new {
$conn_sizer->AddGrowableCol(1, 1);
$left_sizer->Add($conn_sizer, 0, wxEXPAND | wxTOP, 5);
{
my $text = Wx::StaticText->new($box, -1, "Port:", wxDefaultPosition, wxDefaultSize);
my $text = Wx::StaticText->new($self, -1, "Port:", wxDefaultPosition, wxDefaultSize);
$text->SetFont($Slic3r::GUI::small_font);
$conn_sizer->Add($text, 0, wxRIGHT | wxALIGN_CENTER_VERTICAL, 5);
}
my $serial_port_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
{
$self->{serial_port_combobox} = Wx::ComboBox->new($box, -1, $config->serial_port, wxDefaultPosition, wxDefaultSize, []);
$self->{serial_port_combobox} = Wx::ComboBox->new($self, -1, $config->serial_port, wxDefaultPosition, wxDefaultSize, []);
$self->{serial_port_combobox}->SetFont($Slic3r::GUI::small_font);
$self->update_serial_ports;
$serial_port_sizer->Add($self->{serial_port_combobox}, 0, wxRIGHT | wxALIGN_CENTER_VERTICAL, 1);
}
{
$self->{btn_rescan_serial} = my $btn = Wx::BitmapButton->new($box, -1, Wx::Bitmap->new($Slic3r::var->("arrow_rotate_clockwise.png"), wxBITMAP_TYPE_PNG),
$self->{btn_rescan_serial} = my $btn = Wx::BitmapButton->new($self, -1, Wx::Bitmap->new($Slic3r::var->("arrow_rotate_clockwise.png"), wxBITMAP_TYPE_PNG),
wxDefaultPosition, wxDefaultSize, &Wx::wxBORDER_NONE);
$btn->SetToolTipString("Rescan serial ports")
if $btn->can('SetToolTipString');
@ -113,19 +121,19 @@ sub new {
$conn_sizer->Add($serial_port_sizer, 0, wxRIGHT | wxALIGN_CENTER_VERTICAL, 5);
{
my $text = Wx::StaticText->new($box, -1, "Speed:", wxDefaultPosition, wxDefaultSize);
my $text = Wx::StaticText->new($self, -1, "Speed:", wxDefaultPosition, wxDefaultSize);
$text->SetFont($Slic3r::GUI::small_font);
$conn_sizer->Add($text, 0, wxRIGHT | wxALIGN_CENTER_VERTICAL, 5);
}
my $serial_speed_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
{
$self->{serial_speed_combobox} = Wx::ComboBox->new($box, -1, $config->serial_speed, wxDefaultPosition, wxDefaultSize,
$self->{serial_speed_combobox} = Wx::ComboBox->new($self, -1, $config->serial_speed, wxDefaultPosition, wxDefaultSize,
["115200", "250000"]);
$self->{serial_speed_combobox}->SetFont($Slic3r::GUI::small_font);
$serial_speed_sizer->Add($self->{serial_speed_combobox}, 0, wxALIGN_CENTER_VERTICAL, 0);
}
{
$self->{btn_disconnect} = my $btn = Wx::Button->new($box, -1, "Disconnect", wxDefaultPosition, wxDefaultSize);
$self->{btn_disconnect} = my $btn = Wx::Button->new($self, -1, "Disconnect", wxDefaultPosition, wxDefaultSize);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("delete.png"), wxBITMAP_TYPE_PNG));
@ -138,7 +146,7 @@ sub new {
# buttons
{
$self->{btn_connect} = my $btn = Wx::Button->new($box, -1, "Connect to printer", wxDefaultPosition, [-1, 40]);
$self->{btn_connect} = my $btn = Wx::Button->new($self, -1, "Connect to printer", wxDefaultPosition, [-1, 40]);
my $font = $btn->GetFont;
$font->SetPointSize($font->GetPointSize + 2);
$btn->SetFont($font);
@ -157,12 +165,12 @@ sub new {
}
# status
$self->{status_text} = Wx::StaticText->new($box, -1, "", wxDefaultPosition, [200,-1]);
$self->{status_text} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, [200,-1]);
$left_sizer->Add($self->{status_text}, 1, wxEXPAND | wxTOP, 15);
# manual control
{
$self->{btn_manual_control} = my $btn = Wx::Button->new($box, -1, "Manual control", wxDefaultPosition, wxDefaultSize);
$self->{btn_manual_control} = my $btn = Wx::Button->new($self, -1, "Manual control", wxDefaultPosition, wxDefaultSize);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("cog.png"), wxBITMAP_TYPE_PNG));
@ -170,15 +178,16 @@ sub new {
$btn->Hide;
$left_sizer->Add($btn, 0, wxTOP, 15);
EVT_BUTTON($self, $btn, sub {
my $dlg = Slic3r::GUI::Controller::ManualControlDialog->new
($self, $self->config, $self->sender);
$self->{manual_control_dialog} = my $dlg = Slic3r::GUI::Controller::ManualControlDialog->new
($self, $self->config, $self->sender, $self->manual_control_config);
$dlg->ShowModal;
undef $self->{manual_control_dialog};
});
}
# temperature
{
my $temp_panel = $self->{temp_panel} = Wx::Panel->new($box, -1);
my $temp_panel = $self->{temp_panel} = Wx::Panel->new($self, -1);
my $temp_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
my $temp_font = Wx::Font->new($Slic3r::GUI::small_font);
@ -211,11 +220,11 @@ sub new {
# print jobs panel
$self->{print_jobs_sizer} = my $print_jobs_sizer = Wx::BoxSizer->new(wxVERTICAL);
{
my $text = Wx::StaticText->new($box, -1, "Queue:", wxDefaultPosition, wxDefaultSize);
my $text = Wx::StaticText->new($self, -1, "Queue:", wxDefaultPosition, wxDefaultSize);
$text->SetFont($Slic3r::GUI::small_font);
$print_jobs_sizer->Add($text, 0, wxEXPAND, 0);
$self->{jobs_panel} = Wx::ScrolledWindow->new($box, -1, wxDefaultPosition, wxDefaultSize,
$self->{jobs_panel} = Wx::ScrolledWindow->new($self, -1, wxDefaultPosition, wxDefaultSize,
wxVSCROLL | wxBORDER_NONE);
$self->{jobs_panel}->SetScrollbars(0, 1, 0, 1);
$self->{jobs_panel_sizer} = Wx::BoxSizer->new(wxVERTICAL);
@ -239,13 +248,13 @@ sub new {
my $log_sizer = Wx::BoxSizer->new(wxVERTICAL);
{
my $text = Wx::StaticText->new($box, -1, "Log:", wxDefaultPosition, wxDefaultSize);
my $text = Wx::StaticText->new($self, -1, "Log:", wxDefaultPosition, wxDefaultSize);
$text->SetFont($Slic3r::GUI::small_font);
$log_sizer->Add($text, 0, wxEXPAND, 0);
my $log = $self->{log_textctrl} = Wx::TextCtrl->new($box, -1, "", wxDefaultPosition, wxDefaultSize,
my $log = $self->{log_textctrl} = Wx::TextCtrl->new($self, -1, "", wxDefaultPosition, wxDefaultSize,
wxTE_MULTILINE | wxBORDER_NONE);
$log->SetBackgroundColour($box->GetBackgroundColour);
$log->SetBackgroundColour($self->GetBackgroundColour);
$log->SetFont($Slic3r::GUI::small_font);
$log->SetEditable(0);
$log_sizer->Add($self->{log_textctrl}, 1, wxEXPAND, 0);

View File

@ -249,7 +249,7 @@ sub _init_menubar {
$self->_append_menu_item($self->{plater_menu}, "Export plate as STL...", 'Export current plate as STL', sub {
$plater->export_stl;
}, undef, 'brick_go.png');
$self->_append_menu_item($self->{plater_menu}, "Export plate as AMF...", 'Export current plate as AMF', sub {
$self->_append_menu_item($self->{plater_menu}, "Export plate with modifiers as AMF...", 'Export current plate as AMF, including all modifier meshes', sub {
$plater->export_amf;
}, undef, 'brick_go.png');
$self->_append_menu_item($self->{plater_menu}, "Open DLP Projector…\tCtrl+L", 'Open projector window for DLP printing', sub {
@ -303,6 +303,32 @@ sub _init_menubar {
$self->_append_menu_item($self->{viewMenu}, "Rear" , 'Rear View' , sub { $self->select_view('rear' ); });
$self->_append_menu_item($self->{viewMenu}, "Left" , 'Left View' , sub { $self->select_view('left' ); });
$self->_append_menu_item($self->{viewMenu}, "Right" , 'Right View' , sub { $self->select_view('right' ); });
$self->{viewMenu}->AppendSeparator();
$self->{color_toolpaths_by_role} = $self->_append_menu_item($self->{viewMenu},
"Color Toolpaths by Role",
'Color toolpaths according to perimeter/infill/support material',
sub {
$Slic3r::GUI::Settings->{_}{color_toolpaths_by} = 'role';
wxTheApp->save_settings;
$self->{plater}{preview3D}->reload_print;
},
undef, undef, wxITEM_RADIO
);
$self->{color_toolpaths_by_extruder} = $self->_append_menu_item($self->{viewMenu},
"Color Toolpaths by Filament",
'Color toolpaths using the configured extruder/filament color',
sub {
$Slic3r::GUI::Settings->{_}{color_toolpaths_by} = 'extruder';
wxTheApp->save_settings;
$self->{plater}{preview3D}->reload_print;
},
undef, undef, wxITEM_RADIO
);
if ($Slic3r::GUI::Settings->{_}{color_toolpaths_by} eq 'role') {
$self->{color_toolpaths_by_role}->Check(1);
} else {
$self->{color_toolpaths_by_extruder}->Check(1);
}
}
# Help menu
@ -415,11 +441,7 @@ sub quick_slice {
$sprint->apply_config($config);
$sprint->set_model($model);
{
my $extra = $self->extra_variables;
$sprint->placeholder_parser->set($_, $extra->{$_}) for keys %$extra;
}
# FIXME: populate placeholders (preset names etc.)
# select output file
my $output_file;
@ -804,10 +826,10 @@ sub select_view {
}
sub _append_menu_item {
my ($self, $menu, $string, $description, $cb, $id, $icon) = @_;
my ($self, $menu, $string, $description, $cb, $id, $icon, $kind) = @_;
$id //= &Wx::NewId();
my $item = $menu->Append($id, $string, $description);
my $item = $menu->Append($id, $string, $description, $kind);
$self->_set_menu_item_icon($item, $icon);
EVT_MENU($self, $id, $cb);

View File

@ -282,6 +282,9 @@ has 'widget' => (is => 'rw');
has '_options' => (is => 'ro', default => sub { [] });
has '_extra_widgets' => (is => 'ro', default => sub { [] });
use Wx qw(:button :misc :bitmap);
use Wx::Event qw(EVT_BUTTON);
# this method accepts a Slic3r::GUI::OptionsGroup::Option object
sub append_option {
my ($self, $option) = @_;
@ -293,6 +296,26 @@ sub append_widget {
push @{$self->_extra_widgets}, $widget;
}
sub append_button {
my ($self, $text, $icon, $cb, $ref, $disable) = @_;
$self->append_widget(sub {
my ($parent) = @_;
my $btn = Wx::Button->new($parent, -1,
$text, wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->($icon), wxBITMAP_TYPE_PNG));
}
$btn->Disable if $disable;
$$ref = $btn if $ref;
EVT_BUTTON($parent, $btn, $cb);
return $btn;
});
}
sub get_options {
my ($self) = @_;
return [ @{$self->_options} ];
@ -338,7 +361,7 @@ has 'full_labels' => (is => 'ro', default => sub { 0 });
has '_opt_map' => (is => 'ro', default => sub { {} });
sub get_option {
my ($self, $opt_key, $opt_index) = @_;
my ($self, $opt_key, $opt_index, %params) = @_;
$opt_index //= -1;
@ -369,24 +392,25 @@ sub get_option {
labels => $optdef->{labels},
values => $optdef->{values},
readonly => $optdef->{readonly},
%params,
);
}
sub create_single_option_line {
my ($self, $opt_key, $opt_index) = @_;
my ($self, $opt_key, $opt_index, %params) = @_;
my $option;
if (ref($opt_key)) {
$option = $opt_key;
} else {
$option = $self->get_option($opt_key, $opt_index);
$option = $self->get_option($opt_key, $opt_index, %params);
}
return $self->SUPER::create_single_option_line($option);
}
sub append_single_option_line {
my ($self, $option, $opt_index) = @_;
return $self->append_line($self->create_single_option_line($option, $opt_index));
my ($self, $option, $opt_index, %params) = @_;
return $self->append_line($self->create_single_option_line($option, $opt_index, %params));
}
sub reload_config {

View File

@ -548,11 +548,16 @@ sub BUILD {
EVT_TEXT($self->parent, $textctrl, sub {
my $value = $textctrl->GetValue;
if ($value =~ /^-?\d+(\.\d*)?$/) {
$self->set_value($value);
# Update the slider without re-updating the text field being modified.
$self->disable_change_event(1);
$self->slider->SetValue($value*$self->scale);
$self->disable_change_event(0);
$self->_on_change($self->option->opt_id);
}
});
EVT_KILL_FOCUS($textctrl, sub {
$self->_update_textctrl;
$self->_on_kill_focus($self->option->opt_id, @_);
});
}
@ -573,7 +578,9 @@ sub get_value {
sub _update_textctrl {
my ($self) = @_;
$self->textctrl->SetLabel($self->get_value);
$self->textctrl->ChangeValue($self->get_value);
$self->textctrl->SetInsertionPointEnd;
}
sub enable {

View File

@ -14,7 +14,7 @@ use Wx qw(:button :cursor :dialog :filedialog :keycode :icon :font :id :listctrl
:panel :sizer :toolbar :window wxTheApp :notebook :combobox);
use Wx::Event qw(EVT_BUTTON EVT_COMMAND EVT_KEY_DOWN EVT_LIST_ITEM_ACTIVATED
EVT_LIST_ITEM_DESELECTED EVT_LIST_ITEM_SELECTED EVT_MOUSE_EVENTS EVT_PAINT EVT_TOOL
EVT_CHOICE EVT_COMBOBOX EVT_TIMER EVT_NOTEBOOK_PAGE_CHANGED EVT_CLOSE);
EVT_CHOICE EVT_COMBOBOX EVT_TIMER EVT_NOTEBOOK_PAGE_CHANGED EVT_LEFT_UP EVT_CLOSE);
use base 'Wx::Panel';
use constant TB_ADD => &Wx::NewId;
@ -51,7 +51,7 @@ sub new {
my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
$self->{config} = Slic3r::Config->new_from_defaults(qw(
bed_shape complete_objects extruder_clearance_radius skirts skirt_distance brim_width
serial_port serial_speed octoprint_host octoprint_apikey
serial_port serial_speed octoprint_host octoprint_apikey filament_colour
));
$self->{model} = Slic3r::Model->new;
$self->{print} = Slic3r::Print->new;
@ -91,7 +91,7 @@ sub new {
$menu->Destroy;
};
my $on_instances_moved = sub {
$self->update;
$self->on_model_change;
};
# Initialize 3D plater
@ -143,6 +143,7 @@ sub new {
$self->stop_background_process;
$self->statusbar->SetStatusText("Slicing cancelled");
$self->{preview_notebook}->SetSelection(0);
});
$self->start_background_process;
} else {
@ -256,34 +257,13 @@ sub new {
EVT_BUTTON($self, $self->{btn_print}, sub {
$self->{print_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir());
});
EVT_BUTTON($self, $self->{btn_send_gcode}, sub {
my $filename = basename($self->{print}->output_filepath($main::opt{output} // ''));
$filename = Wx::GetTextFromUser("Save to printer with the following name:",
"OctoPrint", $filename, $self);
EVT_LEFT_UP($self->{btn_send_gcode}, sub {
my (undef, $e) = @_;
my $process_dialog = Wx::ProgressDialog->new('Querying OctoPrint…', "Checking whether file already exists…", 100, $self, 0);
$process_dialog->Pulse;
my $ua = LWP::UserAgent->new;
$ua->timeout(5);
my $res = $ua->get("http://" . $self->{config}->octoprint_host . "/api/files/local");
$process_dialog->Destroy;
if ($res->is_success) {
if ($res->decoded_content =~ /"name":\s*"\Q$filename\E"/) {
my $dialog = Wx::MessageDialog->new($self,
"It looks like a file with the same name already exists in the server. "
. "Shall I overwrite it?",
'OctoPrint', wxICON_WARNING | wxYES | wxNO);
return if $dialog->ShowModal() == wxID_NO;
}
}
my $dialog = Wx::MessageDialog->new($self,
"Shall I start the print after uploading the file?",
'OctoPrint', wxICON_QUESTION | wxYES | wxNO);
$self->{send_gcode_file_print} = ($dialog->ShowModal() == wxID_YES);
$self->{send_gcode_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir() . "/$filename");
my $alt = $e->AltDown;
wxTheApp->CallAfter(sub {
$self->prepare_send($alt);
});
});
EVT_BUTTON($self, $self->{btn_export_stl}, \&export_stl);
@ -367,7 +347,7 @@ sub new {
if ($self->{preview3D}) {
$self->{preview3D}->set_bed_shape($self->{config}->bed_shape);
}
$self->update;
$self->on_model_change;
{
my $presets;
@ -437,6 +417,34 @@ sub new {
}
}
}
my $print_info_sizer;
{
my $box = Wx::StaticBox->new($self, -1, "Print Summary");
$print_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
$print_info_sizer->SetMinSize([350,-1]);
my $grid_sizer = Wx::FlexGridSizer->new(2, 2, 5, 5);
$grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
$grid_sizer->AddGrowableCol(1, 1);
$grid_sizer->AddGrowableCol(3, 1);
$print_info_sizer->Add($grid_sizer, 0, wxEXPAND);
my @info = (
fil => "Used Filament",
cost => "Cost",
);
while (my $field = shift @info) {
my $label = shift @info;
my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
$text->SetFont($Slic3r::GUI::small_font);
$grid_sizer->Add($text, 0);
$self->{"print_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
$self->{"print_info_$field"}->SetFont($Slic3r::GUI::small_font);
$grid_sizer->Add($self->{"print_info_$field"}, 0);
}
$self->{"sliced_info_box"} = $print_info_sizer;
}
my $buttons_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$buttons_sizer->AddStretchSpacer(1);
@ -450,6 +458,9 @@ sub new {
$right_sizer->Add($buttons_sizer, 0, wxEXPAND | wxBOTTOM, 5);
$right_sizer->Add($self->{list}, 1, wxEXPAND, 5);
$right_sizer->Add($object_info_sizer, 0, wxEXPAND, 0);
$right_sizer->Add($print_info_sizer, 0, wxEXPAND, 0);
$right_sizer->Hide($print_info_sizer);
$self->{"right_sizer"} = $right_sizer;
my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
$hsizer->Add($self->{preview_notebook}, 1, wxEXPAND | wxTOP, 1);
@ -484,15 +495,14 @@ sub _on_select_preset {
$Slic3r::GUI::Settings->{presets}{"filament_${_}"} = $choice->GetString($filament_presets[$_])
for 1 .. $#filament_presets;
wxTheApp->save_settings;
return;
} else {
# call GetSelection() in scalar context as it's context-aware
$self->{on_select_preset}->($group, scalar $choice->GetSelection)
if $self->{on_select_preset};
}
# call GetSelection() in scalar context as it's context-aware
$self->{on_select_preset}->($group, scalar $choice->GetSelection)
if $self->{on_select_preset};
# get new config and generate on_config_change() event for updating plater and other things
$self->on_config_change($self->GetFrame->config);
# generate on_config_change() event for updating plater and other things
$self->on_config_change();
}
sub GetFrame {
@ -595,7 +605,7 @@ sub add_tin {
sub load_file {
my $self = shift;
my ($input_file) = @_;
my ($input_file, $obj_idx) = @_;
$Slic3r::GUI::Settings->{recent}{skein_directory} = dirname($input_file);
wxTheApp->save_settings;
@ -620,7 +630,19 @@ sub load_file {
$model->convert_multipart_object;
}
}
@obj_idx = $self->load_model_objects(@{$model->objects});
if (defined $obj_idx) {
return () if $obj_idx >= $model->objects_count;
@obj_idx = $self->load_model_objects($model->get_object($obj_idx));
} else {
@obj_idx = $self->load_model_objects(@{$model->objects});
}
my $i = 0;
foreach my $obj_idx (@obj_idx) {
$self->{objects}[$obj_idx]->input_file($input_file);
$self->{objects}[$obj_idx]->input_file_obj_idx($i++);
}
$self->statusbar->SetStatusText("Loaded " . basename($input_file));
}
@ -655,6 +677,9 @@ sub load_model_objects {
# add a default instance and center object around origin
$o->center_around_origin; # also aligns object to Z = 0
$o->add_instance(offset => $bed_centerf);
} else {
# if object has defined positions we still need to ensure it's aligned to Z = 0
$o->align_to_ground;
}
{
@ -697,7 +722,7 @@ sub load_model_objects {
$self->make_thumbnail($obj_idx);
}
$self->arrange if $need_arrange;
$self->update;
$self->on_model_change;
# zoom to objects
$self->{canvas3D}->zoom_to_volumes
@ -707,8 +732,6 @@ sub load_model_objects {
$self->{list}->Select($obj_idx[-1], 1);
$self->object_list_changed;
$self->schedule_background_process;
return @obj_idx;
}
@ -742,8 +765,7 @@ sub remove {
$self->object_list_changed;
$self->select_object(undef);
$self->update;
$self->schedule_background_process;
$self->on_model_change;
}
sub reset {
@ -762,7 +784,7 @@ sub reset {
$self->object_list_changed;
$self->select_object(undef);
$self->update;
$self->on_model_change;
}
sub increase {
@ -787,9 +809,8 @@ sub increase {
if ($Slic3r::GUI::Settings->{_}{autocenter}) {
$self->arrange;
} else {
$self->update;
$self->on_model_change;
}
$self->schedule_background_process;
}
sub decrease {
@ -814,8 +835,7 @@ sub decrease {
$self->{list}->Select($obj_idx, 0);
$self->{list}->Select($obj_idx, 1);
}
$self->update;
$self->schedule_background_process;
$self->on_model_change;
}
sub set_number_of_copies {
@ -829,6 +849,7 @@ sub set_number_of_copies {
# prompt user
my $copies = Wx::GetNumberFromUser("", "Enter the number of copies of the selected object:", "Copies", $model_object->instances_count, 0, 1000, $self);
return if $copies == -1;
my $diff = $copies - $model_object->instances_count;
if ($diff == 0) {
# no variation
@ -887,8 +908,7 @@ sub rotate {
$self->{print}->add_model_object($model_object, $obj_idx);
$self->selection_changed; # refresh info (size etc.)
$self->update;
$self->schedule_background_process;
$self->on_model_change;
}
sub mirror {
@ -915,8 +935,7 @@ sub mirror {
$self->{print}->add_model_object($model_object, $obj_idx);
$self->selection_changed; # refresh info (size etc.)
$self->update;
$self->schedule_background_process;
$self->on_model_change;
}
sub changescale {
@ -970,7 +989,7 @@ sub changescale {
my $newsize = Wx::GetTextFromUser("Enter the new max size for the selected object:",
"Scale", $cursize, $self);
return if !$newsize || $newsize !~ /^\d*(?:\.\d*)?$/ || $newsize < 0;
$scale = $newsize / $cursize * 100;
$scale = $model_instance->scaling_factor * $newsize / $cursize * 100;
} else {
# max scale factor should be above 2540 to allow importing files exported in inches
# Wx::GetNumberFromUser() does not support decimal numbers
@ -997,8 +1016,7 @@ sub changescale {
$self->{print}->add_model_object($model_object, $obj_idx);
$self->selection_changed(1); # refresh info (size, volume etc.)
$self->update;
$self->schedule_background_process;
$self->on_model_change;
}
sub arrange {
@ -1011,7 +1029,7 @@ sub arrange {
# ignore arrange failures on purpose: user has visual feedback and we don't need to warn him
# when parts don't fit in print bed
$self->update(1);
$self->on_model_change(1);
}
sub split_object {
@ -1061,14 +1079,10 @@ sub split_object {
sub schedule_background_process {
my ($self) = @_;
$self->{processed} = 0;
warn 'schedule_background_process() is not supposed to be called when background processing is disabled'
if !$Slic3r::GUI::Settings->{_}{background_processing};
if (!$Slic3r::GUI::Settings->{_}{background_processing}) {
my $sel = $self->{preview_notebook}->GetSelection;
if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) {
$self->{preview_notebook}->SetSelection(0);
}
}
$self->{processed} = 0;
if (defined $self->{apply_config_timer}) {
$self->{apply_config_timer}->Start(PROCESS_DELAY, 1); # 1 = one shot
@ -1080,11 +1094,6 @@ sub schedule_background_process {
sub async_apply_config {
my ($self) = @_;
# reset preview canvases
$self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
$self->{preview3D}->reload_print if $self->{preview3D};
$self->{ObjectLayersDialog}->reload_preview if $self->{ObjectLayersDialog};
# pause process thread before applying new config
# since we don't want to touch data that is being used by the threads
$self->pause_background_process;
@ -1092,11 +1101,24 @@ sub async_apply_config {
# apply new config
my $invalidated = $self->{print}->apply_config($self->GetFrame->config);
return if !$Slic3r::GUI::Settings->{_}{background_processing};
# reset preview canvases (invalidated contents will be hidden)
$self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
$self->{preview3D}->reload_print if $self->{preview3D};
$self->{ObjectLayersDialog}->reload_preview if $self->{ObjectLayersDialog};
if ($invalidated) {
if (!$Slic3r::GUI::Settings->{_}{background_processing}) {
$self->hide_preview;
return;
}
# kill current thread if any
$self->stop_background_process;
# remove the sliced statistics box because something changed.
if ($self->{"right_sizer"}) {
$self->{"right_sizer"}->Hide($self->{"sliced_info_box"});
$self->{"right_sizer"}->Layout;
}
} else {
$self->resume_background_process;
}
@ -1127,6 +1149,10 @@ sub start_background_process {
return;
}
if ($Slic3r::GUI::Settings->{_}{threads}) {
$self->{print}->config->set('threads', $Slic3r::GUI::Settings->{_}{threads});
}
# start thread
@_ = ();
$self->{process_thread} = Slic3r::spawn_thread(sub {
@ -1277,6 +1303,8 @@ sub export_gcode {
# this updates buttons status
$self->object_list_changed;
$self->{"right_sizer"}->Show($self->{"sliced_info_box"});
$self->{"right_sizer"}->Layout;
return $self->{export_gcode_output_file};
}
@ -1373,6 +1401,22 @@ sub on_export_completed {
$self->{print_file} = undef;
$self->{send_gcode_file} = undef;
{
my $fil = sprintf(
'%.2fcm (%.2fcm³%s)',
$self->{print}->total_used_filament / 10,
$self->{print}->total_extruded_volume / 1000,
$self->{print}->total_weight
? sprintf(', %.2fg', $self->{print}->total_weight)
: '',
);
my $cost = $self->{print}->total_cost
? sprintf("%.2f" , $self->{print}->total_cost)
: 'n.a.';
$self->{print_info_fil}->SetLabel($fil);
$self->{print_info_cost}->SetLabel($cost);
}
# this updates buttons status
$self->object_list_changed;
}
@ -1394,6 +1438,52 @@ sub do_print {
$self->GetFrame->select_tab(1);
}
sub prepare_send {
my ($self, $skip_dialog) = @_;
return if !$self->{btn_send_gcode}->IsEnabled;
my $filename = basename($self->{print}->output_filepath($main::opt{output} // ''));
if (!$skip_dialog) {
# When the alt key is pressed, bypass the dialog.
my $dlg = Slic3r::GUI::Plater::OctoPrintSpoolDialog->new($self, $filename);
return unless $dlg->ShowModal == wxID_OK;
$filename = $dlg->{filename};
}
if (!$Slic3r::GUI::Settings->{octoprint}{overwrite}) {
my $progress = Wx::ProgressDialog->new('Querying OctoPrint…',
"Checking whether file already exists…", 100, $self, 0);
$progress->Pulse;
my $ua = LWP::UserAgent->new;
$ua->timeout(5);
my $res = $ua->get(
"http://" . $self->{config}->octoprint_host . "/api/files/local",
'X-Api-Key' => $self->{config}->octoprint_apikey,
);
$progress->Destroy;
if ($res->is_success) {
if ($res->decoded_content =~ /"name":\s*"\Q$filename\E"/) {
my $dialog = Wx::MessageDialog->new($self,
"It looks like a file with the same name already exists in the server. "
. "Shall I overwrite it?",
'OctoPrint', wxICON_WARNING | wxYES | wxNO);
if ($dialog->ShowModal() == wxID_NO) {
return;
}
}
} else {
my $message = "Error while connecting to the OctoPrint server: " . $res->status_line;
Slic3r::GUI::show_error($self, $message);
return;
}
}
$self->{send_gcode_file_print} = $Slic3r::GUI::Settings->{octoprint}{start};
$self->{send_gcode_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir() . "/" . $filename);
}
sub send_gcode {
my ($self) = @_;
@ -1442,13 +1532,14 @@ sub reload_from_disk {
my ($obj_idx, $object) = $self->selected_object;
return if !defined $obj_idx;
my $model_object = $self->{model}->objects->[$obj_idx];
return if !$model_object->input_file
|| !-e $model_object->input_file;
return if !$object->input_file
|| !-e $object->input_file;
my @new_obj_idx = $self->load_file($model_object->input_file);
# Only reload the selected object and not all objects from the input file.
my @new_obj_idx = $self->load_file($object->input_file, $object->input_file_obj_idx);
return if !@new_obj_idx;
my $model_object = $self->{model}->objects->[$obj_idx];
foreach my $new_obj_idx (@new_obj_idx) {
my $o = $self->{model}->objects->[$new_obj_idx];
$o->clear_instances;
@ -1463,6 +1554,8 @@ sub reload_from_disk {
$self->remove($obj_idx);
# TODO: refresh object list which contains wrong count and scale
# Trigger thumbnail generation again, because the remove() method altered
# object indexes before background thumbnail generation called its completion
# event, so the on_thumbnail_made callback is called with the wrong $obj_idx.
@ -1483,6 +1576,23 @@ sub export_object_stl {
$self->statusbar->SetStatusText("STL file exported to $output_file");
}
# Export function for a single AMF output
sub export_object_amf {
my $self = shift;
my ($obj_idx, $object) = $self->selected_object;
return if !defined $obj_idx;
my $local_model = Slic3r::Model->new;
my $model_object = $self->{model}->objects->[$obj_idx];
# copy model_object -> local_model
$local_model->add_object($model_object);
my $output_file = $self->_get_export_file('AMF') or return;
$local_model->write_amf($output_file);
$self->statusbar->SetStatusText("AMF file exported to $output_file");
}
sub export_amf {
my $self = shift;
@ -1497,14 +1607,21 @@ sub _get_export_file {
my $self = shift;
my ($format) = @_;
my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml';
my $suffix = $format eq 'STL' ? '.stl' : '.amf';
my $output_file = $main::opt{output};
{
$output_file = $self->{print}->output_filepath($output_file // '');
$output_file =~ s/\.gcode$/$suffix/i;
my $dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
basename($output_file), &Slic3r::GUI::MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
my $dlg;
$dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
basename($output_file), &Slic3r::GUI::STL_MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT)
if $format eq 'STL';
$dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
basename($output_file), &Slic3r::GUI::AMF_MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT)
if $format eq 'AMF';
if ($dlg->ShowModal != wxID_OK) {
$dlg->Destroy;
return undef;
@ -1549,27 +1666,46 @@ sub on_thumbnail_made {
# this method gets called whenever print center is changed or the objects' bounding box changes
# (i.e. when an object is added/removed/moved/rotated/scaled)
sub update {
sub on_model_change {
my ($self, $force_autocenter) = @_;
my $running = $self->pause_background_process;
if ($Slic3r::GUI::Settings->{_}{autocenter} || $force_autocenter) {
$self->{model}->center_instances_around_point($self->bed_centerf);
}
$self->refresh_canvases;
my $running = $self->pause_background_process;
my $invalidated = $self->{print}->reload_model_instances();
# The mere fact that no steps were invalidated when reloading model instances
# doesn't mean that all steps were done: for example, validation might have
# failed upon previous instance move, so we have no running thread and no steps
# are invalidated on this move, thus we need to schedule a new run.
if ($invalidated || !$running) {
$self->schedule_background_process;
if ($Slic3r::GUI::Settings->{_}{background_processing}) {
if ($invalidated || !$running) {
# The mere fact that no steps were invalidated when reloading model instances
# doesn't mean that all steps were done: for example, validation might have
# failed upon previous instance move, so we have no running thread and no steps
# are invalidated on this move, thus we need to schedule a new run.
$self->schedule_background_process;
if ($self->{"right_sizer"}) {
$self->{"right_sizer"}->Hide($self->{"sliced_info_box"});
$self->{"right_sizer"}->Layout;
}
} else {
$self->resume_background_process;
}
} else {
$self->resume_background_process;
$self->hide_preview;
}
}
sub hide_preview {
my ($self) = @_;
$self->refresh_canvases;
my $sel = $self->{preview_notebook}->GetSelection;
if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) {
$self->{preview_notebook}->SetSelection(0);
}
$self->{processed} = 0;
}
sub on_extruders_change {
@ -1616,8 +1752,14 @@ sub on_extruders_change {
sub on_config_change {
my $self = shift;
my ($config) = @_;
my $config = $self->GetFrame->config;
if ($Slic3r::GUI::autosave) {
$config->save($Slic3r::GUI::autosave);
}
# Apply changes to the plater-specific config options.
foreach my $opt_key (@{$self->{config}->diff($config)}) {
$self->{config}->set($opt_key, $config->get($opt_key));
if ($opt_key eq 'bed_shape') {
@ -1625,7 +1767,7 @@ sub on_config_change {
$self->{canvas3D}->update_bed_size if $self->{canvas3D};
$self->{preview3D}->set_bed_shape($self->{config}->bed_shape)
if $self->{preview3D};
$self->update;
$self->on_model_change;
} elsif ($opt_key eq 'serial_port') {
if ($config->get('serial_port')) {
$self->{btn_print}->Show;
@ -1643,10 +1785,19 @@ sub on_config_change {
}
}
if ($self->{"right_sizer"}) {
$self->{"right_sizer"}->Hide($self->{"sliced_info_box"});
$self->{"right_sizer"}->Layout;
}
return if !$self->GetFrame->is_loaded;
# (re)start timer
$self->schedule_background_process;
if ($Slic3r::GUI::Settings->{_}{background_processing}) {
# (re)start timer
$self->schedule_background_process;
} else {
$self->async_apply_config;
}
}
sub list_item_deselected {
@ -1765,7 +1916,7 @@ sub object_settings_dialog {
if ($dlg->PartsChanged || $dlg->PartSettingsChanged) {
$self->stop_background_process;
$self->{print}->reload_object($obj_idx);
$self->schedule_background_process;
$self->on_model_change;
} else {
$self->resume_background_process;
}
@ -1875,6 +2026,7 @@ sub selected_object {
sub refresh_canvases {
my ($self) = @_;
$self->{canvas}->Refresh;
$self->{canvas3D}->update if $self->{canvas3D};
$self->{preview3D}->reload_print if $self->{preview3D};
@ -1998,6 +2150,9 @@ sub object_menu {
$frame->_append_menu_item($menu, "Export object as STL…", 'Export this single object as STL file', sub {
$self->export_object_stl;
}, undef, 'brick_go.png');
$frame->_append_menu_item($menu, "Export object and modifiers as AMF…", 'Export this single object and all associated modifiers as AMF file', sub {
$self->export_object_amf;
}, undef, 'brick_go.png');
return $menu;
}
@ -2050,6 +2205,8 @@ use List::Util qw(first);
use Slic3r::Geometry qw(X Y Z MIN MAX deg2rad);
has 'name' => (is => 'rw', required => 1);
has 'input_file' => (is => 'rw');
has 'input_file_obj_idx' => (is => 'rw');
has 'thumbnail' => (is => 'rw'); # ExPolygon::Collection in scaled model units with no transforms
has 'transformed_thumbnail' => (is => 'rw');
has 'instance_thumbnails' => (is => 'ro', default => sub { [] }); # array of ExPolygon::Collection objects, each one representing the actual placed thumbnail of each instance in pixel units
@ -2095,4 +2252,73 @@ sub transform_thumbnail {
$self->transformed_thumbnail($t);
}
package Slic3r::GUI::Plater::OctoPrintSpoolDialog;
use Wx qw(:dialog :id :misc :sizer :icon wxTheApp);
use Wx::Event qw(EVT_BUTTON EVT_TEXT_ENTER);
use base 'Wx::Dialog';
sub new {
my $class = shift;
my ($parent, $filename) = @_;
my $self = $class->SUPER::new($parent, -1, "Send to OctoPrint", wxDefaultPosition,
[400, -1]);
$self->{filename} = $filename;
$Slic3r::GUI::Settings->{octoprint} //= {};
my $optgroup;
$optgroup = Slic3r::GUI::OptionsGroup->new(
parent => $self,
title => 'Send to OctoPrint',
on_change => sub {
my ($opt_id) = @_;
if ($opt_id eq 'filename') {
$self->{filename} = $optgroup->get_value($opt_id);
} else {
$Slic3r::GUI::Settings->{octoprint}{$opt_id} = $optgroup->get_value($opt_id);
}
},
label_width => 200,
);
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'filename',
type => 's',
label => 'File name',
width => 200,
tooltip => 'The name used for labelling the print job.',
default => $filename,
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'overwrite',
type => 'bool',
label => 'Overwrite existing file',
tooltip => 'If selected, any existing file with the same name will be overwritten without confirmation.',
default => $Slic3r::GUI::Settings->{octoprint}{overwrite} // 0,
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'start',
type => 'bool',
label => 'Start print',
tooltip => 'If selected, print will start after the upload.',
default => $Slic3r::GUI::Settings->{octoprint}{start} // 0,
));
my $sizer = Wx::BoxSizer->new(wxVERTICAL);
$sizer->Add($optgroup->sizer, 0, wxEXPAND | wxTOP | wxBOTTOM | wxLEFT | wxRIGHT, 10);
my $buttons = $self->CreateStdDialogButtonSizer(wxOK | wxCANCEL);
$sizer->Add($buttons, 0, wxEXPAND | wxBOTTOM | wxLEFT | wxRIGHT, 10);
EVT_BUTTON($self, wxID_OK, sub {
wxTheApp->save_settings;
$self->EndModal(wxID_OK);
$self->Close; # needed on Linux
});
$self->SetSizer($sizer);
$sizer->SetSizeHints($self);
return $self;
}
1;

View File

@ -179,7 +179,10 @@ sub new {
my $old_zoom = $self->_zoom;
# Calculate the zoom delta and apply it to the current zoom factor
my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
my $zoom = -$e->GetWheelRotation() / $e->GetWheelDelta();
if ($Slic3r::GUI::Settings->{_}{invert_zoom}) {
$zoom *= -1;
}
$zoom = max(min($zoom, 4), -4);
$zoom /= 10;
$self->_zoom($self->_zoom / (1-$zoom));

View File

@ -117,6 +117,16 @@ sub load_print {
}
if ($self->IsShown) {
# set colors
$self->canvas->color_toolpaths_by($Slic3r::GUI::Settings->{_}{color_toolpaths_by});
if ($self->canvas->color_toolpaths_by eq 'extruder') {
my @filament_colors = map { s/^#//; [ map $_/255, (unpack 'C*', pack 'H*', $_), 255 ] }
@{$self->print->config->filament_colour};
$self->canvas->colors->[$_] = $filament_colors[$_] for 0..$#filament_colors;
} else {
$self->canvas->colors([ $self->canvas->default_colors ]);
}
# load skirt and brim
$self->canvas->load_print_toolpaths($self->print);

View File

@ -77,7 +77,7 @@ sub new {
{
my $label = Wx::StaticText->new($self, -1, "You can use this section to override the default layer height for parts of this object. Set layer height to zero to skip portions of the input file.",
wxDefaultPosition, [-1, 40]);
wxDefaultPosition, wxDefaultSize);
$label->SetFont(Wx::SystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
$sizer->Add($label, 0, wxEXPAND | wxALL, 10);
}
@ -90,7 +90,7 @@ sub new {
$grid->SetColLabelValue(0, "Min Z (mm)");
$grid->SetColLabelValue(1, "Max Z (mm)");
$grid->SetColLabelValue(2, "Layer height (mm)");
$grid->SetColSize($_, 135) for 0..2;
$grid->SetColSize($_, -1) for 0..2;
$grid->SetDefaultCellAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
# load data

View File

@ -52,6 +52,13 @@ sub new {
tooltip => 'If this is enabled, Slic3r will auto-center objects around the print bed center.',
default => $Slic3r::GUI::Settings->{_}{autocenter},
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'invert_zoom',
type => 'bool',
label => 'Invert zoom in previews',
tooltip => 'If this is enabled, Slic3r will invert the direction of mouse-wheel zoom in preview panes.',
default => $Slic3r::GUI::Settings->{_}{invert_zoom},
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'background_processing',
type => 'bool',
@ -60,6 +67,13 @@ sub new {
default => $Slic3r::GUI::Settings->{_}{background_processing},
readonly => !$Slic3r::have_threads,
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'threads',
type => 'i',
label => 'Threads',
tooltip => $Slic3r::Config::Options->{threads}{tooltip},
default => $Slic3r::GUI::Settings->{_}{threads},
));
$optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new(
opt_id => 'no_controller',
type => 'bool',

View File

@ -74,33 +74,20 @@ sub new {
return $btn;
});
my $serial_test = sub {
my ($parent) = @_;
my $btn = $self->{serial_test_btn} = Wx::Button->new($parent, -1,
"Test", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("wrench.png"), wxBITMAP_TYPE_PNG));
}
EVT_BUTTON($self, $btn, sub {
my $sender = Slic3r::GCode::Sender->new;
my $res = $sender->connect(
$self->{config}->serial_port,
$self->{config}->serial_speed,
);
if ($res && $sender->wait_connected) {
Slic3r::GUI::show_info($self, "Connection to printer works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self, "Connection failed.");
}
});
return $btn;
};
$line->append_option($serial_port);
$line->append_option($optgroup->get_option('serial_speed'));
$line->append_widget($serial_test);
$line->append_button("Test", "wrench.png", sub {
my $sender = Slic3r::GCode::Sender->new;
my $res = $sender->connect(
$self->{config}->serial_port,
$self->{config}->serial_speed,
);
if ($res && $sender->wait_connected) {
Slic3r::GUI::show_info($self, "Connection to printer works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self, "Connection failed.");
}
}, \$self->{serial_test_btn});
$optgroup->append_line($line);
}
}

View File

@ -122,7 +122,7 @@ sub build {
$self->init_config_options(qw(
layer_height perimeters top_solid_layers bottom_solid_layers
fill_density fill_pattern external_fill_pattern
fill_density fill_pattern top_infill_pattern bottom_infill_pattern
support_material support_material_spacing raft_layers
support_material_contact_distance dont_support_bridges
perimeter_speed infill_speed travel_speed
@ -147,7 +147,8 @@ sub build {
my $optgroup = $self->new_optgroup('Infill');
$optgroup->append_single_option_line('fill_density');
$optgroup->append_single_option_line('fill_pattern');
$optgroup->append_single_option_line('external_fill_pattern');
$optgroup->append_single_option_line('top_infill_pattern');
$optgroup->append_single_option_line('bottom_infill_pattern');
}
{
@ -191,7 +192,7 @@ sub _update {
$self->get_field($_)->toggle($have_infill)
for qw(fill_pattern);
$self->get_field($_)->toggle($have_solid_infill)
for qw(external_fill_pattern);
for qw(top_infill_pattern bottom_infill_pattern);
$self->get_field($_)->toggle($have_infill || $have_solid_infill)
for qw(infill_speed);

View File

@ -461,13 +461,13 @@ sub build {
my $self = shift;
$self->init_config_options(qw(
adaptive_slicing adaptive_slicing_quality adaptive_slicing_z_gradation match_horizontal_surfaces
adaptive_slicing adaptive_slicing_quality match_horizontal_surfaces
layer_height first_layer_height
perimeters spiral_vase
top_solid_layers bottom_solid_layers
extra_perimeters avoid_crossing_perimeters thin_walls overhangs
seam_position external_perimeters_first
fill_density fill_pattern external_fill_pattern fill_gaps
fill_density fill_pattern top_infill_pattern bottom_infill_pattern fill_gaps
infill_every_layers infill_only_where_needed
solid_infill_every_layers fill_angle solid_infill_below_area
only_retract_when_crossing_perimeters infill_first
@ -480,10 +480,10 @@ sub build {
perimeter_acceleration infill_acceleration bridge_acceleration
first_layer_acceleration default_acceleration
skirts skirt_distance skirt_height min_skirt_length
brim_connections_width brim_width
brim_connections_width brim_width interior_brim_width
support_material support_material_threshold support_material_enforce_layers
raft_layers
support_material_pattern support_material_spacing support_material_angle
support_material_pattern support_material_spacing support_material_angle
support_material_interface_layers support_material_interface_spacing
support_material_contact_distance dont_support_bridges
notes
@ -498,7 +498,7 @@ sub build {
external_perimeter_extrusion_width infill_extrusion_width solid_infill_extrusion_width
top_infill_extrusion_width support_material_extrusion_width
infill_overlap bridge_flow_ratio
xy_size_compensation threads resolution
xy_size_compensation resolution
));
$self->{config}->set('print_settings_id', '');
@ -510,7 +510,6 @@ sub build {
$optgroup->append_single_option_line('first_layer_height');
$optgroup->append_single_option_line('adaptive_slicing');
$optgroup->append_single_option_line('adaptive_slicing_quality');
$optgroup->append_single_option_line('adaptive_slicing_z_gradation');
$optgroup->append_single_option_line('match_horizontal_surfaces');
}
{
@ -547,7 +546,14 @@ sub build {
my $optgroup = $page->new_optgroup('Infill');
$optgroup->append_single_option_line('fill_density');
$optgroup->append_single_option_line('fill_pattern');
$optgroup->append_single_option_line('external_fill_pattern');
{
my $line = Slic3r::GUI::OptionsGroup::Line->new(
label => 'External infill pattern',
);
$line->append_option($optgroup->get_option('top_infill_pattern'));
$line->append_option($optgroup->get_option('bottom_infill_pattern'));
$optgroup->append_line($line);
}
}
{
my $optgroup = $page->new_optgroup('Reducing printing time');
@ -577,6 +583,7 @@ sub build {
{
my $optgroup = $page->new_optgroup('Brim');
$optgroup->append_single_option_line('brim_width');
$optgroup->append_single_option_line('interior_brim_width');
$optgroup->append_single_option_line('brim_connections_width');
}
}
@ -609,16 +616,12 @@ sub build {
my $page = $self->add_options_page('Speed', 'time.png');
{
my $optgroup = $page->new_optgroup('Speed for print moves');
$optgroup->append_single_option_line('perimeter_speed');
$optgroup->append_single_option_line('small_perimeter_speed');
$optgroup->append_single_option_line('external_perimeter_speed');
$optgroup->append_single_option_line('infill_speed');
$optgroup->append_single_option_line('solid_infill_speed');
$optgroup->append_single_option_line('top_solid_infill_speed');
$optgroup->append_single_option_line('gap_fill_speed');
$optgroup->append_single_option_line('support_material_speed');
$optgroup->append_single_option_line('support_material_interface_speed');
$optgroup->append_single_option_line('bridge_speed');
$optgroup->append_single_option_line($_, undef, width => 100)
for qw(perimeter_speed small_perimeter_speed external_perimeter_speed
infill_speed solid_infill_speed top_solid_infill_speed
gap_fill_speed bridge_speed
support_material_speed support_material_interface_speed
);
}
{
my $optgroup = $page->new_optgroup('Speed for non-print moves');
@ -670,14 +673,11 @@ sub build {
my $optgroup = $page->new_optgroup('Extrusion width',
label_width => 180,
);
$optgroup->append_single_option_line('extrusion_width');
$optgroup->append_single_option_line('first_layer_extrusion_width');
$optgroup->append_single_option_line('perimeter_extrusion_width');
$optgroup->append_single_option_line('external_perimeter_extrusion_width');
$optgroup->append_single_option_line('infill_extrusion_width');
$optgroup->append_single_option_line('solid_infill_extrusion_width');
$optgroup->append_single_option_line('top_infill_extrusion_width');
$optgroup->append_single_option_line('support_material_extrusion_width');
$optgroup->append_single_option_line($_, undef, width => 100)
for qw(extrusion_width first_layer_extrusion_width
perimeter_extrusion_width external_perimeter_extrusion_width
infill_extrusion_width solid_infill_extrusion_width
top_infill_extrusion_width support_material_extrusion_width);
}
{
my $optgroup = $page->new_optgroup('Overlap');
@ -690,7 +690,6 @@ sub build {
{
my $optgroup = $page->new_optgroup('Other');
$optgroup->append_single_option_line('xy_size_compensation');
$optgroup->append_single_option_line('threads') if $Slic3r::have_threads;
$optgroup->append_single_option_line('resolution');
}
}
@ -750,14 +749,13 @@ sub _update {
my $config = $self->{config};
if ($config->spiral_vase && !($config->perimeters == 1 && $config->top_solid_layers == 0 && $config->fill_density == 0 && $config->infill_only_where_needed == 0 && $config->support_material == 0)) {
if ($config->spiral_vase && !($config->perimeters == 1 && $config->top_solid_layers == 0 && $config->fill_density == 0 && $config->support_material == 0)) {
my $dialog = Wx::MessageDialog->new($self,
"The Spiral Vase mode requires:\n"
. "- one perimeter\n"
. "- no top solid layers\n"
. "- 0% fill density\n"
. "- no support material\n"
. "- no infill where necessary\n"
. "\nShall I adjust those settings in order to enable Spiral Vase?",
'Spiral Vase', wxICON_WARNING | wxYES | wxNO);
if ($dialog->ShowModal() == wxID_YES) {
@ -766,7 +764,6 @@ sub _update {
$new_conf->set("top_solid_layers", 0);
$new_conf->set("fill_density", 0);
$new_conf->set("support_material", 0);
$new_conf->set("infill_only_where_needed", 0);
$self->load_config($new_conf);
} else {
my $new_conf = Slic3r::Config->new;
@ -805,7 +802,7 @@ sub _update {
}
if ($config->fill_density == 100
&& !first { $_ eq $config->fill_pattern } @{$Slic3r::Config::Options->{external_fill_pattern}{values}}) {
&& !first { $_ eq $config->fill_pattern } @{$Slic3r::Config::Options->{top_infill_pattern}{values}}) {
my $dialog = Wx::MessageDialog->new($self,
"The " . $config->fill_pattern . " infill pattern is not supposed to work at 100% density.\n"
. "\nShall I switch to rectilinear fill pattern?",
@ -828,7 +825,7 @@ sub _update {
my $have_adaptive_slicing = $config->adaptive_slicing;
$self->get_field($_)->toggle($have_adaptive_slicing)
for qw(adaptive_slicing_quality adaptive_slicing_z_gradation match_horizontal_surfaces);
for qw(adaptive_slicing_quality match_horizontal_surfaces);
$self->get_field($_)->toggle(!$have_adaptive_slicing)
for qw(layer_height);
@ -841,8 +838,8 @@ sub _update {
my $have_solid_infill = ($config->top_solid_layers > 0) || ($config->bottom_solid_layers > 0);
# solid_infill_extruder uses the same logic as in Print::extruders()
$self->get_field($_)->toggle($have_solid_infill)
for qw(external_fill_pattern infill_first solid_infill_extruder solid_infill_extrusion_width
solid_infill_speed);
for qw(top_infill_pattern bottom_infill_pattern infill_first solid_infill_extruder
solid_infill_extrusion_width solid_infill_speed);
$self->get_field($_)->toggle($have_infill || $have_solid_infill)
for qw(fill_angle infill_extrusion_width infill_speed bridge_speed);
@ -868,17 +865,19 @@ sub _update {
$self->get_field($_)->toggle($have_skirt)
for qw(skirt_distance skirt_height);
my $have_brim = $config->brim_width > 0 || $config->brim_connections_width;
my $have_brim = $config->brim_width > 0 || $config->interior_brim_width
|| $config->brim_connections_width;
# perimeter_extruder uses the same logic as in Print::extruders()
$self->get_field('perimeter_extruder')->toggle($have_perimeters || $have_brim);
my $have_support_material = $config->support_material || $config->raft_layers > 0;
my $have_support_interface = $config->support_material_interface_layers > 0;
$self->get_field($_)->toggle($have_support_material)
for qw(support_material_threshold support_material_pattern
for qw(support_material_threshold support_material_pattern
support_material_spacing support_material_angle
support_material_interface_layers dont_support_bridges
support_material_extrusion_width support_material_contact_distance);
$self->get_field($_)->toggle($have_support_material && $have_support_interface)
for qw(support_material_interface_spacing support_material_interface_extruder
support_material_interface_speed);
@ -908,11 +907,12 @@ sub build {
my $self = shift;
$self->init_config_options(qw(
filament_colour filament_diameter filament_notes filament_max_volumetric_speed extrusion_multiplier
filament_colour filament_diameter filament_notes filament_max_volumetric_speed extrusion_multiplier filament_density filament_cost
temperature first_layer_temperature bed_temperature first_layer_bed_temperature
fan_always_on cooling
min_fan_speed max_fan_speed bridge_fan_speed disable_fan_first_layers
fan_below_layer_time slowdown_below_layer_time min_print_speed
start_filament_gcode end_filament_gcode
));
$self->{config}->set('filament_settings_id', '');
@ -924,7 +924,6 @@ sub build {
$optgroup->append_single_option_line('filament_diameter', 0);
$optgroup->append_single_option_line('extrusion_multiplier', 0);
}
{
my $optgroup = $page->new_optgroup('Temperature (°C)');
@ -946,6 +945,11 @@ sub build {
$optgroup->append_line($line);
}
}
{
my $optgroup = $page->new_optgroup('Optional information');
$optgroup->append_single_option_line('filament_density', 0);
$optgroup->append_single_option_line('filament_cost', 0);
}
}
{
@ -1010,6 +1014,27 @@ sub build {
$optgroup->append_single_option_line($option);
}
}
{
my $page = $self->add_options_page('Custom G-code', 'script.png');
{
my $optgroup = $page->new_optgroup('Start G-code',
label_width => 0,
);
my $option = $optgroup->get_option('start_filament_gcode', 0);
$option->full_width(1);
$option->height(150);
$optgroup->append_single_option_line($option);
}
{
my $optgroup = $page->new_optgroup('End G-code',
label_width => 0,
);
my $option = $optgroup->get_option('end_filament_gcode', 0);
$option->full_width(1);
$option->height(150);
$optgroup->append_single_option_line($option);
}
}
}
sub _update {
@ -1066,7 +1091,7 @@ sub build {
my (%params) = @_;
$self->init_config_options(qw(
bed_shape z_offset has_heatbed
bed_shape z_offset z_steps_per_mm has_heatbed
gcode_flavor use_relative_e_distances
serial_port serial_speed
octoprint_host octoprint_apikey
@ -1079,32 +1104,6 @@ sub build {
));
$self->{config}->set('printer_settings_id', '');
my $bed_shape_widget = sub {
my ($parent) = @_;
my $btn = Wx::Button->new($parent, -1, "Set…", wxDefaultPosition, wxDefaultSize,
wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("cog.png"), wxBITMAP_TYPE_PNG));
}
my $sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$sizer->Add($btn);
EVT_BUTTON($self, $btn, sub {
my $dlg = Slic3r::GUI::BedShapeDialog->new($self, $self->{config}->bed_shape);
if ($dlg->ShowModal == wxID_OK) {
my $value = $dlg->GetValue;
$self->{config}->set('bed_shape', $value);
$self->update_dirty;
$self->_on_value_change('bed_shape', $value);
}
});
return $sizer;
};
$self->{extruders_count} = 1;
{
@ -1113,9 +1112,17 @@ sub build {
my $optgroup = $page->new_optgroup('Size and coordinates');
my $line = Slic3r::GUI::OptionsGroup::Line->new(
label => 'Bed shape',
widget => $bed_shape_widget,
label => 'Bed shape',
);
$line->append_button("Set…", "cog.png", sub {
my $dlg = Slic3r::GUI::BedShapeDialog->new($self, $self->{config}->bed_shape);
if ($dlg->ShowModal == wxID_OK) {
my $value = $dlg->GetValue;
$self->{config}->set('bed_shape', $value);
$self->update_dirty;
$self->_on_value_change('bed_shape', $value);
}
});
$optgroup->append_line($line);
$optgroup->append_single_option_line('z_offset');
@ -1162,108 +1169,63 @@ sub build {
return $btn;
});
my $serial_test = sub {
my ($parent) = @_;
my $btn = $self->{serial_test_btn} = Wx::Button->new($parent, -1,
"Test", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("wrench.png"), wxBITMAP_TYPE_PNG));
}
EVT_BUTTON($self, $btn, sub {
my $sender = Slic3r::GCode::Sender->new;
my $res = $sender->connect(
$self->{config}->serial_port,
$self->{config}->serial_speed,
);
if ($res && $sender->wait_connected) {
Slic3r::GUI::show_info($self, "Connection to printer works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self, "Connection failed.");
}
});
return $btn;
};
$line->append_option($serial_port);
$line->append_option($optgroup->get_option('serial_speed'));
$line->append_widget($serial_test);
$line->append_button("Test", "wrench.png", sub {
my $sender = Slic3r::GCode::Sender->new;
my $res = $sender->connect(
$self->{config}->serial_port,
$self->{config}->serial_speed,
);
if ($res && $sender->wait_connected) {
Slic3r::GUI::show_info($self, "Connection to printer works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self, "Connection failed.");
}
}, \$self->{serial_test_btn});
$optgroup->append_line($line);
}
{
my $optgroup = $page->new_optgroup('OctoPrint upload');
# append two buttons to the Host line
my $octoprint_host_browse = sub {
my ($parent) = @_;
my $btn = Wx::Button->new($parent, -1, "Browse…", wxDefaultPosition, wxDefaultSize, wxBU_LEFT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("zoom.png"), wxBITMAP_TYPE_PNG));
}
if (!eval "use Net::Bonjour; 1") {
$btn->Disable;
}
EVT_BUTTON($self, $btn, sub {
# look for devices
my $entries;
{
my $res = Net::Bonjour->new('http');
$res->discover;
$entries = [ $res->entries ];
}
if (@{$entries}) {
my $dlg = Slic3r::GUI::BonjourBrowser->new($self, $entries);
if ($dlg->ShowModal == wxID_OK) {
my $value = $dlg->GetValue . ":" . $dlg->GetPort;
$self->{config}->set('octoprint_host', $value);
$self->update_dirty;
$self->_on_value_change('octoprint_host', $value);
$self->reload_config;
}
} else {
Wx::MessageDialog->new($self, 'No Bonjour device found', 'Device Browser', wxOK | wxICON_INFORMATION)->ShowModal;
}
});
return $btn;
};
my $octoprint_host_test = sub {
my ($parent) = @_;
my $btn = $self->{octoprint_host_test_btn} = Wx::Button->new($parent, -1,
"Test", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT);
$btn->SetFont($Slic3r::GUI::small_font);
if ($Slic3r::GUI::have_button_icons) {
$btn->SetBitmap(Wx::Bitmap->new($Slic3r::var->("wrench.png"), wxBITMAP_TYPE_PNG));
}
EVT_BUTTON($self, $btn, sub {
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $res = $ua->get(
"http://" . $self->{config}->octoprint_host . "/api/version",
'X-Api-Key' => $self->{config}->octoprint_apikey,
);
if ($res->is_success) {
Slic3r::GUI::show_info($self, "Connection to OctoPrint works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self,
"I wasn't able to connect to OctoPrint (" . $res->status_line . "). "
. "Check hostname and OctoPrint version (at least 1.1.0 is required).");
}
});
return $btn;
};
my $host_line = $optgroup->create_single_option_line('octoprint_host');
$host_line->append_widget($octoprint_host_browse);
$host_line->append_widget($octoprint_host_test);
$host_line->append_button("Browse…", "zoom.png", sub {
# look for devices
my $entries;
{
my $res = Net::Bonjour->new('http');
$res->discover;
$entries = [ $res->entries ];
}
if (@{$entries}) {
my $dlg = Slic3r::GUI::BonjourBrowser->new($self, $entries);
if ($dlg->ShowModal == wxID_OK) {
my $value = $dlg->GetValue . ":" . $dlg->GetPort;
$self->{config}->set('octoprint_host', $value);
$self->update_dirty;
$self->_on_value_change('octoprint_host', $value);
$self->reload_config;
}
} else {
Wx::MessageDialog->new($self, 'No Bonjour device found', 'Device Browser', wxOK | wxICON_INFORMATION)->ShowModal;
}
}, undef, !eval "use Net::Bonjour; 1");
$host_line->append_button("Test", "wrench.png", sub {
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $res = $ua->get(
"http://" . $self->{config}->octoprint_host . "/api/version",
'X-Api-Key' => $self->{config}->octoprint_apikey,
);
if ($res->is_success) {
Slic3r::GUI::show_info($self, "Connection to OctoPrint works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self,
"I wasn't able to connect to OctoPrint (" . $res->status_line . "). "
. "Check hostname and OctoPrint version (at least 1.1.0 is required).");
}
}, \$self->{octoprint_host_test_btn});
$optgroup->append_line($host_line);
$optgroup->append_single_option_line('octoprint_apikey');
}
@ -1278,10 +1240,11 @@ sub build {
$optgroup->append_single_option_line('use_volumetric_e');
$optgroup->append_single_option_line('pressure_advance');
$optgroup->append_single_option_line('vibration_limit');
$optgroup->append_single_option_line('z_steps_per_mm');
}
}
{
my $page = $self->add_options_page('Custom G-code', 'cog.png');
my $page = $self->add_options_page('Custom G-code', 'script.png');
{
my $optgroup = $page->new_optgroup('Start G-code',
label_width => 0,

View File

@ -52,33 +52,6 @@ sub set_material {
return $material;
}
sub looks_like_multipart_object {
my ($self) = @_;
return 0 if $self->objects_count == 1;
return 0 if any { $_->volumes_count > 1 } @{$self->objects};
return 0 if any { @{$_->config->get_keys} > 1 } @{$self->objects};
my %heights = map { $_ => 1 } map $_->mesh->bounding_box->z_min, map @{$_->volumes}, @{$self->objects};
return scalar(keys %heights) > 1;
}
sub convert_multipart_object {
my ($self) = @_;
my @objects = @{$self->objects};
my $object = $self->add_object(
input_file => $objects[0]->input_file,
);
foreach my $v (map @{$_->volumes}, @objects) {
my $volume = $object->add_volume($v);
$volume->set_name($v->object->name);
}
$object->add_instance($_) for map @{$_->instances}, @objects;
$self->delete_object($_) for reverse 0..($self->objects_count-2);
}
# Extends C++ class Slic3r::ModelMaterial
package Slic3r::Model::Material;

View File

@ -48,7 +48,7 @@ sub BUILD {
$self->_cooling_buffer(Slic3r::GCode::CoolingBuffer->new($self->_gcodegen));
$self->_spiral_vase(Slic3r::GCode::SpiralVase->new(config => $self->config))
$self->_spiral_vase(Slic3r::GCode::SpiralVase->new($self->config))
if $self->config->spiral_vase;
$self->_vibration_limit(Slic3r::GCode::VibrationLimit->new(config => $self->config))
@ -114,6 +114,9 @@ sub export {
# set extruder(s) temperature before and after start G-code
$self->_print_first_layer_temperature(0);
printf $fh "%s\n", $gcodegen->placeholder_parser->process($self->config->start_gcode);
foreach my $start_gcode (@{ $self->config->start_filament_gcode }) { # process filament gcode in order
printf $fh "%s\n", $gcodegen->placeholder_parser->process($start_gcode);
}
$self->_print_first_layer_temperature(1);
# set other general things
@ -141,12 +144,12 @@ sub export {
}
# calculate wiping points if needed
if ($self->config->ooze_prevention) {
if ($self->config->ooze_prevention && (my @extruders = @{$self->print->extruders}) > 1) {
my @skirt_points = map @$_, map @$_, @{$self->print->skirt};
if (@skirt_points) {
my $outer_skirt = convex_hull(\@skirt_points);
my @skirts = ();
foreach my $extruder_id (@{$self->print->extruders}) {
foreach my $extruder_id (@extruders) {
my $extruder_offset = $self->config->get_at('extruder_offset', $extruder_id);
push @skirts, my $s = $outer_skirt->clone;
$s->translate(-scale($extruder_offset->x), -scale($extruder_offset->y)); #)
@ -247,6 +250,9 @@ sub export {
# write end commands to file
print $fh $gcodegen->retract; # TODO: process this retract through PressureRegulator in order to discharge fully
print $fh $gcodegen->writer->set_fan(0);
foreach my $end_gcode (@{ $self->config->end_filament_gcode }) { # Process filament-specific gcode in extruder order.
printf $fh "%s\n", $gcodegen->placeholder_parser->process($end_gcode);
}
printf $fh "%s\n", $gcodegen->placeholder_parser->process($self->config->end_gcode);
print $fh $gcodegen->writer->update_progress($gcodegen->layer_count, $gcodegen->layer_count, 1); # 100%
print $fh $gcodegen->writer->postamble;
@ -255,17 +261,33 @@ sub export {
$self->print->clear_filament_stats;
$self->print->total_used_filament(0);
$self->print->total_extruded_volume(0);
$self->print->total_weight(0);
$self->print->total_cost(0);
foreach my $extruder (@{$gcodegen->writer->extruders}) {
my $used_filament = $extruder->used_filament;
my $extruded_volume = $extruder->extruded_volume;
my $filament_weight = $extruded_volume * $extruder->filament_density / 1000;
my $filament_cost = $filament_weight * ($extruder->filament_cost / 1000);
$self->print->set_filament_stats($extruder->id, $used_filament);
printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
$used_filament, $extruded_volume/1000;
if ($filament_weight > 0) {
$self->print->total_weight($self->print->total_weight + $filament_weight);
printf $fh "; filament used = %.1fg\n",
$filament_weight;
if ($filament_cost > 0) {
$self->print->total_cost($self->print->total_cost + $filament_cost);
printf $fh "; filament cost = %.1f\n",
$filament_cost;
}
}
$self->print->total_used_filament($self->print->total_used_filament + $used_filament);
$self->print->total_extruded_volume($self->print->total_extruded_volume + $extruded_volume);
}
printf $fh "; total filament cost = %.1f\n",
$self->print->total_cost;
# append full config
print $fh "\n";
@ -301,9 +323,10 @@ sub process_layer {
# check whether we're going to apply spiralvase logic
if (defined $self->_spiral_vase) {
$self->_spiral_vase->enable(
($layer->id > 0 || $self->print->config->brim_width == 0 || $self->print->config->brim_connections_width == 0)
&& ($layer->id >= $self->print->config->skirt_height && !$self->print->has_infinite_skirt)
$self->_spiral_vase->set_enable(
$layer->id > 0
&& ($self->print->config->skirts == 0
|| ($layer->id >= $self->print->config->skirt_height && !$self->print->has_infinite_skirt))
&& !defined(first { $_->region->config->bottom_solid_layers > $layer->id } @{$layer->regions})
&& !defined(first { $_->perimeters->items_count > 1 } @{$layer->regions})
&& !defined(first { $_->fills->items_count > 0 } @{$layer->regions})
@ -439,7 +462,7 @@ sub process_layer {
# extrude brim
if (!$self->_brim_done) {
$gcode .= $self->_gcodegen->set_extruder($self->print->regions->[0]->config->perimeter_extruder-1);
$gcode .= $self->_gcodegen->set_extruder($self->print->brim_extruder-1);
$self->_gcodegen->set_origin(Slic3r::Pointf->new(0,0));
$self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp(1);
$gcode .= $self->_gcodegen->extrude($_, 'brim', $object->config->support_material_speed)
@ -555,7 +578,7 @@ sub process_layer {
}
# tweak extruder ordering to save toolchanges
my @extruders = sort keys %by_extruder;
my @extruders = sort { $a <=> $b } keys %by_extruder;
if (@extruders > 1) {
my $last_extruder_id = $self->_gcodegen->writer->extruder->id;
if (exists $by_extruder{$last_extruder_id}) {

View File

@ -3,7 +3,7 @@ package Slic3r::Print::Object;
use strict;
use warnings;
use List::Util qw(min max sum first);
use List::Util qw(min max sum first any);
use Slic3r::Flow ':roles';
use Slic3r::Geometry qw(X Y Z PI scale unscale chained_path epsilon);
use Slic3r::Geometry::Clipper qw(diff diff_ex intersection intersection_ex union union_ex
@ -48,346 +48,9 @@ sub slice {
return if $self->step_done(STEP_SLICE);
$self->set_step_started(STEP_SLICE);
$self->print->status_cb->(10, "Processing triangulated mesh");
{
my @nozzle_diameters = map $self->print->config->get_at('nozzle_diameter', $_),
@{$self->print->object_extruders};
$self->config->set('layer_height', min(@nozzle_diameters, $self->config->layer_height));
}
# init layers
{
$self->clear_layers;
# make layers taking custom heights into account
my $id = 0;
my $print_z = 0;
my $first_object_layer_height = -1;
my $first_object_layer_distance = -1;
# add raft layers
if ($self->config->raft_layers > 0) {
$id += $self->config->raft_layers;
# raise first object layer Z by the thickness of the raft itself
# plus the extra distance required by the support material logic
my $first_layer_height = $self->config->get_value('first_layer_height');
$print_z += $first_layer_height;
# use a large height
my $support_material_layer_height;
{
my @nozzle_diameters = (
map $self->print->config->get_at('nozzle_diameter', $_),
@{$self->support_material_extruders},
);
$support_material_layer_height = 0.75 * min(@nozzle_diameters);
}
$print_z += $support_material_layer_height * ($self->config->raft_layers - 1);
# compute the average of all nozzles used for printing the object
my $nozzle_diameter;
{
my @nozzle_diameters = (
map $self->print->config->get_at('nozzle_diameter', $_), @{$self->print->object_extruders}
);
$nozzle_diameter = sum(@nozzle_diameters)/@nozzle_diameters;
}
$first_object_layer_distance = $self->_support_material->contact_distance($self->config->layer_height, $nozzle_diameter);
# force first layer print_z according to the contact distance
# (the loop below will raise print_z by such height)
$first_object_layer_height = $first_object_layer_distance - $self->config->support_material_contact_distance;
}
my $slice_z = 0;
my $height = 0;
my $adaptive_height = 0;
my @layers = ();
# determine min and max layer height from extruder capabilities.
my %extruders;
for my $region_id (0 .. ($self->region_count - 1)) {
foreach (qw(perimeter_extruder infill_extruder solid_infill_extruder)) {
my $extruder_id = $self->print->get_region($region_id)->config->get($_)-1;
$extruders{$extruder_id} = $extruder_id;
}
}
my $min_height = max(map {$self->print->config->get_at('min_layer_height', $_)} (values %extruders));
my $max_height = min(map {$self->print->config->get_at('max_layer_height', $_)} (values %extruders));
$self->_slice;
if(!$self->layer_height_spline->updateRequired) { # layer heights are already generated, just update layers from spline
@layers = @{$self->layer_height_spline->getInterpolatedLayers};
}else{ # create new set of layers
# create stateful objects and variables for the adaptive slicing process
my @adaptive_slicing;
if ($self->config->adaptive_slicing) {
for my $region_id (0 .. ($self->region_count - 1)) {
my $mesh;
foreach my $volume_id (@{ $self->get_region_volumes($region_id) }) {
my $volume = $self->model_object->volumes->[$volume_id];
next if $volume->modifier;
if (defined $mesh) {
$mesh->merge($volume->mesh);
} else {
$mesh = $volume->mesh->clone;
}
}
if (defined $mesh) {
$adaptive_slicing[$region_id] = Slic3r::AdaptiveSlicing->new(
mesh => $mesh,
size => $self->size->z
);
}
}
}
# loop until we have at least one layer and the max slice_z reaches the object height
my $max_z = unscale($self->size->z);
while (($slice_z) < $max_z) {
if ($self->config->adaptive_slicing) {
$height = 999;
my $adaptive_quality = $self->config->get_value('adaptive_slicing_quality');
if($self->layer_height_spline->getCuspValue >= 0) {
$self->config->set('adaptive_slicing_quality', $self->layer_height_spline->getCuspValue);
$adaptive_quality = $self->layer_height_spline->getCuspValue;
}
Slic3r::debugf "\n Slice layer: %d\n", $id;
# determine next layer height
for my $region_id (0 .. ($self->region_count - 1)) {
# get cusp height
next if(!defined $adaptive_slicing[$region_id]);
my $adaptive_height = $adaptive_slicing[$region_id]->next_layer_height(scale $slice_z, $adaptive_quality, $min_height, $max_height);
# check for horizontal features and object size
if($self->config->get_value('match_horizontal_surfaces')) {
my $horizontal_dist = $adaptive_slicing[$region_id]->horizontal_facet_distance(scale $slice_z+$adaptive_height, $min_height);
if(($horizontal_dist < $min_height) && ($horizontal_dist > 0)) {
Slic3r::debugf "Horizontal feature ahead, distance: %f\n", $horizontal_dist;
# can we shrink the current layer a bit?
if($adaptive_height-($min_height-$horizontal_dist) > $min_height) {
# yes we can
$adaptive_height = $adaptive_height-($min_height-$horizontal_dist);
Slic3r::debugf "Shrink layer height to %f\n", $adaptive_height;
}else{
# no, current layer would become too thin
$adaptive_height = $adaptive_height+$horizontal_dist;
Slic3r::debugf "Widen layer height to %f\n", $adaptive_height;
}
}
}
$height = ($id == 0)
? $self->config->get_value('first_layer_height')
: min($adaptive_height, $height);
}
}else{
# assign the default height to the layer according to the general settings
$height = ($id == 0)
? $self->config->get_value('first_layer_height')
: $self->config->layer_height;
}
# look for an applicable custom range
if (my $range = first { $_->[0] <= $slice_z && $_->[1] > $slice_z } @{$self->layer_height_ranges}) {
$height = $range->[2];
# if user set custom height to zero we should just skip the range and resume slicing over it
if ($height == 0) {
$slice_z += $range->[1] - $range->[0];
next;
}
}
# set first layer height if raft is active
if ($first_object_layer_height != -1 && !@layers) {
$height = $first_object_layer_height;
#$print_z += ($first_object_layer_distance - $height);
}
$slice_z += $height;
$id++;
# collect layers for spline smoothing
push (@layers, $slice_z);
}
$self->layer_height_spline->setLayers(\@layers);
if ($self->config->adaptive_slicing) { # smoothing after adaptive algorithm
@layers = @{$self->layer_height_spline->getInterpolatedLayers};
}
}
$id = 0;
if ($self->config->raft_layers > 0) {
$id = $self->config->raft_layers;
}
# generate layer objects
$slice_z = 0;
my $gradation = $self->config->get_value('adaptive_slicing_z_gradation');
foreach my $z (@layers) {
$height = $z - $slice_z;
# apply z-gradation
if($gradation > 0) {
my $gradation_effect = unscale((scale($height)) % (scale($gradation)));
if($gradation_effect > $gradation/2 && ($height + ($gradation-$gradation_effect)) <= $max_height) { # round up
$height = $height + ($gradation-$gradation_effect);
}else{ # round down
$height = $height - $gradation_effect;
}
#$height = $height - unscale((scale($height)) % (scale($gradation)));
}
$print_z += $height;
$slice_z += $height/2;
Slic3r::debugf "Layer %d: height = %s; slice_z = %s; print_z = %s\n", $id, $height, $slice_z, $print_z;
$self->add_layer($id, $height, $print_z, $slice_z);
if ($self->layer_count >= 2) {
my $lc = $self->layer_count;
$self->get_layer($lc - 2)->set_upper_layer($self->get_layer($lc - 1));
$self->get_layer($lc - 1)->set_lower_layer($self->get_layer($lc - 2));
}
$id++;
$slice_z += $height/2; # add the other half layer
}
}
# make sure all layers contain layer region objects for all regions
my $regions_count = $self->print->region_count;
foreach my $layer (@{ $self->layers }) {
$layer->region($_) for 0 .. ($regions_count-1);
}
# get array of Z coordinates for slicing
my @z = map $_->slice_z, @{$self->layers};
# slice all non-modifier volumes
for my $region_id (0..($self->region_count - 1)) {
my $expolygons_by_layer = $self->_slice_region($region_id, \@z, 0);
for my $layer_id (0..$#$expolygons_by_layer) {
my $layerm = $self->get_layer($layer_id)->regions->[$region_id];
$layerm->slices->clear;
foreach my $expolygon (@{ $expolygons_by_layer->[$layer_id] }) {
$layerm->slices->append(Slic3r::Surface->new(
expolygon => $expolygon,
surface_type => S_TYPE_INTERNAL,
));
}
}
}
# then slice all modifier volumes
if ($self->region_count > 1) {
for my $region_id (0..$self->region_count) {
my $expolygons_by_layer = $self->_slice_region($region_id, \@z, 1);
# loop through the other regions and 'steal' the slices belonging to this one
for my $other_region_id (0..$self->region_count) {
next if $other_region_id == $region_id;
for my $layer_id (0..$#$expolygons_by_layer) {
my $layerm = $self->get_layer($layer_id)->regions->[$region_id];
my $other_layerm = $self->get_layer($layer_id)->regions->[$other_region_id];
next if !defined $other_layerm;
my $other_slices = [ map $_->p, @{$other_layerm->slices} ]; # Polygons
my $my_parts = intersection_ex(
$other_slices,
[ map @$_, @{ $expolygons_by_layer->[$layer_id] } ],
);
next if !@$my_parts;
# append new parts to our region
foreach my $expolygon (@$my_parts) {
$layerm->slices->append(Slic3r::Surface->new(
expolygon => $expolygon,
surface_type => S_TYPE_INTERNAL,
));
}
# remove such parts from original region
$other_layerm->slices->clear;
$other_layerm->slices->append(Slic3r::Surface->new(
expolygon => $_,
surface_type => S_TYPE_INTERNAL,
)) for @{ diff_ex($other_slices, [ map @$_, @$my_parts ]) };
}
}
}
}
# remove last layer(s) if empty
$self->delete_layer($self->layer_count - 1)
while $self->layer_count && (!map @{$_->slices}, @{$self->get_layer($self->layer_count - 1)->regions});
foreach my $layer (@{ $self->layers }) {
# apply size compensation
if ($self->config->xy_size_compensation != 0) {
my $delta = scale($self->config->xy_size_compensation);
if (@{$layer->regions} == 1) {
# single region
my $layerm = $layer->regions->[0];
my $slices = [ map $_->p, @{$layerm->slices} ];
$layerm->slices->clear;
$layerm->slices->append(Slic3r::Surface->new(
expolygon => $_,
surface_type => S_TYPE_INTERNAL,
)) for @{offset_ex($slices, $delta)};
} else {
if ($delta < 0) {
# multiple regions, shrinking
# we apply the offset to the combined shape, then intersect it
# with the original slices for each region
my $slices = union([ map $_->p, map @{$_->slices}, @{$layer->regions} ]);
$slices = offset($slices, $delta);
foreach my $layerm (@{$layer->regions}) {
my $this_slices = intersection_ex(
$slices,
[ map $_->p, @{$layerm->slices} ],
);
$layerm->slices->clear;
$layerm->slices->append(Slic3r::Surface->new(
expolygon => $_,
surface_type => S_TYPE_INTERNAL,
)) for @$this_slices;
}
} else {
# multiple regions, growing
# this is an ambiguous case, since it's not clear how to grow regions where they are going to overlap
# so we give priority to the first one and so on
for my $i (0..$#{$layer->regions}) {
my $layerm = $layer->regions->[$i];
my $slices = offset_ex([ map $_->p, @{$layerm->slices} ], $delta);
if ($i > 0) {
$slices = diff_ex(
[ map @$_, @$slices ],
[ map $_->p, map @{$_->slices}, map $layer->regions->[$_], 0..($i-1) ], # slices of already processed regions
);
}
$layerm->slices->clear;
$layerm->slices->append(Slic3r::Surface->new(
expolygon => $_,
surface_type => S_TYPE_INTERNAL,
)) for @$slices;
}
}
}
}
# merge all regions' slices to get islands
$layer->make_slices;
}
# detect slicing errors
my $warning_thrown = 0;
for my $i (0 .. ($self->layer_count - 1)) {
@ -535,6 +198,8 @@ sub generate_support_material {
$self->_support_material->generate($self);
$self->set_step_done(STEP_SUPPORTMATERIAL);
my $stats = sprintf "Weight: %.1fg, Cost: %.1f" , $self->print->total_weight, $self->print->total_cost;
$self->print->status_cb->(85, $stats);
}
sub _support_material {
@ -562,9 +227,9 @@ sub _support_material {
# fill_surfaces but we only turn them into VOID surfaces, thus preserving the boundaries.
sub clip_fill_surfaces {
my $self = shift;
# sanity check for incompatible options:
# spiral_vase and infill_only_where_needed
return unless $self->config->infill_only_where_needed and not $self->config->spiral_vase;
return unless $self->config->infill_only_where_needed
&& any { $_->config->fill_density > 0 } @{$self->print->regions};
# We only want infill under ceilings; this is almost like an
# internal support material.
@ -622,6 +287,8 @@ sub clip_fill_surfaces {
# apply new internal infill to regions
foreach my $layerm (@{$lower_layer->regions}) {
next if $layerm->region->config->fill_density == 0;
my (@internal, @other) = ();
foreach my $surface (map $_->clone, @{$layerm->fill_surfaces}) {
if ($surface->surface_type == S_TYPE_INTERNAL || $surface->surface_type == S_TYPE_INTERNALVOID) {

View File

@ -9,11 +9,12 @@ package Slic3r::Print::Simple;
use Moo;
use Slic3r::Geometry qw(X Y);
use Slic3r::Geometry::Clipper qw(diff);
has '_print' => (
is => 'ro',
default => sub { Slic3r::Print->new },
handles => [qw(apply_config extruders output_filepath
handles => [qw(apply_config config extruders output_filepath
total_used_filament total_extruded_volume
placeholder_parser process)],
);
@ -45,7 +46,6 @@ has 'status_cb' => (
has 'print_center' => (
is => 'rw',
default => sub { Slic3r::Pointf->new(100,100) },
);
has 'dont_arrange' => (
@ -57,6 +57,13 @@ has 'output_file' => (
is => 'rw',
);
sub _bed_polygon {
my ($self) = @_;
my $bed_shape = $self->_print->config->bed_shape;
return Slic3r::Polygon->new_scale(@$bed_shape);
}
sub set_model {
# $model is of type Slic3r::Model
my ($self, $model) = @_;
@ -73,16 +80,24 @@ sub set_model {
$instance->set_rotation($instance->rotation + $self->rotate);
}
my $bed_shape = $self->_print->config->bed_shape;
my $bb = Slic3r::Geometry::BoundingBoxf->new_from_points($bed_shape);
if ($self->duplicate_grid->[X] > 1 || $self->duplicate_grid->[Y] > 1) {
$model->duplicate_objects_grid($self->duplicate_grid->[X], $self->duplicate_grid->[Y], $self->_print->config->duplicate_distance);
} elsif ($need_arrange) {
$model->duplicate_objects($self->duplicate, $self->_print->config->min_object_distance);
$model->duplicate_objects($self->duplicate, $self->_print->config->min_object_distance, $bb);
} elsif ($self->duplicate > 1) {
# if all input objects have defined position(s) apply duplication to the whole model
$model->duplicate($self->duplicate, $self->_print->config->min_object_distance);
$model->duplicate($self->duplicate, $self->_print->config->min_object_distance, $bb);
}
$_->translate(0,0,-$_->bounding_box->z_min) for @{$model->objects};
$model->center_instances_around_point($self->print_center) if (! $self->dont_arrange);
if (!$self->dont_arrange) {
my $print_center = $self->print_center
// Slic3r::Pointf->new_unscale(@{ $self->_bed_polygon->centroid });
$model->center_instances_around_point($print_center);
}
foreach my $model_object (@{$model->objects}) {
$self->_print->auto_assign_extruders($model_object);
@ -99,6 +114,13 @@ sub _before_export {
sub _after_export {
my ($self) = @_;
# check that all parts fit in bed shape, and warn if they don't
# TODO: use actual toolpaths instead of total bounding box
if (@{diff([$self->_print->bounding_box->polygon], [$self->_bed_polygon])}) {
warn "Warning: the supplied parts might not fit in the configured bed shape. "
. "You might want to review the result before printing.\n";
}
$self->_print->set_status_cb(undef);
}

View File

@ -92,7 +92,7 @@ sub contact_area {
# if user specified a custom angle threshold, convert it to radians
my $threshold_rad;
if ($self->object_config->support_material_threshold) {
if (!$self->object_config->support_material_threshold =~ /%$/) {
$threshold_rad = deg2rad($self->object_config->support_material_threshold + 1); # +1 makes the threshold inclusive
Slic3r::debugf "Threshold angle = %d°\n", rad2deg($threshold_rad);
}
@ -152,7 +152,7 @@ sub contact_area {
} else {
$diff = diff(
[ map $_->p, @{$layerm->slices} ],
offset([ map @$_, @{$lower_layer->slices} ], +$fw*2),
offset([ map @$_, @{$lower_layer->slices} ], +$self->object_config->get_abs_value_over('support_material_threshold', $fw)),
);
# collapse very tiny spots

View File

@ -133,6 +133,13 @@ sub mesh {
$facets = [
[0,1,2],[1,0,3],[2,1,4],[2,5,0],[0,6,3],[1,3,7],[1,8,4],[4,9,2],[10,5,2],[5,6,0],[6,11,3],[3,12,7],[7,8,1],[4,8,11],[4,11,9],[9,10,2],[10,13,5],[14,6,5],[9,11,6],[11,12,3],[12,8,7],[11,8,15],[13,10,9],[5,13,14],[14,13,6],[6,13,9],[15,12,11],[15,8,12]
];
} elsif ($name eq 'step') {
$vertices = [
[0,20,5],[0,20,0],[0,0,5],[0,0,0],[20,0,0],[20,0,5],[1,19,5],[1,1,5],[19,1,5],[20,20,5],[19,19,5],[20,20,0],[19,19,10],[1,19,10],[1,1,10],[19,1,10]
];
$facets = [
[0,1,2],[1,3,2],[3,4,5],[2,3,5],[6,0,2],[6,2,7],[5,8,7],[5,7,2],[9,10,8],[9,8,5],[9,0,6],[9,6,10],[9,11,1],[9,1,0],[3,1,11],[4,3,11],[5,11,9],[5,4,11],[12,10,6],[12,6,13],[6,7,14],[13,6,14],[7,8,15],[14,7,15],[15,8,10],[15,10,12],[12,13,14],[12,14,15]
];
} elsif ($name eq 'slopy_cube') {
$vertices = [
[-10,-10,0], [-10,-10,20], [-10,10,0], [-10,10,20], [0,-10,10], [10,-10,0], [2.92893,-10,10], [10,-10,2.92893],

View File

@ -59,11 +59,12 @@ API=${BINTRAY_API_KEY}
USER=${BINTRAY_API_USER}
echo "Creating version: $version"
curl -X POST -d "{ \"name\": \"$version\", \"released\": \"ISO8601 $(date +%Y-%m-%d'T'%H:%M:%S)\", \"desc\": \"This version...\", \"github_release_notes_file\": \"RELEASE.txt\", \"github_use_tag_release_notes\": true, \"vcs_tag\": \"$version\" }" -u${USER}:${API} https://api.bintray.com/content/lordofhyphens/Slic3r/${SLIC3R_PKG}/versions
curl -s -X POST -d "{ \"name\": \"$version\", \"released\": \"ISO8601 $(date +%Y-%m-%d'T'%H:%M:%S)\", \"desc\": \"This version...\", \"github_release_notes_file\": \"RELEASE.txt\", \"github_use_tag_release_notes\": true, \"vcs_tag\": \"$version\" }" -u${USER}:${API} https://api.bintray.com/content/lordofhyphens/Slic3r/${SLIC3R_PKG}/versions
echo "Publishing ${file} to ${version}..."
curl -H "X-Bintray-Package: $SLIC3R_PKG" -H "X-Bintray-Version: $version" -H 'X-Bintray-Publish: 1' -H 'X-Bintray-Override: 1' -T $file -u${USER}:${API} https://api.bintray.com/content/lordofhyphens/Slic3r/$(basename $1)
curl -s -H "X-Bintray-Package: $SLIC3R_PKG" -H "X-Bintray-Version: $version" -H 'X-Bintray-Publish: 1' -H 'X-Bintray-Override: 1' -T $file -u${USER}:${API} https://api.bintray.com/content/lordofhyphens/Slic3r/$(basename $1)
#curl -X POST -u${USER}:${API} https://api.bintray.com/content/lordofhyphens/Slic3r/${SLIC3R_PKG}/$version/publish
# Wait 5s for the server to catch up
#sleep 5
#curl -H 'Content-Type: application/json' -X PUT -d "{ \"list_in_downloads\":true }" -u${USER}:${API} https://api.bintray.com/file_metadata/lordofhyphens/Slic3r/$(basename $1)
exit 0

View File

@ -91,7 +91,9 @@ rm -rf $macosfolder/local-lib/lib/perl5/darwin-thread-multi-2level/Alien/wxWidge
echo "Relocating dylib paths..."
for bundle in $(find $macosfolder/local-lib/lib/perl5/darwin-thread-multi-2level/auto/Wx -name '*.bundle') $(find $macosfolder/local-lib/lib/perl5/darwin-thread-multi-2level/Alien/wxWidgets -name '*.dylib' -type f); do
chmod +w $bundle
find $SLIC3R_DIR/local-lib -name '*.dylib' -exec bash -c 'install_name_tool -change "{}" "@executable_path/local-lib/lib/perl5/darwin-thread-multi-2level/Alien/wxWidgets/osx_cocoa_3_0_2_uni/lib/$(basename {})" '$bundle \;
for dylib in $(otool -l $bundle | grep .dylib | grep local-lib | awk '{print $2}'); do
install_name_tool -change "$dylib" "@executable_path/local-lib/lib/perl5/darwin-thread-multi-2level/Alien/wxWidgets/osx_cocoa_3_0_2_uni/lib/$(basename $dylib)" $bundle
done
done
echo "Copying startup script..."

View File

@ -91,6 +91,8 @@ cat << EOF >> $plistfile
</array>
<key>LSMinimumSystemVersion</key>
<string>10.7</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
EOF

View File

@ -1,4 +1,4 @@
#!/bin/bash
DIR=$(dirname "$0")
$DIR/perl-local -I$DIR/local-lib/lib/perl5 $DIR/slic3r.pl $@
"$DIR/perl-local" -I"$DIR/local-lib/lib/perl5" "$DIR/slic3r.pl" $@

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="0.0.0.0" name="Slic3r" type="Win32" />
<description>Slic3r</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="Win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- The ID below indicates application support for Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
<!-- The ID below indicates application support for Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
<!-- The ID below indicates application support for Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- The ID below indicates application support for Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- The ID below indicates application support for Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>

View File

@ -22,4 +22,4 @@ BEGIN
VALUE "Translation", 0x409, 1252
END
END
1 Manifest slic3r.exe.manifest

View File

@ -29,6 +29,7 @@ my %cli_options = ();
'debug' => \$Slic3r::debug,
'gui' => \$opt{gui},
'o|output=s' => \$opt{output},
'j|threads=i' => \$opt{threads},
'save=s' => \$opt{save},
'load=s@' => \$opt{load},
@ -109,6 +110,7 @@ if ((!@ARGV || $opt{gui}) && !$opt{save} && eval "require Slic3r::GUI; 1") {
$Slic3r::GUI::no_plater = $opt{no_plater};
$Slic3r::GUI::mode = $opt{gui_mode};
$Slic3r::GUI::autosave = $opt{autosave};
$Slic3r::GUI::threads = $opt{threads};
}
$gui = Slic3r::GUI->new;
setlocale(LC_NUMERIC, 'C');
@ -253,7 +255,7 @@ if (@ARGV) { # slicing from command line
rotate => deg2rad($opt{rotate} // 0),
duplicate => $opt{duplicate} // 1,
duplicate_grid => $opt{duplicate_grid} // [1,1],
print_center => $opt{print_center} // Slic3r::Pointf->new(100,100),
print_center => $opt{print_center},
dont_arrange => $opt{dont_arrange} // 0,
status_cb => sub {
my ($percent, $message) = @_;
@ -263,6 +265,7 @@ if (@ARGV) { # slicing from command line
);
$sprint->apply_config($config);
$sprint->config->set('threads', $opt{threads}) if $opt{threads};
$sprint->set_model($model);
if ($opt{export_svg}) {
@ -293,7 +296,7 @@ sub usage {
my $j = '';
if ($Slic3r::have_threads) {
$j = <<"EOF";
-j, --threads <num> Number of threads to use (1+, default: $config->{threads})
-j, --threads <num> Number of threads to use
EOF
}
@ -347,6 +350,8 @@ $j
(default: 100,100)
--z-offset Additional height in mm to add to vertical coordinates
(+/-, default: $config->{z_offset})
--z-steps-per-mm Number of full steps per mm of the Z axis. Experimental feature for
preventing rounding issues.
--gcode-flavor The type of G-code to generate (reprap/teacup/repetier/makerware/sailfish/mach3/machinekit/smoothie/no-extrusion,
default: $config->{gcode_flavor})
--use-relative-e-distances Enable this to get relative E values (default: no)
@ -431,7 +436,10 @@ $j
--fill-angle Infill angle in degrees (range: 0-90, default: $config->{fill_angle})
--fill-pattern Pattern to use to fill non-solid layers (default: $config->{fill_pattern})
--fill-gaps Fill gaps with single passes (default: yes)
--external-fill-pattern Pattern to use to fill solid layers (default: $config->{external_fill_pattern})
--external-infill-pattern Pattern to use to fill solid layers.
(Shortcut for --top-infill-pattern and --bottom-infill-pattern)
--top-infill-pattern Pattern to use to fill top solid layers (default: $config->{top_infill_pattern})
--bottom-infill-pattern Pattern to use to fill bottom solid layers (default: $config->{bottom_infill_pattern})
--start-gcode Load initial G-code from the supplied file. This will overwrite
the default command (home all axes [G28]).
--end-gcode Load final G-code from the supplied file. This will overwrite
@ -458,7 +466,7 @@ $j
--extra-perimeters Add more perimeters when needed (default: yes)
--avoid-crossing-perimeters Optimize travel moves so that no perimeters are crossed (default: no)
--thin-walls Detect single-width walls (default: yes)
--overhangs Experimental option to use bridge flow, speed and fan for overhangs
--detect-bridging-perimeters Detect bridging perimeters and apply bridge flow, speed and fan
(default: yes)
Support material options:
@ -530,6 +538,8 @@ $j
of filament on the first layer, for each extruder (mm, 0+, default: $config->{min_skirt_length})
--brim-width Width of the brim that will get added to each object to help adhesion
(mm, default: $config->{brim_width})
--interior-brim-width Width of the brim that will get printed inside object holes to help adhesion
(mm, default: $config->{interior_brim_width})
Transform options:
--scale Factor for scaling input object (default: 1)

View File

@ -2,7 +2,7 @@ cmake_minimum_required (VERSION 2.8)
project (slic3r)
# only on newer GCCs: -ftemplate-backtrace-limit=0
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -DM_PI=3.14159265358979323846 -D_GLIBCXX_USE_C99 -DHAS_BOOL -DNOGDI -DBOOST_ASIO_DISABLE_KQUEUE")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -DM_PI=3.14159265358979323846 -D_GLIBCXX_USE_C99 -DHAS_BOOL -DNOGDI -DBOOST_ASIO_DISABLE_KQUEUE")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -DSLIC3R_DEBUG")
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.7.0)
@ -14,7 +14,8 @@ endif(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.7.0)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
IF(CMAKE_HOST_APPLE)
set(CMAKE_EXE_LINKER_FLAGS "-framework IOKit -framework CoreFoundation")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++ -DBOOST_THREAD_DONT_USE_CHRONO -DBOOST_NO_CXX11_RVALUE_REFERENCES -DBOOST_THREAD_USES_MOVE")
set(CMAKE_EXE_LINKER_FLAGS "-framework IOKit -framework CoreFoundation -lc++")
ELSE(CMAKE_HOST_APPLE)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
ENDIF(CMAKE_HOST_APPLE)
@ -54,6 +55,8 @@ add_library(libslic3r STATIC
${LIBDIR}/libslic3r/Flow.cpp
${LIBDIR}/libslic3r/GCode.cpp
${LIBDIR}/libslic3r/GCode/CoolingBuffer.cpp
${LIBDIR}/libslic3r/GCode/SpiralVase.cpp
${LIBDIR}/libslic3r/GCodeReader.cpp
${LIBDIR}/libslic3r/GCodeSender.cpp
${LIBDIR}/libslic3r/GCodeWriter.cpp
${LIBDIR}/libslic3r/Geometry.cpp
@ -82,6 +85,7 @@ add_library(libslic3r STATIC
${LIBDIR}/libslic3r/SVG.cpp
${LIBDIR}/libslic3r/TriangleMesh.cpp
)
add_library(admesh STATIC
${LIBDIR}/admesh/connect.c
${LIBDIR}/admesh/normals.c
@ -90,6 +94,8 @@ add_library(admesh STATIC
${LIBDIR}/admesh/stlinit.c
${LIBDIR}/admesh/util.c
)
set_property(TARGET admesh PROPERTY C_STANDARD 99)
add_library(clipper STATIC ${LIBDIR}/clipper.cpp)
add_library(expat STATIC
${LIBDIR}/expat/xmlparse.c

View File

@ -51,66 +51,62 @@ my $horizontal_feature_test = sub {
my $height_gradation_test = sub {
my (@z) = $generate_gcode->();
my $gradation = $config->get('adaptive_slicing_z_gradation');
my $gradation = 1 / $config->get('z_steps_per_mm');
# +1 is a "dirty fix" to avoid rounding issues with the modulo operator...
my @results = map {unscale((scale($_)+1) % scale($gradation))} @z;
ok (_eq(sum(@results), 0), 'layer z is multiple of gradation ' . $gradation );
1;
};
my $print = Slic3r::Test::init_print('slopy_cube', config => $config);
$print->models->[0]->mesh->repair();
my $adaptive_slicing = Slic3r::AdaptiveSlicing->new(
mesh => Slic3r::Test::mesh('slopy_cube'),
size => 20
);
my $adaptive_slicing = Slic3r::SlicingAdaptive->new();
my $mesh = Slic3r::Test::mesh('slopy_cube');
$adaptive_slicing->add_mesh($mesh);
$adaptive_slicing->prepare(20);
subtest 'max layer_height limited by extruder capabilities' => sub {
plan tests => 3;
is ($adaptive_slicing->next_layer_height(scale 1, 0.2, 0.1, 0.15), 0.15, 'low');
is ($adaptive_slicing->next_layer_height(scale 1, 0.2, 0.1, 0.4), 0.4, 'higher');
is ($adaptive_slicing->next_layer_height(scale 1, 0.2, 0.1, 0.65), 0.65, 'highest');
ok (_eq($adaptive_slicing->next_layer_height(1, 0.5, 0.1, 0.15), 0.15), 'low');
ok (_eq($adaptive_slicing->next_layer_height(1, 0.2, 0.1, 0.4), 0.4), 'higher');
ok (_eq($adaptive_slicing->next_layer_height(1, 0.2, 0.1, 0.65), 0.65), 'highest');
};
subtest 'min layer_height limited by extruder capabilities' => sub {
plan tests => 3;
is ($adaptive_slicing->next_layer_height(scale 4, 0.01, 0.1, 0.15), 0.1, 'low');
is ($adaptive_slicing->next_layer_height(scale 4, 0.02, 0.2, 0.4), 0.2, 'higher');
is ($adaptive_slicing->next_layer_height(scale 4, 0.01, 0.3, 0.65), 0.3, 'highest');
ok (_eq($adaptive_slicing->next_layer_height(4, 0.01, 0.1, 0.15), 0.1), 'low');
ok (_eq($adaptive_slicing->next_layer_height(4, 0.02, 0.2, 0.4), 0.2), 'higher');
ok (_eq($adaptive_slicing->next_layer_height(4, 0.01, 0.3, 0.65), 0.3), 'highest');
};
subtest 'correct layer_height depending on the facet normals' => sub {
plan tests => 3;
ok (_eq($adaptive_slicing->next_layer_height(scale 1, 0.1, 0.1, 0.5), 0.5), 'limit');
ok (_eq($adaptive_slicing->next_layer_height(scale 4, 0.2, 0.1, 0.5), 0.1546), '45deg facet, quality_value: 0.2');
ok (_eq($adaptive_slicing->next_layer_height(scale 4, 0.5, 0.1, 0.5), 0.3352), '45deg facet, quality_value: 0.5');
ok (_eq($adaptive_slicing->next_layer_height(1, 0.1, 0.1, 0.5), 0.5), 'limit');
ok (_eq($adaptive_slicing->next_layer_height(4, 0.2, 0.1, 0.5), 0.1546), '45deg facet, quality_value: 0.2');
ok (_eq($adaptive_slicing->next_layer_height(4, 0.5, 0.1, 0.5), 0.3352), '45deg facet, quality_value: 0.5');
};
# 2.92893 ist lower slope edge
# distance to slope must be higher than min extruder cap.
# slopes layer height must be greater than the distance to the slope
ok (_eq($adaptive_slicing->next_layer_height(scale 2.798, 0.2, 0.1, 0.5), 0.1546), 'reducing layer_height due to higher slopy facet');
ok (_eq($adaptive_slicing->next_layer_height(2.798, 0.2, 0.1, 0.5), 0.1546), 'reducing layer_height due to higher slopy facet');
# slopes layer height must be smaller than the distance to the slope
ok (_eq($adaptive_slicing->next_layer_height(scale 2.6289, 0.15, 0.1, 0.5), 0.3), 'reducing layer_height to z-diff');
ok (_eq($adaptive_slicing->next_layer_height(2.6289, 0.15, 0.1, 0.5), 0.3), 'reducing layer_height to z-diff');
subtest 'horizontal planes' => sub {
plan tests => 3;
print "facet_distance: " . $adaptive_slicing->horizontal_facet_distance(scale 1, 1.2) . "\n";
ok (_eq($adaptive_slicing->horizontal_facet_distance(scale 1, 1.2), 1.2), 'max_height limit');
ok (_eq($adaptive_slicing->horizontal_facet_distance(scale 8.5, 4), 1.5), 'normal horizontal facet');
ok (_eq($adaptive_slicing->horizontal_facet_distance(scale 17, 5), 3.0), 'object maximum');
ok (_eq($adaptive_slicing->horizontal_facet_distance(1, 1.2), 1.2), 'max_height limit');
ok (_eq($adaptive_slicing->horizontal_facet_distance(8.5, 4), 1.5), 'normal horizontal facet');
ok (_eq($adaptive_slicing->horizontal_facet_distance(17, 5), 3.0), 'object maximum');
};
# shrink current layer to fit another layer under horizontal facet
@ -127,25 +123,25 @@ $config->set('adaptive_slicing_quality', [0.19]);
subtest 'shrink to match horizontal facets' => sub {
plan skip_all => 'spline smoothing currently prevents exact horizontal facet matching';
plan tests => 3;
$horizontal_feature_test->();
plan tests => 3;
$horizontal_feature_test->();
};
# widen current layer to match horizontal facet
$config->set('adaptive_slicing_quality', [0.1]);
subtest 'widen to match horizontal facets' => sub {
plan skip_all => 'spline smoothing currently prevents exact horizontal facet matching';
plan tests => 3;
$horizontal_feature_test->();
plan tests => 3;
$horizontal_feature_test->();
};
subtest 'layer height gradation' => sub {
plan tests => 5;
foreach my $gradation (0.001, 0.01, 0.02, 0.05, 0.08) {
$config->set('adaptive_slicing_z_gradation', $gradation);
$height_gradation_test->();
}
plan tests => 5;
foreach my $gradation (1/0.001*4, 1/0.01*4, 1/0.02*4, 1/0.05*4, 1/0.08*4) {
$config->set('z_steps_per_mm', $gradation);
$height_gradation_test->();
}
};
__END__

View File

@ -2,7 +2,7 @@ use Test::More;
use strict;
use warnings;
plan tests => 92;
plan tests => 93;
BEGIN {
use FindBin;
@ -10,10 +10,10 @@ BEGIN {
use local::lib "$FindBin::Bin/../local-lib";
}
use List::Util qw(first sum);
use List::Util qw(first sum max);
use Slic3r;
use Slic3r::Geometry qw(PI X Y scaled_epsilon scale unscale convex_hull);
use Slic3r::Geometry::Clipper qw(union diff diff_ex offset offset2_ex diff_pl);
use Slic3r::Geometry::Clipper qw(union diff diff_ex offset offset2_ex diff_pl union_ex);
use Slic3r::Surface qw(:types);
use Slic3r::Test;
@ -373,4 +373,46 @@ for my $pattern (qw(rectilinear honeycomb hilbertcurve concentric)) {
is scalar(@$diff), 0, 'no missing parts in solid shell when fill_density is 0';
}
{
# GH: #2697
my $config = Slic3r::Config->new_from_defaults;
$config->set('perimeter_extrusion_width', 0.72);
$config->set('top_infill_extrusion_width', 0.1);
$config->set('infill_extruder', 2); # in order to distinguish infill
$config->set('solid_infill_extruder', 2); # in order to distinguish infill
my $print = Slic3r::Test::init_print('20mm_cube', config => $config);
my %infill = (); # Z => [ Line, Line ... ]
my %other = (); # Z => [ Line, Line ... ]
my $tool = undef;
Slic3r::GCode::Reader->new->parse(Slic3r::Test::gcode($print), sub {
my ($self, $cmd, $args, $info) = @_;
if ($cmd =~ /^T(\d+)/) {
$tool = $1;
} elsif ($cmd eq 'G1' && $info->{extruding} && $info->{dist_XY} > 0) {
my $z = 1 * $self->Z;
my $line = Slic3r::Line->new_scale(
[ $self->X, $self->Y ],
[ $info->{new_X}, $info->{new_Y} ],
);
if ($tool == $config->infill_extruder-1) {
$infill{$z} //= [];
push @{$infill{$z}}, $line;
} else {
$other{$z} //= [];
push @{$other{$z}}, $line;
}
}
});
my $top_z = max(keys %infill);
my $top_infill_grow_d = scale($config->top_infill_extrusion_width)/2;
my $top_infill = union([ map @{$_->grow($top_infill_grow_d)}, @{ $infill{$top_z} } ]);
my $perimeters_grow_d = scale($config->perimeter_extrusion_width)/2;
my $perimeters = union([ map @{$_->grow($perimeters_grow_d)}, @{ $other{$top_z} } ]);
my $covered = union_ex([ @$top_infill, @$perimeters ]);
my @holes = map @{$_->holes}, @$covered;
ok sum(map unscale unscale $_->area*-1, @holes) < 1, 'no gaps between top solid infill and perimeters';
}
__END__

View File

@ -1,4 +1,4 @@
use Test::More tests => 21;
use Test::More tests => 24;
use strict;
use warnings;
@ -11,6 +11,7 @@ BEGIN {
use List::Util qw(first sum);
use Slic3r;
use Slic3r::Geometry qw(epsilon);
use Slic3r::Surface qw(S_TYPE_TOP);
use Slic3r::Test;
{
@ -185,7 +186,7 @@ use Slic3r::Test;
my $first_layer_temperature_set = 0;
my $temperature_set = 0;
my @z_steps = ();
Slic3r::GCode::Reader->new->parse(Slic3r::Test::gcode($print), sub {
Slic3r::GCode::Reader->new(Z => $config->z_offset)->parse(Slic3r::Test::gcode($print), sub {
my ($self, $cmd, $args, $info) = @_;
if ($cmd eq 'G1') {
@ -318,4 +319,23 @@ use Slic3r::Test;
is $diagonal_moves, 0, 'no spiral moves on two-island object';
}
{
# GH: #3732
my $config = Slic3r::Config->new_from_defaults;
$config->set('perimeters', 2);
$config->set('extrusion_width', 0.55);
$config->set('first_layer_height', 0.25);
$config->set('infill_overlap', '50%');
$config->set('layer_height', 0.25);
$config->set('perimeters', 2);
$config->set('extra_perimeters', 1);
my $tprint = Slic3r::Test::init_print('step', config => $config);
$tprint->print->process;
my $layerm19 = $tprint->print->get_object(0)->get_layer(19)->get_region(0);
is scalar(@{$layerm19->slices->filter_by_type(S_TYPE_TOP)}), 1, 'top slice detected';
is scalar(@{$layerm19->fill_surfaces->filter_by_type(S_TYPE_TOP)}), 0, 'no top fill_surface detected';
is $layerm19->perimeters->items_count, 3, 'extra perimeter detected';
}
__END__

View File

@ -1,4 +1,4 @@
use Test::More tests => 6;
use Test::More tests => 8;
use strict;
use warnings;
@ -89,6 +89,39 @@ use Slic3r::Test;
ok Slic3r::Test::gcode($print), 'successful G-code generation when skirt_height = 0 and skirts > 0';
}
{
my $config = Slic3r::Config->new_from_defaults;
$config->set('skirts', 0);
$config->set('brim_width', 5);
$config->set('perimeter_extruder', 2);
$config->set('support_material_extruder', 3);
my $test = sub {
my $print = Slic3r::Test::init_print('20mm_cube', config => $config);
my $tool = undef;
my $brim_tool = undef;
Slic3r::GCode::Reader->new->parse(Slic3r::Test::gcode($print), sub {
my ($self, $cmd, $args, $info) = @_;
if ($cmd =~ /^T(\d+)/) {
$tool = $1;
} elsif ($cmd eq 'G1' && $info->{extruding} && $info->{dist_XY} > 0) {
if (!defined $brim_tool) {
# first extrusion is brim
$brim_tool = $tool;
}
}
});
return $brim_tool;
};
is $test->(), $config->perimeter_extruder-1,
'brim is printed with the extruder used for the perimeters of first object';
$config->set('raft_layers', 1);
is $test->(), $config->support_material_extruder-1,
'if raft is enabled, brim is printed with the extruder used for it';
}
{
my $config = Slic3r::Config->new_from_defaults;
$config->set('layer_height', 0.4);

View File

@ -23,7 +23,7 @@ while (<>) {
my $dist = sqrt( (($x-$X)**2) + (($y-$Y)**2) );
if ($dist > 0) {
my $mm_per_mm = $e_length / $dist; # dE/dXY
my $mm3_per_mm = ($filament_diameter[$T] ** 2) * PI/4 * $mm_per_mm;
my $mm3_per_mm = (($filament_diameter[$T] // 0) ** 2) * PI/4 * $mm_per_mm;
my $vol_speed = $F/60 * $mm3_per_mm;
my $comment = sprintf ' ; dXY = %.3fmm ; dE = %.5fmm ; dE/XY = %.5fmm/mm; volspeed = %.5fmm^3/sec',
$dist, $e_length, $mm_per_mm, $vol_speed;

BIN
var/script.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 748 B

BIN
var/tick.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 537 B

View File

@ -15,13 +15,18 @@ my $mswin = $^O eq 'MSWin32';
# HAS_BOOL : stops Perl/lib/CORE/handy.h from doing "# define bool char" for MSVC
# NOGDI : prevents inclusion of wingdi.h which defines functions Polygon() and Polyline() in global namespace
# BOOST_ASIO_DISABLE_KQUEUE : prevents a Boost ASIO bug on OS X: https://svn.boost.org/trac/boost/ticket/5339
# std=c++11 Enforce usage of C++11 (required now). Minimum compiler supported: gcc 4.9, clang 3.3, MSVC 14.0
my @cflags = qw(-D_GLIBCXX_USE_C99 -DHAS_BOOL -DNOGDI -DSLIC3RXS -DBOOST_ASIO_DISABLE_KQUEUE
-std=c++11);
my @cflags = qw(-D_GLIBCXX_USE_C99 -DHAS_BOOL -DNOGDI -DSLIC3RXS -DBOOST_ASIO_DISABLE_KQUEUE);
if ($cpp_guess->is_gcc) {
# GCC is pedantic with c++11 std, so undefine strict ansi to get M_PI back
push @cflags, qw(-U__STRICT_ANSI__);
}
if (`$Config{cc} -v` =~ /gcc version 4\.6\./) {
# Compatibility with GCC 4.6 is not a requirement, but as long as code compiles on it we try to support it.
push @cflags, qw(-std=c++0x);
} else {
# std=c++11 Enforce usage of C++11 (required now). Minimum compiler supported: gcc 4.9, clang 3.3, MSVC 14.0
push @cflags, qw(-std=c++11);
}
my @ldflags = ();
if ($^O eq 'darwin') {
push @cflags, qw(-stdlib=libc++);
@ -34,6 +39,19 @@ if ($^O eq 'darwin') {
# that prevents this from happening, not needed with newer Boost versions.
# See here for more details: https://svn.boost.org/trac/boost/ticket/7671
push @cflags, qw(-DBOOST_THREAD_DONT_USE_CHRONO -DBOOST_NO_CXX11_RVALUE_REFERENCES -DBOOST_THREAD_USES_MOVE);
# ExtUtils::CppGuess has a hard-coded -lstdc++, so we filter it out
{
no strict 'refs';
no warnings 'redefine';
my $func = "ExtUtils::CppGuess::_get_lflags";
my $orig = *$func{CODE};
*{$func} = sub {
my $lflags = $orig->(@_);
$lflags =~ s/\s*-lstdc\+\+//;
return $lflags;
};
}
}
if ($mswin) {
# In case windows.h is included, we don't want the min / max macros to be active.
@ -75,8 +93,8 @@ if (defined $ENV{BOOST_INCLUDEDIR}) {
}
my @boost_libs = ();
if (defined $ENV{BOOST_LIBRARYDIR}) {
push @boost_libs, $ENV{BOOST_LIBRARYDIR}
if (defined $ENV{BOOST_LIBRARYPATH}) {
push @boost_libs, $ENV{BOOST_LIBRARYPATH}
} elsif (defined $ENV{BOOST_DIR}) {
my $subdir = $ENV{BOOST_DIR} . ($mswin ? '\stage\lib' : '/stage/lib');
if (-d $subdir) {
@ -154,12 +172,12 @@ Slic3r requires the Boost libraries. Please make sure they are installed.
If they are installed, this script should be able to locate them in several
standard locations. If this is not the case, you might want to supply their
path through the BOOST_DIR environment variable:
path through the BOOST_INCLUDEPATH and BOOST_LIBRARYPATH environment variables:
BOOST_DIR=/path/to/boost perl Build.PL
BOOST_INCLUDEPATH=/usr/local/include BOOST_LIBRARYPATH=/usr/lib perl Build.PL
Or you may specify BOOST_INCLUDEPATH and BOOST_LIBRARYPATH separatly, which
is handy, if you have built Boost libraries with mutliple settings.
If you just compiled Boost in its source directory without installing it in the
system you can just provide the BOOST_DIR variable pointing to that directory.
EOF

View File

@ -66,6 +66,10 @@ src/libslic3r/GCode.cpp
src/libslic3r/GCode.hpp
src/libslic3r/GCode/CoolingBuffer.cpp
src/libslic3r/GCode/CoolingBuffer.hpp
src/libslic3r/GCode/SpiralVase.cpp
src/libslic3r/GCode/SpiralVase.hpp
src/libslic3r/GCodeReader.cpp
src/libslic3r/GCodeReader.hpp
src/libslic3r/GCodeSender.cpp
src/libslic3r/GCodeSender.hpp
src/libslic3r/GCodeWriter.cpp

View File

@ -259,6 +259,7 @@ for my $class (qw(
Slic3r::Print::Object
Slic3r::Print::Region
Slic3r::Print::State
Slic3r::SlicingAdaptive
Slic3r::Surface
Slic3r::Surface::Collection
Slic3r::TriangleMesh

View File

@ -318,6 +318,28 @@ stl_read(stl_file *stl, int first_facet, int first) {
}
#endif
#if 1
{
// Positive and negative zeros are possible in the floats, which are considered equal by the FP unit.
// When using a memcmp on raw floats, those numbers report to be different.
// Unify all +0 and -0 to +0 to make the floats equal under memcmp.
uint32_t *f = (uint32_t*)&facet;
for (int j = 0; j < 12; ++ j, ++ f) // 3x vertex + normal: 4x3 = 12 floats
if (*f == 0x80000000)
// Negative zero, switch to positive zero.
*f = 0;
}
#else
{
// Due to the nature of the floating point numbers, close to zero values may be represented with singificantly higher precision
// than the rest of the vertices. Round them to zero.
float *f = (float*)&facet;
for (int j = 0; j < 12; ++ j, ++ f) // 3x vertex + normal: 4x3 = 12 floats
if (*f > -1e-12f && *f < 1e-12f)
// Negative zero, switch to positive zero.
*f = 0;
}
#endif
/* Write the facet into memory. */
memcpy(stl->facet_start+i, &facet, SIZEOF_STL_FACET);
stl_facet_stats(stl, facet, first);

View File

@ -192,11 +192,11 @@ void stl_transform(stl_file *stl, float *trafo3x4) {
for (i_face = 0; i_face < stl->stats.number_of_facets; ++ i_face) {
stl_vertex *vertices = stl->facet_start[i_face].vertex;
for (i_vertex = 0; i_vertex < 3; ++ i_vertex) {
stl_vertex &v_dst = vertices[i_vertex];
stl_vertex v_src = v_dst;
v_dst.x = trafo3x4[0] * v_src.x + trafo3x4[1] * v_src.y + trafo3x4[2] * v_src.z + trafo3x4[3];
v_dst.y = trafo3x4[4] * v_src.x + trafo3x4[5] * v_src.y + trafo3x4[6] * v_src.z + trafo3x4[7];
v_dst.z = trafo3x4[8] * v_src.x + trafo3x4[9] * v_src.y + trafo3x4[10] * v_src.z + trafo3x4[11];
stl_vertex* v_dst = &vertices[i_vertex];
stl_vertex v_src = *v_dst;
v_dst->x = trafo3x4[0] * v_src.x + trafo3x4[1] * v_src.y + trafo3x4[2] * v_src.z + trafo3x4[3];
v_dst->y = trafo3x4[4] * v_src.x + trafo3x4[5] * v_src.y + trafo3x4[6] * v_src.z + trafo3x4[7];
v_dst->z = trafo3x4[8] * v_src.x + trafo3x4[9] * v_src.y + trafo3x4[10] * v_src.z + trafo3x4[11];
}
}
stl_get_size(stl);

View File

@ -76,7 +76,7 @@ enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
#else
typedef signed long long cInt;
static cInt const loRange = 0x3FFFFFFF;
static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
constexpr cInt hiRange = 0x3FFFFFFFFFFFFFFFLL;
typedef signed long long long64; //used by Int128 class
typedef unsigned long long ulong64;

View File

@ -295,6 +295,43 @@ _clipper_do(const ClipperLib::ClipType clipType, const Polygons &subject,
return retval;
}
// The Clipper library has difficulties processing overlapping polygons.
// Namely, the function Clipper::JoinCommonEdges() has potentially a terrible time complexity if the output
// of the operation is of the PolyTree type.
// This function implements a following workaround:
// 1) Peform the Clipper operation with the output to Paths. This method handles overlaps in a reasonable time.
// 2) Run Clipper Union once again to extract the PolyTree from the result of 1).
inline ClipperLib::PolyTree _clipper_do_polytree2(const ClipperLib::ClipType clipType, const Polygons &subject,
const Polygons &clip, const ClipperLib::PolyFillType fillType, const bool safety_offset_)
{
// read input
ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(subject);
ClipperLib::Paths input_clip = Slic3rMultiPoints_to_ClipperPaths(clip);
// perform safety offset
if (safety_offset_) {
if (clipType == ClipperLib::ctUnion) {
safety_offset(&input_subject);
} else {
safety_offset(&input_clip);
}
}
ClipperLib::Clipper clipper;
clipper.AddPaths(input_subject, ClipperLib::ptSubject, true);
clipper.AddPaths(input_clip, ClipperLib::ptClip, true);
// Perform the operation with the output to input_subject.
// This pass does not generate a PolyTree, which is a very expensive operation with the current Clipper library
// if there are overlapping edges.
clipper.Execute(clipType, input_subject, fillType, fillType);
// Perform an additional Union operation to generate the PolyTree ordering.
clipper.Clear();
clipper.AddPaths(input_subject, ClipperLib::ptSubject, true);
ClipperLib::PolyTree retval;
clipper.Execute(ClipperLib::ctUnion, retval, fillType, fillType);
return retval;
}
ClipperLib::PolyTree
_clipper_do(const ClipperLib::ClipType clipType, const Polylines &subject,
const Polygons &clip, const ClipperLib::PolyFillType fillType,
@ -337,7 +374,7 @@ _clipper_ex(ClipperLib::ClipType clipType, const Polygons &subject,
const Polygons &clip, bool safety_offset_)
{
// perform operation
ClipperLib::PolyTree polytree = _clipper_do<ClipperLib::PolyTree>(clipType, subject, clip, ClipperLib::pftNonZero, safety_offset_);
ClipperLib::PolyTree polytree = _clipper_do_polytree2(clipType, subject, clip, ClipperLib::pftNonZero, safety_offset_);
// convert into ExPolygons
return PolyTreeToExPolygons(polytree);

View File

@ -19,7 +19,8 @@ namespace Slic3r {
// How about 2^17=131072?
// By the way, is the scalling needed at all? Cura runs all the computation with a fixed point precision of 1um, while Slic3r scales to 1nm,
// further scaling by 10e5 brings us to
#define CLIPPER_OFFSET_SCALE 100000.0
constexpr float CLIPPER_OFFSET_SCALE = 100000.0;
constexpr auto MAX_COORD = ClipperLib::hiRange / CLIPPER_OFFSET_SCALE;
//-----------------------------------------------------------
// legacy code from Clipper documentation

View File

@ -9,6 +9,8 @@
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ini_parser.hpp>
@ -106,7 +108,6 @@ bool unescape_string_cstyle(const std::string &str, std::string &str_out)
bool unescape_strings_cstyle(const std::string &str, std::vector<std::string> &out)
{
out.clear();
if (str.empty())
return true;
@ -192,7 +193,9 @@ ConfigOptionDef::ConfigOptionDef(const ConfigOptionDef &other)
full_label(other.full_label), category(other.category), tooltip(other.tooltip),
sidetext(other.sidetext), cli(other.cli), ratio_over(other.ratio_over),
multiline(other.multiline), full_width(other.full_width), readonly(other.readonly),
height(other.height), width(other.width), min(other.min), max(other.max)
height(other.height), width(other.width), min(other.min), max(other.max),
aliases(other.aliases), shortcut(other.shortcut), enum_values(other.enum_values),
enum_labels(other.enum_labels), enum_keys_map(other.enum_keys_map)
{
if (other.default_value != NULL)
this->default_value = other.default_value->clone();
@ -212,6 +215,19 @@ ConfigDef::add(const t_config_option_key &opt_key, ConfigOptionType type)
return opt;
}
ConfigOptionDef*
ConfigDef::add(const t_config_option_key &opt_key, const ConfigOptionDef &def)
{
this->options.insert(std::make_pair(opt_key, def));
return &this->options[opt_key];
}
bool
ConfigDef::has(const t_config_option_key &opt_key) const
{
return this->options.count(opt_key) > 0;
}
const ConfigOptionDef*
ConfigDef::get(const t_config_option_key &opt_key) const
{
@ -280,12 +296,27 @@ ConfigBase::serialize(const t_config_option_key &opt_key) const {
}
bool
ConfigBase::set_deserialize(const t_config_option_key &opt_key, std::string str, bool append) {
ConfigBase::set_deserialize(t_config_option_key opt_key, std::string str, bool append) {
const ConfigOptionDef* optdef = this->def->get(opt_key);
if (optdef == NULL) throw UnknownOptionException();
if (optdef == NULL) {
// If we didn't find an option, look for any other option having this as an alias.
for (const auto &opt : this->def->options) {
for (const t_config_option_key &opt_key2 : opt.second.aliases) {
if (opt_key2 == opt_key) {
opt_key = opt_key2;
optdef = &opt.second;
break;
}
}
if (optdef != NULL) break;
}
if (optdef == NULL)
throw UnknownOptionException();
}
if (!optdef->shortcut.empty()) {
for (std::vector<t_config_option_key>::const_iterator it = optdef->shortcut.begin(); it != optdef->shortcut.end(); ++it) {
if (!this->set_deserialize(*it, str)) return false;
for (const t_config_option_key &shortcut : optdef->shortcut) {
if (!this->set_deserialize(shortcut, str)) return false;
}
return true;
}
@ -365,7 +396,9 @@ ConfigBase::load(const std::string &file)
pt::read_ini(file, tree);
BOOST_FOREACH(const pt::ptree::value_type &v, tree) {
try {
this->set_deserialize(v.first.c_str(), v.second.get_value<std::string>().c_str());
t_config_option_key opt_key = v.first;
std::string value = v.second.get_value<std::string>();
this->set_deserialize(opt_key, value);
} catch (UnknownOptionException &e) {
// ignore
}
@ -491,56 +524,109 @@ DynamicConfig::erase(const t_config_option_key &opt_key) {
this->options.erase(opt_key);
}
void
DynamicConfig::read_cli(const std::vector<std::string> &tokens, t_config_option_keys* extra)
{
std::vector<const char*> _argv;
// push a bogus executable name (argv[0])
_argv.push_back("");
for (size_t i = 0; i < tokens.size(); ++i)
_argv.push_back(const_cast<const char*>(tokens[i].c_str()));
this->read_cli(_argv.size(), &_argv[0], extra);
}
void
DynamicConfig::read_cli(const int argc, const char** argv, t_config_option_keys* extra)
{
// cache the CLI option => opt_key mapping
std::map<std::string,std::string> opts;
for (const auto &oit : this->def->options) {
std::string cli = oit.second.cli;
cli = cli.substr(0, cli.find("="));
boost::trim_right_if(cli, boost::is_any_of("!"));
std::vector<std::string> tokens;
boost::split(tokens, cli, boost::is_any_of("|"));
for (const std::string &t : tokens)
opts[t] = oit.first;
}
bool parse_options = true;
for (int i = 1; i < argc; ++i) {
std::string token = argv[i];
// Store non-option arguments in the provided vector.
if (!parse_options || !boost::starts_with(token, "-")) {
extra->push_back(token);
continue;
}
// Stop parsing tokens as options when -- is supplied.
if (token == "--") {
// stop parsing tokens as options
parse_options = false;
} else if (parse_options && boost::starts_with(token, "-")) {
boost::algorithm::trim_left_if(token, boost::algorithm::is_any_of("-"));
// TODO: handle --key=value
// look for the option def
t_config_option_key opt_key;
const ConfigOptionDef* optdef;
for (t_optiondef_map::const_iterator oit = this->def->options.begin();
oit != this->def->options.end(); ++oit) {
optdef = &oit->second;
if (optdef->cli == token
|| optdef->cli == token + '!'
|| boost::starts_with(optdef->cli, token + "=")
|| boost::starts_with(optdef->cli, token + "|")
|| (token.length() == 1 && boost::contains(optdef->cli, "|" + token))) {
opt_key = oit->first;
break;
}
continue;
}
// Remove leading dashes
boost::trim_left_if(token, boost::is_any_of("-"));
// Remove the "no-" prefix used to negate boolean options.
bool no = false;
if (boost::starts_with(token, "no-")) {
no = true;
boost::replace_first(token, "no-", "");
}
// Read value when supplied in the --key=value form.
std::string value;
{
size_t equals_pos = token.find("=");
if (equals_pos != std::string::npos) {
value = token.substr(equals_pos+1);
token.erase(equals_pos);
}
if (opt_key.empty()) {
printf("Warning: unknown option --%s\n", token.c_str());
}
// Look for the cli -> option mapping.
const auto it = opts.find(token);
if (it == opts.end()) {
printf("Warning: unknown option --%s\n", token.c_str());
continue;
}
const t_config_option_key opt_key = it->second;
const ConfigOptionDef &optdef = this->def->options.at(opt_key);
// If the option type expects a value and it was not already provided,
// look for it in the next token.
if (optdef.type != coBool && optdef.type != coBools && value.empty()) {
if (i == (argc-1)) {
printf("No value supplied for --%s\n", token.c_str());
continue;
}
if (ConfigOptionBool* opt = this->opt<ConfigOptionBool>(opt_key, true)) {
opt->value = !boost::starts_with(token, "no-");
} else if (ConfigOptionBools* opt = this->opt<ConfigOptionBools>(opt_key, true)) {
opt->values.push_back(!boost::starts_with(token, "no-"));
} else {
// we expect one more token carrying the value
if (i == (argc-1)) {
printf("No value supplied for --%s\n", token.c_str());
exit(1);
}
this->set_deserialize(opt_key, argv[++i], true);
}
value = argv[++i];
}
// Store the option value.
const bool existing = this->has(opt_key);
if (ConfigOptionBool* opt = this->opt<ConfigOptionBool>(opt_key, true)) {
opt->value = !no;
} else if (ConfigOptionBools* opt = this->opt<ConfigOptionBools>(opt_key, true)) {
if (!existing) opt->values.clear(); // remove the default values
opt->values.push_back(!no);
} else if (ConfigOptionStrings* opt = this->opt<ConfigOptionStrings>(opt_key, true)) {
if (!existing) opt->values.clear(); // remove the default values
opt->deserialize(value, true);
} else if (ConfigOptionFloats* opt = this->opt<ConfigOptionFloats>(opt_key, true)) {
if (!existing) opt->values.clear(); // remove the default values
opt->deserialize(value, true);
} else if (ConfigOptionPoints* opt = this->opt<ConfigOptionPoints>(opt_key, true)) {
if (!existing) opt->values.clear(); // remove the default values
opt->deserialize(value, true);
} else {
extra->push_back(token);
this->set_deserialize(opt_key, value, true);
}
}
}
@ -597,4 +683,27 @@ ConfigOptionPoint3::deserialize(std::string str, bool append) {
return true;
};
bool
ConfigOptionPoints::deserialize(std::string str, bool append) {
if (!append) this->values.clear();
std::vector<std::string> tokens;
boost::split(tokens, str, boost::is_any_of("x,"));
if (tokens.size() % 2) return false;
try {
for (size_t i = 0; i < tokens.size(); ++i) {
Pointf point;
point.x = boost::lexical_cast<coordf_t>(tokens[i]);
point.y = boost::lexical_cast<coordf_t>(tokens[++i]);
this->values.push_back(point);
}
} catch (boost::bad_lexical_cast &e) {
printf("%s\n", e.what());
return false;
}
return true;
}
}

View File

@ -248,6 +248,7 @@ class ConfigOptionStrings : public ConfigOptionVector<std::string>
};
bool deserialize(std::string str, bool append = false) {
if (!append) this->values.clear();
return unescape_strings_cstyle(str, this->values);
};
};
@ -390,24 +391,7 @@ class ConfigOptionPoints : public ConfigOptionVector<Pointf>
return vv;
};
bool deserialize(std::string str, bool append = false) {
if (!append) this->values.clear();
std::istringstream is(str);
std::string point_str;
while (std::getline(is, point_str, ',')) {
Pointf point;
std::istringstream iss(point_str);
std::string coord_str;
if (std::getline(iss, coord_str, 'x')) {
std::istringstream(coord_str) >> point.x;
if (std::getline(iss, coord_str, 'x')) {
std::istringstream(coord_str) >> point.y;
}
}
this->values.push_back(point);
}
return true;
};
bool deserialize(std::string str, bool append = false);
};
class ConfigOptionBool : public ConfigOptionSingle<bool>
@ -641,6 +625,8 @@ class ConfigDef
public:
t_optiondef_map options;
ConfigOptionDef* add(const t_config_option_key &opt_key, ConfigOptionType type);
ConfigOptionDef* add(const t_config_option_key &opt_key, const ConfigOptionDef &def);
bool has(const t_config_option_key &opt_key) const;
const ConfigOptionDef* get(const t_config_option_key &opt_key) const;
void merge(const ConfigDef &other);
};
@ -667,7 +653,7 @@ class ConfigBase
bool equals(ConfigBase &other);
t_config_option_keys diff(ConfigBase &other);
std::string serialize(const t_config_option_key &opt_key) const;
bool set_deserialize(const t_config_option_key &opt_key, std::string str, bool append = false);
virtual bool set_deserialize(t_config_option_key opt_key, std::string str, bool append = false);
double get_abs_value(const t_config_option_key &opt_key) const;
double get_abs_value(const t_config_option_key &opt_key, double ratio_over) const;
void setenv_();
@ -690,6 +676,7 @@ class DynamicConfig : public virtual ConfigBase
virtual ConfigOption* optptr(const t_config_option_key &opt_key, bool create = false);
t_config_option_keys keys() const;
void erase(const t_config_option_key &opt_key);
void read_cli(const std::vector<std::string> &tokens, t_config_option_keys* extra);
void read_cli(const int argc, const char **argv, t_config_option_keys* extra);
private:

View File

@ -129,6 +129,14 @@ ExPolygon::has_boundary_point(const Point &point) const
return false;
}
void
ExPolygon::remove_vertical_collinear_points(coord_t tolerance)
{
this->contour.remove_vertical_collinear_points(tolerance);
for (Polygon &p : this->holes)
p.remove_vertical_collinear_points(tolerance);
}
void
ExPolygon::simplify_p(double tolerance, Polygons* polygons) const
{
@ -506,4 +514,12 @@ ExPolygon::dump_perl() const
return ret.str();
}
std::ostream&
operator <<(std::ostream &s, const ExPolygons &expolygons)
{
for (const ExPolygon &e : expolygons)
s << e.dump_perl() << std::endl;
return s;
}
}

View File

@ -4,6 +4,7 @@
#include "libslic3r.h"
#include "Polygon.hpp"
#include "Polyline.hpp"
#include <ostream>
#include <vector>
namespace Slic3r {
@ -29,6 +30,7 @@ class ExPolygon
bool contains(const Point &point) const;
bool contains_b(const Point &point) const;
bool has_boundary_point(const Point &point) const;
void remove_vertical_collinear_points(coord_t tolerance);
void simplify_p(double tolerance, Polygons* polygons) const;
Polygons simplify_p(double tolerance) const;
ExPolygons simplify(double tolerance) const;
@ -61,6 +63,8 @@ operator+(ExPolygons src1, const ExPolygons &src2) {
return src1;
};
std::ostream& operator <<(std::ostream &s, const ExPolygons &expolygons);
}
// start Boost

View File

@ -116,12 +116,20 @@ Polygons
ExPolygonCollection::contours() const
{
Polygons contours;
for (ExPolygons::const_iterator it = this->expolygons.begin(); it != this->expolygons.end(); ++it) {
contours.push_back(it->contour);
}
for (const ExPolygon &ex : this->expolygons)
contours.push_back(ex.contour);
return contours;
}
Polygons
ExPolygonCollection::holes() const
{
Polygons holes;
for (const ExPolygon &ex : this->expolygons)
append_to(holes, ex.holes);
return holes;
}
void
ExPolygonCollection::append(const ExPolygons &expp)
{

View File

@ -31,6 +31,7 @@ class ExPolygonCollection
Polygon convex_hull() const;
Lines lines() const;
Polygons contours() const;
Polygons holes() const;
void append(const ExPolygons &expolygons);
};

View File

@ -111,6 +111,18 @@ Extruder::filament_diameter() const
return this->config->filament_diameter.get_at(this->id);
}
double
Extruder::filament_density() const
{
return this->config->filament_density.get_at(this->id);
}
double
Extruder::filament_cost() const
{
return this->config->filament_cost.get_at(this->id);
}
double
Extruder::extrusion_multiplier() const
{

View File

@ -29,6 +29,8 @@ class Extruder
double used_filament() const;
double filament_diameter() const;
double filament_density() const;
double filament_cost() const;
double extrusion_multiplier() const;
double retract_length() const;
double retract_lift() const;

View File

@ -49,7 +49,13 @@ void FillPlanePath::_fill_surface_single(
}
// polylines = intersection_pl(polylines_src, offset((Polygons)expolygon, scale_(0.02)));
polylines = intersection_pl(polylines, (Polygons)expolygon);
// Extend paths in order to ensure overlap with perimeters
for (Polyline &p : polylines) {
p.extend_start(this->endpoints_overlap);
p.extend_end(this->endpoints_overlap);
}
/*
if (1) {
require "Slic3r/SVG.pm";

View File

@ -35,6 +35,7 @@ class FillArchimedeanChords : public FillPlanePath
public:
virtual Fill* clone() const { return new FillArchimedeanChords(*this); };
virtual ~FillArchimedeanChords() {}
virtual bool can_solid() const { return true; };
protected:
virtual bool _centered() const { return true; }
@ -46,6 +47,7 @@ class FillHilbertCurve : public FillPlanePath
public:
virtual Fill* clone() const { return new FillHilbertCurve(*this); };
virtual ~FillHilbertCurve() {}
virtual bool can_solid() const { return true; };
protected:
virtual bool _centered() const { return false; }
@ -57,6 +59,7 @@ class FillOctagramSpiral : public FillPlanePath
public:
virtual Fill* clone() const { return new FillOctagramSpiral(*this); };
virtual ~FillOctagramSpiral() {}
virtual bool can_solid() const { return true; };
protected:
virtual bool _centered() const { return true; }

View File

@ -1,3 +1,9 @@
//#define DEBUG_RECTILINEAR
#ifdef DEBUG_RECTILINEAR
#undef NDEBUG
#include "../SVG.hpp"
#endif
#include "../ClipperUtils.hpp"
#include "../ExPolygon.hpp"
#include "../PolylineCollection.hpp"
@ -7,17 +13,16 @@
#include "FillRectilinear.hpp"
//#define DEBUG_RECTILINEAR
#ifdef DEBUG_RECTILINEAR
#include "../SVG.hpp"
#endif
namespace Slic3r {
void
FillRectilinear::_fill_single_direction(ExPolygon expolygon,
const direction_t &direction, coord_t x_shift, Polylines* out)
{
// Remove almost collinear points (vertical ones might break this algorithm
// because of rounding).
expolygon.remove_vertical_collinear_points(1);
// rotate polygons so that we can work with vertical lines here
expolygon.rotate(-direction.first);
@ -58,6 +63,27 @@ FillRectilinear::_fill_single_direction(ExPolygon expolygon,
// Whenever between two intersection points we find vertices of the original polygon,
// store them in the 'skipped' member of the latter point.
struct IntersectionPoint : Point {
enum ipType { ipTypeLower, ipTypeUpper, ipTypeMiddle };
ipType type;
// skipped contains the polygon points accumulated between the previous intersection
// point and the current one, in the original polygon winding order (does not contain
// either points)
Points skipped;
// next contains a polygon portion connecting this point to the first intersection
// point found following the polygon in any direction but having:
// x > this->x || (x == this->x && y > this->y)
// (it doesn't contain *this but it contains the target intersection point)
Points next;
IntersectionPoint() : Point() {};
IntersectionPoint(coord_t x, coord_t y, ipType _type) : Point(x,y), type(_type) {};
};
typedef std::map<coord_t,IntersectionPoint> vertical_t; // <y,point>
typedef std::map<coord_t,vertical_t> grid_t; // <x,<y,point>>
grid_t grid;
{
const Polygons polygons = expolygon;

View File

@ -23,27 +23,6 @@ protected:
void _fill_single_direction(ExPolygon expolygon, const direction_t &direction,
coord_t x_shift, Polylines* out);
struct IntersectionPoint : Point {
enum ipType { ipTypeLower, ipTypeUpper, ipTypeMiddle };
ipType type;
// skipped contains the polygon points accumulated between the previous intersection
// point and the current one, in the original polygon winding order (does not contain
// either points)
Points skipped;
// next contains a polygon portion connecting this point to the first intersection
// point found following the polygon in any direction but having:
// x > this->x || (x == this->x && y > this->y)
// (it doesn't contain *this but it contains the target intersection point)
Points next;
IntersectionPoint() : Point() {};
IntersectionPoint(coord_t x, coord_t y, ipType _type) : Point(x,y), type(_type) {};
};
typedef std::map<coord_t,IntersectionPoint> vertical_t; // <y,point>
typedef std::map<coord_t,vertical_t> grid_t; // <x,<y,point>>
};
class FillAlignedRectilinear : public FillRectilinear

View File

@ -91,14 +91,14 @@ Flow::_auto_width(FlowRole role, float nozzle_diameter, float height) {
float width = ((nozzle_diameter*nozzle_diameter) * PI + (height*height) * (4.0 - PI)) / (4.0 * height);
float min = nozzle_diameter * 1.05;
float max = -1;
float max = nozzle_diameter * 3; // cap width to 3x nozzle diameter
if (role == frExternalPerimeter || role == frSupportMaterial || role == frSupportMaterialInterface) {
min = max = nozzle_diameter;
} else if (role != frInfill) {
// do not limit width for sparse infill so that we use full native flow for it
max = nozzle_diameter * 1.7;
}
if (max != -1 && width > max) width = max;
if (width > max) width = max;
if (width < min) width = min;
return width;

View File

@ -7,8 +7,8 @@
namespace Slic3r {
#define BRIDGE_EXTRA_SPACING 0.05
#define OVERLAP_FACTOR 1.0
constexpr auto BRIDGE_EXTRA_SPACING = 0.05;
constexpr auto OVERLAP_FACTOR = 1.0;
enum FlowRole {
frExternalPerimeter,

View File

@ -453,8 +453,8 @@ GCode::extrude(ExtrusionLoop loop, std::string description, double speed)
paths.front().polyline.points[0],
paths.front().polyline.points[1]
);
double distance = std::min(
scale_(EXTRUDER_CONFIG(nozzle_diameter)),
const double distance = std::min(
(double)scale_(EXTRUDER_CONFIG(nozzle_diameter)),
first_segment.length()
);
Point point = first_segment.point_at(distance);

View File

@ -0,0 +1,95 @@
#include "SpiralVase.hpp"
#include <sstream>
namespace Slic3r {
std::string
_format_z(float z)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(3)
<< z;
return ss.str();
}
std::string
SpiralVase::process_layer(const std::string &gcode)
{
/* This post-processor relies on several assumptions:
- all layers are processed through it, including those that are not supposed
to be transformed, in order to update the reader with the XY positions
- each call to this method includes a full layer, with a single Z move
at the beginning
- each layer is composed by suitable geometry (i.e. a single complete loop)
- loops were not clipped before calling this method */
// If we're not going to modify G-code, just feed it to the reader
// in order to update positions.
if (!this->enable) {
this->_reader.parse(gcode, {});
return gcode;
}
// Get total XY length for this layer by summing all extrusion moves.
float total_layer_length = 0;
float layer_height = 0;
float z;
bool set_z = false;
{
GCodeReader r = this->_reader; // clone
r.parse(gcode, [&total_layer_length, &layer_height, &z, &set_z]
(GCodeReader &, GCodeReader::GCodeLine &line) {
if (line.cmd == "G1") {
if (line.extruding()) {
total_layer_length += line.dist_XY();
} else if (line.has('Z')) {
layer_height += line.dist_Z();
if (!set_z) {
z = line.new_Z();
set_z = true;
}
}
}
});
}
// Remove layer height from initial Z.
z -= layer_height;
std::string new_gcode;
this->_reader.parse(gcode, [&new_gcode, &z, &layer_height, &total_layer_length]
(GCodeReader &, GCodeReader::GCodeLine line) {
if (line.cmd == "G1") {
if (line.has('Z')) {
// If this is the initial Z move of the layer, replace it with a
// (redundant) move to the last Z of previous layer.
line.set('Z', _format_z(z));
new_gcode += line.raw + '\n';
return;
} else {
float dist_XY = line.dist_XY();
if (dist_XY > 0) {
// horizontal move
if (line.extruding()) {
z += dist_XY * layer_height / total_layer_length;
line.set('Z', _format_z(z));
new_gcode += line.raw + '\n';
}
return;
/* Skip travel moves: the move to first perimeter point will
cause a visible seam when loops are not aligned in XY; by skipping
it we blend the first loop move in the XY plane (although the smoothness
of such blend depend on how long the first segment is; maybe we should
enforce some minimum length?). */
}
}
}
new_gcode += line.raw + '\n';
});
return new_gcode;
}
}

View File

@ -0,0 +1,29 @@
#ifndef slic3r_SpiralVase_hpp_
#define slic3r_SpiralVase_hpp_
#include "libslic3r.h"
#include "GCode.hpp"
#include "GCodeReader.hpp"
namespace Slic3r {
class SpiralVase {
public:
bool enable;
SpiralVase(const PrintConfig &config)
: enable(false), _config(&config)
{
this->_reader.Z = this->_config->z_offset;
this->_reader.apply_config(*this->_config);
};
std::string process_layer(const std::string &gcode);
private:
const PrintConfig* _config;
GCodeReader _reader;
};
}
#endif

View File

@ -0,0 +1,94 @@
#include "GCodeReader.hpp"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
namespace Slic3r {
void
GCodeReader::apply_config(const PrintConfigBase &config)
{
this->_config.apply(config, true);
this->_extrusion_axis = this->_config.get_extrusion_axis()[0];
}
void
GCodeReader::parse(const std::string &gcode, callback_t callback)
{
std::istringstream ss(gcode);
std::string line;
while (std::getline(ss, line)) {
GCodeLine gline(this);
gline.raw = line;
if (this->verbose)
std::cout << line << std::endl;
// strip comment
{
size_t pos = line.find(';');
if (pos != std::string::npos) {
gline.comment = line.substr(pos+1);
line.erase(pos);
}
}
// command and args
{
std::vector<std::string> args;
boost::split(args, line, boost::is_any_of(" "));
// first one is cmd
gline.cmd = args.front();
args.erase(args.begin());
for (std::string &arg : args) {
if (arg.size() < 2) continue;
gline.args.insert(std::make_pair(arg[0], arg.substr(1)));
}
}
// convert extrusion axis
if (this->_extrusion_axis != 'E') {
const auto it = gline.args.find(this->_extrusion_axis);
if (it != gline.args.end()) {
std::swap(gline.args['E'], it->second);
gline.args.erase(it);
}
}
if (gline.has('E') && this->_config.use_relative_e_distances)
this->E = 0;
if (callback) callback(*this, gline);
// update coordinates
if (gline.cmd == "G0" || gline.cmd == "G1" || gline.cmd == "G92") {
this->X = gline.new_X();
this->Y = gline.new_Y();
this->Z = gline.new_Z();
this->E = gline.new_E();
this->F = gline.new_F();
}
}
}
void
GCodeReader::GCodeLine::set(char arg, std::string value)
{
const std::string space(" ");
if (this->has(arg)) {
size_t pos = this->raw.find(space + arg)+2;
size_t end = this->raw.find(' ', pos+1);
this->raw = this->raw.replace(pos, end-pos, value);
} else {
size_t pos = this->raw.find(' ');
if (pos == std::string::npos) {
this->raw += space + arg + value;
} else {
this->raw = this->raw.replace(pos, 0, space + arg + value);
}
}
this->args[arg] = value;
}
}

View File

@ -0,0 +1,64 @@
#ifndef slic3r_GCodeReader_hpp_
#define slic3r_GCodeReader_hpp_
#include "libslic3r.h"
#include <cmath>
#include <cstdlib>
#include <functional>
#include <string>
#include "PrintConfig.hpp"
namespace Slic3r {
class GCodeReader;
class GCodeReader {
public:
class GCodeLine {
public:
GCodeReader* reader;
std::string raw;
std::string cmd;
std::string comment;
std::map<char,std::string> args;
GCodeLine(GCodeReader* _reader) : reader(_reader) {};
bool has(char arg) const { return this->args.count(arg) > 0; };
float new_X() const { return this->has('X') ? atof(this->args.at('X').c_str()) : this->reader->X; };
float new_Y() const { return this->has('Y') ? atof(this->args.at('Y').c_str()) : this->reader->Y; };
float new_Z() const { return this->has('Z') ? atof(this->args.at('Z').c_str()) : this->reader->Z; };
float new_E() const { return this->has('E') ? atof(this->args.at('E').c_str()) : this->reader->E; };
float new_F() const { return this->has('F') ? atof(this->args.at('F').c_str()) : this->reader->F; };
float dist_X() const { return this->new_X() - this->reader->X; };
float dist_Y() const { return this->new_Y() - this->reader->Y; };
float dist_Z() const { return this->new_Z() - this->reader->Z; };
float dist_E() const { return this->new_E() - this->reader->E; };
float dist_XY() const {
float x = this->dist_X();
float y = this->dist_Y();
return sqrt(x*x + y*y);
};
bool extruding() const { return this->cmd == "G1" && this->dist_E() > 0; };
bool retracting() const { return this->cmd == "G1" && this->dist_E() < 0; };
bool travel() const { return this->cmd == "G1" && !this->has('E'); };
void set(char arg, std::string value);
};
typedef std::function<void(GCodeReader&, GCodeLine&)> callback_t;
float X, Y, Z, E, F;
bool verbose;
callback_t callback;
GCodeReader() : X(0), Y(0), Z(0), E(0), F(0), verbose(false), _extrusion_axis('E') {};
void apply_config(const PrintConfigBase &config);
void parse(const std::string &gcode, callback_t callback);
private:
GCodeConfig _config;
char _extrusion_axis;
};
} /* namespace Slic3r */
#endif /* slic3r_GCodeReader_hpp_ */

View File

@ -26,10 +26,10 @@
std::fstream fs;
#endif
#define KEEP_SENT 20
namespace Slic3r {
constexpr auto KEEP_SENT = 20;
namespace asio = boost::asio;
GCodeSender::GCodeSender()
@ -46,30 +46,30 @@ bool
GCodeSender::connect(std::string devname, unsigned int baud_rate)
{
this->disconnect();
this->set_error_status(false);
try {
this->serial.open(devname);
this->serial.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::odd));
this->serial.set_option(asio::serial_port_base::character_size(asio::serial_port_base::character_size(8)));
this->serial.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none));
this->serial.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one));
this->set_baud_rate(baud_rate);
this->serial.close();
this->serial.open(devname);
this->serial.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none));
// set baud rate again because set_option overwrote it
this->set_baud_rate(baud_rate);
this->open = true;
this->reset();
} catch (boost::system::system_error &e) {
printf("Caught error\n");
this->set_error_status(true);
return false;
}
this->serial.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::odd));
this->serial.set_option(asio::serial_port_base::character_size(asio::serial_port_base::character_size(8)));
this->serial.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none));
this->serial.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one));
this->set_baud_rate(baud_rate);
this->serial.close();
this->serial.open(devname);
this->serial.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none));
// set baud rate again because set_option overwrote it
this->set_baud_rate(baud_rate);
this->open = true;
this->reset();
// a reset firmware expect line numbers to start again from 1
this->sent = 0;
this->last_sent.clear();

View File

@ -609,6 +609,13 @@ MedialAxis::process_edge_neighbors(const VD::edge_type* edge, ThickPolyline* pol
bool
MedialAxis::validate_edge(const VD::edge_type* edge)
{
// prevent overflows and detect almost-infinite edges
if (std::abs(edge->vertex0()->x()) > (double)MAX_COORD
|| std::abs(edge->vertex0()->y()) > (double)MAX_COORD
|| std::abs(edge->vertex1()->x()) > (double)MAX_COORD
|| std::abs(edge->vertex1()->y()) > (double)MAX_COORD)
return false;
// construct the line representing this edge of the Voronoi diagram
const Line line(
Point( edge->vertex0()->x(), edge->vertex0()->y() ),

View File

@ -1,4 +1,6 @@
#include "../IO.hpp"
#include <iostream>
#include <fstream>
#include <string.h>
#include <map>
#include <string>
@ -87,11 +89,12 @@ struct AMFParserContext
NODE_TYPE_DELTAX, // amf/constellation/instance/deltax
NODE_TYPE_DELTAY, // amf/constellation/instance/deltay
NODE_TYPE_RZ, // amf/constellation/instance/rz
NODE_TYPE_SCALE, // amf/constellation/instance/scale
NODE_TYPE_METADATA, // anywhere under amf/*/metadata
};
struct Instance {
Instance() : deltax_set(false), deltay_set(false), rz_set(false) {}
Instance() : deltax_set(false), deltay_set(false), rz_set(false), scale_set(false) {}
// Shift in the X axis.
float deltax;
bool deltax_set;
@ -101,6 +104,9 @@ struct AMFParserContext
// Rotation around the Z axis.
float rz;
bool rz_set;
// Scaling factor
float scale;
bool scale_set;
};
struct Object {
@ -210,6 +216,8 @@ void AMFParserContext::startElement(const char *name, const char **atts)
node_type_new = NODE_TYPE_DELTAY;
else if (strcmp(name, "rz") == 0)
node_type_new = NODE_TYPE_RZ;
else if (strcmp(name, "scale") == 0)
node_type_new = NODE_TYPE_SCALE;
}
break;
case 4:
@ -266,7 +274,7 @@ void AMFParserContext::characters(const XML_Char *s, int len)
{
switch (m_path.size()) {
case 4:
if (m_path.back() == NODE_TYPE_DELTAX || m_path.back() == NODE_TYPE_DELTAY || m_path.back() == NODE_TYPE_RZ)
if (m_path.back() == NODE_TYPE_DELTAX || m_path.back() == NODE_TYPE_DELTAY || m_path.back() == NODE_TYPE_RZ || m_path.back() == NODE_TYPE_SCALE)
m_value[0].append(s, len);
break;
case 6:
@ -312,6 +320,12 @@ void AMFParserContext::endElement(const char *name)
m_instance->rz_set = true;
m_value[0].clear();
break;
case NODE_TYPE_SCALE:
assert(m_instance);
m_instance->scale = float(atof(m_value[0].c_str()));
m_instance->scale_set = true;
m_value[0].clear();
break;
// Object vertices:
case NODE_TYPE_VERTEX:
@ -426,6 +440,7 @@ void AMFParserContext::endDocument()
mi->offset.x = instance.deltax;
mi->offset.y = instance.deltay;
mi->rotation = instance.rz_set ? instance.rz : 0.f;
mi->scaling_factor = instance.scale_set ? instance.scale : 1.f;
}
}
}
@ -482,105 +497,121 @@ AMF::read(std::string input_file, Model* model)
bool
AMF::write(Model& model, std::string output_file)
{
FILE *file = ::fopen(output_file.c_str(), "wb");
if (file == NULL)
return false;
fprintf(file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(file, "<amf unit=\"millimeter\">\n");
fprintf(file, "<metadata type=\"cad\">Slic3r %s</metadata>\n", SLIC3R_VERSION);
using namespace std;
ofstream file;
file.open(output_file, ios::out | ios::trunc);
file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl
<< "<amf unit=\"millimeter\">" << endl
<< "<metadata type=\"cad\">Slic3r " << SLIC3R_VERSION << "</metadata>" << endl;
for (const auto &material : model.materials) {
if (material.first.empty())
continue;
// note that material-id must never be 0 since it's reserved by the AMF spec
fprintf(file, " <material id=\"%s\">\n", material.first.c_str());
file << " <material id=\"" << material.first << "\">" << endl;
for (const auto &attr : material.second->attributes)
fprintf(file, " <metadata type=\"%s\">%s</metadata>\n", attr.first.c_str(), attr.second.c_str());
file << " <metadata type=\"" << attr.first << "\">" << attr.second << "</metadata>" << endl;
for (const std::string &key : material.second->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), material.second->config.serialize(key).c_str());
fprintf(file, " </material>\n");
file << " <metadata type=\"slic3r." << key << "\">"
<< material.second->config.serialize(key) << "</metadata>" << endl;
file << " </material>" << endl;
}
std::string instances;
for (size_t object_id = 0; object_id < model.objects.size(); ++ object_id) {
ostringstream instances;
for (size_t object_id = 0; object_id < model.objects.size(); ++object_id) {
ModelObject *object = model.objects[object_id];
fprintf(file, " <object id=\"%zu\">\n", object_id);
file << " <object id=\"" << object_id << "\">" << endl;
for (const std::string &key : object->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), object->config.serialize(key).c_str());
if (! object->name.empty())
fprintf(file, " <metadata type=\"name\">%s</metadata>\n", object->name.c_str());
file << " <metadata type=\"slic3r." << key << "\">"
<< object->config.serialize(key) << "</metadata>" << endl;
if (!object->name.empty())
file << " <metadata type=\"name\">" << object->name << "</metadata>" << endl;
//FIXME Store the layer height ranges (ModelObject::layer_height_ranges)
fprintf(file, " <mesh>\n");
fprintf(file, " <vertices>\n");
std::vector<int> vertices_offsets;
int num_vertices = 0;
//FIXME: Store the layer height ranges (ModelObject::layer_height_ranges)
file << " <mesh>" << endl;
file << " <vertices>" << endl;
std::vector<size_t> vertices_offsets;
size_t num_vertices = 0;
for (ModelVolume *volume : object->volumes) {
volume->mesh.require_shared_vertices();
vertices_offsets.push_back(num_vertices);
if (! volume->mesh.repaired)
CONFESS("store_amf() requires repair()");
auto &stl = volume->mesh.stl;
if (stl.v_shared == NULL)
stl_generate_shared_vertices(&stl);
for (size_t i = 0; i < stl.stats.shared_vertices; ++ i) {
fprintf(file, " <vertex>\n");
fprintf(file, " <coordinates>\n");
fprintf(file, " <x>%f</x>\n", stl.v_shared[i].x);
fprintf(file, " <y>%f</y>\n", stl.v_shared[i].y);
fprintf(file, " <z>%f</z>\n", stl.v_shared[i].z);
fprintf(file, " </coordinates>\n");
fprintf(file, " </vertex>\n");
}
const auto &stl = volume->mesh.stl;
for (size_t i = 0; i < stl.stats.shared_vertices; ++i)
// Subtract origin_translation in order to restore the coordinates of the parts
// before they were imported. Otherwise, when this AMF file is reimported parts
// will be placed in the plater correctly, but we will have lost origin_translation
// thus any additional part added will not align with the others.
// In order to do this we compensate for this translation in the instance placement
// below.
file << " <vertex>" << endl
<< " <coordinates>" << endl
<< " <x>" << (stl.v_shared[i].x - object->origin_translation.x) << "</x>" << endl
<< " <y>" << (stl.v_shared[i].y - object->origin_translation.y) << "</y>" << endl
<< " <z>" << (stl.v_shared[i].z - object->origin_translation.z) << "</z>" << endl
<< " </coordinates>" << endl
<< " </vertex>" << endl;
num_vertices += stl.stats.shared_vertices;
}
fprintf(file, " </vertices>\n");
for (size_t i_volume = 0; i_volume < object->volumes.size(); ++ i_volume) {
file << " </vertices>" << endl;
for (size_t i_volume = 0; i_volume < object->volumes.size(); ++i_volume) {
ModelVolume *volume = object->volumes[i_volume];
int vertices_offset = vertices_offsets[i_volume];
if (volume->material_id().empty())
fprintf(file, " <volume>\n");
file << " <volume>" << endl;
else
fprintf(file, " <volume materialid=\"%s\">\n", volume->material_id().c_str());
file << " <volume materialid=\"" << volume->material_id() << "\">" << endl;
for (const std::string &key : volume->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), volume->config.serialize(key).c_str());
if (! volume->name.empty())
fprintf(file, " <metadata type=\"name\">%s</metadata>\n", volume->name.c_str());
file << " <metadata type=\"slic3r." << key << "\">"
<< volume->config.serialize(key) << "</metadata>" << endl;
if (!volume->name.empty())
file << " <metadata type=\"name\">" << volume->name << "</metadata>" << endl;
if (volume->modifier)
fprintf(file, " <metadata type=\"slic3r.modifier\">1</metadata>\n");
for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++ i) {
fprintf(file, " <triangle>\n");
file << " <metadata type=\"slic3r.modifier\">1</metadata>" << endl;
for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++i) {
file << " <triangle>" << endl;
for (int j = 0; j < 3; ++ j)
fprintf(file, " <v%d>%d</v%d>\n", j+1, volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset, j+1);
fprintf(file, " </triangle>\n");
}
fprintf(file, " </volume>\n");
}
fprintf(file, " </mesh>\n");
fprintf(file, " </object>\n");
if (! object->instances.empty()) {
for (ModelInstance *instance : object->instances) {
char buf[512];
sprintf(buf,
" <instance objectid=\"%zu\">\n"
" <deltax>%lf</deltax>\n"
" <deltay>%lf</deltay>\n"
" <rz>%lf</rz>\n"
" </instance>\n",
object_id,
instance->offset.x,
instance->offset.y,
instance->rotation);
//FIXME missing instance->scaling_factor
instances.append(buf);
file << " <v" << (j+1) << ">"
<< (volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset)
<< "</v" << (j+1) << ">" << endl;
file << " </triangle>" << endl;
}
file << " </volume>" << endl;
}
file << " </mesh>" << endl;
file << " </object>" << endl;
for (const ModelInstance* instance : object->instances)
instances
<< " <instance objectid=\"" << object_id << "\">" << endl
<< " <deltax>" << instance->offset.x + object->origin_translation.x << "</deltax>" << endl
<< " <deltay>" << instance->offset.y + object->origin_translation.y << "</deltay>" << endl
<< " <rz>%" << instance->rotation << "</rz>" << endl
<< " <scale>" << instance->scaling_factor << "</scale>" << endl
<< " </instance>" << endl;
}
if (! instances.empty()) {
fprintf(file, " <constellation id=\"1\">\n");
fwrite(instances.data(), instances.size(), 1, file);
fprintf(file, " </constellation>\n");
}
fprintf(file, "</amf>\n");
fclose(file);
std::string instances_str = instances.str();
if (!instances_str.empty())
file << " <constellation id=\"1\">" << endl
<< instances_str
<< " </constellation>" << endl;
file << "</amf>" << endl;
file.close();
return true;
}

View File

@ -247,4 +247,183 @@ Layer::make_fills()
}
}
// This function analyzes slices of a region (SurfaceCollection slices).
// Each region slice (instance of Surface) is analyzed, whether it is supported or whether it is the top surface.
// Initially all slices are of type S_TYPE_INTERNAL.
// Slices are compared against the top / bottom slices and regions and classified to the following groups:
// S_TYPE_TOP - Part of a region, which is not covered by any upper layer. This surface will be filled with a top solid infill.
// S_TYPE_BOTTOMBRIDGE - Part of a region, which is not fully supported, but it hangs in the air, or it hangs losely on a support or a raft.
// S_TYPE_BOTTOM - Part of a region, which is not supported by the same region, but it is supported either by another region, or by a soluble interface layer.
// S_TYPE_INTERNAL - Part of a region, which is supported by the same region type.
// If a part of a region is of S_TYPE_BOTTOM and S_TYPE_TOP, the S_TYPE_BOTTOM wins.
void
Layer::detect_surfaces_type()
{
PrintObject &object = *this->object();
for (size_t region_id = 0; region_id < this->regions.size(); ++region_id) {
LayerRegion &layerm = *this->regions[region_id];
// comparison happens against the *full* slices (considering all regions)
// unless internal shells are requested
// We call layer->slices or layerm->slices on these neighbor layers
// and we convert them into Polygons so we only care about their total
// coverage. We only write to layerm->slices so we can read layer->slices safely.
Layer* const &upper_layer = this->upper_layer;
Layer* const &lower_layer = this->lower_layer;
// collapse very narrow parts (using the safety offset in the diff is not enough)
const float offs = layerm.flow(frExternalPerimeter).scaled_width() / 10.f;
const Polygons layerm_slices_surfaces = layerm.slices;
// find top surfaces (difference between current surfaces
// of current layer and upper one)
SurfaceCollection top;
if (upper_layer != NULL) {
Polygons upper_slices;
if (object.config.interface_shells.value) {
const LayerRegion* upper_layerm = upper_layer->get_region(region_id);
boost::lock_guard<boost::mutex> l(upper_layerm->_slices_mutex);
upper_slices = upper_layerm->slices;
} else {
upper_slices = upper_layer->slices;
}
top.append(
offset2_ex(
diff(layerm_slices_surfaces, upper_slices, true),
-offs, offs
),
stTop
);
} else {
// if no upper layer, all surfaces of this one are solid
// we clone surfaces because we're going to clear the slices collection
top = layerm.slices;
for (Surface &s : top.surfaces) s.surface_type = stTop;
}
// find bottom surfaces (difference between current surfaces
// of current layer and lower one)
SurfaceCollection bottom;
if (lower_layer != NULL) {
// If we have soluble support material, don't bridge. The overhang will be squished against a soluble layer separating
// the support from the print.
const SurfaceType surface_type_bottom =
(object.config.support_material.value && object.config.support_material_contact_distance.value == 0)
? stBottom
: stBottomBridge;
// Any surface lying on the void is a true bottom bridge (an overhang)
bottom.append(
offset2_ex(
diff(layerm_slices_surfaces, lower_layer->slices, true),
-offs, offs
),
surface_type_bottom
);
// if user requested internal shells, we need to identify surfaces
// lying on other slices not belonging to this region
if (object.config.interface_shells) {
// non-bridging bottom surfaces: any part of this layer lying
// on something else, excluding those lying on our own region
const LayerRegion* lower_layerm = lower_layer->get_region(region_id);
boost::lock_guard<boost::mutex> l(lower_layerm->_slices_mutex);
bottom.append(
offset2_ex(
diff(
intersection(layerm_slices_surfaces, lower_layer->slices), // supported
lower_layerm->slices,
true
),
-offs, offs
),
stBottom
);
}
} else {
// if no lower layer, all surfaces of this one are solid
// we clone surfaces because we're going to clear the slices collection
bottom = layerm.slices;
// if we have raft layers, consider bottom layer as a bridge
// just like any other bottom surface lying on the void
const SurfaceType surface_type_bottom =
(object.config.raft_layers.value > 0 && object.config.support_material_contact_distance.value > 0)
? stBottomBridge
: stBottom;
for (Surface &s : bottom.surfaces) s.surface_type = surface_type_bottom;
}
// now, if the object contained a thin membrane, we could have overlapping bottom
// and top surfaces; let's do an intersection to discover them and consider them
// as bottom surfaces (to allow for bridge detection)
if (!top.empty() && !bottom.empty()) {
const Polygons top_polygons = to_polygons(STDMOVE(top));
top.clear();
top.append(
// TODO: maybe we don't need offset2?
offset2_ex(diff(top_polygons, bottom, true), -offs, offs),
stTop
);
}
// save surfaces to layer
{
boost::lock_guard<boost::mutex> l(layerm._slices_mutex);
layerm.slices.clear();
layerm.slices.append(STDMOVE(top));
layerm.slices.append(STDMOVE(bottom));
// find internal surfaces (difference between top/bottom surfaces and others)
{
Polygons topbottom = top; append_to(topbottom, (Polygons)bottom);
layerm.slices.append(
// TODO: maybe we don't need offset2?
offset2_ex(
diff(layerm_slices_surfaces, topbottom, true),
-offs, offs
),
stInternal
);
}
}
#ifdef SLIC3R_DEBUG
printf(" layer %zu has %zu bottom, %zu top and %zu internal surfaces\n",
this->id(), bottom.size(), top.size(),
layerm.slices.size()-bottom.size()-top.size());
#endif
{
/* Fill in layerm->fill_surfaces by trimming the layerm->slices by the cummulative layerm->fill_surfaces.
Note: this method should be idempotent, but fill_surfaces gets modified
in place. However we're now only using its boundaries (which are invariant)
so we're safe. This guarantees idempotence of prepare_infill() also in case
that combine_infill() turns some fill_surface into VOID surfaces. */
const Polygons fill_boundaries = layerm.fill_surfaces;
layerm.fill_surfaces.clear();
// No other instance of this function is writing to this layer, so we can read safely.
for (const Surface &surface : layerm.slices.surfaces) {
// No other instance of this function modifies fill_surfaces.
layerm.fill_surfaces.append(
intersection_ex(surface, fill_boundaries),
surface.surface_type
);
}
}
}
}
void
Layer::process_external_surfaces()
{
for (LayerRegion* &layerm : this->regions)
layerm->process_external_surfaces();
}
}

View File

@ -7,6 +7,7 @@
#include "ExtrusionEntityCollection.hpp"
#include "ExPolygonCollection.hpp"
#include "PolylineCollection.hpp"
#include <boost/thread.hpp>
namespace Slic3r {
@ -60,12 +61,13 @@ class LayerRegion
void prepare_fill_surfaces();
void make_perimeters(const SurfaceCollection &slices, SurfaceCollection* fill_surfaces);
void make_fill();
void process_external_surfaces(const Layer* lower_layer);
void process_external_surfaces();
double infill_area_threshold() const;
private:
Layer *_layer;
PrintRegion *_region;
mutable boost::mutex _slices_mutex;
LayerRegion(Layer *layer, PrintRegion *region)
: _layer(layer), _region(region) {};
@ -108,12 +110,13 @@ class Layer {
template <class T> bool any_bottom_region_slice_contains(const T &item) const;
void make_perimeters();
void make_fills();
void detect_surfaces_type();
void process_external_surfaces();
protected:
size_t _id; // sequential number of layer, 0-based
PrintObject* _object;
Layer(size_t id, PrintObject *object, coordf_t height, coordf_t print_z,
coordf_t slice_z);
virtual ~Layer();

View File

@ -65,8 +65,10 @@ LayerRegion::make_perimeters(const SurfaceCollection &slices, SurfaceCollection*
g.process();
}
// This function reads lower_layer->slices and writes this->bridged and this->fill_surfaces,
// so it's thread-safe.
void
LayerRegion::process_external_surfaces(const Layer* lower_layer)
LayerRegion::process_external_surfaces()
{
const Surfaces &surfaces = this->fill_surfaces.surfaces;
const double margin = scale_(EXTERNAL_INFILL_MARGIN);
@ -82,10 +84,10 @@ LayerRegion::process_external_surfaces(const Layer* lower_layer)
also, supply the original expolygon instead of the grown one, because in case
of very thin (but still working) anchors, the grown expolygon would go beyond them */
double angle = -1;
if (lower_layer != NULL && surface->is_bridge()) {
if (this->layer()->lower_layer != NULL && surface->is_bridge()) {
BridgeDetector bd(
surface->expolygon,
lower_layer->slices,
this->layer()->lower_layer->slices,
this->flow(frInfill, true).scaled_width()
);
@ -229,12 +231,13 @@ LayerRegion::prepare_fill_surfaces()
}
// turn too small internal regions into solid regions according to the user setting
if (this->region()->config.fill_density.value > 0) {
const float &fill_density = this->region()->config.fill_density;
if (fill_density > 0 && fill_density < 100) {
// scaling an area requires two calls!
double min_area = scale_(scale_(this->region()->config.solid_infill_below_area.value));
for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
if (surface->surface_type == stInternal && surface->area() <= min_area)
surface->surface_type = stInternalSolid;
const double min_area = scale_(scale_(this->region()->config.solid_infill_below_area.value));
for (Surface &surface : this->fill_surfaces.surfaces) {
if (surface.surface_type == stInternal && surface.area() <= min_area)
surface.surface_type = stInternalSolid;
}
}
}

View File

@ -67,7 +67,9 @@ LayerRegion::make_fill()
group_attrib[i].is_solid = true;
group_attrib[i].fw = (surface.surface_type == stTop) ? top_solid_infill_flow.width : solid_infill_flow.width;
group_attrib[i].pattern = surface.is_external() ? this->region()->config.external_fill_pattern.value : ipRectilinear;
group_attrib[i].pattern = surface.surface_type == stTop ? this->region()->config.top_infill_pattern.value
: surface.is_bottom() ? this->region()->config.bottom_infill_pattern.value
: ipRectilinear;
}
// Loop through solid groups, find compatible groups and append them to this one.
for (size_t i = 0; i < groups.size(); ++i) {
@ -171,8 +173,8 @@ LayerRegion::make_fill()
if (surface.is_solid()) {
density = 100.;
fill_pattern = (surface.is_external() && !is_bridge)
? this->region()->config.external_fill_pattern.value
fill_pattern = (surface.surface_type == stTop) ? this->region()->config.top_infill_pattern.value
: (surface.is_bottom() && !is_bridge) ? this->region()->config.bottom_infill_pattern.value
: ipRectilinear;
} else if (density <= 0)
continue;

View File

@ -2,6 +2,7 @@
#include "Geometry.hpp"
#include "IO.hpp"
#include <iostream>
#include <set>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
@ -92,9 +93,8 @@ Model::delete_object(size_t idx)
void
Model::clear_objects()
{
// int instead of size_t because it can be -1 when vector is empty
for (int i = this->objects.size()-1; i >= 0; --i)
this->delete_object(i);
while (!this->objects.empty())
this->delete_object(0);
}
void
@ -255,13 +255,26 @@ bool
Model::_arrange(const Pointfs &sizes, coordf_t dist, const BoundingBoxf* bb, Pointfs &out) const
{
// we supply unscaled data to arrange()
return Slic3r::Geometry::arrange(
bool result = Slic3r::Geometry::arrange(
sizes.size(), // number of parts
BoundingBoxf(sizes).max, // width and height of a single cell
dist, // distance between cells
bb, // bounding box of the area to fill
out // output positions
);
if (!result && bb != NULL) {
// Try to arrange again ignoring bb
result = Slic3r::Geometry::arrange(
sizes.size(), // number of parts
BoundingBoxf(sizes).max, // width and height of a single cell
dist, // distance between cells
NULL, // bounding box of the area to fill
out // output positions
);
}
return result;
}
/* arrange objects preserving their instance count
@ -360,6 +373,43 @@ Model::print_info() const
(*o)->print_info();
}
bool
Model::looks_like_multipart_object() const
{
if (this->objects.size() == 1) return false;
for (const ModelObject* o : this->objects) {
if (o->volumes.size() > 1) return false;
if (o->config.keys().size() > 1) return false;
}
std::set<coordf_t> heights;
for (const ModelObject* o : this->objects)
for (const ModelVolume* v : o->volumes)
heights.insert(v->mesh.bounding_box().min.z);
return heights.size() > 1;
}
void
Model::convert_multipart_object()
{
if (this->objects.empty()) return;
ModelObject* object = this->add_object();
object->input_file = this->objects.front()->input_file;
for (const ModelObject* o : this->objects) {
for (const ModelVolume* v : o->volumes) {
ModelVolume* v2 = object->add_volume(*v);
v2->name = o->name;
}
}
for (const ModelInstance* i : this->objects.front()->instances)
object->add_instance(*i);
while (this->objects.size() > 1)
this->delete_object(0);
}
ModelMaterial::ModelMaterial(Model *model) : model(model) {}
ModelMaterial::ModelMaterial(Model *model, const ModelMaterial &other)
: attributes(other.attributes), config(other.config), model(model)
@ -454,9 +504,8 @@ ModelObject::delete_volume(size_t idx)
void
ModelObject::clear_volumes()
{
// int instead of size_t because it can be -1 when vector is empty
for (int i = this->volumes.size()-1; i >= 0; --i)
this->delete_volume(i);
while (!this->volumes.empty())
this->delete_volume(0);
}
ModelInstance*
@ -495,8 +544,8 @@ ModelObject::delete_last_instance()
void
ModelObject::clear_instances()
{
for (size_t i = 0; i < this->instances.size(); ++i)
this->delete_instance(i);
while (!this->instances.empty())
this->delete_last_instance();
}
// this returns the bounding box of the *transformed* instances
@ -586,6 +635,20 @@ ModelObject::instance_bounding_box(size_t instance_idx) const
return bb;
}
void
ModelObject::align_to_ground()
{
// calculate the displacements needed to
// center this object around the origin
BoundingBoxf3 bb;
for (const ModelVolume* v : this->volumes)
if (!v->modifier)
bb.merge(v->mesh.bounding_box());
this->translate(0, 0, -bb.min.z);
this->origin_translation.translate(0, 0, -bb.min.z);
}
void
ModelObject::center_around_origin()
{

View File

@ -74,6 +74,8 @@ class Model
void duplicate_objects(size_t copies_num, coordf_t dist, const BoundingBoxf* bb = NULL);
void duplicate_objects_grid(size_t x, size_t y, coordf_t dist);
void print_info() const;
bool looks_like_multipart_object() const;
void convert_multipart_object();
};
// Material, which may be shared across multiple ModelObjects of a single Model.
@ -149,6 +151,7 @@ class ModelObject
TriangleMesh raw_mesh() const;
BoundingBoxf3 raw_bounding_box() const;
BoundingBoxf3 instance_bounding_box(size_t instance_idx) const;
void align_to_ground();
void center_around_origin();
void translate(const Vectorf3 &vector);
void translate(coordf_t x, coordf_t y, coordf_t z);

View File

@ -9,11 +9,11 @@
#include <utility>
#include <vector>
#define MP_INNER_MARGIN scale_(1.0)
#define MP_OUTER_MARGIN scale_(2.0)
namespace Slic3r {
constexpr coord_t MP_INNER_MARGIN = scale_(1.0);
constexpr coord_t MP_OUTER_MARGIN = scale_(2.0);
class MotionPlanner;
class MotionPlannerEnv

View File

@ -315,8 +315,7 @@ PerimeterGenerator::process()
);
// append infill areas to fill_surfaces
for (ExPolygons::const_iterator ex = expp.begin(); ex != expp.end(); ++ex)
this->fill_surfaces->surfaces.push_back(Surface(stInternal, *ex)); // use a bogus surface type
this->fill_surfaces->append(expp, stInternal); // use a bogus surface type
}
}
}

View File

@ -148,6 +148,33 @@ Polygon::contains(const Point &point) const
return result;
}
void
Polygon::douglas_peucker(double tolerance)
{
this->points.push_back(this->points.front());
this->points = MultiPoint::_douglas_peucker(this->points, tolerance);
this->points.pop_back();
}
void
Polygon::remove_vertical_collinear_points(coord_t tolerance)
{
Points &pp = this->points;
pp.push_back(pp.front());
for (size_t i = 0; i < pp.size()-1; ++i) {
while (i < pp.size()-1) {
const Point &p = pp[i];
const Point &next = pp[i+1];
if (next.x == p.x && std::abs(next.y - p.y) <= tolerance) {
pp.erase(pp.begin() + i);
} else {
break;
}
}
}
pp.pop_back();
}
// this only works on CCW polygons as CW will be ripped out by Clipper's simplify_polygons()
Polygons
Polygon::simplify(double tolerance) const

View File

@ -39,6 +39,8 @@ class Polygon : public MultiPoint {
// Does an unoriented polygon contain a point?
// Tested by counting intersections along a horizontal line.
bool contains(const Point &point) const;
void douglas_peucker(double tolerance);
void remove_vertical_collinear_points(coord_t tolerance);
Polygons simplify(double tolerance) const;
void simplify(double tolerance, Polygons &polygons) const;
void triangulate_convex(Polygons* polygons) const;

View File

@ -73,12 +73,6 @@ Print::clear_objects()
this->clear_regions();
}
PrintObject*
Print::get_object(size_t idx)
{
return objects.at(idx);
}
void
Print::delete_object(size_t idx)
{
@ -167,11 +161,13 @@ Print::invalidate_state_by_config_options(const std::vector<t_config_option_key>
|| *opt_key == "ooze_prevention") {
steps.insert(psSkirt);
} else if (*opt_key == "brim_width"
|| *opt_key == "interior_brim_width"
|| *opt_key == "brim_connections_width") {
steps.insert(psBrim);
steps.insert(psSkirt);
} else if (*opt_key == "nozzle_diameter"
|| *opt_key == "resolution") {
|| *opt_key == "resolution"
|| *opt_key == "z_steps_per_mm") {
osteps.insert(posSlice);
} else if (*opt_key == "avoid_crossing_perimeters"
|| *opt_key == "bed_shape"
@ -191,6 +187,7 @@ Print::invalidate_state_by_config_options(const std::vector<t_config_option_key>
|| *opt_key == "extrusion_multiplier"
|| *opt_key == "fan_always_on"
|| *opt_key == "fan_below_layer_time"
|| *opt_key == "filament_colour"
|| *opt_key == "filament_diameter"
|| *opt_key == "first_layer_acceleration"
|| *opt_key == "first_layer_bed_temperature"
@ -308,7 +305,10 @@ Print::object_extruders() const
FOREACH_REGION(this, region) {
// these checks reflect the same logic used in the GUI for enabling/disabling
// extruder selection fields
if ((*region)->config.perimeters.value > 0 || this->config.brim_width.value > 0 || this->config.brim_connections_width.value > 0)
if ((*region)->config.perimeters.value > 0
|| this->config.brim_width.value > 0
|| this->config.interior_brim_width.value > 0
|| this->config.brim_connections_width.value > 0)
extruders.insert((*region)->config.perimeter_extruder - 1);
if ((*region)->config.fill_density.value > 0)
@ -349,6 +349,17 @@ Print::extruders() const
return extruders;
}
size_t
Print::brim_extruder() const
{
size_t e = this->get_region(0)->config.perimeter_extruder;
for (const PrintObject* object : this->objects) {
if (object->config.raft_layers > 0)
e = object->config.support_material_extruder;
}
return e;
}
void
Print::_simplify_slices(double distance)
{
@ -661,7 +672,7 @@ Print::validate() const
if (this->config.spiral_vase) {
size_t total_copies_count = 0;
FOREACH_OBJECT(this, i_object) total_copies_count += (*i_object)->copies().size();
if (total_copies_count > 1)
if (total_copies_count > 1 && !this->config.complete_objects)
return "The Spiral Vase option can only be used when printing a single object.";
if (this->regions.size() > 1)
return "The Spiral Vase option can only be used when printing single material objects.";
@ -790,7 +801,9 @@ Print::_make_brim()
// checking whether we need to generate them
this->brim.clear();
if (this->config.brim_width == 0 && this->config.brim_connections_width == 0) {
if (this->config.brim_width == 0
&& this->config.interior_brim_width == 0
&& this->config.brim_connections_width == 0) {
this->state.set_done(psBrim);
return;
}
@ -819,12 +832,10 @@ Print::_make_brim()
it != support_layer0.support_interface_fills.entities.end(); ++it)
append_to(object_islands, offset((*it)->as_polyline(), grow_distance));
}
for (Points::const_iterator copy = (*object)->_shifted_copies.begin(); copy != (*object)->_shifted_copies.end();
++copy) {
for (Polygons::const_iterator p = object_islands.begin(); p != object_islands.end(); ++p) {
Polygon p2 = *p;
p2.translate(*copy);
islands.push_back(p2);
for (const Point &copy : (*object)->_shifted_copies) {
for (Polygon p : object_islands) {
p.translate(copy);
islands.push_back(p);
}
}
}
@ -838,7 +849,7 @@ Print::_make_brim()
// perimeters because here we're offsetting outwards)
append_to(loops, offset2(
islands,
flow.scaled_spacing() * (i + 0.5),
flow.scaled_width() + flow.scaled_spacing() * (i - 1.0 + 0.5),
flow.scaled_spacing() * -1.0,
100000,
ClipperLib::jtSquare
@ -855,17 +866,17 @@ Print::_make_brim()
}
if (this->config.brim_connections_width > 0) {
// get islands to connects
for (Polygons::iterator p = islands.begin(); p != islands.end(); ++p)
*p = Geometry::convex_hull(p->points);
// get islands to connect
for (Polygon &p : islands)
p = Geometry::convex_hull(p.points);
islands = offset(islands, flow.scaled_spacing() * (num_loops-0.2), 10000, jtSquare);
// compute centroid for each island
Points centroids;
centroids.reserve(islands.size());
for (Polygons::const_iterator p = islands.begin(); p != islands.end(); ++p)
centroids.push_back(p->centroid());
for (const Polygon &p : islands)
centroids.push_back(p.centroid());
// in order to check visibility we need to account for the connections width,
// so let's use grown islands
@ -883,7 +894,7 @@ Print::_make_brim()
}
}
std::auto_ptr<Fill> filler(Fill::new_from_type(ipRectilinear));
std::unique_ptr<Fill> filler(Fill::new_from_type(ipRectilinear));
filler->min_spacing = flow.spacing();
filler->dont_adjust = true;
filler->density = 1;
@ -912,6 +923,47 @@ Print::_make_brim()
}
}
if (this->config.interior_brim_width > 0) {
// collect all island holes to fill
Polygons holes;
for (const PrintObject* object : this->objects) {
const Layer &layer0 = *object->get_layer(0);
Polygons o_holes = layer0.slices.holes();
// When we have no infill on this layer, consider the internal part
// of the model as a hole.
for (const LayerRegion* layerm : layer0.regions) {
if (layerm->fills.empty())
append_to(o_holes, (Polygons)layerm->fill_surfaces);
}
for (const Point &copy : object->_shifted_copies) {
for (Polygon p : o_holes) {
p.translate(copy);
holes.push_back(p);
}
}
}
Polygons loops;
const int num_loops = floor(this->config.interior_brim_width / flow.width + 0.5);
for (int i = 1; i <= num_loops; ++i) {
append_to(loops, offset2(
holes,
-flow.scaled_spacing() * (i + 0.5),
flow.scaled_spacing()
));
}
loops = union_pt_chained(loops);
for (const Polygon &p : loops) {
ExtrusionPath path(erSkirt, mm3_per_mm, flow.width, first_layer_height);
path.polyline = p.split_at_first_point();
this->brim.append(ExtrusionLoop(path));
}
}
this->state.set_done(psBrim);
}

View File

@ -13,6 +13,7 @@
#include "Layer.hpp"
#include "Model.hpp"
#include "PlaceholderParser.hpp"
#include "SlicingAdaptive.hpp"
#include "LayerHeightSpline.hpp"
namespace Slic3r {
@ -120,14 +121,16 @@ class PrintObject
size_t total_layer_count() const;
size_t layer_count() const;
void clear_layers();
Layer* get_layer(int idx);
Layer* get_layer(int idx) { return this->layers.at(idx); };
const Layer* get_layer(int idx) const { return this->layers.at(idx); };
// print_z: top of the layer; slice_z: center of the layer.
Layer* add_layer(int id, coordf_t height, coordf_t print_z, coordf_t slice_z);
void delete_layer(int idx);
size_t support_layer_count() const;
void clear_support_layers();
SupportLayer* get_support_layer(int idx);
SupportLayer* get_support_layer(int idx) { return this->support_layers.at(idx); };
const SupportLayer* get_support_layer(int idx) const { return this->support_layers.at(idx); };
SupportLayer* add_support_layer(int id, coordf_t height, coordf_t print_z);
void delete_support_layer(int idx);
@ -140,6 +143,9 @@ class PrintObject
void detect_surfaces_type();
void process_external_surfaces();
void bridge_over_infill();
coordf_t adjust_layer_height(coordf_t layer_height) const;
std::vector<coordf_t> generate_object_layers(coordf_t first_layer_height);
void _slice();
std::vector<ExPolygons> _slice_region(size_t region_id, std::vector<float> z, bool modifier);
void _make_perimeters();
void _infill();
@ -169,7 +175,7 @@ class Print
PrintRegionPtrs regions;
PlaceholderParser placeholder_parser;
// TODO: status_cb
double total_used_filament, total_extruded_volume;
double total_used_filament, total_extruded_volume, total_cost, total_weight;
std::map<size_t,float> filament_stats;
PrintState<PrintStep> state;
@ -181,7 +187,8 @@ class Print
// methods for handling objects
void clear_objects();
PrintObject* get_object(size_t idx);
PrintObject* get_object(size_t idx) { return this->objects.at(idx); };
const PrintObject* get_object(size_t idx) const { return this->objects.at(idx); };
void delete_object(size_t idx);
void reload_object(size_t idx);
bool reload_model_instances();
@ -213,6 +220,7 @@ class Print
std::set<size_t> object_extruders() const;
std::set<size_t> support_material_extruders() const;
std::set<size_t> extruders() const;
size_t brim_extruder() const;
void _simplify_slices(double distance);
double max_allowed_layer_height() const;
bool has_support_material() const;

View File

@ -1,10 +1,26 @@
#include "PrintConfig.hpp"
#include <boost/algorithm/string/replace.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
namespace Slic3r {
PrintConfigDef::PrintConfigDef()
{
ConfigOptionDef external_fill_pattern;
external_fill_pattern.type = coEnum;
external_fill_pattern.enum_keys_map = ConfigOptionEnum<InfillPattern>::get_enum_values();
external_fill_pattern.enum_values.push_back("rectilinear");
external_fill_pattern.enum_values.push_back("concentric");
external_fill_pattern.enum_values.push_back("hilbertcurve");
external_fill_pattern.enum_values.push_back("archimedeanchords");
external_fill_pattern.enum_values.push_back("octagramspiral");
external_fill_pattern.enum_labels.push_back("Rectilinear");
external_fill_pattern.enum_labels.push_back("Concentric");
external_fill_pattern.enum_labels.push_back("Hilbert Curve");
external_fill_pattern.enum_labels.push_back("Archimedean Chords");
external_fill_pattern.enum_labels.push_back("Octagram Spiral");
ConfigOptionDef* def;
def = this->add("adaptive_slicing", coBool);
@ -22,14 +38,6 @@ PrintConfigDef::PrintConfigDef()
def->max = 1;
def->default_value = new ConfigOptionFloat(0.15);
def = this->add("adaptive_slicing_z_gradation", coFloat);
def->label = "Min layer height gradation";
def->tooltip = "Limit layer heights to a multiple of this value to avoid stepping inaccuracies at the Z-axis. Typical value for a Prusa i3, 1/16 micro-stepping is 0.004mm. Set zero do disable this option.";
def->sidetext = "mm";
def->cli = "adaptive-slicing-z-gradation=f";
def->min = 0;
def->default_value = new ConfigOptionFloat(0);
def = this->add("avoid_crossing_perimeters", coBool);
def->label = "Avoid crossing perimeters";
def->tooltip = "Optimize travel moves in order to minimize the crossing of perimeters. This is mostly useful with Bowden extruders which suffer from oozing. This feature slows down both the print and the G-code generation.";
@ -70,6 +78,14 @@ PrintConfigDef::PrintConfigDef()
def->height = 50;
def->default_value = new ConfigOptionString("");
def = this->add("bottom_infill_pattern", external_fill_pattern);
def->label = "Bottom";
def->full_label = "Bottom infill pattern";
def->category = "Infill";
def->tooltip = "Infill pattern for bottom layers. This only affects the external visible layer, and not its adjacent solid shells.";
def->cli = "bottom-infill-pattern=s";
def->default_value = new ConfigOptionEnum<InfillPattern>(ipRectilinear);
def = this->add("bottom_solid_layers", coInt);
def->label = "Bottom";
def->category = "Layers and Perimeters";
@ -126,7 +142,7 @@ PrintConfigDef::PrintConfigDef()
def->default_value = new ConfigOptionFloat(0);
def = this->add("brim_width", coFloat);
def->label = "Brim width";
def->label = "Exterior brim width";
def->tooltip = "Horizontal width of the brim that will be printed around each object on the first layer.";
def->sidetext = "mm";
def->cli = "brim-width=f";
@ -187,29 +203,31 @@ PrintConfigDef::PrintConfigDef()
def->height = 120;
def->default_value = new ConfigOptionString("M104 S0 ; turn off temperature\nG28 X0 ; home X axis\nM84 ; disable motors\n");
def = this->add("external_fill_pattern", coEnum);
def = this->add("end_filament_gcode", coStrings);
def->label = "End G-code";
def->tooltip = "This end procedure is inserted at the end of the output file, before the printer end gcode. Note that you can use placeholder variables for all Slic3r settings. If you have multiple extruders, the gcode is processed in extruder order.";
def->cli = "end-filament-gcode=s@";
def->multiline = true;
def->full_width = true;
def->height = 120;
{
ConfigOptionStrings* opt = new ConfigOptionStrings();
opt->values.push_back("; Filament-specific end gcode \n;END gcode for filament\n");
def->default_value = opt;
}
def = this->add("external_fill_pattern", external_fill_pattern);
def->label = "Top/bottom fill pattern";
def->category = "Infill";
def->tooltip = "Fill pattern for top/bottom infill. This only affects the external visible layer, and not its adjacent solid shells.";
def->cli = "external-fill-pattern|solid-fill-pattern=s";
def->enum_keys_map = ConfigOptionEnum<InfillPattern>::get_enum_values();
def->enum_values.push_back("rectilinear");
def->enum_values.push_back("alignedrectilinear");
def->enum_values.push_back("concentric");
def->enum_values.push_back("hilbertcurve");
def->enum_values.push_back("archimedeanchords");
def->enum_values.push_back("octagramspiral");
def->enum_labels.push_back("Rectilinear");
def->enum_labels.push_back("Aligned Rectilinear");
def->enum_labels.push_back("Concentric");
def->enum_labels.push_back("Hilbert Curve");
def->enum_labels.push_back("Archimedean Chords");
def->enum_labels.push_back("Octagram Spiral");
def->cli = "external-fill-pattern|external-infill-pattern|solid-fill-pattern=s";
def->aliases.push_back("solid_fill_pattern");
def->default_value = new ConfigOptionEnum<InfillPattern>(ipRectilinear);
def->shortcut.push_back("top_infill_pattern");
def->shortcut.push_back("bottom_infill_pattern");
def = this->add("external_perimeter_extrusion_width", coFloatOrPercent);
def->label = "↳ external";
def->full_label = "External perimeters extrusion width";
def->gui_type = "f_enum_open";
def->category = "Extrusion Width";
def->tooltip = "Set this to a non-zero value to set a manual extrusion width for external perimeters. If auto is chosen, a value will be used that maximizes accuracy of the external visible surfaces. If expressed as percentage (for example 200%) it will be computed over layer height.";
@ -222,6 +240,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("external_perimeter_speed", coFloatOrPercent);
def->label = "↳ external";
def->full_label = "External perimeters speed";
def->gui_type = "f_enum_open";
def->category = "Speed";
def->tooltip = "This separate setting will affect the speed of external perimeters (the visible ones). If expressed as percentage (for example: 80%) it will be calculated on the perimeters speed setting above.";
@ -378,6 +397,30 @@ PrintConfigDef::PrintConfigDef()
opt->values.push_back(3);
def->default_value = opt;
}
def = this->add("filament_density", coFloats);
def->label = "Density";
def->tooltip = "Enter your filament density here. This is only for statistical information. A decent way is to weigh a known length of filament and compute the ratio of the length to volume. Better is to calculate the volume directly through displacement.";
def->sidetext = "g/cm³";
def->cli = "filament-density=f@";
def->min = 0;
{
ConfigOptionFloats* opt = new ConfigOptionFloats();
opt->values.push_back(0);
def->default_value = opt;
}
def = this->add("filament_cost", coFloats);
def->label = "Cost";
def->tooltip = "Enter your filament cost per kg here. This is only for statistical information.";
def->sidetext = "money/kg";
def->cli = "filament-cost=f@";
def->min = 0;
{
ConfigOptionFloats* opt = new ConfigOptionFloats();
opt->values.push_back(0);
def->default_value = opt;
}
def = this->add("filament_settings_id", coString);
def->default_value = new ConfigOptionString("");
@ -434,6 +477,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("fill_gaps", coBool);
def->label = "Fill gaps";
def->category = "Infill";
def->tooltip = "If this is enabled, gaps will be filled with single passes. Enable this for better quality, disable it for shorter printing times.";
def->cli = "fill-gaps!";
def->default_value = new ConfigOptionBool(true);
@ -530,6 +574,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("gap_fill_speed", coFloat);
def->label = "↳ gaps";
def->full_label = "Gap fill speed";
def->gui_type = "f_enum_open";
def->category = "Speed";
def->tooltip = "Speed for filling gaps. Since these are usually single lines you might want to use a low speed for better sticking. If expressed as percentage (for example: 80%) it will be calculated on the infill speed setting above.";
@ -652,6 +697,14 @@ PrintConfigDef::PrintConfigDef()
def->enum_labels.push_back("auto");
def->default_value = new ConfigOptionFloat(80);
def = this->add("interior_brim_width", coFloat);
def->label = "Interior brim width";
def->tooltip = "Horizontal width of the brim that will be printed inside object holes on the first layer.";
def->sidetext = "mm";
def->cli = "interior-brim-width=f";
def->min = 0;
def->default_value = new ConfigOptionFloat(0);
def = this->add("interface_shells", coBool);
def->label = "Interface shells";
def->tooltip = "Force the generation of solid shells between adjacent materials/volumes. Useful for multi-extruder prints with translucent materials or manual soluble support material.";
@ -797,7 +850,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("ooze_prevention", coBool);
def->label = "Enable";
def->tooltip = "This option will drop the temperature of the inactive extruders to prevent oozing. It will enable a tall skirt automatically and move extruders outside such skirt when changing temperatures.";
def->tooltip = "During multi-extruder prints, this option will drop the temperature of the inactive extruders to prevent oozing. It will enable a tall skirt automatically and move extruders outside such skirt when changing temperatures.";
def->cli = "ooze-prevention!";
def->default_value = new ConfigOptionBool(false);
@ -812,7 +865,7 @@ PrintConfigDef::PrintConfigDef()
def->label = "Detect bridging perimeters";
def->category = "Layers and Perimeters";
def->tooltip = "Experimental option to adjust flow for overhangs (bridge flow will be used), to apply bridge speed to them and enable fan.";
def->cli = "overhangs!";
def->cli = "overhangs|detect-bridging-perimeters!";
def->default_value = new ConfigOptionBool(true);
def = this->add("perimeter_acceleration", coFloat);
@ -907,7 +960,7 @@ PrintConfigDef::PrintConfigDef()
def->default_value = new ConfigOptionFloat(4);
def = this->add("resolution", coFloat);
def->label = "Resolution";
def->label = "Resolution (deprecated)";
def->tooltip = "Minimum detail resolution, used to simplify the input file for speeding up the slicing job and reducing memory usage. High-resolution models often carry more detail than printers can render. Set to zero to disable any simplification and use full resolution from input.";
def->sidetext = "mm";
def->cli = "resolution=f";
@ -1100,6 +1153,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("small_perimeter_speed", coFloatOrPercent);
def->label = "↳ small";
def->full_label = "Small perimeters speed";
def->gui_type = "f_enum_open";
def->category = "Speed";
def->tooltip = "This separate setting will affect the speed of perimeters having radius <= 6.5mm (usually holes). If expressed as percentage (for example: 80%) it will be calculated on the perimeters speed setting above.";
@ -1139,6 +1193,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("solid_infill_extrusion_width", coFloatOrPercent);
def->label = "↳ solid";
def->full_label = "Solid infill extrusion width";
def->gui_type = "f_enum_open";
def->category = "Extrusion Width";
def->tooltip = "Set this to a non-zero value to set a manual extrusion width for infill for solid surfaces. If expressed as percentage (for example 90%) it will be computed over layer height.";
@ -1151,6 +1206,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("solid_infill_speed", coFloatOrPercent);
def->label = "↳ solid";
def->full_label = "Solid infill speed";
def->gui_type = "f_enum_open";
def->category = "Speed";
def->tooltip = "Speed for printing solid regions (top/bottom/internal horizontal shells). This can be expressed as a percentage (for example: 80%) over the default infill speed above.";
@ -1195,6 +1251,19 @@ PrintConfigDef::PrintConfigDef()
def->height = 120;
def->default_value = new ConfigOptionString("G28 ; home all axes\nG1 Z5 F5000 ; lift nozzle\n");
def = this->add("start_filament_gcode", coStrings);
def->label = "Start G-code";
def->tooltip = "This start procedure is inserted at the beginning, after any printer start gcode. This is used to override settings for a specific filament. If Slic3r detects M104, M109, M140 or M190 in your custom codes, such commands will not be prepended automatically so you're free to customize the order of heating commands and other custom actions. Note that you can use placeholder variables for all Slic3r settings, so you can put a \"M109 S[first_layer_temperature]\" command wherever you want. If you have multiple extruders, the gcode is processed in extruder order.";
def->cli = "start-filament-gcode=s@";
def->multiline = true;
def->full_width = true;
def->height = 120;
{
ConfigOptionStrings* opt = new ConfigOptionStrings();
opt->values.push_back("; Filament gcode\n");
def->default_value = opt;
}
def = this->add("support_material", coBool);
def->label = "Generate support material";
def->category = "Support material";
@ -1284,6 +1353,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("support_material_interface_speed", coFloatOrPercent);
def->label = "↳ interface";
def->category = "Support material interface speed";
def->gui_type = "f_enum_open";
def->category = "Support material";
def->tooltip = "Speed for printing support material interface layers. If expressed as percentage (for example 50%) it will be calculated over support material speed.";
@ -1320,6 +1390,9 @@ PrintConfigDef::PrintConfigDef()
def->min = 0;
def->default_value = new ConfigOptionFloat(2.5);
def = this->add("support_material_speed", coFloat);
def->label = "Support material";
def->gui_type = "f_enum_open";
@ -1332,15 +1405,15 @@ PrintConfigDef::PrintConfigDef()
def->enum_labels.push_back("auto");
def->default_value = new ConfigOptionFloat(60);
def = this->add("support_material_threshold", coInt);
def = this->add("support_material_threshold", coFloatOrPercent);
def->label = "Overhang threshold";
def->category = "Support material";
def->tooltip = "Support material will not be generated for overhangs whose slope angle (90° = vertical) is above the given threshold. In other words, this value represent the most horizontal slope (measured from the horizontal plane) that you can print without support material. Set to zero for automatic detection (recommended).";
def->sidetext = "°";
def->cli = "support-material-threshold=i";
def->tooltip = "Support material will not be generated for overhangs whose slope angle (90° = vertical) is above the given threshold. In other words, this value represent the most horizontal slope (measured from the horizontal plane) that you can print without support material. Set to a percentage to automatically detect based on some % of overhanging perimeter width instead (recommended).";
def->sidetext = "° (or %)";
def->cli = "support-material-threshold=s";
def->min = 0;
def->max = 90;
def->default_value = new ConfigOptionInt(0);
def->max = 300;
def->default_value = new ConfigOptionFloatOrPercent(60, true);
def = this->add("temperature", coInts);
def->label = "Other layers";
@ -1365,7 +1438,6 @@ PrintConfigDef::PrintConfigDef()
def = this->add("threads", coInt);
def->label = "Threads";
def->tooltip = "Threads are used to parallelize long-running tasks. Optimal threads number is slightly above the number of available cores/processors.";
def->cli = "threads|j=i";
def->readonly = true;
def->min = 1;
{
@ -1384,6 +1456,7 @@ PrintConfigDef::PrintConfigDef()
def = this->add("top_infill_extrusion_width", coFloatOrPercent);
def->label = "↳ top solid";
def->full_label = "Top solid infill extrusion width";
def->gui_type = "f_enum_open";
def->category = "Extrusion Width";
def->tooltip = "Set this to a non-zero value to set a manual extrusion width for infill for top surfaces. You may want to use thinner extrudates to fill all narrow regions and get a smoother finish. If expressed as percentage (for example 90%) it will be computed over layer height.";
@ -1394,8 +1467,17 @@ PrintConfigDef::PrintConfigDef()
def->enum_labels.push_back("default");
def->default_value = new ConfigOptionFloatOrPercent(0, false);
def = this->add("top_infill_pattern", external_fill_pattern);
def->label = "Top";
def->full_label = "Top infill pattern";
def->category = "Infill";
def->tooltip = "Infill pattern for top layers. This only affects the external visible layer, and not its adjacent solid shells.";
def->cli = "top-infill-pattern=s";
def->default_value = new ConfigOptionEnum<InfillPattern>(ipRectilinear);
def = this->add("top_solid_infill_speed", coFloatOrPercent);
def->label = "↳ top solid";
def->full_label = "Top solid infill speed";
def->gui_type = "f_enum_open";
def->category = "Speed";
def->tooltip = "Speed for printing top solid layers (it only applies to the uppermost external layers and not to their internal solid layers). You may want to slow down this to get a nicer surface finish. This can be expressed as a percentage (for example: 80%) over the solid infill speed above.";
@ -1475,6 +1557,12 @@ PrintConfigDef::PrintConfigDef()
def->sidetext = "mm";
def->cli = "z-offset=f";
def->default_value = new ConfigOptionFloat(0);
def = this->add("z_steps_per_mm", coFloat);
def->label = "Z full steps/mm";
def->tooltip = "Set this to the number of *full* steps (not microsteps) needed for moving the Z axis by 1mm; you can calculate this by dividing the number of microsteps configured in your firmware by the microstepping amount (8, 16, 32). Slic3r will round your configured layer height to the nearest multiple of that value in order to ensure the best accuracy. This is most useful for machines with imperial leadscrews or belt-driven Z or for unusual layer heights with metric leadscrews. Set to zero to disable this experimental feature.";
def->cli = "z-steps-per-mm=f";
def->default_value = new ConfigOptionFloat(0);
}
PrintConfigDef print_config_def;
@ -1496,6 +1584,17 @@ DynamicPrintConfig::normalize() {
}
}
/*
if (this->has("external_fill_pattern")) {
InfillPattern p = this->opt<ConfigOptionEnum<InfillPattern> >("external_fill_pattern");
this->erase("external_fill_pattern");
if (!this->has("bottom_infill_pattern"))
this->opt<ConfigOptionEnum<InfillPattern> >("bottom_infill_pattern", true)->value = p;
if (!this->has("top_infill_pattern"))
this->opt<ConfigOptionEnum<InfillPattern> >("top_infill_pattern", true)->value = p;
}
*/
if (!this->has("solid_infill_extruder") && this->has("infill_extruder"))
this->option("solid_infill_extruder", true)->setInt(this->option("infill_extruder")->getInt());
@ -1525,6 +1624,79 @@ PrintConfigBase::min_object_distance() const
: duplicate_distance;
}
bool
PrintConfigBase::set_deserialize(t_config_option_key opt_key, std::string str, bool append)
{
this->_handle_legacy(opt_key, str);
if (opt_key.empty()) return true; // ignore option
return ConfigBase::set_deserialize(opt_key, str, append);
}
void
PrintConfigBase::_handle_legacy(t_config_option_key &opt_key, std::string &value) const
{
// handle legacy options
if (opt_key == "extrusion_width_ratio" || opt_key == "bottom_layer_speed_ratio"
|| opt_key == "first_layer_height_ratio") {
boost::replace_first(opt_key, "_ratio", "");
if (opt_key == "bottom_layer_speed") opt_key = "first_layer_speed";
try {
float v = boost::lexical_cast<float>(value);
if (v != 0)
value = boost::lexical_cast<std::string>(v*100) + "%";
} catch (boost::bad_lexical_cast &) {
value = "0";
}
} else if (opt_key == "gcode_flavor" && value == "makerbot") {
value = "makerware";
} else if (opt_key == "fill_density" && value.find("%") == std::string::npos) {
try {
// fill_density was turned into a percent value
float v = boost::lexical_cast<float>(value);
value = boost::lexical_cast<std::string>(v*100) + "%";
} catch (boost::bad_lexical_cast &) {}
} else if (opt_key == "randomize_start" && value == "1") {
opt_key = "seam_position";
value = "random";
} else if (opt_key == "bed_size" && !value.empty()) {
opt_key = "bed_shape";
ConfigOptionPoint p;
p.deserialize(value);
std::ostringstream oss;
oss << "0x0," << p.value.x << "x0," << p.value.x << "x" << p.value.y << ",0x" << p.value.y;
value = oss.str();
} else if ((opt_key == "perimeter_acceleration" && value == "25")
|| (opt_key == "infill_acceleration" && value == "50")) {
/* For historical reasons, the world's full of configs having these very low values;
to avoid unexpected behavior we need to ignore them. Banning these two hard-coded
values is a dirty hack and will need to be removed sometime in the future, but it
will avoid lots of complaints for now. */
value = "0";
}
// cemetery of old config settings
if (opt_key == "duplicate_x" || opt_key == "duplicate_y" || opt_key == "multiply_x"
|| opt_key == "multiply_y" || opt_key == "support_material_tool"
|| opt_key == "acceleration" || opt_key == "adjust_overhang_flow"
|| opt_key == "standby_temperature" || opt_key == "scale" || opt_key == "rotate"
|| opt_key == "duplicate" || opt_key == "duplicate_grid" || opt_key == "rotate"
|| opt_key == "scale" || opt_key == "duplicate_grid"
|| opt_key == "start_perimeters_at_concave_points"
|| opt_key == "start_perimeters_at_non_overhang" || opt_key == "randomize_start"
|| opt_key == "seal_position" || opt_key == "bed_size"
|| opt_key == "print_center" || opt_key == "g0" || opt_key == "threads")
{
opt_key = "";
return;
}
if (!this->def->has(opt_key)) {
printf("Unknown option %s\n", opt_key.c_str());
opt_key = "";
return;
}
}
CLIConfigDef::CLIConfigDef()
{
ConfigOptionDef* def;

View File

@ -112,8 +112,11 @@ class PrintConfigBase : public virtual ConfigBase
PrintConfigBase() {
this->def = &print_config_def;
};
bool set_deserialize(t_config_option_key opt_key, std::string str, bool append = false);
double min_object_distance() const;
protected:
void _handle_legacy(t_config_option_key &opt_key, std::string &value) const;
};
// Slic3r dynamic configuration, used to override the configuration
@ -141,7 +144,6 @@ class PrintObjectConfig : public virtual StaticPrintConfig
{
public:
ConfigOptionBool adaptive_slicing;
ConfigOptionFloat adaptive_slicing_z_gradation;
ConfigOptionFloat adaptive_slicing_quality;
ConfigOptionBool dont_support_bridges;
ConfigOptionFloatOrPercent extrusion_width;
@ -165,7 +167,7 @@ class PrintObjectConfig : public virtual StaticPrintConfig
ConfigOptionEnum<SupportMaterialPattern> support_material_pattern;
ConfigOptionFloat support_material_spacing;
ConfigOptionFloat support_material_speed;
ConfigOptionInt support_material_threshold;
ConfigOptionFloatOrPercent support_material_threshold;
ConfigOptionFloat xy_size_compensation;
PrintObjectConfig(bool initialize = true) : StaticPrintConfig() {
@ -175,7 +177,6 @@ class PrintObjectConfig : public virtual StaticPrintConfig
virtual ConfigOption* optptr(const t_config_option_key &opt_key, bool create = false) {
OPT_PTR(adaptive_slicing);
OPT_PTR(adaptive_slicing_z_gradation);
OPT_PTR(adaptive_slicing_quality);
OPT_PTR(dont_support_bridges);
OPT_PTR(extrusion_width);
@ -210,10 +211,10 @@ class PrintObjectConfig : public virtual StaticPrintConfig
class PrintRegionConfig : public virtual StaticPrintConfig
{
public:
ConfigOptionEnum<InfillPattern> bottom_infill_pattern;
ConfigOptionInt bottom_solid_layers;
ConfigOptionFloat bridge_flow_ratio;
ConfigOptionFloat bridge_speed;
ConfigOptionEnum<InfillPattern> external_fill_pattern;
ConfigOptionFloatOrPercent external_perimeter_extrusion_width;
ConfigOptionFloatOrPercent external_perimeter_speed;
ConfigOptionBool external_perimeters_first;
@ -241,6 +242,7 @@ class PrintRegionConfig : public virtual StaticPrintConfig
ConfigOptionFloatOrPercent solid_infill_speed;
ConfigOptionBool thin_walls;
ConfigOptionFloatOrPercent top_infill_extrusion_width;
ConfigOptionEnum<InfillPattern> top_infill_pattern;
ConfigOptionInt top_solid_layers;
ConfigOptionFloatOrPercent top_solid_infill_speed;
@ -250,10 +252,10 @@ class PrintRegionConfig : public virtual StaticPrintConfig
}
virtual ConfigOption* optptr(const t_config_option_key &opt_key, bool create = false) {
OPT_PTR(bottom_infill_pattern);
OPT_PTR(bottom_solid_layers);
OPT_PTR(bridge_flow_ratio);
OPT_PTR(bridge_speed);
OPT_PTR(external_fill_pattern);
OPT_PTR(external_perimeter_extrusion_width);
OPT_PTR(external_perimeter_speed);
OPT_PTR(external_perimeters_first);
@ -281,6 +283,7 @@ class PrintRegionConfig : public virtual StaticPrintConfig
OPT_PTR(solid_infill_speed);
OPT_PTR(thin_walls);
OPT_PTR(top_infill_extrusion_width);
OPT_PTR(top_infill_pattern);
OPT_PTR(top_solid_infill_speed);
OPT_PTR(top_solid_layers);
@ -294,9 +297,12 @@ class GCodeConfig : public virtual StaticPrintConfig
public:
ConfigOptionString before_layer_gcode;
ConfigOptionString end_gcode;
ConfigOptionStrings end_filament_gcode;
ConfigOptionString extrusion_axis;
ConfigOptionFloats extrusion_multiplier;
ConfigOptionFloats filament_diameter;
ConfigOptionFloats filament_density;
ConfigOptionFloats filament_cost;
ConfigOptionFloats filament_max_volumetric_speed;
ConfigOptionBool gcode_comments;
ConfigOptionEnum<GCodeFlavor> gcode_flavor;
@ -313,6 +319,7 @@ class GCodeConfig : public virtual StaticPrintConfig
ConfigOptionFloats retract_restart_extra_toolchange;
ConfigOptionFloats retract_speed;
ConfigOptionString start_gcode;
ConfigOptionStrings start_filament_gcode;
ConfigOptionString toolchange_gcode;
ConfigOptionFloat travel_speed;
ConfigOptionBool use_firmware_retraction;
@ -327,9 +334,12 @@ class GCodeConfig : public virtual StaticPrintConfig
virtual ConfigOption* optptr(const t_config_option_key &opt_key, bool create = false) {
OPT_PTR(before_layer_gcode);
OPT_PTR(end_gcode);
OPT_PTR(end_filament_gcode);
OPT_PTR(extrusion_axis);
OPT_PTR(extrusion_multiplier);
OPT_PTR(filament_diameter);
OPT_PTR(filament_density);
OPT_PTR(filament_cost);
OPT_PTR(filament_max_volumetric_speed);
OPT_PTR(gcode_comments);
OPT_PTR(gcode_flavor);
@ -346,6 +356,7 @@ class GCodeConfig : public virtual StaticPrintConfig
OPT_PTR(retract_restart_extra_toolchange);
OPT_PTR(retract_speed);
OPT_PTR(start_gcode);
OPT_PTR(start_filament_gcode);
OPT_PTR(toolchange_gcode);
OPT_PTR(travel_speed);
OPT_PTR(use_firmware_retraction);
@ -399,6 +410,7 @@ class PrintConfig : public GCodeConfig
ConfigOptionBool gcode_arcs;
ConfigOptionFloat infill_acceleration;
ConfigOptionBool infill_first;
ConfigOptionFloat interior_brim_width;
ConfigOptionInt max_fan_speed;
ConfigOptionFloats max_layer_height;
ConfigOptionInt min_fan_speed;
@ -426,6 +438,7 @@ class PrintConfig : public GCodeConfig
ConfigOptionFloat vibration_limit;
ConfigOptionBools wipe;
ConfigOptionFloat z_offset;
ConfigOptionFloat z_steps_per_mm;
PrintConfig(bool initialize = true) : GCodeConfig(false) {
if (initialize)
@ -461,6 +474,7 @@ class PrintConfig : public GCodeConfig
OPT_PTR(gcode_arcs);
OPT_PTR(infill_acceleration);
OPT_PTR(infill_first);
OPT_PTR(interior_brim_width);
OPT_PTR(max_fan_speed);
OPT_PTR(max_layer_height);
OPT_PTR(min_fan_speed);
@ -488,6 +502,7 @@ class PrintConfig : public GCodeConfig
OPT_PTR(vibration_limit);
OPT_PTR(wipe);
OPT_PTR(z_offset);
OPT_PTR(z_steps_per_mm);
// look in parent class
ConfigOption* opt;
@ -622,6 +637,7 @@ class CLIConfig
ConfigOptionString save;
ConfigOptionFloat scale;
ConfigOptionPoint3 scale_to_fit;
ConfigOptionBool threads;
CLIConfig() : ConfigBase(), StaticConfig() {
this->def = &cli_config_def;
@ -645,6 +661,7 @@ class CLIConfig
OPT_PTR(save);
OPT_PTR(scale);
OPT_PTR(scale_to_fit);
OPT_PTR(threads);
return NULL;
};

View File

@ -3,6 +3,7 @@
#include "ClipperUtils.hpp"
#include "Geometry.hpp"
#include <algorithm>
#include <vector>
namespace Slic3r {
@ -166,12 +167,6 @@ PrintObject::clear_layers()
this->delete_layer(i);
}
Layer*
PrintObject::get_layer(int idx)
{
return this->layers.at(idx);
}
Layer*
PrintObject::add_layer(int id, coordf_t height, coordf_t print_z, coordf_t slice_z)
{
@ -201,12 +196,6 @@ PrintObject::clear_support_layers()
this->delete_support_layer(i);
}
SupportLayer*
PrintObject::get_support_layer(int idx)
{
return this->support_layers.at(idx);
}
SupportLayer*
PrintObject::add_support_layer(int id, coordf_t height, coordf_t print_z)
{
@ -240,15 +229,15 @@ PrintObject::invalidate_state_by_config_options(const std::vector<t_config_optio
|| *opt_key == "external_perimeters_first") {
steps.insert(posPerimeters);
} else if (*opt_key == "layer_height"
|| *opt_key == "min_layer_height"
|| *opt_key == "min_layer_height"
|| *opt_key == "max_layer_height"
|| *opt_key == "first_layer_height"
|| *opt_key == "xy_size_compensation"
|| *opt_key == "adaptive_slicing"
|| *opt_key == "adaptive_slicing_z_gradation"
|| *opt_key == "adaptive_slicing_quality"
|| *opt_key == "match_horizontal_surfaces"
|| *opt_key == "raft_layers") {
|| *opt_key == "match_horizontal_surfaces"
|| *opt_key == "raft_layers") {
steps.insert(posSlice);
} else if (*opt_key == "support_material"
|| *opt_key == "support_material_angle"
@ -275,7 +264,8 @@ PrintObject::invalidate_state_by_config_options(const std::vector<t_config_optio
|| *opt_key == "solid_infill_extruder"
|| *opt_key == "infill_extrusion_width") {
steps.insert(posPrepareInfill);
} else if (*opt_key == "external_fill_pattern"
} else if (*opt_key == "top_infill_pattern"
|| *opt_key == "bottom_infill_pattern"
|| *opt_key == "fill_angle"
|| *opt_key == "fill_pattern"
|| *opt_key == "top_infill_extrusion_width"
@ -364,184 +354,24 @@ PrintObject::has_support_material() const
|| this->config.support_material_enforce_layers > 0;
}
// This function analyzes slices of a region (SurfaceCollection slices).
// Each region slice (instance of Surface) is analyzed, whether it is supported or whether it is the top surface.
// Initially all slices are of type S_TYPE_INTERNAL.
// Slices are compared against the top / bottom slices and regions and classified to the following groups:
// S_TYPE_TOP - Part of a region, which is not covered by any upper layer. This surface will be filled with a top solid infill.
// S_TYPE_BOTTOMBRIDGE - Part of a region, which is not fully supported, but it hangs in the air, or it hangs losely on a support or a raft.
// S_TYPE_BOTTOM - Part of a region, which is not supported by the same region, but it is supported either by another region, or by a soluble interface layer.
// S_TYPE_INTERNAL - Part of a region, which is supported by the same region type.
// If a part of a region is of S_TYPE_BOTTOM and S_TYPE_TOP, the S_TYPE_BOTTOM wins.
void
PrintObject::detect_surfaces_type()
{
//Slic3r::debugf "Detecting solid surfaces...\n";
FOREACH_REGION(this->_print, region) {
size_t region_id = region - this->_print->regions.begin();
FOREACH_LAYER(this, layer_it) {
size_t layer_idx = layer_it - this->layers.begin();
Layer &layer = **layer_it;
LayerRegion &layerm = *layer.get_region(region_id);
// comparison happens against the *full* slices (considering all regions)
// unless internal shells are requested
const Layer* upper_layer = layer_idx < (this->layer_count()-1) ? this->get_layer(layer_idx+1) : NULL;
const Layer* lower_layer = layer_idx > 0 ? this->get_layer(layer_idx-1) : NULL;
// collapse very narrow parts (using the safety offset in the diff is not enough)
const float offset = layerm.flow(frExternalPerimeter).scaled_width() / 10.f;
const Polygons layerm_slices_surfaces = layerm.slices;
// find top surfaces (difference between current surfaces
// of current layer and upper one)
SurfaceCollection top;
if (upper_layer != NULL) {
const Polygons upper_slices = this->config.interface_shells.value
? (Polygons)upper_layer->get_region(region_id)->slices
: (Polygons)upper_layer->slices;
top.append(
offset2_ex(
diff(layerm_slices_surfaces, upper_slices, true),
-offset, offset
),
stTop
);
} else {
// if no upper layer, all surfaces of this one are solid
// we clone surfaces because we're going to clear the slices collection
top = layerm.slices;
for (Surfaces::iterator it = top.surfaces.begin(); it != top.surfaces.end(); ++ it)
it->surface_type = stTop;
}
// find bottom surfaces (difference between current surfaces
// of current layer and lower one)
SurfaceCollection bottom;
if (lower_layer != NULL) {
// If we have soluble support material, don't bridge. The overhang will be squished against a soluble layer separating
// the support from the print.
const SurfaceType surface_type_bottom =
(this->config.support_material.value && this->config.support_material_contact_distance.value == 0)
? stBottom
: stBottomBridge;
// Any surface lying on the void is a true bottom bridge (an overhang)
bottom.append(
offset2_ex(
diff(layerm_slices_surfaces, lower_layer->slices, true),
-offset, offset
),
surface_type_bottom
);
// if user requested internal shells, we need to identify surfaces
// lying on other slices not belonging to this region
if (this->config.interface_shells) {
// non-bridging bottom surfaces: any part of this layer lying
// on something else, excluding those lying on our own region
bottom.append(
offset2_ex(
diff(
intersection(layerm_slices_surfaces, lower_layer->slices), // supported
lower_layer->get_region(region_id)->slices,
true
),
-offset, offset
),
stBottom
);
}
} else {
// if no lower layer, all surfaces of this one are solid
// we clone surfaces because we're going to clear the slices collection
bottom = layerm.slices;
// if we have raft layers, consider bottom layer as a bridge
// just like any other bottom surface lying on the void
const SurfaceType surface_type_bottom =
(this->config.raft_layers.value > 0 && this->config.support_material_contact_distance.value > 0)
? stBottomBridge
: stBottom;
for (Surfaces::iterator it = bottom.surfaces.begin(); it != bottom.surfaces.end(); ++ it)
it->surface_type = surface_type_bottom;
}
// now, if the object contained a thin membrane, we could have overlapping bottom
// and top surfaces; let's do an intersection to discover them and consider them
// as bottom surfaces (to allow for bridge detection)
if (!top.empty() && !bottom.empty()) {
const Polygons top_polygons = to_polygons(STDMOVE(top));
top.clear();
top.append(
offset2_ex(diff(top_polygons, bottom, true), -offset, offset),
stTop
);
}
// save surfaces to layer
layerm.slices.clear();
layerm.slices.append(STDMOVE(top));
layerm.slices.append(STDMOVE(bottom));
// find internal surfaces (difference between top/bottom surfaces and others)
{
Polygons topbottom = top; append_to(topbottom, (Polygons)bottom);
layerm.slices.append(
offset2_ex(
diff(layerm_slices_surfaces, topbottom, true),
-offset, offset
),
stInternal
);
}
/*
Slic3r::debugf " layer %d has %d bottom, %d top and %d internal surfaces\n",
$layerm->layer->id, scalar(@bottom), scalar(@top), scalar(@internal) if $Slic3r::debug;
*/
} // for each layer of a region
/* Fill in layerm->fill_surfaces by trimming the layerm->slices by the cummulative layerm->fill_surfaces.
Note: this method should be idempotent, but fill_surfaces gets modified
in place. However we're now only using its boundaries (which are invariant)
so we're safe. This guarantees idempotence of prepare_infill() also in case
that combine_infill() turns some fill_surface into VOID surfaces. */
FOREACH_LAYER(this, layer_it) {
LayerRegion &layerm = *(*layer_it)->get_region(region_id);
const Polygons fill_boundaries = layerm.fill_surfaces;
layerm.fill_surfaces.clear();
for (Surfaces::const_iterator surface = layerm.slices.surfaces.begin();
surface != layerm.slices.surfaces.end(); ++ surface) {
layerm.fill_surfaces.append(
intersection_ex(*surface, fill_boundaries),
surface->surface_type
);
}
}
}
parallelize<Layer*>(
std::queue<Layer*>(std::deque<Layer*>(this->layers.begin(), this->layers.end())), // cast LayerPtrs to std::queue<Layer*>
boost::bind(&Slic3r::Layer::detect_surfaces_type, _1),
this->_print->config.threads.value
);
}
void
PrintObject::process_external_surfaces()
{
FOREACH_REGION(this->_print, region) {
size_t region_id = region - this->_print->regions.begin();
FOREACH_LAYER(this, layer_it) {
const Layer* lower_layer = (layer_it == this->layers.begin())
? NULL
: *(layer_it-1);
(*layer_it)->get_region(region_id)->process_external_surfaces(lower_layer);
}
}
parallelize<Layer*>(
std::queue<Layer*>(std::deque<Layer*>(this->layers.begin(), this->layers.end())), // cast LayerPtrs to std::queue<Layer*>
boost::bind(&Slic3r::Layer::process_external_surfaces, _1),
this->_print->config.threads.value
);
}
/* This method applies bridge flow to the first internal solid layer above
@ -725,6 +555,330 @@ PrintObject::bridge_over_infill()
}
}
// adjust the layer height to the next multiple of the z full-step resolution
coordf_t PrintObject::adjust_layer_height(coordf_t layer_height) const
{
coordf_t result = layer_height;
if(this->_print->config.z_steps_per_mm > 0) {
coordf_t min_dz = 1 / this->_print->config.z_steps_per_mm * 4;
result = int(layer_height / min_dz + 0.5) * min_dz;
}
return result > 0 ? result : layer_height;
}
// generate a vector of print_z coordinates in object coordinate system (starting with 0) but including
// the first_layer_height if provided.
std::vector<coordf_t> PrintObject::generate_object_layers(coordf_t first_layer_height) {
std::vector<coordf_t> result;
// collect values from config
coordf_t min_nozzle_diameter = 1.0;
coordf_t min_layer_height = 0.0;
coordf_t max_layer_height = 10.0;
std::set<size_t> object_extruders = this->_print->object_extruders();
for (std::set<size_t>::const_iterator it_extruder = object_extruders.begin(); it_extruder != object_extruders.end(); ++ it_extruder) {
min_nozzle_diameter = std::min(min_nozzle_diameter, this->_print->config.nozzle_diameter.get_at(*it_extruder));
min_layer_height = std::max(min_layer_height, this->_print->config.min_layer_height.get_at(*it_extruder));
max_layer_height = std::min(max_layer_height, this->_print->config.max_layer_height.get_at(*it_extruder));
}
coordf_t layer_height = std::min(min_nozzle_diameter, this->config.layer_height.getFloat());
layer_height = this->adjust_layer_height(layer_height);
this->config.layer_height.value = layer_height;
// respect first layer height
if(first_layer_height) {
result.push_back(first_layer_height);
}
coordf_t print_z = first_layer_height;
coordf_t height = first_layer_height;
if(!this->layer_height_spline.updateRequired()) { // layer heights are already generated, just update layers from spline
// we don't need to respect first layer here, it's correctly provided by the spline object
result = this->layer_height_spline.getInterpolatedLayers();
}else{ // create new set of layers
// create stateful objects and variables for the adaptive slicing process
SlicingAdaptive as;
coordf_t adaptive_quality = this->config.adaptive_slicing_quality.value;
if(this->config.adaptive_slicing.value) {
const ModelVolumePtrs volumes = this->model_object()->volumes;
for (ModelVolumePtrs::const_iterator it = volumes.begin(); it != volumes.end(); ++ it)
if (! (*it)->modifier)
as.add_mesh(&(*it)->mesh);
as.prepare(unscale(this->size.z));
}
// loop until we have at least one layer and the max slice_z reaches the object height
while (print_z < unscale(this->size.z)) {
if (this->config.adaptive_slicing.value) {
height = 999;
// FIXME: this should de done directly via config at the dialog...
if(this->layer_height_spline.getCuspValue() >= 0) {
adaptive_quality = this->layer_height_spline.getCuspValue(); //FIXME: rename variable (cusp)
this->config.adaptive_slicing_quality.value = adaptive_quality;
}
// determine next layer height
height = as.next_layer_height(print_z, adaptive_quality, min_layer_height, max_layer_height);
// check for horizontal features and object size
if(this->config.match_horizontal_surfaces.value) {
coordf_t horizontal_dist = as.horizontal_facet_distance(print_z + height, min_layer_height);
if((horizontal_dist < min_layer_height) && (horizontal_dist > 0)) {
// std::cout << "Horizontal feature ahead, distance: " << horizontal_dist << std::endl;
// can we shrink the current layer a bit?
if(height-(min_layer_height - horizontal_dist) > min_layer_height) {
// yes we can
height -= (min_layer_height - horizontal_dist);
// std::cout << "Shrink layer height to " << height << std::endl;
}else{
// no, current layer would become too thin
height += horizontal_dist;
// std::cout << "Widen layer height to " << height << std::endl;
}
}
}
}else{
height = layer_height;
}
// look for an applicable custom range
for (t_layer_height_ranges::const_iterator it_range = this->layer_height_ranges.begin(); it_range != this->layer_height_ranges.end(); ++ it_range) {
if(print_z >= it_range->first.first && print_z <= it_range->first.second) {
if(it_range->second > 0) {
height = it_range->second;
}
}
}
print_z += height;
result.push_back(print_z);
}
// Reduce or thicken the top layer in order to match the original object size.
// This is not actually related to z_steps_per_mm but we only enable it in case
// user provided that value, as it means they really care about the layer height
// accuracy and we don't provide unexpected result for people noticing the last
// layer has a different layer height.
if (this->_print->config.z_steps_per_mm > 0 && result.size() > 1 && !this->config.adaptive_slicing.value) {
coordf_t diff = result.back() - unscale(this->size.z);
int last_layer = result.size()-1;
if (diff < 0) {
// we need to thicken last layer
coordf_t new_h = result[last_layer] - result[last_layer-1];
new_h = std::min(min_nozzle_diameter, new_h - diff); // add (negativ) diff value
std::cout << new_h << std::endl;
result[last_layer] = result[last_layer-1] + new_h;
} else {
// we need to reduce last layer
coordf_t new_h = result[last_layer] - result[last_layer-1];
if(min_nozzle_diameter/2 < new_h) { //prevent generation of a too small layer
new_h = std::max(min_nozzle_diameter/2, new_h - diff); // subtract (positive) diff value
std::cout << new_h << std::endl;
result[last_layer] = result[last_layer-1] + new_h;
}
}
}
// Store layer vector for interactive manipulation
this->layer_height_spline.setLayers(result);
if (this->config.adaptive_slicing.value) { // smoothing after adaptive algorithm
result = this->layer_height_spline.getInterpolatedLayers();
}
}
// apply z-gradation (this is redundant for static layer height...)
coordf_t gradation = 1 / this->_print->config.z_steps_per_mm * 4;
if(this->_print->config.z_steps_per_mm > 0) {
coordf_t last_z = 0;
coordf_t height;
for(std::vector<coordf_t>::iterator l = result.begin(); l != result.end(); ++l) {
height = *l - last_z;
coordf_t gradation_effect = unscale((scale_(height)) % (scale_(gradation)));
if(gradation_effect > gradation/2 && (height + (gradation-gradation_effect)) <= max_layer_height) { // round up
height = height + (gradation-gradation_effect);
}else{ // round down
height = height - gradation_effect;
}
height = std::min(std::max(height, min_layer_height), max_layer_height);
*l = last_z + height;
last_z = *l;
}
}
return result;
}
// 1) Decides Z positions of the layers,
// 2) Initializes layers and their regions
// 3) Slices the object meshes
// 4) Slices the modifier meshes and reclassifies the slices of the object meshes by the slices of the modifier meshes
// 5) Applies size compensation (offsets the slices in XY plane)
// 6) Replaces bad slices by the slices reconstructed from the upper/lower layer
// Resulting expolygons of layer regions are marked as Internal.
//
// this should be idempotent
void PrintObject::_slice()
{
coordf_t raft_height = 0;
coordf_t print_z = 0;
coordf_t height = 0;
coordf_t first_layer_height = this->config.first_layer_height.get_abs_value(this->config.layer_height.value);
// take raft layers into account
int id = 0;
if (this->config.raft_layers > 0) {
id = this->config.raft_layers;
coordf_t min_support_nozzle_diameter = 1.0;
std::set<size_t> support_material_extruders = this->_print->support_material_extruders();
for (std::set<size_t>::const_iterator it_extruder = support_material_extruders.begin(); it_extruder != support_material_extruders.end(); ++ it_extruder) {
min_support_nozzle_diameter = std::min(min_support_nozzle_diameter, this->_print->config.nozzle_diameter.get_at(*it_extruder));
}
coordf_t support_material_layer_height = 0.75 * min_support_nozzle_diameter;
// raise first object layer Z by the thickness of the raft itself
// plus the extra distance required by the support material logic
raft_height += first_layer_height;
raft_height += support_material_layer_height * (this->config.raft_layers - 1);
// reset for later layer generation
first_layer_height = 0;
// detachable support
if(this->config.support_material_contact_distance > 0) {
first_layer_height = min_support_nozzle_diameter;
raft_height += this->config.support_material_contact_distance;
}
}
// Initialize layers and their slice heights.
std::vector<float> slice_zs;
{
this->clear_layers();
// All print_z values for this object, without the raft.
std::vector<coordf_t> object_layers = this->generate_object_layers(first_layer_height);
// Reserve object layers for the raft. Last layer of the raft is the contact layer.
slice_zs.reserve(object_layers.size());
Layer *prev = nullptr;
coordf_t lo = raft_height;
coordf_t hi = lo;
for (size_t i_layer = 0; i_layer < object_layers.size(); i_layer++) {
lo = hi; // store old value
hi = object_layers[i_layer] + raft_height;
coordf_t slice_z = 0.5 * (lo + hi) - raft_height;
Layer *layer = this->add_layer(id++, hi - lo, hi, slice_z);
slice_zs.push_back(float(slice_z));
if (prev != nullptr) {
prev->upper_layer = layer;
layer->lower_layer = prev;
}
// Make sure all layers contain layer region objects for all regions.
for (size_t region_id = 0; region_id < this->_print->regions.size(); ++ region_id)
layer->add_region(this->print()->regions[region_id]);
prev = layer;
}
}
if (this->print()->regions.size() == 1) {
// Optimized for a single region. Slice the single non-modifier mesh.
std::vector<ExPolygons> expolygons_by_layer = this->_slice_region(0, slice_zs, false);
for (size_t layer_id = 0; layer_id < expolygons_by_layer.size(); ++ layer_id)
this->layers[layer_id]->regions.front()->slices.append(std::move(expolygons_by_layer[layer_id]), stInternal);
} else {
// Slice all non-modifier volumes.
for (size_t region_id = 0; region_id < this->print()->regions.size(); ++ region_id) {
std::vector<ExPolygons> expolygons_by_layer = this->_slice_region(region_id, slice_zs, false);
for (size_t layer_id = 0; layer_id < expolygons_by_layer.size(); ++ layer_id)
this->layers[layer_id]->regions[region_id]->slices.append(std::move(expolygons_by_layer[layer_id]), stInternal);
}
// Slice all modifier volumes.
for (size_t region_id = 0; region_id < this->print()->regions.size(); ++ region_id) {
std::vector<ExPolygons> expolygons_by_layer = this->_slice_region(region_id, slice_zs, true);
// loop through the other regions and 'steal' the slices belonging to this one
for (size_t other_region_id = 0; other_region_id < this->print()->regions.size(); ++ other_region_id) {
if (region_id == other_region_id)
continue;
for (size_t layer_id = 0; layer_id < expolygons_by_layer.size(); ++ layer_id) {
Layer *layer = layers[layer_id];
LayerRegion *layerm = layer->regions[region_id];
LayerRegion *other_layerm = layer->regions[other_region_id];
if (layerm == nullptr || other_layerm == nullptr)
continue;
Polygons other_slices = to_polygons(other_layerm->slices);
ExPolygons my_parts = intersection_ex(other_slices, to_polygons(expolygons_by_layer[layer_id]));
if (my_parts.empty())
continue;
// Remove such parts from original region.
other_layerm->slices.set(diff_ex(other_slices, to_polygons(my_parts)), stInternal);
// Append new parts to our region.
layerm->slices.append(std::move(my_parts), stInternal);
}
}
}
}
// remove last layer(s) if empty
bool done = false;
while (! this->layers.empty()) {
const Layer *layer = this->layers.back();
for (size_t region_id = 0; region_id < this->print()->regions.size(); ++ region_id)
if (layer->regions[region_id] != nullptr && ! layer->regions[region_id]->slices.empty()) {
done = true;
break;
}
if(done) {
break;
}
this->delete_layer(int(this->layers.size()) - 1);
}
for (size_t layer_id = 0; layer_id < layers.size(); ++ layer_id) {
Layer *layer = this->layers[layer_id];
// Apply size compensation and perform clipping of multi-part objects.
float delta = float(scale_(this->config.xy_size_compensation.value));
bool scale = delta != 0.f;
if (layer->regions.size() == 1) {
if (scale) {
// Single region, growing or shrinking.
LayerRegion *layerm = layer->regions.front();
layerm->slices.set(offset_ex(to_expolygons(std::move(layerm->slices.surfaces)), delta), stInternal);
}
} else if (scale) {
// Multiple regions, growing, shrinking or just clipping one region by the other.
// When clipping the regions, priority is given to the first regions.
Polygons processed;
for (size_t region_id = 0; region_id < layer->regions.size(); ++ region_id) {
LayerRegion *layerm = layer->regions[region_id];
ExPolygons slices = to_expolygons(std::move(layerm->slices.surfaces));
if (scale)
slices = offset_ex(slices, delta);
if (region_id > 0)
// Trim by the slices of already processed regions.
slices = diff_ex(to_polygons(std::move(slices)), processed);
if (region_id + 1 < layer->regions.size())
// Collect the already processed regions to trim the to be processed regions.
processed += to_polygons(slices);
layerm->slices.set(std::move(slices), stInternal);
}
}
// Merge all regions' slices to get islands, chain them by a shortest path.
layer->make_slices();
}
}
// called from slice()
std::vector<ExPolygons>
PrintObject::_slice_region(size_t region_id, std::vector<float> z, bool modifier)
@ -789,7 +943,6 @@ PrintObject::_make_perimeters()
size_t region_id = region_it - this->_print->regions.begin();
const PrintRegion &region = **region_it;
if (!region.config.extra_perimeters
|| region.config.perimeters == 0
|| region.config.fill_density == 0
@ -798,7 +951,13 @@ PrintObject::_make_perimeters()
for (size_t i = 0; i <= (this->layer_count()-2); ++i) {
LayerRegion &layerm = *this->get_layer(i)->get_region(region_id);
const LayerRegion &upper_layerm = *this->get_layer(i+1)->get_region(region_id);
const Polygons upper_layerm_polygons = upper_layerm.slices;
// In order to avoid diagonal gaps (GH #3732) we ignore the external half of the upper
// perimeter, since it's not truly covering this layer.
const Polygons upper_layerm_polygons = offset(
upper_layerm.slices,
-upper_layerm.flow(frExternalPerimeter).scaled_width()/2
);
// Filter upper layer polygons in intersection_ppl by their bounding boxes?
// my $upper_layerm_poly_bboxes= [ map $_->bounding_box, @{$upper_layerm_polygons} ];

View File

@ -57,7 +57,7 @@ SLAPrint::slice()
// generate infill
if (this->config.fill_density < 100) {
std::auto_ptr<Fill> fill(Fill::new_from_type(this->config.fill_pattern.value));
std::unique_ptr<Fill> fill(Fill::new_from_type(this->config.fill_pattern.value));
fill->bounding_box.merge(Point::new_scale(bb.min.x, bb.min.y));
fill->bounding_box.merge(Point::new_scale(bb.max.x, bb.max.y));
fill->min_spacing = this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value);
@ -184,7 +184,7 @@ SLAPrint::_infill_layer(size_t i, const Fill* _fill)
// Generate internal infill
{
std::auto_ptr<Fill> fill(_fill->clone());
std::unique_ptr<Fill> fill(_fill->clone());
fill->layer_id = i;
fill->z = layer.print_z;

View File

@ -0,0 +1,182 @@
#include "libslic3r.h"
#include "TriangleMesh.hpp"
#include "SlicingAdaptive.hpp"
#ifdef SLIC3R_DEBUG
#undef NDEBUG
#define DEBUG
#define _DEBUG
#endif
/* This constant essentially describes the volumetric error at the surface which is induced
* by stacking "elliptic" extrusion threads.
* It is empirically determined by
* 1. measuring the surface profile of printed parts to find
* the ratio between layer height and profile height and then
* 2. computing the geometric difference between the model-surface and the elliptic profile.
* [Link to detailed description follows]
*/
#define SURFACE_CONST 0.18403
namespace Slic3r
{
void SlicingAdaptive::clear()
{
m_meshes.clear();
m_faces.clear();
m_face_normal_z.clear();
}
std::pair<float, float> face_z_span(const stl_facet *f)
{
return std::pair<float, float>(
std::min(std::min(f->vertex[0].z, f->vertex[1].z), f->vertex[2].z),
std::max(std::max(f->vertex[0].z, f->vertex[1].z), f->vertex[2].z));
}
void SlicingAdaptive::prepare(coordf_t object_size)
{
this->object_size = object_size;
// 1) Collect faces of all meshes.
int nfaces_total = 0;
for (std::vector<const TriangleMesh*>::const_iterator it_mesh = m_meshes.begin(); it_mesh != m_meshes.end(); ++ it_mesh)
nfaces_total += (*it_mesh)->stl.stats.number_of_facets;
m_faces.reserve(nfaces_total);
for (std::vector<const TriangleMesh*>::const_iterator it_mesh = m_meshes.begin(); it_mesh != m_meshes.end(); ++ it_mesh)
for (int i = 0; i < (*it_mesh)->stl.stats.number_of_facets; ++ i)
m_faces.push_back((*it_mesh)->stl.facet_start + i);
// 2) Sort faces lexicographically by their Z span.
std::sort(m_faces.begin(), m_faces.end(), [](const stl_facet *f1, const stl_facet *f2) {
std::pair<float, float> span1 = face_z_span(f1);
std::pair<float, float> span2 = face_z_span(f2);
return span1 < span2;
});
// 3) Generate Z components of the facet normals.
m_face_normal_z.assign(m_faces.size(), 0.f);
for (size_t iface = 0; iface < m_faces.size(); ++ iface)
m_face_normal_z[iface] = m_faces[iface]->normal.z;
// 4) Reset current facet pointer
this->current_facet = 0;
}
float SlicingAdaptive::next_layer_height(coordf_t z, coordf_t quality_factor, coordf_t min_layer_height, coordf_t max_layer_height)
{
float height = max_layer_height;
// factor must be between 0-1, 0 is highest quality, 1 highest print speed.
// currently disabled but planned for the future
// Invert the slider scale (100% should represent a very high quality for the user)
//float quality_factor = std::max(0.f, std::min(1.f, 1 - m_slicing_params.adaptive_slicing_quality/100.f));
float delta_min = SURFACE_CONST * min_layer_height;
float delta_max = SURFACE_CONST * max_layer_height + 0.5 * max_layer_height;
float scaled_quality_factor = quality_factor * (delta_max - delta_min) + delta_min;
bool first_hit = false;
// find all facets intersecting the slice-layer
int ordered_id = current_facet;
for (; ordered_id < int(m_faces.size()); ++ ordered_id) {
std::pair<float, float> zspan = face_z_span(m_faces[ordered_id]);
// facet's minimum is higher than slice_z -> end loop
if (zspan.first >= z)
break;
// facet's maximum is higher than slice_z -> store the first event for next layer_height call to begin at this point
if (zspan.second > z) {
// first event?
if (! first_hit) {
first_hit = true;
current_facet = ordered_id;
}
// skip touching facets which could otherwise cause small height values
if (zspan.second <= z + EPSILON)
continue;
// compute height for this facet and store minimum of all heights
height = std::min(height, this->_layer_height_from_facet(ordered_id, scaled_quality_factor));
}
}
// lower height limit due to printer capabilities
height = std::max<float>(height, min_layer_height);
// check for sloped facets inside the determined layer and correct height if necessary
if (height > min_layer_height) {
for (; ordered_id < int(m_faces.size()); ++ ordered_id) {
std::pair<float, float> zspan = face_z_span(m_faces[ordered_id]);
// facet's minimum is higher than slice_z + height -> end loop
if (zspan.first >= z + height)
break;
// skip touching facets which could otherwise cause small cusp values
if (zspan.second <= z + EPSILON)
continue;
// Compute new height for this facet and check against height.
float reduced_height = this->_layer_height_from_facet(ordered_id, scaled_quality_factor);
float z_diff = zspan.first - z;
if (reduced_height > z_diff) {
if (reduced_height < height) {
#ifdef DEBUG
std::cout << "adaptive layer computation: height is reduced from " << height;
#endif
height = reduced_height;
#ifdef DEBUG
std::cout << "to " << height << " due to higher facet" << std::endl;
#endif
}
} else {
#ifdef DEBUG
std::cout << "cusp computation, height is reduced from " << height;
#endif
height = z_diff;
#ifdef DEBUG
std::cout << "to " << height << " due to z-diff" << std::endl;
#endif
}
}
// lower height limit due to printer capabilities again
height = std::max(height, float(min_layer_height));
}
#ifdef DEBUG
std::cout << "adaptive layer computation, layer-bottom at z:" << z << ", quality_factor:" << quality_factor << ", resulting layer height:" << height << std::endl;
#endif
return height;
}
// Returns the distance to the next horizontal facet in Z-dir
// to consider horizontal object features in slice thickness
float SlicingAdaptive::horizontal_facet_distance(coordf_t z, coordf_t max_layer_height)
{
for (size_t i = 0; i < m_faces.size(); ++ i) {
std::pair<float, float> zspan = face_z_span(m_faces[i]);
// facet's minimum is higher than max forward distance -> end loop
if (zspan.first > z + max_layer_height)
break;
// min_z == max_z -> horizontal facet
if (zspan.first > z && zspan.first == zspan.second)
return zspan.first - z;
}
// objects maximum?
return (z + max_layer_height > this->object_size) ?
std::max<float>(this->object_size - z, 0.f) :
max_layer_height;
}
// for a given facet, compute maximum height within the allowed surface roughness / stairstepping deviation
float SlicingAdaptive::_layer_height_from_facet(int ordered_id, float scaled_quality_factor)
{
float normal_z = std::abs(m_face_normal_z[ordered_id]);
float height = scaled_quality_factor/(SURFACE_CONST + normal_z/2);
return (normal_z == 0.f) ? 9999.f : height;
}
}; // namespace Slic3r

View File

@ -0,0 +1,38 @@
#ifndef slic3r_SlicingAdaptive_hpp_
#define slic3r_SlicingAdaptive_hpp_
#include "admesh/stl.h"
namespace Slic3r
{
class TriangleMesh;
class SlicingAdaptive
{
public:
SlicingAdaptive() {};
~SlicingAdaptive() {};
void clear();
void add_mesh(const TriangleMesh *mesh) { m_meshes.push_back(mesh); }
void prepare(coordf_t object_size);
float next_layer_height(coordf_t z, coordf_t quality_factor, coordf_t min_layer_height, coordf_t max_layer_height);
float horizontal_facet_distance(coordf_t z, coordf_t max_layer_height);
private:
float _layer_height_from_facet(int ordered_id, float scaled_quality_factor);
protected:
// id of the current facet from last iteration
coordf_t object_size;
int current_facet;
std::vector<const TriangleMesh*> m_meshes;
// Collected faces of all meshes, sorted by raising Z of the bottom most face.
std::vector<const stl_facet*> m_faces;
// Z component of face normals, normalized.
std::vector<float> m_face_normal_z;
};
}; // namespace Slic3r
#endif /* slic3r_SlicingAdaptive_hpp_ */

View File

@ -4,7 +4,7 @@
namespace Slic3r {
// how much we extend support around the actual contact area
#define SUPPORT_MATERIAL_MARGIN 1.5
constexpr coordf_t SUPPORT_MATERIAL_MARGIN = 1.5;
}

View File

@ -62,6 +62,93 @@ to_polygons(const SurfacesConstPtr &surfaces)
return pp;
}
inline ExPolygons to_expolygons(const Surfaces &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back(it->expolygon);
return expolygons;
}
inline ExPolygons to_expolygons(Surfaces &&src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.emplace_back(ExPolygon(std::move(it->expolygon)));
src.clear();
return expolygons;
}
inline ExPolygons to_expolygons(const SurfacesPtr &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back((*it)->expolygon);
return expolygons;
}
// Count a nuber of polygons stored inside the vector of expolygons.
// Useful for allocating space for polygons when converting expolygons to polygons.
inline size_t number_polygons(const Surfaces &surfaces)
{
size_t n_polygons = 0;
for (Surfaces::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += it->expolygon.holes.size() + 1;
return n_polygons;
}
inline size_t number_polygons(const SurfacesPtr &surfaces)
{
size_t n_polygons = 0;
for (SurfacesPtr::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += (*it)->expolygon.holes.size() + 1;
return n_polygons;
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const Surfaces &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(it->expolygon.contour);
dst.insert(dst.end(), it->expolygon.holes.begin(), it->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, Surfaces &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move(it->expolygon.contour));
std::move(std::begin(it->expolygon.holes), std::end(it->expolygon.holes), std::back_inserter(dst));
it->expolygon.holes.clear();
}
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const SurfacesPtr &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back((*it)->expolygon.contour);
dst.insert(dst.end(), (*it)->expolygon.holes.begin(), (*it)->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, SurfacesPtr &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move((*it)->expolygon.contour));
std::move(std::begin((*it)->expolygon.holes), std::end((*it)->expolygon.holes), std::back_inserter(dst));
(*it)->expolygon.holes.clear();
}
}
}
#endif

View File

@ -23,12 +23,23 @@ class SurfaceCollection
template <class T> bool any_bottom_contains(const T &item) const;
SurfacesPtr filter_by_type(SurfaceType type);
void filter_by_type(SurfaceType type, Polygons* polygons);
void set(const SurfaceCollection &coll) { surfaces = coll.surfaces; }
void set(SurfaceCollection &&coll) { surfaces = std::move(coll.surfaces); }
void set(const ExPolygons &src, SurfaceType surfaceType) { clear(); this->append(src, surfaceType); }
void set(const ExPolygons &src, const Surface &surfaceTempl) { clear(); this->append(src, surfaceTempl); }
void set(const Surfaces &src) { clear(); this->append(src); }
void set(ExPolygons &&src, SurfaceType surfaceType) { clear(); this->append(std::move(src), surfaceType); }
void set(ExPolygons &&src, const Surface &surfaceTempl) { clear(); this->append(std::move(src), surfaceTempl); }
void set(Surfaces &&src) { clear(); this->append(std::move(src)); }
void append(const SurfaceCollection &coll);
void append(const Surfaces &surfaces);
void append(const ExPolygons &src, const Surface &templ);
void append(const ExPolygons &src, SurfaceType surfaceType);
size_t polygons_count() const;
bool empty() const { return this->surfaces.empty(); };
size_t size() const { return this->surfaces.size(); };
void clear() { this->surfaces.clear(); };
};

View File

@ -58,6 +58,7 @@ class TriangleMesh
bool needed_repair() const;
size_t facets_count() const;
void extrude_tin(float offset);
void require_shared_vertices();
static TriangleMesh make_cube(double x, double y, double z);
static TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360));
@ -67,7 +68,6 @@ class TriangleMesh
bool repaired;
private:
void require_shared_vertices();
friend class TriangleMeshSlicer<X>;
friend class TriangleMeshSlicer<Y>;
friend class TriangleMeshSlicer<Z>;

View File

@ -10,33 +10,6 @@
#include <vector>
#include <boost/thread.hpp>
#define SLIC3R_VERSION "1.3.0-dev"
//FIXME This epsilon value is used for many non-related purposes:
// For a threshold of a squared Euclidean distance,
// for a trheshold in a difference of radians,
// for a threshold of a cross product of two non-normalized vectors etc.
#define EPSILON 1e-4
// Scaling factor for a conversion from coord_t to coordf_t: 10e-6
// This scaling generates a following fixed point representation with for a 32bit integer:
// 0..4294mm with 1nm resolution
#define SCALING_FACTOR 0.000001
// RESOLUTION, SCALED_RESOLUTION: Used as an error threshold for a Douglas-Peucker polyline simplification algorithm.
#define RESOLUTION 0.0125
#define SCALED_RESOLUTION (RESOLUTION / SCALING_FACTOR)
#define PI 3.141592653589793238
// When extruding a closed loop, the loop is interrupted and shortened a bit to reduce the seam.
#define LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER 0.15
// Maximum perimeter length for the loop to apply the small perimeter speed.
#define SMALL_PERIMETER_LENGTH (6.5 / SCALING_FACTOR) * 2 * PI
#define INSET_OVERLAP_TOLERANCE 0.4
#define EXTERNAL_INFILL_MARGIN 3
#define scale_(val) ((val) / SCALING_FACTOR)
#define unscale(val) ((val) * SCALING_FACTOR)
#define SCALED_EPSILON scale_(EPSILON)
typedef long coord_t;
typedef double coordf_t;
/* Implementation of CONFESS("foo"): */
#ifdef _MSC_VER
#define CONFESS(...) confess_at(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)
@ -61,6 +34,35 @@ void confess_at(const char *file, int line, const char *func, const char *pat, .
namespace Slic3r {
constexpr auto SLIC3R_VERSION = "1.3.0-dev";
typedef long coord_t;
typedef double coordf_t;
// Scaling factor for a conversion from coord_t to coordf_t: 10e-6
// This scaling generates a following fixed point representation with for a 32bit integer:
// 0..4294mm with 1nm resolution
constexpr auto SCALING_FACTOR = 0.000001;
inline constexpr coord_t scale_(const coordf_t &val) { return val / SCALING_FACTOR; }
inline constexpr coordf_t unscale(const coord_t &val) { return val * SCALING_FACTOR; }
//FIXME This epsilon value is used for many non-related purposes:
// For a threshold of a squared Euclidean distance,
// for a trheshold in a difference of radians,
// for a threshold of a cross product of two non-normalized vectors etc.
constexpr auto EPSILON = 1e-4;
constexpr auto SCALED_EPSILON = scale_(EPSILON);
// RESOLUTION, SCALED_RESOLUTION: Used as an error threshold for a Douglas-Peucker polyline simplification algorithm.
constexpr auto RESOLUTION = 0.0125;
constexpr auto SCALED_RESOLUTION = scale_(RESOLUTION);
constexpr auto PI = 3.141592653589793238;
// When extruding a closed loop, the loop is interrupted and shortened a bit to reduce the seam.
constexpr auto LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER = 0.15;
// Maximum perimeter length for the loop to apply the small perimeter speed.
constexpr coord_t SMALL_PERIMETER_LENGTH = scale_(6.5) * 2 * PI;
constexpr coordf_t INSET_OVERLAP_TOLERANCE = 0.4;
constexpr coordf_t EXTERNAL_INFILL_MARGIN = 3;
enum Axis { X=0, Y, Z };
template <class T>

View File

@ -15,6 +15,7 @@ REGISTER_CLASS(Filler, "Filler");
REGISTER_CLASS(AvoidCrossingPerimeters, "GCode::AvoidCrossingPerimeters");
REGISTER_CLASS(CoolingBuffer, "GCode::CoolingBuffer");
REGISTER_CLASS(OozePrevention, "GCode::OozePrevention");
REGISTER_CLASS(SpiralVase, "GCode::SpiralVase");
REGISTER_CLASS(Wipe, "GCode::Wipe");
REGISTER_CLASS(GCode, "GCode");
REGISTER_CLASS(GCodeSender, "GCode::Sender");
@ -55,6 +56,7 @@ REGISTER_CLASS(GCodeConfig, "Config::GCode");
REGISTER_CLASS(PrintConfig, "Config::Print");
REGISTER_CLASS(FullPrintConfig, "Config::Full");
REGISTER_CLASS(SLAPrint, "SLAPrint");
REGISTER_CLASS(SlicingAdaptive, "SlicingAdaptive");
REGISTER_CLASS(Surface, "Surface");
REGISTER_CLASS(SurfaceCollection, "Surface::Collection");
REGISTER_CLASS(TriangleMesh, "TriangleMesh");

View File

@ -4,7 +4,7 @@ use strict;
use warnings;
use Slic3r::XS;
use Test::More tests => 147;
use Test::More tests => 159;
use Data::Dumper;
foreach my $config (Slic3r::Config->new, Slic3r::Config::Static::new_FullPrintConfig) {
@ -251,4 +251,46 @@ foreach my $config (Slic3r::Config->new, Slic3r::Config::Static::new_FullPrintCo
ok 1, 'did not crash on reading invalid items in config';
}
{
my $parse = sub {
my @argv = @_;
my $config = Slic3r::Config->new;
$config->read_cli(\@argv);
return $config;
};
{
my $config = $parse->(qw(--extra-perimeters --perimeters 1 --layer-height 0.45
--fill-density 70% --detect-bridging-perimeters --notes=foobar));
is $config->get('extra_perimeters'), 1, 'read_cli(): bool';
is $config->get('perimeters'), 1, 'read_cli(): int';
is $config->get('layer_height'), 0.45, 'read_cli(): float';
is $config->serialize('fill_density'), '70%', 'read_cli(): percent';
is $config->get('overhangs'), 1, 'read_cli(): alternative';
is $config->get('notes'), 'foobar', 'read_cli(): key=val';
}
{
my $config = $parse->(qw(--extra-perimeters --no-extra-perimeters));
ok $config->has('extra_perimeters'), 'read_cli(): negated bool';
is_deeply $config->get('extra_perimeters'), 0, 'read_cli(): negated bool';
}
{
my $config = $parse->(qw(--wipe --no-wipe --wipe));
is_deeply $config->get('wipe'), [1,0,1], 'read_cli(): bools array';
}
{
my $config = $parse->(qw(--post-process foo --post-process bar));
is_deeply $config->get('post_process'), ['foo', 'bar'], 'read_cli(): strings array';
}
{
my $config = $parse->(qw(--retract-speed 0.4 --retract-speed 0.5));
is_deeply $config->get('retract_speed'), [0.4, 0.5], 'read_cli(): floats array';
}
{
no warnings 'qw';
my $config = $parse->(qw(--extruder-offset 0,0 --extruder-offset 10x5));
is_deeply [ map $_->pp, @{$config->get('extruder_offset')} ],
[[0,0], [10,5]], 'read_cli(): points array';
}
}
__END__

View File

@ -8,7 +8,10 @@ use Test::More tests => 1;
{
eval {
local $SIG{ALRM} = sub { die "Timed out waiting for exception\n" }; # NB: \n required
alarm 30;
Slic3r::xspp_test_croak_hangs_on_strawberry();
alarm 0;
};
is $@, "xspp_test_croak_hangs_on_strawberry: exception catched\n", 'croak from inside a C++ exception delivered';
}

View File

@ -40,6 +40,8 @@
double min_object_distance();
%name{_load} void load(std::string file);
%name{_save} void save(std::string file);
std::vector<std::string> read_cli(std::vector<std::string> _argv)
%code{% THIS->read_cli(_argv, &RETVAL); %};
};
%name{Slic3r::Config::Static} class StaticPrintConfig {

Some files were not shown because too many files have changed in this diff Show More