2026-03-11_4
This commit is contained in:
@@ -0,0 +1,674 @@
|
||||
After-Creation-Menu-Template GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<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 General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,62 @@
|
||||
'''
|
||||
Copyright (C) 2020 Manuel Rais
|
||||
manu@g-lul.com
|
||||
|
||||
Created by Manuel Rais and Christophe Seux
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
if "bpy" in locals():
|
||||
import importlib
|
||||
importlib.reload(operators)
|
||||
importlib.reload(props)
|
||||
importlib.reload(panels)
|
||||
importlib.reload(prefs)
|
||||
importlib.reload(menus)
|
||||
|
||||
else:
|
||||
import bpy
|
||||
from . import operators
|
||||
from . import props
|
||||
from . import panels
|
||||
from . import prefs
|
||||
from . import menus
|
||||
|
||||
|
||||
def get_user_preferences(context):
|
||||
if hasattr(context, "user_preferences"):
|
||||
return context.user_preferences
|
||||
return context.preferences
|
||||
|
||||
|
||||
def register():
|
||||
operators.register()
|
||||
props.register()
|
||||
menus.register()
|
||||
prefs.register()
|
||||
|
||||
# Apply preferences of the panel location.
|
||||
context = bpy.context
|
||||
pref = get_user_preferences(context).addons[__package__].preferences
|
||||
prefs.BoneWidget_preferences.panel_category_update_fn(pref, context)
|
||||
panels.register()
|
||||
|
||||
|
||||
def unregister():
|
||||
operators.unregister()
|
||||
props.unregister()
|
||||
menus.unregister()
|
||||
prefs.unregister()
|
||||
panels.unregister()
|
||||
@@ -0,0 +1,34 @@
|
||||
schema_version = "1.0.0"
|
||||
|
||||
id = "bone_widget"
|
||||
version = "2.3.3"
|
||||
name = "Bone Widget"
|
||||
tagline = "Easily Create Bone Widgets"
|
||||
maintainer = "Wayne Dixon <waylowinternet@gmail.com>"
|
||||
|
||||
type = "add-on"
|
||||
|
||||
website = "https://github.com/waylow/boneWidget"
|
||||
|
||||
tags = ["Rigging"]
|
||||
|
||||
blender_version_min = "4.2.0"
|
||||
|
||||
license = [
|
||||
"SPDX:GPL-3.0-or-later",
|
||||
]
|
||||
|
||||
[permissions]
|
||||
files = "Import/export json and image files from/to disk"
|
||||
|
||||
[build]
|
||||
paths_exclude_pattern = [
|
||||
"/.git/",
|
||||
"__pycache__/",
|
||||
"images/",
|
||||
".*",
|
||||
"*.blend",
|
||||
"*.blend[0123456789]",
|
||||
"*.md",
|
||||
"*.zip",
|
||||
]
|
||||
@@ -0,0 +1,168 @@
|
||||
from .props import ImportColorSet
|
||||
|
||||
|
||||
class BoneWidgetImportData:
|
||||
"""
|
||||
Tracks import status for BoneWidgets, including successes, failures, and duplicates.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.new_imported_items: int = 0 # Count of new successfully imported items
|
||||
self.total_num_imports: int = 0 # Total number of attempted imports
|
||||
self.failed_imports: list[Widget | ColorSet] = []
|
||||
self.skipped_imports: list[Widget | ColorSet] = []
|
||||
self.imported_items: list[Widget | ColorSet] = []
|
||||
self.duplicate_imports: list[Widget | ColorSet] = []
|
||||
self.import_type: str | None = None # Type of import operation (None if undefined)
|
||||
self.json_import_error: bool = False # Flag for JSON parsing errors
|
||||
|
||||
def imported(self) -> int:
|
||||
"""Returns the number of newly imported items or total imported items."""
|
||||
return self.new_imported_items or len(self.imported_items)
|
||||
|
||||
def skipped(self) -> int:
|
||||
"""Returns the number of skipped imports."""
|
||||
return len(self.skipped_imports)
|
||||
|
||||
def failed(self) -> int:
|
||||
"""Returns the number of failed imports."""
|
||||
return len(self.failed_imports)
|
||||
|
||||
def total(self) -> int:
|
||||
"""Returns the total number of attempted imports."""
|
||||
return self.total_num_imports
|
||||
|
||||
def reset_imports(self) -> None:
|
||||
"""Resets import tracking data, clearing skipped, imported, and duplicate items."""
|
||||
self.skipped_imports = []
|
||||
self.imported_items = {}
|
||||
self.duplicate_imports = {}
|
||||
|
||||
|
||||
class Widget:
|
||||
def __init__(self, name: str, widget_dict: dict):
|
||||
self._name: str = name if name else "Unnamed Widget"
|
||||
self._vertices: list[list[float]] = widget_dict.get("vertices", [[]]) # Ensure list structure
|
||||
self._edges: list[list[int]] = widget_dict.get("edges", [[]])
|
||||
self._faces: list[list[int]] = widget_dict.get("faces", [[]])
|
||||
self._image: str = widget_dict.get("image", "") or "user_defined.png"
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Returns the widget name."""
|
||||
return self._name
|
||||
|
||||
@name.setter
|
||||
def name(self, new_name: str) -> None:
|
||||
self._name = new_name
|
||||
|
||||
@property
|
||||
def vertices(self) -> list[list[float]]:
|
||||
"""Returns the list of vertices."""
|
||||
return self._vertices
|
||||
|
||||
@property
|
||||
def edges(self) -> list[list[int]]:
|
||||
"""Returns the list of edges."""
|
||||
return self._edges
|
||||
|
||||
@property
|
||||
def faces(self) -> list[list[int]]:
|
||||
"""Returns the list of faces."""
|
||||
return self._faces
|
||||
|
||||
@property
|
||||
def image(self) -> str:
|
||||
"""Returns the image filename."""
|
||||
return self._image
|
||||
|
||||
def __repr__(self):
|
||||
return f"Widget({self.name})"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if not isinstance(other, Widget):
|
||||
return False
|
||||
return (
|
||||
self.vertices == other.vertices and
|
||||
self.edges == other.edges and
|
||||
self.faces == other.faces and
|
||||
self.image == other.image
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, dict[str, list | str]]:
|
||||
"""
|
||||
Returns a dictionary with the widget's name as the key,
|
||||
and its attributes as the value. Matches the structure of the
|
||||
original widgets collection.
|
||||
"""
|
||||
return {
|
||||
self.name: {
|
||||
"vertices": self.vertices,
|
||||
"edges": self.edges,
|
||||
"faces": self.faces,
|
||||
"image": self.image
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class ColorSet:
|
||||
def __init__(self, color_dict: dict[str, list[float]]):
|
||||
self._name: str = color_dict.get("name", "Unnamed ColorSet")
|
||||
self._normal: list[float] = color_dict.get("normal", [])
|
||||
self._select: list[float] = color_dict.get("select", [])
|
||||
self._active: list[float] = color_dict.get("active", [])
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Returns the color set name."""
|
||||
return self._name
|
||||
|
||||
@name.setter
|
||||
def name(self, new_name: str) -> None:
|
||||
"""Sets a new color set name."""
|
||||
self._name = new_name
|
||||
|
||||
@property
|
||||
def normal(self) -> list[float]:
|
||||
"""Returns the normal color values."""
|
||||
return self._normal
|
||||
|
||||
@property
|
||||
def select(self) -> list[float]:
|
||||
"""Returns the select color values."""
|
||||
return self._select
|
||||
|
||||
@property
|
||||
def active(self) -> list[float]:
|
||||
"""Returns the active color values."""
|
||||
return self._active
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ColorSet({self.name})"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if not isinstance(other, ColorSet):
|
||||
return False
|
||||
return (
|
||||
self.normal == other.normal and
|
||||
self.select == other.select and
|
||||
self.active == other.active
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_pg(cls, pg: ImportColorSet) -> "ColorSet":
|
||||
"""
|
||||
Creates a ColorSet instance from a Blender PropertyGroup -> ImportColorSet.
|
||||
|
||||
Args:
|
||||
pg (ImportColorSet): The PropertyGroup holding color data.
|
||||
|
||||
Returns:
|
||||
ColorSet: A new instance based on the property group.
|
||||
"""
|
||||
return cls({
|
||||
"name": pg.name,
|
||||
"normal": list(pg.normal),
|
||||
"select": list(pg.select),
|
||||
"active": list(pg.active)
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,647 @@
|
||||
import bpy
|
||||
import os
|
||||
import json
|
||||
import numpy
|
||||
import re
|
||||
from .main_functions import get_preferences
|
||||
from ..classes import BoneWidgetImportData, Widget, ColorSet
|
||||
from .. import __package__
|
||||
|
||||
JSON_DEFAULT_WIDGETS = "widgets.json"
|
||||
JSON_USER_WIDGETS = "user_widgets.json"
|
||||
JSON_COLOR_PRESETS = "custom_color_sets.json"
|
||||
|
||||
widget_data = {}
|
||||
|
||||
|
||||
def get_addon_dir():
|
||||
return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
|
||||
def get_custom_dir():
|
||||
pref = get_preferences(bpy.context)
|
||||
if pref.use_default_location:
|
||||
return bpy.utils.extension_path_user(
|
||||
package=__package__, path="bone_widget_custom_data", create=True
|
||||
)
|
||||
else:
|
||||
return pref.user_data_location
|
||||
|
||||
|
||||
def get_default_image_dir(image_folder):
|
||||
return os.path.abspath(os.path.join(get_addon_dir(), image_folder))
|
||||
|
||||
|
||||
def get_custom_image_dir(image_folder):
|
||||
return os.path.abspath(os.path.join(get_custom_dir(), image_folder))
|
||||
|
||||
|
||||
def get_custom_color_preset_dir():
|
||||
return os.path.abspath(os.path.join(get_custom_dir(), JSON_COLOR_PRESETS))
|
||||
|
||||
|
||||
def get_widget_directory(file):
|
||||
if file == JSON_DEFAULT_WIDGETS:
|
||||
return os.path.join(get_addon_dir(), file)
|
||||
elif file == JSON_USER_WIDGETS:
|
||||
return os.path.join(get_custom_dir(), file)
|
||||
|
||||
|
||||
def validate_json_data(data: dict, required_keys: tuple, can_be_empty: bool = True) -> bool:
|
||||
required_keys = set(required_keys)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
|
||||
# Check if all required keys are present
|
||||
if not required_keys.issubset(data.keys()):
|
||||
return False
|
||||
|
||||
if not can_be_empty:
|
||||
# Check if values are not empty
|
||||
if any(not data[key] for key in required_keys):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def update_preview_collection():
|
||||
from .functions.preview_functions import create_preview_collection
|
||||
create_preview_collection()
|
||||
|
||||
|
||||
def objectDataToDico(object, custom_image):
|
||||
verts = []
|
||||
depsgraph = bpy.context.evaluated_depsgraph_get()
|
||||
mesh = object.evaluated_get(depsgraph).to_mesh()
|
||||
|
||||
for v in mesh.vertices:
|
||||
verts.append(tuple(numpy.array(tuple(v.co)) *
|
||||
(object.scale[0], object.scale[1], object.scale[2])))
|
||||
|
||||
polygons = []
|
||||
for p in mesh.polygons:
|
||||
polygons.append(tuple(p.vertices))
|
||||
|
||||
edges = []
|
||||
for e in mesh.edges:
|
||||
edges.append(e.key)
|
||||
|
||||
custom_image = custom_image if custom_image != "" else "user_defined.png"
|
||||
|
||||
wgts = {"vertices": verts, "edges": edges,
|
||||
"faces": polygons, "image": custom_image}
|
||||
|
||||
return (wgts)
|
||||
|
||||
|
||||
def read_widgets(filename=""):
|
||||
global widget_data
|
||||
wgts = {}
|
||||
|
||||
if not filename:
|
||||
files = [JSON_DEFAULT_WIDGETS, JSON_USER_WIDGETS]
|
||||
else:
|
||||
files = [filename]
|
||||
|
||||
for file in files:
|
||||
jsonFile = get_widget_directory(file)
|
||||
if os.path.exists(jsonFile):
|
||||
f = open(jsonFile, 'r')
|
||||
wgts.update(json.load(f))
|
||||
f.close()
|
||||
|
||||
if not filename: # if both files have been read
|
||||
widget_data = wgts.copy()
|
||||
|
||||
return (wgts)
|
||||
|
||||
|
||||
def get_widget_data(widget):
|
||||
return widget_data[widget]
|
||||
|
||||
|
||||
def write_widgets(wgts, file):
|
||||
jsonFile = get_widget_directory(file)
|
||||
# if os.path.exists(jsonFile):
|
||||
f = open(jsonFile, 'w')
|
||||
f.write(json.dumps(wgts))
|
||||
f.close()
|
||||
|
||||
|
||||
def add_remove_widgets(context, addOrRemove, items, widgets, widget_name="", custom_image=""):
|
||||
wgts = {}
|
||||
|
||||
# file from where the widget should be read or written to
|
||||
file = JSON_USER_WIDGETS
|
||||
|
||||
widget_items = []
|
||||
for widget_item in items:
|
||||
widget_items.append(widget_item[1])
|
||||
|
||||
activeShape = None
|
||||
ob_name = None
|
||||
return_message = ""
|
||||
if addOrRemove == 'add':
|
||||
wgts = read_widgets(file)
|
||||
bw_widget_prefix = get_preferences(context).widget_prefix
|
||||
for ob in widgets:
|
||||
if not widget_name:
|
||||
if ob.name.startswith(bw_widget_prefix):
|
||||
ob_name = ob.name[len(bw_widget_prefix):]
|
||||
else:
|
||||
ob_name = ob.name
|
||||
else:
|
||||
ob_name = widget_name
|
||||
|
||||
if (ob_name) not in widget_items:
|
||||
widget_items.append(ob_name)
|
||||
wgts[ob_name] = objectDataToDico(ob, custom_image)
|
||||
activeShape = ob_name
|
||||
return_message = "Widget - " + ob_name + " has been added!"
|
||||
|
||||
elif addOrRemove == 'remove':
|
||||
user_widgets = read_widgets(file)
|
||||
if widgets in user_widgets:
|
||||
wgts = user_widgets
|
||||
else:
|
||||
file = JSON_DEFAULT_WIDGETS
|
||||
wgts = read_widgets(file)
|
||||
|
||||
del wgts[widgets]
|
||||
if widgets in widget_items:
|
||||
widget_index = widget_items.index(widgets)
|
||||
activeShape = widget_items[widget_index +
|
||||
1] if widget_index == 0 else widget_items[widget_index - 1]
|
||||
widget_items.remove(widgets)
|
||||
return_message = "Widget - " + widgets + " has been removed!"
|
||||
|
||||
if activeShape is not None:
|
||||
|
||||
write_widgets(wgts, file)
|
||||
|
||||
# update the preview panel
|
||||
update_preview_collection()
|
||||
|
||||
# trigger an update and display widget
|
||||
bpy.context.window_manager.widget_list = activeShape
|
||||
|
||||
return 'INFO', return_message
|
||||
elif ob_name is not None:
|
||||
return 'WARNING', "Widget - " + ob_name + " already exists!"
|
||||
|
||||
|
||||
def export_widget_library(filepath):
|
||||
wgts = read_widgets(JSON_USER_WIDGETS)
|
||||
|
||||
if wgts:
|
||||
# variables needed for exporting widgets
|
||||
dest_dir = os.path.dirname(filepath)
|
||||
json_dir = get_custom_dir()
|
||||
image_folder = 'custom_thumbnails'
|
||||
custom_image_dir = get_custom_image_dir(image_folder)
|
||||
|
||||
filename = os.path.basename(filepath)
|
||||
if not filename:
|
||||
filename = "widget_library.zip"
|
||||
elif not filename.endswith('.zip'):
|
||||
filename += ".zip"
|
||||
|
||||
# start the zipping process
|
||||
try:
|
||||
from zipfile import ZipFile
|
||||
with ZipFile(os.path.join(dest_dir, filename), "w") as zip:
|
||||
# write the json file
|
||||
file = os.path.join(json_dir, JSON_USER_WIDGETS)
|
||||
arcname = os.path.basename(file)
|
||||
zip.write(file, arcname=arcname)
|
||||
|
||||
# write the custom images if present
|
||||
if os.path.exists(custom_image_dir):
|
||||
from pathlib import Path
|
||||
for filepath in Path(custom_image_dir).iterdir():
|
||||
arcname = os.path.join(
|
||||
image_folder, os.path.basename(filepath))
|
||||
zip.write(filepath, arcname=arcname)
|
||||
except Exception as e:
|
||||
print("Error exporting widget library: ", e)
|
||||
return 0
|
||||
|
||||
return len(wgts)
|
||||
|
||||
|
||||
def import_widget_library(filepath, action=""):
|
||||
required_data_keys = ("vertices", "faces", "edges", "image") # json data
|
||||
wgts = {}
|
||||
|
||||
from zipfile import ZipFile
|
||||
# dest_dir = os.path.abspath(os.path.join(get_addon_dir(), '..'))
|
||||
dest_dir = bpy.app.tempdir
|
||||
|
||||
widget_import = BoneWidgetImportData()
|
||||
|
||||
widget_import.import_type = "widget"
|
||||
|
||||
if os.path.exists(filepath) and action:
|
||||
try:
|
||||
|
||||
with ZipFile(filepath, 'r') as zip_file:
|
||||
# extract images
|
||||
for file in zip_file.namelist():
|
||||
if file.startswith('custom_thumbnails/'):
|
||||
zip_file.extract(file, dest_dir)
|
||||
elif file.endswith('.json'): # extract data from the .json file
|
||||
f = zip_file.read(file)
|
||||
json_data = f.decode('utf8').replace("'", '"')
|
||||
wgts = json.loads(json_data)
|
||||
|
||||
# validate wgts data type
|
||||
if not isinstance(wgts, dict):
|
||||
raise TypeError(
|
||||
f"Expected a dictionary, but got {type(wgts).__name__}")
|
||||
|
||||
current_wgts = read_widgets(JSON_USER_WIDGETS)
|
||||
|
||||
# check for duplicate names
|
||||
for name, data in sorted(wgts.items()): # sorting by keys
|
||||
widget_import.total_num_imports += 1
|
||||
# validate json data
|
||||
if not validate_json_data(data, required_data_keys):
|
||||
widget_import.failed_imports.append(Widget(name, data))
|
||||
continue
|
||||
|
||||
if action == "ASK":
|
||||
widget_import.skipped_imports.append(Widget(name, data))
|
||||
elif action == "OVERWRITE":
|
||||
widget_import.imported_items.append(Widget(name, data))
|
||||
elif action == "SKIP":
|
||||
# check for duplicates
|
||||
data_match = data == current_wgts[name]
|
||||
if data_match:
|
||||
widget_import.skipped_imports.append(
|
||||
Widget(name, data))
|
||||
# widget_import.duplicate_imports.update({name : data})
|
||||
elif name not in current_wgts:
|
||||
widget_import.imported_items.append(Widget(name, data))
|
||||
else:
|
||||
widget_import.skipped_imports.append(
|
||||
Widget(name, data))
|
||||
else:
|
||||
widget_import.failed_imports.append(Widget(name, data))
|
||||
|
||||
except TypeError as e: # Handle data type errors specifically
|
||||
print(f"Error while importing widget library: {e}")
|
||||
widget_import.json_import_error = True
|
||||
except Exception as e:
|
||||
print(f"Error while importing widget library: {e}")
|
||||
for name, data in wgts.items():
|
||||
widget_import.failed_imports.append(Widget(name, data))
|
||||
widget_import.total_num_imports = widget_import.failed()
|
||||
return widget_import
|
||||
|
||||
|
||||
def update_widget_library(new_widgets: dict[str, dict[str, list | str]],
|
||||
new_images: set[str], zip_filepath: str) -> None:
|
||||
# store the currently selected widget
|
||||
current_widget = bpy.context.window_manager.widget_list
|
||||
|
||||
wgts = read_widgets(JSON_USER_WIDGETS)
|
||||
wgts.update(new_widgets)
|
||||
|
||||
write_widgets(wgts, JSON_USER_WIDGETS)
|
||||
|
||||
# extract any images needed from zip library
|
||||
if new_images:
|
||||
from zipfile import ZipFile
|
||||
dest_dir = get_custom_dir()
|
||||
if os.path.exists(zip_filepath):
|
||||
try:
|
||||
with ZipFile(zip_filepath, 'r') as zip_file:
|
||||
for file in zip_file.namelist():
|
||||
if file.startswith('custom_thumbnails/') and file.split("/")[1] in new_images:
|
||||
zip_file.extract(file, dest_dir)
|
||||
except Exception as e:
|
||||
print("Failed to extract custom images: ", e)
|
||||
else:
|
||||
print("zip file path doesn't exist!! - ", zip_filepath)
|
||||
|
||||
# update the preview panel
|
||||
update_preview_collection()
|
||||
|
||||
# trigger an update and display original but updated widget
|
||||
bpy.context.window_manager.widget_list = current_widget
|
||||
|
||||
|
||||
def update_custom_image(image_name):
|
||||
current_widget = bpy.context.window_manager.widget_list
|
||||
current_widget_data = get_widget_data(current_widget)
|
||||
|
||||
# swap out the image
|
||||
current_widget_data['image'] = image_name
|
||||
|
||||
# update and write the new data
|
||||
wgts = read_widgets(JSON_USER_WIDGETS)
|
||||
if current_widget in wgts:
|
||||
wgts[current_widget] = current_widget_data
|
||||
write_widgets(wgts, JSON_USER_WIDGETS)
|
||||
else:
|
||||
wgts = read_widgets(JSON_DEFAULT_WIDGETS)
|
||||
wgts[current_widget] = current_widget_data
|
||||
write_widgets(wgts, JSON_DEFAULT_WIDGETS)
|
||||
|
||||
# update the preview panel
|
||||
update_preview_collection()
|
||||
|
||||
# trigger an update and display original but updated widget
|
||||
bpy.context.window_manager.widget_list = current_widget
|
||||
|
||||
|
||||
def reset_default_images():
|
||||
current_widget = bpy.context.window_manager.widget_list
|
||||
wgts = read_widgets(JSON_DEFAULT_WIDGETS)
|
||||
|
||||
for name, data in wgts.items():
|
||||
image = f"{name}.png"
|
||||
data["image"] = image
|
||||
|
||||
write_widgets(wgts, JSON_DEFAULT_WIDGETS)
|
||||
|
||||
# update the preview panel
|
||||
update_preview_collection()
|
||||
|
||||
# trigger an update and display original but updated widget
|
||||
bpy.context.window_manager.widget_list = current_widget
|
||||
|
||||
|
||||
################ COLOR PRESETS ################
|
||||
|
||||
def read_color_presets():
|
||||
presets = {}
|
||||
|
||||
# Read the JSON file
|
||||
json_file = get_custom_color_preset_dir()
|
||||
if os.path.exists(json_file):
|
||||
with open(json_file, "r") as file:
|
||||
presets = json.load(file)
|
||||
|
||||
presets = {item["name"]: item for item in presets} # convert to dictionary
|
||||
|
||||
return presets
|
||||
|
||||
|
||||
def update_color_presets(new_presets, zip_filepath):
|
||||
for preset in new_presets:
|
||||
add_color_set(bpy.context, preset)
|
||||
|
||||
# extract any images needed from zip library
|
||||
# if new_images:
|
||||
# from zipfile import ZipFile
|
||||
# dest_dir = os.path.abspath(os.path.join(get_addon_dir(), '..'))
|
||||
# if os.path.exists(zip_filepath):
|
||||
# try:
|
||||
# with ZipFile(zip_filepath, 'r') as zip_file:
|
||||
# for file in zip_file.namelist():
|
||||
# if file.startswith('custom_thumbnails/') and file.split("/")[1] in new_images:
|
||||
# zip_file.extract(file, dest_dir)
|
||||
# except:
|
||||
# pass
|
||||
|
||||
|
||||
def import_color_presets(filepath, action=""):
|
||||
required_data_keys = ("name", "normal", "select", "active") # json data
|
||||
presets = None
|
||||
|
||||
from zipfile import ZipFile
|
||||
dest_dir = get_custom_dir()
|
||||
|
||||
presets_import = BoneWidgetImportData()
|
||||
|
||||
presets_import.import_type = "colorset"
|
||||
|
||||
if os.path.exists(filepath) and action:
|
||||
try:
|
||||
with ZipFile(filepath, 'r') as zip_file:
|
||||
# extract images
|
||||
for file in zip_file.namelist():
|
||||
# if file.startswith('preset_thumbnails/'):
|
||||
# zip_file.extract(file, dest_dir)
|
||||
if file.endswith('.json'): # extract data from the .json file
|
||||
f = zip_file.read(file)
|
||||
json_data = f.decode('utf8').replace("'", '"')
|
||||
presets = json.loads(json_data)
|
||||
|
||||
# validate presets data type
|
||||
if not isinstance(presets, list):
|
||||
raise TypeError(
|
||||
f"Expected a list, but got {type(presets).__name__}")
|
||||
|
||||
current_presets = read_color_presets()
|
||||
|
||||
# check for duplicate presets
|
||||
for preset in presets:
|
||||
presets_import.total_num_imports += 1
|
||||
|
||||
# validate json data
|
||||
if not validate_json_data(preset, required_data_keys, False):
|
||||
presets_import.failed_imports.append(ColorSet(preset))
|
||||
continue
|
||||
|
||||
name = preset['name']
|
||||
if action == "ASK":
|
||||
presets_import.skipped_imports.append(ColorSet(preset))
|
||||
elif action == "OVERWRITE":
|
||||
presets_import.imported_items.append(ColorSet(preset))
|
||||
elif action == "SKIP":
|
||||
# name and colors match or just colors match
|
||||
if colors_match(preset, current_presets[name]):
|
||||
presets_import.skipped_imports.append(ColorSet(preset))
|
||||
elif not name in current_presets:
|
||||
presets_import.imported_items.append(ColorSet(preset))
|
||||
else:
|
||||
presets_import.skipped_imports.append(ColorSet(preset))
|
||||
else:
|
||||
presets_import.failed_imports.append(ColorSet(preset))
|
||||
|
||||
except TypeError as e: # Handle data type errors specifically
|
||||
print(f"Error while importing color presets: {e}")
|
||||
presets_import.json_import_error = True
|
||||
except Exception as e:
|
||||
print(f"Error while importing color presets: {e}")
|
||||
for preset in presets:
|
||||
presets_import.failed_imports.append(ColorSet(preset))
|
||||
presets_import.total_num_imports = presets_import.failed()
|
||||
return presets_import
|
||||
|
||||
|
||||
def colors_match(set1, set2):
|
||||
if isinstance(set1, dict):
|
||||
return set1['normal'] == set2['normal'] \
|
||||
and set1['select'] == set2['select'] \
|
||||
and set1['active'] == set2['active']
|
||||
elif isinstance(set1, bpy.types.ThemeBoneColorSet):
|
||||
return set1.normal == set2.normal \
|
||||
and set1.select == set2.select \
|
||||
and set1.active == set2.active
|
||||
|
||||
|
||||
def scan_armature_color_presets(context, armature):
|
||||
found_color_sets = set()
|
||||
|
||||
colorsets_import = BoneWidgetImportData()
|
||||
colorsets_import.import_type = "colorset"
|
||||
|
||||
current_color_sets = context.window_manager.custom_color_presets
|
||||
|
||||
# edit bones
|
||||
for bone in armature.bones:
|
||||
if bone.color.is_custom:
|
||||
is_unique_colorset = True
|
||||
for color_set in current_color_sets:
|
||||
if colors_match(bone.color.custom, color_set):
|
||||
is_unique_colorset = False # not unique
|
||||
break
|
||||
|
||||
color_data = (tuple(bone.color.custom.normal), tuple(
|
||||
bone.color.custom.select), tuple(bone.color.custom.active))
|
||||
if is_unique_colorset and not color_data in found_color_sets:
|
||||
color_set = {attr: list(getattr(bone.color.custom, attr)[:3]) for attr in [
|
||||
"normal", "active", "select"]}
|
||||
color_set['name'] = bone.name
|
||||
colorsets_import.skipped_imports.append(ColorSet(color_set))
|
||||
found_color_sets.add(color_data)
|
||||
|
||||
# pose bones
|
||||
pose_bone = context.object.pose.bones.get(bone.name)
|
||||
if pose_bone.color.is_custom:
|
||||
is_unique_colorset = True
|
||||
for color_set in current_color_sets:
|
||||
if colors_match(pose_bone.color.custom, color_set):
|
||||
is_unique_colorset = False # not unique
|
||||
break
|
||||
|
||||
color_data = (tuple(pose_bone.color.custom.normal), tuple(
|
||||
pose_bone.color.custom.select), tuple(pose_bone.color.custom.active))
|
||||
if is_unique_colorset and not color_data in found_color_sets:
|
||||
color_set = {attr: list(getattr(pose_bone.color.custom, attr)[
|
||||
:3]) for attr in ["normal", "active", "select"]}
|
||||
color_set['name'] = bone.name
|
||||
colorsets_import.skipped_imports.append(ColorSet(color_set))
|
||||
found_color_sets.add(color_data)
|
||||
|
||||
return colorsets_import
|
||||
|
||||
|
||||
def export_color_presets(filepath, context):
|
||||
color_presets = len(context.window_manager.custom_color_presets)
|
||||
|
||||
if color_presets:
|
||||
dest_dir = os.path.dirname(filepath)
|
||||
json_dir = get_custom_dir()
|
||||
# image_folder = 'preset_thumbnails'
|
||||
# custom_image_dir = get_custom_image_dir(image_folder)
|
||||
|
||||
filename = os.path.basename(filepath)
|
||||
if not filename:
|
||||
filename = "color_presets.zip"
|
||||
elif not filename.endswith('.zip'):
|
||||
filename += ".zip"
|
||||
|
||||
# start the zipping process
|
||||
try:
|
||||
from zipfile import ZipFile
|
||||
with ZipFile(os.path.join(dest_dir, filename), "w") as zip:
|
||||
# write the json file
|
||||
file = os.path.join(json_dir, JSON_COLOR_PRESETS)
|
||||
arcname = os.path.basename(file)
|
||||
zip.write(file, arcname=arcname)
|
||||
except Exception as e:
|
||||
print("Error exporting color presets: ", e)
|
||||
return 0
|
||||
|
||||
return color_presets
|
||||
|
||||
|
||||
def add_color_set_from_bone(context, bone, suffix_name):
|
||||
new_item = context.window_manager.custom_color_presets.add()
|
||||
|
||||
color_set = bone.color.custom
|
||||
|
||||
new_name = bone.name + suffix_name # CHANGE LATER
|
||||
|
||||
# check if the name already ends with an incremented number
|
||||
match = re.match(r"^(.*)\.(\d{3})$", new_name)
|
||||
count = int(match.group(2)) if match else 1
|
||||
base_name = match.group(1) if match else new_name
|
||||
|
||||
while any(item.name == new_name for item in context.window_manager.custom_color_presets):
|
||||
new_name = f"{base_name}.{count:03d}"
|
||||
count += 1
|
||||
|
||||
new_item.name = new_name
|
||||
|
||||
if not color_set: # new default color set
|
||||
new_item.normal = (1.0, 0.0, 0.0)
|
||||
new_item.select = (0.0, 1.0, 0.0)
|
||||
new_item.active = (0.0, 0.0, 1.0)
|
||||
else:
|
||||
new_item.normal = color_set.normal
|
||||
new_item.select = color_set.select
|
||||
new_item.active = color_set.active
|
||||
|
||||
|
||||
def add_color_set(context, color_set=None):
|
||||
new_item = context.window_manager.custom_color_presets.add()
|
||||
|
||||
base_name = "Color Set" if not color_set else color_set.name
|
||||
new_name = base_name
|
||||
|
||||
# check if the name already ends with an incremented number
|
||||
match = re.match(r"^(.*)\.(\d{3})$", base_name)
|
||||
count = int(match.group(2)) if match else 1
|
||||
base_name = match.group(1) if match else new_name
|
||||
|
||||
while any(item.name == new_name for item in context.window_manager.custom_color_presets):
|
||||
new_name = f"{base_name}.{count:03d}"
|
||||
count += 1
|
||||
|
||||
new_item.name = new_name
|
||||
|
||||
if not color_set: # new default color set
|
||||
new_item.normal = (1.0, 0.0, 0.0)
|
||||
new_item.select = (0.0, 1.0, 0.0)
|
||||
new_item.active = (0.0, 0.0, 1.0)
|
||||
else:
|
||||
new_item.normal = color_set.normal
|
||||
new_item.select = color_set.select
|
||||
new_item.active = color_set.active
|
||||
|
||||
|
||||
def save_color_sets(context):
|
||||
if not bpy.context.window_manager.turn_off_colorset_save:
|
||||
bpy.context.window_manager.turn_off_colorset_save = True
|
||||
color_sets = [{
|
||||
"name": item.name,
|
||||
"normal": list(item.normal),
|
||||
"select": list(item.select),
|
||||
"active": list(item.active)
|
||||
} for item in context.window_manager.custom_color_presets]
|
||||
|
||||
filepath = get_custom_color_preset_dir()
|
||||
with open(filepath, 'w') as f:
|
||||
json.dump(color_sets, f, indent=4)
|
||||
bpy.context.window_manager.turn_off_colorset_save = False
|
||||
|
||||
|
||||
def load_color_presets():
|
||||
filepath = get_custom_color_preset_dir()
|
||||
if os.path.exists(filepath):
|
||||
with open(filepath, 'r') as f:
|
||||
color_sets = json.load(f)
|
||||
bpy.context.window_manager.custom_color_presets.clear()
|
||||
bpy.context.window_manager.turn_off_colorset_save = True
|
||||
for item in color_sets:
|
||||
new_item = bpy.context.window_manager.custom_color_presets.add()
|
||||
new_item.name = item["name"]
|
||||
new_item.normal = item["normal"]
|
||||
new_item.select = item["select"]
|
||||
new_item.active = item["active"]
|
||||
bpy.context.window_manager.turn_off_colorset_save = False
|
||||
@@ -0,0 +1,614 @@
|
||||
import bpy
|
||||
import numpy
|
||||
from mathutils import Matrix, Vector
|
||||
from .. import __package__
|
||||
|
||||
|
||||
def get_collection(context):
|
||||
# check user preferences for the name of the collection
|
||||
if not get_preferences(context).use_rigify_defaults:
|
||||
bw_collection_name = get_preferences(
|
||||
context).bonewidget_collection_name
|
||||
else:
|
||||
bw_collection_name = "WGTS_" + context.active_object.name
|
||||
|
||||
collection = recursive_layer_collection(
|
||||
context.scene.collection, bw_collection_name)
|
||||
if collection: # if it already exists
|
||||
return collection
|
||||
|
||||
collection = bpy.data.collections.get(bw_collection_name)
|
||||
|
||||
if collection: # if it exists but not linked to scene
|
||||
context.scene.collection.children.link(collection)
|
||||
return collection
|
||||
|
||||
else: # create a new collection
|
||||
collection = bpy.data.collections.new(bw_collection_name)
|
||||
context.scene.collection.children.link(collection)
|
||||
# hide new collection
|
||||
viewlayer_collection = context.view_layer.layer_collection.children[collection.name]
|
||||
viewlayer_collection.hide_viewport = True
|
||||
return collection
|
||||
|
||||
|
||||
def recursive_layer_collection(layer_collection, collection_name):
|
||||
found = None
|
||||
if (layer_collection.name == collection_name):
|
||||
return layer_collection
|
||||
for layer in layer_collection.children:
|
||||
found = recursive_layer_collection(layer, collection_name)
|
||||
if found:
|
||||
return found
|
||||
|
||||
|
||||
def get_view_layer_collection(context, widget=None):
|
||||
widget_collection = bpy.data.collections[bpy.data.objects[widget.name].users_collection[0].name]
|
||||
# save current active layer_collection
|
||||
saved_layer_collection = bpy.context.view_layer.layer_collection
|
||||
# actually find the view_layer we want
|
||||
layer_collection = recursive_layer_collection(
|
||||
saved_layer_collection, widget_collection.name)
|
||||
# make sure the collection (data level) is not hidden
|
||||
widget_collection.hide_viewport = False
|
||||
|
||||
# change the active view layer
|
||||
bpy.context.view_layer.active_layer_collection = layer_collection
|
||||
# make sure it isn't excluded so it can be edited
|
||||
layer_collection.exclude = False
|
||||
# return the active view layer to what it was
|
||||
bpy.context.view_layer.active_layer_collection = saved_layer_collection
|
||||
|
||||
return layer_collection
|
||||
|
||||
|
||||
def match_bone_matrix(widget, match_bone):
|
||||
if widget == None:
|
||||
return
|
||||
widget.matrix_local = match_bone.bone.matrix_local
|
||||
widget.matrix_world = match_bone.id_data.matrix_world @ match_bone.bone.matrix_local
|
||||
if match_bone.custom_shape_transform:
|
||||
# if it has a transform override, apply this to the widget loc and rot
|
||||
org_scale = widget.matrix_world.to_scale()
|
||||
org_scale_mat = Matrix.Scale(1, 4, org_scale)
|
||||
target_matrix = match_bone.custom_shape_transform.id_data.matrix_world @ match_bone.custom_shape_transform.bone.matrix_local
|
||||
loc = target_matrix.to_translation()
|
||||
loc_mat = Matrix.Translation(loc)
|
||||
rot = target_matrix.to_euler().to_matrix()
|
||||
widget.matrix_world = loc_mat @ rot.to_4x4() @ org_scale_mat
|
||||
|
||||
if match_bone.use_custom_shape_bone_size:
|
||||
ob_scale = bpy.context.scene.objects[match_bone.id_data.name].scale
|
||||
widget.scale = [match_bone.bone.length * ob_scale[0],
|
||||
match_bone.bone.length * ob_scale[1], match_bone.bone.length * ob_scale[2]]
|
||||
|
||||
# if the user has added any custom transforms to the bone widget display - calculate this too
|
||||
loc = match_bone.custom_shape_translation
|
||||
rot = match_bone.custom_shape_rotation_euler
|
||||
scale = match_bone.custom_shape_scale_xyz
|
||||
widget.scale *= scale
|
||||
widget.matrix_world = widget.matrix_world @ Matrix.LocRotScale(
|
||||
loc, rot, widget.scale)
|
||||
|
||||
widget.data.update()
|
||||
|
||||
|
||||
def from_widget_find_bone(widget):
|
||||
match_bone = None
|
||||
for ob in bpy.context.scene.objects:
|
||||
if ob.type == "ARMATURE":
|
||||
for bone in ob.pose.bones:
|
||||
if bone.custom_shape == widget:
|
||||
match_bone = bone
|
||||
return match_bone
|
||||
|
||||
|
||||
def create_widget(bone, widget, relative, size, slide, rotation, collection, use_face_data, wireframe_width):
|
||||
if not get_preferences(bpy.context).use_rigify_defaults:
|
||||
bw_widget_prefix = get_preferences(bpy.context).widget_prefix
|
||||
else:
|
||||
bw_widget_prefix = "WGT-" + bpy.context.active_object.name + "_"
|
||||
|
||||
matrix_bone = bone
|
||||
|
||||
# delete the existing shape
|
||||
if bone.custom_shape:
|
||||
bpy.data.objects.remove(
|
||||
bpy.data.objects[bone.custom_shape.name], do_unlink=True)
|
||||
|
||||
# make the data name include the prefix
|
||||
new_data = bpy.data.meshes.new(bw_widget_prefix + bone.name)
|
||||
|
||||
bone.use_custom_shape_bone_size = relative
|
||||
|
||||
# deal with face data
|
||||
faces = widget['faces'] if use_face_data else []
|
||||
|
||||
# add the verts
|
||||
new_data.from_pydata(numpy.array(
|
||||
widget['vertices']) * size, widget['edges'], faces)
|
||||
|
||||
# Create transform matrices (slide vector and rotation)
|
||||
widget_matrix = Matrix()
|
||||
|
||||
# make the slide value always relative to the bone length
|
||||
if not relative: # TODO: shift this to user preference?
|
||||
slide = Vector(slide) # turn slide into a vector
|
||||
slide *= bone.length
|
||||
trans = Matrix.Translation(slide)
|
||||
|
||||
rot = rotation.to_matrix().to_4x4()
|
||||
|
||||
# Translate then rotate the matrix
|
||||
widget_matrix = widget_matrix @ trans
|
||||
widget_matrix = widget_matrix @ rot
|
||||
|
||||
# transform the widget with this matrix
|
||||
new_data.transform(widget_matrix)
|
||||
|
||||
new_data.update(calc_edges=True)
|
||||
|
||||
new_object = bpy.data.objects.new(bw_widget_prefix + bone.name, new_data)
|
||||
|
||||
new_object.data = new_data
|
||||
new_object.name = bw_widget_prefix + bone.name
|
||||
collection.objects.link(new_object)
|
||||
|
||||
new_object.matrix_world = bpy.context.active_object.matrix_world @ matrix_bone.bone.matrix_local
|
||||
new_object.scale = [matrix_bone.bone.length,
|
||||
matrix_bone.bone.length, matrix_bone.bone.length]
|
||||
layer = bpy.context.view_layer
|
||||
layer.update()
|
||||
|
||||
bone.custom_shape = new_object
|
||||
# show faces if use face data is enabled
|
||||
bone.bone.show_wire = not use_face_data
|
||||
|
||||
if bpy.app.version >= (4, 2, 0):
|
||||
bone.custom_shape_wire_width = wireframe_width
|
||||
|
||||
|
||||
def symmetrize_widget(bone, collection):
|
||||
if not get_preferences(bpy.context).use_rigify_defaults:
|
||||
bw_widget_prefix = get_preferences(bpy.context).widget_prefix
|
||||
rigify_object_name = ''
|
||||
else:
|
||||
bw_widget_prefix = "WGT-"
|
||||
rigify_object_name = bpy.context.active_object.name + "_"
|
||||
|
||||
mirror_bone = find_mirror_object(bone)
|
||||
if not mirror_bone:
|
||||
return
|
||||
|
||||
widget = bone.custom_shape
|
||||
if not widget or not widget.data:
|
||||
return
|
||||
|
||||
# clean up existing mirrored widget if it's different
|
||||
mirror_widget = mirror_bone.custom_shape
|
||||
if mirror_widget and mirror_widget != widget:
|
||||
existing = bpy.context.scene.objects.get(mirror_widget.name)
|
||||
if existing:
|
||||
bpy.data.objects.remove(existing)
|
||||
|
||||
# create mirrored mesh data
|
||||
new_data = widget.data.copy()
|
||||
for vert in new_data.vertices:
|
||||
vert.co.x *= -1 # mirror along X-axis
|
||||
|
||||
new_object = widget.copy()
|
||||
new_object.data = new_data
|
||||
new_object.name = bw_widget_prefix + rigify_object_name + mirror_bone.name
|
||||
bpy.data.collections[collection.name].objects.link(new_object)
|
||||
|
||||
# use custom shape transform if available
|
||||
transform_bone = mirror_bone.custom_shape_transform or mirror_bone
|
||||
new_object.matrix_local = transform_bone.bone.matrix_local
|
||||
new_object.scale = [transform_bone.bone.length] * 3
|
||||
new_object.data.flip_normals()
|
||||
|
||||
bpy.context.view_layer.update()
|
||||
|
||||
mirror_bone.custom_shape = new_object
|
||||
mirror_bone.bone.show_wire = bone.bone.show_wire
|
||||
mirror_bone.use_custom_shape_bone_size = bone.use_custom_shape_bone_size
|
||||
|
||||
symmetrize_color = get_preferences(bpy.context).symmetrize_color
|
||||
if bpy.app.version >= (4, 0, 0) and symmetrize_color:
|
||||
# pose bone colors
|
||||
mirror_bone.bone.color.custom.normal = bone.bone.color.custom.normal
|
||||
mirror_bone.bone.color.custom.select = bone.bone.color.custom.select
|
||||
mirror_bone.bone.color.custom.active = bone.bone.color.custom.active
|
||||
mirror_bone.bone.color.palette = bone.bone.color.palette
|
||||
|
||||
# edit bone colors
|
||||
mirror_bone.color.custom.normal = bone.color.custom.normal
|
||||
mirror_bone.color.custom.select = bone.color.custom.select
|
||||
mirror_bone.color.custom.active = bone.color.custom.active
|
||||
mirror_bone.color.palette = bone.color.palette
|
||||
|
||||
if bpy.app.version >= (4, 2, 0):
|
||||
mirror_bone.custom_shape_wire_width = bone.custom_shape_wire_width
|
||||
|
||||
|
||||
def symmetrize_widget_helper(bone, collection, active_object, widgets_and_bones):
|
||||
bw_symmetry_suffix = get_preferences(bpy.context).symmetry_suffix
|
||||
bw_symmetry_suffix = bw_symmetry_suffix.split(";")
|
||||
|
||||
suffix_1 = bw_symmetry_suffix[0].replace(" ", "")
|
||||
suffix_2 = bw_symmetry_suffix[1].replace(" ", "")
|
||||
|
||||
if active_object.name.endswith(suffix_1):
|
||||
if bone.name.endswith(suffix_1) and widgets_and_bones[bone]:
|
||||
symmetrize_widget(bone, collection)
|
||||
elif active_object.name.endswith(suffix_2):
|
||||
if bone.name.endswith(suffix_2) and widgets_and_bones[bone]:
|
||||
symmetrize_widget(bone, collection)
|
||||
|
||||
|
||||
def delete_unused_widgets():
|
||||
if not get_preferences(bpy.context).use_rigify_defaults:
|
||||
bw_collection_name = get_preferences(
|
||||
bpy.context).bonewidget_collection_name
|
||||
else:
|
||||
bw_collection_name = 'WGTS_' + bpy.context.active_object.name
|
||||
|
||||
collection = recursive_layer_collection(
|
||||
bpy.context.scene.collection, bw_collection_name)
|
||||
widget_list = []
|
||||
|
||||
for ob in bpy.data.objects:
|
||||
if ob.type == 'ARMATURE':
|
||||
for bone in ob.pose.bones:
|
||||
if bone.custom_shape:
|
||||
widget_list.append(bone.custom_shape)
|
||||
|
||||
unwanted_list = [
|
||||
ob for ob in collection.all_objects if ob not in widget_list]
|
||||
|
||||
for ob in unwanted_list:
|
||||
bpy.data.objects.remove(bpy.data.objects[ob.name], do_unlink=True)
|
||||
|
||||
return
|
||||
|
||||
|
||||
def edit_widget(active_bone):
|
||||
widget = active_bone.custom_shape
|
||||
|
||||
collection = get_view_layer_collection(bpy.context, widget)
|
||||
collection.hide_viewport = False
|
||||
|
||||
# hide all other objects in collection
|
||||
for obj in collection.collection.all_objects:
|
||||
if obj.name != widget.name:
|
||||
obj.hide_set(True)
|
||||
else:
|
||||
obj.hide_set(False) # in case user manually hid it
|
||||
|
||||
armature = active_bone.id_data
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
bpy.context.active_object.select_set(False)
|
||||
|
||||
if bpy.context.space_data.local_view:
|
||||
bpy.ops.view3d.localview()
|
||||
|
||||
# select object and make it active
|
||||
widget.select_set(True)
|
||||
bpy.context.view_layer.objects.active = widget
|
||||
bpy.ops.object.mode_set(mode='EDIT')
|
||||
bpy.context.tool_settings.mesh_select_mode = (
|
||||
True, False, False) # enter vertex mode
|
||||
|
||||
|
||||
def return_to_armature(widget):
|
||||
bone = from_widget_find_bone(widget)
|
||||
armature = bone.id_data
|
||||
|
||||
if bpy.context.active_object.mode == 'EDIT':
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
|
||||
collection = get_view_layer_collection(bpy.context, widget)
|
||||
collection.hide_viewport = True
|
||||
|
||||
# unhide all objects in the collection
|
||||
for obj in collection.collection.all_objects:
|
||||
obj.hide_set(False)
|
||||
|
||||
if bpy.context.space_data.local_view:
|
||||
bpy.ops.view3d.localview()
|
||||
|
||||
bpy.context.view_layer.objects.active = armature
|
||||
armature.select_set(True)
|
||||
bpy.ops.object.mode_set(mode='POSE')
|
||||
if bpy.app.version < (5, 0, 0):
|
||||
armature.data.bones[bone.name].select = True
|
||||
armature.data.bones.active = armature.data.bones[bone.name]
|
||||
|
||||
|
||||
def find_mirror_object(object):
|
||||
bw_symmetry_suffix = get_preferences(bpy.context).symmetry_suffix
|
||||
bw_symmetry_suffix = bw_symmetry_suffix.split(";")
|
||||
|
||||
suffix_1 = bw_symmetry_suffix[0].replace(" ", "")
|
||||
suffix_2 = bw_symmetry_suffix[1].replace(" ", "")
|
||||
|
||||
if object.name.endswith(suffix_1):
|
||||
suffix = suffix_2
|
||||
suffix_length = len(suffix_1)
|
||||
|
||||
elif object.name.endswith(suffix_2):
|
||||
suffix = suffix_1
|
||||
suffix_length = len(suffix_2)
|
||||
|
||||
elif object.name.endswith(suffix_1.lower()):
|
||||
suffix = suffix_2.lower()
|
||||
suffix_length = len(suffix_1)
|
||||
elif object.name.endswith(suffix_2.lower()):
|
||||
suffix = suffix_1.lower()
|
||||
suffix_length = len(suffix_2)
|
||||
else: # what if the widget ends in .001?
|
||||
print('Object suffix unknown, using blank')
|
||||
suffix = ''
|
||||
|
||||
object_name = list(object.name)
|
||||
object_base_name = object_name[:-suffix_length]
|
||||
mirrored_object_name = "".join(object_base_name) + suffix
|
||||
|
||||
if object.id_data.type == 'ARMATURE':
|
||||
return object.id_data.pose.bones.get(mirrored_object_name)
|
||||
else:
|
||||
return bpy.context.scene.objects.get(mirrored_object_name)
|
||||
|
||||
|
||||
def find_match_bones():
|
||||
bw_symmetry_suffix = get_preferences(bpy.context).symmetry_suffix
|
||||
bw_symmetry_suffix = bw_symmetry_suffix.split(";")
|
||||
|
||||
suffix_1 = bw_symmetry_suffix[0].replace(" ", "")
|
||||
suffix_2 = bw_symmetry_suffix[1].replace(" ", "")
|
||||
|
||||
widgets_and_bones = {}
|
||||
|
||||
if bpy.context.object.type == 'ARMATURE':
|
||||
for bone in bpy.context.selected_pose_bones:
|
||||
if bone.name.endswith(suffix_1) or bone.name.endswith(suffix_2):
|
||||
widgets_and_bones[bone] = bone.custom_shape
|
||||
mirror_bone = find_mirror_object(bone)
|
||||
if mirror_bone:
|
||||
widgets_and_bones[mirror_bone] = mirror_bone.custom_shape
|
||||
|
||||
armature = bpy.context.object
|
||||
active_object = bpy.context.active_pose_bone
|
||||
else:
|
||||
for shape in bpy.context.selected_objects:
|
||||
bone = from_widget_find_bone(shape)
|
||||
if bone.name.endswith(("L", "R")):
|
||||
widgets_and_bones[from_widget_find_bone(shape)] = shape
|
||||
|
||||
mirrorShape = find_mirror_object(shape)
|
||||
if mirrorShape:
|
||||
widgets_and_bones[mirrorShape] = mirrorShape
|
||||
|
||||
active_object = from_widget_find_bone(bpy.context.object)
|
||||
armature = active_object.id_data
|
||||
return (widgets_and_bones, active_object, armature)
|
||||
|
||||
|
||||
def resync_widget_names():
|
||||
if not get_preferences(bpy.context).use_rigify_defaults:
|
||||
bw_collection_name = get_preferences(
|
||||
bpy.context).bonewidget_collection_name
|
||||
bw_widget_prefix = get_preferences(bpy.context).widget_prefix
|
||||
else:
|
||||
bw_collection_name = 'WGTS_' + bpy.context.active_object.name
|
||||
bw_widget_prefix = 'WGT-' + bpy.context.active_object.name + '_'
|
||||
|
||||
widgets_and_bones = {}
|
||||
|
||||
if bpy.context.object.type == 'ARMATURE':
|
||||
for bone in bpy.context.active_object.pose.bones:
|
||||
if bone.custom_shape:
|
||||
widgets_and_bones[bone] = bone.custom_shape
|
||||
|
||||
for k, v in widgets_and_bones.items():
|
||||
if k.name != (bw_widget_prefix + k.name):
|
||||
bpy.data.objects[v.name].name = str(bw_widget_prefix + k.name)
|
||||
|
||||
|
||||
def clear_bone_widgets():
|
||||
if bpy.context.object.type == 'ARMATURE':
|
||||
for bone in bpy.context.selected_pose_bones:
|
||||
if bone.custom_shape:
|
||||
bone.custom_shape = None
|
||||
bone.custom_shape_transform = None
|
||||
|
||||
|
||||
def add_object_as_widget(context, collection):
|
||||
selected_objects = bpy.context.selected_objects
|
||||
|
||||
if len(selected_objects) != 2:
|
||||
print('Only a widget object and the pose bone(s)')
|
||||
return {'FINISHED'}
|
||||
|
||||
allowed_object_types = ['MESH', 'CURVE']
|
||||
|
||||
widget_object = None
|
||||
|
||||
for ob in selected_objects:
|
||||
if ob.type in allowed_object_types:
|
||||
widget_object = ob
|
||||
|
||||
if widget_object:
|
||||
active_bone = context.active_pose_bone
|
||||
|
||||
# deal with any existing shape
|
||||
if active_bone.custom_shape:
|
||||
bpy.data.objects.remove(
|
||||
bpy.data.objects[active_bone.custom_shape.name], do_unlink=True)
|
||||
|
||||
# duplicate shape
|
||||
widget = widget_object.copy()
|
||||
widget.data = widget.data.copy()
|
||||
# rename it
|
||||
bw_widget_prefix = get_preferences(context).widget_prefix
|
||||
widget_name = bw_widget_prefix + active_bone.name
|
||||
widget.name = widget_name
|
||||
widget.data.name = widget_name
|
||||
# link it
|
||||
collection.objects.link(widget)
|
||||
|
||||
# match transforms
|
||||
widget.matrix_world = bpy.context.active_object.matrix_world @ active_bone.bone.matrix_local
|
||||
widget.scale = [active_bone.bone.length,
|
||||
active_bone.bone.length, active_bone.bone.length]
|
||||
layer = bpy.context.view_layer
|
||||
layer.update()
|
||||
|
||||
active_bone.custom_shape = widget
|
||||
active_bone.bone.show_wire = True
|
||||
|
||||
# deselect original object
|
||||
widget_object.select_set(False)
|
||||
|
||||
|
||||
def set_bone_color(context, color, clear_both_modes=None):
|
||||
if context.object.mode == "POSE":
|
||||
if color == 'DEFAULT' and clear_both_modes != None:
|
||||
for bone in context.selected_pose_bones:
|
||||
bone.color.palette = 'DEFAULT'
|
||||
|
||||
if clear_both_modes:
|
||||
bone.bone.color.palette = 'DEFAULT'
|
||||
return
|
||||
|
||||
for bone in context.selected_pose_bones:
|
||||
bone.color.palette = color # this will get the selected bone color
|
||||
|
||||
if color == "CUSTOM":
|
||||
bone.color.custom.normal = context.scene.bw_settings.custom_pose_color_set.normal
|
||||
bone.color.custom.select = context.scene.bw_settings.custom_pose_color_set.select
|
||||
bone.color.custom.active = context.scene.bw_settings.custom_pose_color_set.active
|
||||
|
||||
# set the edit bone colors if applicable (while in pose mode)
|
||||
if get_preferences(context).edit_bone_colors == 'DEFAULT':
|
||||
bone.bone.color.palette = 'DEFAULT' # this will reset the edit bone color
|
||||
|
||||
elif get_preferences(context).edit_bone_colors == 'LINKED':
|
||||
bone.bone.color.palette = color # set the edit bone colors
|
||||
|
||||
# Set the custom color to edit bones (if applicable)
|
||||
if color == "CUSTOM":
|
||||
bone.bone.color.custom.normal = context.scene.bw_settings.custom_pose_color_set.normal
|
||||
bone.bone.color.custom.select = context.scene.bw_settings.custom_pose_color_set.select
|
||||
bone.bone.color.custom.active = context.scene.bw_settings.custom_pose_color_set.active
|
||||
|
||||
elif context.object.mode == "EDIT":
|
||||
if color == 'DEFAULT' and clear_both_modes != None:
|
||||
for edit_bone in context.selected_bones:
|
||||
edit_bone.color.palette = 'DEFAULT'
|
||||
|
||||
if clear_both_modes:
|
||||
pose_bone = context.object.pose.bones.get(edit_bone.name)
|
||||
pose_bone.color.palette = 'DEFAULT'
|
||||
|
||||
return
|
||||
|
||||
for edit_bone in context.selected_bones:
|
||||
if get_preferences(context).edit_bone_colors == 'DEFAULT':
|
||||
# this will get the edit bone color back to default
|
||||
edit_bone.color.palette = 'DEFAULT'
|
||||
|
||||
elif get_preferences(context).edit_bone_colors == 'LINKED':
|
||||
edit_bone.color.palette = color # set the edit mode color
|
||||
|
||||
# get the pose bone
|
||||
pose_bone = context.object.pose.bones.get(edit_bone.name)
|
||||
pose_bone.color.palette = color # set the pose mode color
|
||||
|
||||
if color == "CUSTOM":
|
||||
# set edit bone custom colors
|
||||
edit_bone.color.custom.normal = context.scene.bw_settings.custom_edit_color_set.normal
|
||||
edit_bone.color.custom.select = context.scene.bw_settings.custom_edit_color_set.select
|
||||
edit_bone.color.custom.active = context.scene.bw_settings.custom_edit_color_set.active
|
||||
# set pose bone custom colors
|
||||
pose_bone.color.custom.normal = context.scene.bw_settings.custom_edit_color_set.normal
|
||||
pose_bone.color.custom.select = context.scene.bw_settings.custom_edit_color_set.select
|
||||
pose_bone.color.custom.active = context.scene.bw_settings.custom_edit_color_set.active
|
||||
|
||||
elif get_preferences(context).edit_bone_colors == 'SEPARATE':
|
||||
edit_bone.color.palette = color # set the edit mode color
|
||||
|
||||
if color == "CUSTOM":
|
||||
# set edit bone custom colors
|
||||
edit_bone.color.custom.normal = context.scene.bw_settings.custom_edit_color_set.normal
|
||||
edit_bone.color.custom.select = context.scene.bw_settings.custom_edit_color_set.select
|
||||
edit_bone.color.custom.active = context.scene.bw_settings.custom_edit_color_set.active
|
||||
|
||||
|
||||
def copy_bone_color(context, bone):
|
||||
live_update_current_state = context.scene.bw_settings.live_update_on
|
||||
context.scene.bw_settings.live_update_on = False
|
||||
|
||||
if bone.color.is_custom:
|
||||
if context.object.mode == 'POSE':
|
||||
context.scene.bw_settings.custom_pose_color_set.normal = bone.color.custom.normal
|
||||
context.scene.bw_settings.custom_pose_color_set.select = bone.color.custom.select
|
||||
context.scene.bw_settings.custom_pose_color_set.active = bone.color.custom.active
|
||||
else:
|
||||
context.scene.bw_settings.custom_edit_color_set.normal = bone.color.custom.normal
|
||||
context.scene.bw_settings.custom_edit_color_set.select = bone.color.custom.select
|
||||
context.scene.bw_settings.custom_edit_color_set.active = bone.color.custom.active
|
||||
elif bone.color.palette != "DEFAULT": # bone has a theme assigned
|
||||
theme = bone.color.palette
|
||||
theme_id = int(theme[-2:]) - 1
|
||||
theme_color_set = bpy.context.preferences.themes[0].bone_color_sets[theme_id]
|
||||
|
||||
palette = context.scene.bw_settings.custom_pose_color_set if context.object.mode == 'POSE' \
|
||||
else context.scene.bw_settings.custom_edit_color_set
|
||||
|
||||
palette.normal = theme_color_set.normal
|
||||
palette.select = theme_color_set.select
|
||||
palette.active = theme_color_set.active
|
||||
|
||||
context.scene.bw_settings.live_update_on = live_update_current_state
|
||||
|
||||
|
||||
def update_bone_color(self, context):
|
||||
if context.scene.bw_settings.live_update_on:
|
||||
set_bone_color(context, "CUSTOM")
|
||||
|
||||
|
||||
def advanced_options_toggled(self, context):
|
||||
if self.advanced_options:
|
||||
self.global_size_advanced = (self.global_size_simple,) * 3
|
||||
self.slide_advanced[1] = self.slide_simple
|
||||
else:
|
||||
self.global_size_simple = self.global_size_advanced[1]
|
||||
self.slide_simple = self.slide_advanced[1]
|
||||
|
||||
|
||||
def bone_color_items(self, context):
|
||||
items = [("DEFAULT", "Default Colors", "", "", 0)]
|
||||
for i in range(1, 16):
|
||||
items.append((f"THEME{i:02}", f"Theme {i:02}",
|
||||
"", f"COLORSET_{i:02}_VEC", i))
|
||||
return items
|
||||
|
||||
|
||||
def bone_color_items_short(self, context):
|
||||
items = []
|
||||
for i in range(1, 16):
|
||||
items.append((f"THEME{i:02}", f"Theme {i:02}",
|
||||
"", f"COLORSET_{i:02}_VEC", i))
|
||||
items.append(("CUSTOM", "Custom", "", "COLOR", 16))
|
||||
return items
|
||||
|
||||
|
||||
def live_update_toggle(self, context):
|
||||
context.scene.bw_settings.live_update_on = self.live_update_toggle
|
||||
|
||||
|
||||
def get_preferences(context):
|
||||
return context.preferences.addons[__package__].preferences
|
||||
@@ -0,0 +1,301 @@
|
||||
import bpy
|
||||
import bpy.utils.previews
|
||||
from .json_functions import read_widgets, get_widget_data, get_default_image_dir, get_custom_image_dir, JSON_USER_WIDGETS
|
||||
import os
|
||||
from .. import __package__
|
||||
from mathutils import Vector
|
||||
|
||||
preview_collections = {}
|
||||
|
||||
|
||||
def create_preview_collection():
|
||||
if preview_collections:
|
||||
del bpy.types.WindowManager.widget_list
|
||||
for pcoll in preview_collections.values():
|
||||
bpy.utils.previews.remove(pcoll)
|
||||
preview_collections.clear()
|
||||
|
||||
pcoll = bpy.utils.previews.new()
|
||||
pcoll.widget_list = ()
|
||||
preview_collections["widgets"] = pcoll
|
||||
|
||||
bpy.types.WindowManager.widget_list = bpy.props.EnumProperty(
|
||||
items=generate_previews(), name="Shape", description="Shape", update=preview_update
|
||||
)
|
||||
|
||||
|
||||
def generate_previews():
|
||||
enum_items = []
|
||||
|
||||
pcoll = preview_collections["widgets"]
|
||||
if pcoll.widget_list:
|
||||
return pcoll.widget_list
|
||||
|
||||
directory = get_default_image_dir('thumbnails')
|
||||
custom_directory = get_custom_image_dir("custom_thumbnails")
|
||||
|
||||
if directory and os.path.exists(directory):
|
||||
widget_data = {item[0]: item[1].get(
|
||||
"image", "missing_image.png") for item in read_widgets().items()}
|
||||
widget_names = sorted(widget_data.keys())
|
||||
|
||||
for i, name in enumerate(widget_names):
|
||||
image = widget_data.get(name, "")
|
||||
if image is not None:
|
||||
filepath = os.path.join(directory, image)
|
||||
|
||||
# try in custom_thumbnails if above failed
|
||||
if not os.path.exists(filepath):
|
||||
filepath = os.path.join(custom_directory, image)
|
||||
|
||||
# if image still not found, let the user know
|
||||
if not os.path.exists(filepath):
|
||||
filepath = os.path.join(directory, "missing_image.png")
|
||||
|
||||
icon = pcoll.get(name)
|
||||
if not icon:
|
||||
thumb = pcoll.load(name, filepath, 'IMAGE')
|
||||
else:
|
||||
thumb = pcoll[name]
|
||||
|
||||
face_data_info = "Contains Face Data" if get_widget_data(
|
||||
name).get("faces") else ""
|
||||
enum_items.append((name, name, face_data_info, thumb.icon_id, i))
|
||||
|
||||
pcoll.widget_list = enum_items
|
||||
return enum_items
|
||||
|
||||
|
||||
def preview_update(self, context):
|
||||
generate_previews()
|
||||
|
||||
|
||||
def get_preview_default():
|
||||
return bpy.context.preferences.addons[__package__].preferences.preview_default
|
||||
|
||||
|
||||
def copy_custom_image(filepath, filename):
|
||||
if os.path.exists(filepath):
|
||||
image_directory = get_custom_image_dir('custom_thumbnails')
|
||||
destination_path = os.path.join(image_directory, filename)
|
||||
|
||||
try:
|
||||
# create custom thumbnail folder if not existing
|
||||
if not os.path.exists(image_directory):
|
||||
os.makedirs(image_directory)
|
||||
|
||||
import shutil
|
||||
shutil.copyfile(filepath, destination_path)
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def remove_custom_image(filename):
|
||||
image_directory = get_custom_image_dir('custom_thumbnails')
|
||||
destination_path = os.path.join(image_directory, filename)
|
||||
|
||||
if os.path.isfile(destination_path):
|
||||
# make sure the image is only used once - else stop
|
||||
count = 0
|
||||
for v in read_widgets(JSON_USER_WIDGETS).values():
|
||||
if v.get("image") == filename:
|
||||
count += 1
|
||||
if count > 1:
|
||||
return False
|
||||
|
||||
try:
|
||||
os.remove(destination_path)
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
#### Thumbnail Render Functions ####
|
||||
def create_wireframe_copy(obj, use_color, color, thickness):
|
||||
copy = obj.copy()
|
||||
copy.data = obj.data.copy()
|
||||
if not use_color:
|
||||
copy.color = color
|
||||
|
||||
# Create a new Geometry Nodes modifier
|
||||
geo_mod = copy.modifiers.new(name="BoneWidget_WireFrame", type='NODES')
|
||||
|
||||
# Create a new node group and assign it to the modifier
|
||||
node_group = bpy.data.node_groups.new(
|
||||
name="BONEWIDGET_GeometryGroup", type='GeometryNodeTree')
|
||||
geo_mod.node_group = node_group
|
||||
|
||||
# Add input and output sockets
|
||||
node_group.interface.new_socket(
|
||||
name="Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
|
||||
node_group.interface.new_socket(
|
||||
name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
|
||||
|
||||
# Add Thickness input
|
||||
thickness_socket = node_group.interface.new_socket(
|
||||
name="Thickness", in_out="INPUT", socket_type="NodeSocketFloat")
|
||||
thickness_socket.default_value = 0.5
|
||||
thickness_socket.min_value = 0.01
|
||||
thickness_socket.max_value = 2
|
||||
|
||||
# Create nodes
|
||||
node_input = node_group.nodes.new('NodeGroupInput')
|
||||
node_output = node_group.nodes.new('NodeGroupOutput')
|
||||
node_uv_sphere = node_group.nodes.new('GeometryNodeMeshUVSphere')
|
||||
node_mesh_to_curve = node_group.nodes.new('GeometryNodeMeshToCurve')
|
||||
node_curve_circle = node_group.nodes.new(
|
||||
'GeometryNodeCurvePrimitiveCircle')
|
||||
node_instance_on_points = node_group.nodes.new(
|
||||
'GeometryNodeInstanceOnPoints')
|
||||
node_curve_to_mesh = node_group.nodes.new('GeometryNodeCurveToMesh')
|
||||
node_join_geometry = node_group.nodes.new('GeometryNodeJoinGeometry')
|
||||
|
||||
# Set initial values (internal)
|
||||
node_uv_sphere.inputs["Segments"].default_value = 8
|
||||
node_uv_sphere.inputs["Rings"].default_value = 8
|
||||
node_curve_circle.inputs["Resolution"].default_value = 8
|
||||
|
||||
# Position nodes for better visualization (optional)
|
||||
node_input.location = (-400, 0)
|
||||
node_uv_sphere.location = (-150, 100)
|
||||
node_mesh_to_curve.location = (-150, -50)
|
||||
node_curve_circle.location = (-150, -150)
|
||||
node_instance_on_points.location = (100, 250)
|
||||
node_curve_to_mesh.location = (100, -100)
|
||||
node_join_geometry.location = (350, 0)
|
||||
node_output.location = (550, 0)
|
||||
|
||||
# Connect nodes
|
||||
node_group.links.new(
|
||||
node_input.outputs["Geometry"], node_instance_on_points.inputs["Points"])
|
||||
node_group.links.new(
|
||||
node_input.outputs["Geometry"], node_mesh_to_curve.inputs["Mesh"])
|
||||
node_group.links.new(
|
||||
node_input.outputs["Thickness"], node_uv_sphere.inputs["Radius"])
|
||||
node_group.links.new(
|
||||
node_input.outputs["Thickness"], node_curve_circle.inputs["Radius"])
|
||||
node_group.links.new(
|
||||
node_uv_sphere.outputs["Mesh"], node_instance_on_points.inputs["Instance"])
|
||||
node_group.links.new(
|
||||
node_mesh_to_curve.outputs["Curve"], node_curve_to_mesh.inputs["Curve"])
|
||||
node_group.links.new(
|
||||
node_curve_circle.outputs["Curve"], node_curve_to_mesh.inputs["Profile Curve"])
|
||||
node_group.links.new(
|
||||
node_instance_on_points.outputs["Instances"], node_join_geometry.inputs["Geometry"])
|
||||
node_group.links.new(
|
||||
node_curve_to_mesh.outputs["Mesh"], node_join_geometry.inputs["Geometry"])
|
||||
node_group.links.new(
|
||||
node_join_geometry.outputs["Geometry"], node_output.inputs["Geometry"])
|
||||
|
||||
# scale this so it isn't so sensitive
|
||||
geo_mod["Socket_2"] = (thickness / 10)
|
||||
|
||||
return copy
|
||||
|
||||
|
||||
def setup_viewport(context):
|
||||
area = context.area
|
||||
space = context.space_data
|
||||
region_3d = space.region_3d
|
||||
original_view_matrix = region_3d.view_matrix.copy()
|
||||
|
||||
bpy.ops.view3d.view_selected()
|
||||
|
||||
return original_view_matrix
|
||||
|
||||
|
||||
def restore_viewport_position(context, view_matrix, view_perspective):
|
||||
if context.space_data.type == 'VIEW_3D':
|
||||
region_3d = context.space_data.region_3d
|
||||
|
||||
# Restore viewport matrix position
|
||||
region_3d.view_matrix = view_matrix
|
||||
|
||||
# Restore viewport perspective
|
||||
region_3d.view_perspective = view_perspective
|
||||
|
||||
|
||||
def render_widget_thumbnail(image_name, widget_object, image_directory):
|
||||
if image_directory: # If True save to the current directory but...
|
||||
if bpy.data.filepath: # Check the file has been saved
|
||||
image_directory = os.path.dirname(bpy.data.filepath)
|
||||
else:
|
||||
# Fall back if it hasn't been saved
|
||||
image_directory = os.path.expanduser("~")
|
||||
# add '.png' to the name
|
||||
image_name = image_name + '.png'
|
||||
|
||||
else: # if False use the add-on location
|
||||
image_directory = get_custom_image_dir('custom_thumbnails')
|
||||
|
||||
destination_path = os.path.join(image_directory, image_name)
|
||||
|
||||
scene = bpy.context.scene
|
||||
scene.render.engine = 'BLENDER_WORKBENCH'
|
||||
scene.render.resolution_x, scene.render.resolution_y = (512, 512)
|
||||
scene.render.resolution_percentage = 100
|
||||
scene.render.image_settings.file_format = 'PNG'
|
||||
scene.render.image_settings.color_mode = 'RGBA'
|
||||
scene.view_settings.view_transform = 'Standard'
|
||||
scene.render.film_transparent = True
|
||||
scene.display.shading.light = 'FLAT'
|
||||
scene.display.shading.color_type = 'OBJECT'
|
||||
scene.render.filepath = image_directory
|
||||
|
||||
# Reframe Camera
|
||||
camera = scene.camera
|
||||
obj = widget_object
|
||||
frame_object_with_padding(camera, obj, padding=0.1)
|
||||
|
||||
bpy.ops.render.render(write_still=False)
|
||||
bpy.data.images['Render Result'].save_render(
|
||||
filepath=bpy.path.abspath(destination_path))
|
||||
|
||||
return bpy.path.abspath(destination_path)
|
||||
|
||||
|
||||
def add_camera_from_view(context):
|
||||
name = "BoneWidget_Thumbnail_Camera"
|
||||
|
||||
region_3d = context.region_data
|
||||
space = context.space_data
|
||||
|
||||
if region_3d is None or space.type != 'VIEW_3D':
|
||||
print("This must be run from a 3D Viewport.")
|
||||
return None
|
||||
|
||||
# Create camera data and object
|
||||
cam_data = bpy.data.cameras.new(name)
|
||||
cam_obj = bpy.data.objects.new(name, cam_data)
|
||||
context.scene.collection.objects.link(cam_obj)
|
||||
|
||||
# Align camera to current viewport
|
||||
cam_obj.matrix_world = region_3d.view_matrix.inverted()
|
||||
|
||||
# Make it the active camera
|
||||
context.scene.camera = cam_obj
|
||||
|
||||
return cam_obj
|
||||
|
||||
|
||||
def frame_object_with_padding(camera, obj, padding=0.1):
|
||||
depsgraph = bpy.context.evaluated_depsgraph_get()
|
||||
|
||||
# Get bounding box corners in world space
|
||||
coords = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
|
||||
|
||||
# Find center of bounding box
|
||||
center = sum(coords, Vector()) / len(coords)
|
||||
|
||||
# Scale each point away from the center to apply padding
|
||||
scaled_coords = [(center + (co - center) * (1 + padding)) for co in coords]
|
||||
|
||||
# Flatten the list of Vectors into a list of floats
|
||||
flat_coords = [v for co in scaled_coords for v in co]
|
||||
|
||||
# Use the camera fitting function
|
||||
cam_location, _ = camera.camera_fit_coords(depsgraph, flat_coords)
|
||||
camera.location = cam_location
|
||||
@@ -0,0 +1,59 @@
|
||||
from bpy.types import Menu
|
||||
|
||||
|
||||
class BONEWIDGET_MT_bw_specials(Menu):
|
||||
bl_label = "Bone Widget Specials"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.operator("bonewidget.add_widgets", icon="ADD",
|
||||
text="Add Widget to Library")
|
||||
layout.operator("bonewidget.remove_widgets", icon="REMOVE",
|
||||
text="Remove Widget from Library")
|
||||
layout.separator()
|
||||
layout.operator("bonewidget.add_custom_image", icon="FILE_IMAGE",
|
||||
text="Add Custom Image to Widget")
|
||||
layout.operator("bonewidget.render_widget_thumbnail", icon="RESTRICT_RENDER_OFF",
|
||||
text="Render Object as Thumbnail")
|
||||
layout.separator()
|
||||
layout.operator("bonewidget.import_widget_library",
|
||||
icon="IMPORT", text="Import Widget Library")
|
||||
layout.operator("bonewidget.export_widget_library",
|
||||
icon="EXPORT", text="Export Widget Library")
|
||||
|
||||
|
||||
class BONEWIDGET_MT_bw_color_presets_specials(Menu):
|
||||
bl_label = "Color Presets Specials"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
btn_text = "Add Preset from Theme" if "THEME" in context.scene.bw_settings.bone_widget_colors else "Add Preset from Palette"
|
||||
layout.operator("bonewidget.add_color_set_from",
|
||||
text=btn_text, icon="ADD")
|
||||
layout.operator("bonewidget.add_preset_from_bone",
|
||||
icon="ADD", text="Add Preset from Bone")
|
||||
layout.operator("bonewidget.add_presets_from_armature",
|
||||
icon="ADD", text="Add Preset from Armature")
|
||||
layout.separator()
|
||||
layout.operator("bonewidget.import_color_presets",
|
||||
icon="IMPORT", text="Import Color Presets")
|
||||
layout.operator("bonewidget.export_color_presets",
|
||||
icon="EXPORT", text="Export Color Presets")
|
||||
|
||||
|
||||
classes = (
|
||||
BONEWIDGET_MT_bw_specials,
|
||||
BONEWIDGET_MT_bw_color_presets_specials,
|
||||
)
|
||||
|
||||
|
||||
def register():
|
||||
from bpy.utils import register_class
|
||||
for cls in classes:
|
||||
register_class(cls)
|
||||
|
||||
|
||||
def unregister():
|
||||
from bpy.utils import unregister_class
|
||||
for cls in classes:
|
||||
unregister_class(cls)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,280 @@
|
||||
import bpy
|
||||
import bpy.utils.previews
|
||||
from .props import PresetColorSetItem
|
||||
from .functions.main_functions import (
|
||||
recursive_layer_collection,
|
||||
get_preferences,
|
||||
)
|
||||
from .functions.preview_functions import (
|
||||
create_preview_collection,
|
||||
preview_collections,
|
||||
get_preview_default,
|
||||
)
|
||||
from .functions.json_functions import load_color_presets
|
||||
|
||||
from .menus import BONEWIDGET_MT_bw_specials
|
||||
|
||||
|
||||
class BONEWIDGET_PT_bw_panel:
|
||||
"""BoneWidget Addon UI"""
|
||||
bl_space_type = 'VIEW_3D'
|
||||
bl_region_type = 'UI'
|
||||
bl_category = "Rigging"
|
||||
bl_label = "Bone Widget"
|
||||
|
||||
|
||||
class BONEWIDGET_PT_bw_panel_main(BONEWIDGET_PT_bw_panel, bpy.types.Panel):
|
||||
bl_idname = 'BONEWIDGET_PT_bw_panel_main'
|
||||
bl_label = "Bone Widget"
|
||||
|
||||
def draw(self, context):
|
||||
if context.window_manager.load_presets_on_startup:
|
||||
load_color_presets()
|
||||
context.window_manager.load_presets_on_startup = False
|
||||
|
||||
# cache call to get preferences
|
||||
preferences = get_preferences(context)
|
||||
|
||||
layout = self.layout
|
||||
|
||||
# preview toggle checkbox
|
||||
row = layout.row(align=True)
|
||||
row.prop(context.window_manager, "toggle_preview")
|
||||
|
||||
# preview view
|
||||
if context.window_manager.toggle_preview:
|
||||
row = layout.row(align=True)
|
||||
preview_panel_size = preferences.preview_panel_size
|
||||
preview_popup_size = preferences.preview_popup_size
|
||||
row.template_icon_view(context.window_manager, "widget_list", show_labels=True,
|
||||
scale=preview_panel_size, scale_popup=preview_popup_size)
|
||||
|
||||
# dropdown list
|
||||
row = layout.row(align=True)
|
||||
row.prop(context.window_manager, "widget_list", expand=False, text="")
|
||||
|
||||
row = layout.row(align=True)
|
||||
row.menu("BONEWIDGET_MT_bw_specials", icon='DOWNARROW_HLT', text="")
|
||||
row.operator("bonewidget.create_widget",
|
||||
icon="OBJECT_DATAMODE", text="Create")
|
||||
|
||||
if context.mode == "POSE":
|
||||
row.operator("bonewidget.edit_widget", icon="OUTLINER_DATA_MESH")
|
||||
else:
|
||||
row.operator("bonewidget.return_to_armature",
|
||||
icon="LOOP_BACK", text='To bone')
|
||||
|
||||
layout.separator()
|
||||
|
||||
# Symmetry buttons etc
|
||||
row = layout.row(align=True)
|
||||
row.operator("bonewidget.symmetrize_shape",
|
||||
icon='MOD_MIRROR', text="Symmetrize Shape")
|
||||
icon = 'RESTRICT_COLOR_OFF'
|
||||
if preferences.symmetrize_color:
|
||||
icon = 'RESTRICT_COLOR_ON'
|
||||
row.prop(preferences, "symmetrize_color",
|
||||
icon=icon, text='', toggle=True)
|
||||
row = layout.row()
|
||||
row.operator("bonewidget.match_bone_transforms",
|
||||
icon='GROUP_BONE', text="Match Bone Transforms")
|
||||
row = layout.row()
|
||||
row.operator("bonewidget.resync_widget_names",
|
||||
icon='FILE_REFRESH', text="Resync Widget Names")
|
||||
|
||||
# Clear Bone Widget buttons etc
|
||||
layout.separator()
|
||||
layout.operator("bonewidget.clear_widgets",
|
||||
icon='X', text="Clear Bone Widget")
|
||||
layout.operator("bonewidget.delete_unused_widgets",
|
||||
icon='TRASH', text="Delete Unused Widgets")
|
||||
|
||||
if context.mode == 'POSE':
|
||||
layout.operator("bonewidget.add_as_widget",
|
||||
text="Use Selected Object",
|
||||
icon='RESTRICT_SELECT_OFF')
|
||||
|
||||
# if the bw collection exists, show the visibility toggle
|
||||
if not preferences.use_rigify_defaults: # rigify
|
||||
bw_collection_name = preferences.bonewidget_collection_name
|
||||
|
||||
elif context.active_object: # active object
|
||||
bw_collection_name = 'WGTS_' + context.active_object.name
|
||||
|
||||
else: # this is needed because sometimes there is no active object
|
||||
bw_collection_name = None
|
||||
|
||||
bw_collection = recursive_layer_collection(
|
||||
context.view_layer.layer_collection, bw_collection_name)
|
||||
|
||||
if bw_collection is not None:
|
||||
if bw_collection.hide_viewport:
|
||||
icon = "HIDE_ON"
|
||||
text = "Show Collection"
|
||||
else:
|
||||
icon = "HIDE_OFF"
|
||||
text = "Hide Collection"
|
||||
row = layout.row()
|
||||
row.separator()
|
||||
row = layout.row()
|
||||
row.operator("bonewidget.toggle_collection_visibilty",
|
||||
icon=icon, text=text)
|
||||
|
||||
# BONE COLORS
|
||||
if bpy.app.version >= (4, 0, 0):
|
||||
layout.separator()
|
||||
row = layout.row(align=True)
|
||||
row.operator("bonewidget.set_bone_color",
|
||||
text="Set Bone Color", icon="BRUSHES_ALL")
|
||||
row.scale_x = 3.0
|
||||
icon_row = row.row()
|
||||
icon_row.enabled = (context.object is not None and context.object.type == 'ARMATURE' and
|
||||
context.object.mode in {'POSE', 'EDIT'})
|
||||
icon_row.template_icon_view(
|
||||
context.scene.bw_settings, "bone_widget_colors", show_labels=False, scale=1, scale_popup=1.8)
|
||||
if context.scene.bw_settings.bone_widget_colors == "CUSTOM":
|
||||
|
||||
custom_pose_color = context.scene.bw_settings.custom_pose_color_set
|
||||
custom_edit_color = context.scene.bw_settings.custom_edit_color_set
|
||||
|
||||
if context.object.mode == 'POSE': # display pose bone colors
|
||||
row = layout.row(align=True)
|
||||
row.prop(custom_pose_color, "normal", text="")
|
||||
row.prop(custom_pose_color, "select", text="")
|
||||
row.prop(custom_pose_color, "active", text="")
|
||||
# edit bone colors
|
||||
elif context.object.mode == "EDIT" and preferences.edit_bone_colors != 'DEFAULT':
|
||||
row = layout.row(align=True)
|
||||
row.prop(custom_edit_color, "normal", text="")
|
||||
row.prop(custom_edit_color, "select", text="")
|
||||
row.prop(custom_edit_color, "active", text="")
|
||||
|
||||
if context.object.mode == 'POSE' or (context.object.mode == 'EDIT' and
|
||||
preferences.edit_bone_colors != 'DEFAULT'):
|
||||
row.separator(factor=0.5)
|
||||
row.prop(context.scene.bw_settings, "live_update_toggle",
|
||||
text="", icon="UV_SYNC_SELECT")
|
||||
|
||||
row = layout.row()
|
||||
row.operator("bonewidget.copy_bone_color",
|
||||
text="Copy Bone Color", icon="COPYDOWN")
|
||||
|
||||
row = layout.row(align=True)
|
||||
row.operator("bonewidget.clear_bone_color",
|
||||
text="Clear Bone Color", icon="PANEL_CLOSE")
|
||||
|
||||
icon = 'BONE_DATA'
|
||||
if preferences.clear_both_modes:
|
||||
icon = 'GROUP_BONE'
|
||||
row.prop(preferences, "clear_both_modes",
|
||||
icon=icon, text='', toggle=True)
|
||||
|
||||
|
||||
class BONEWIDGET_PT_bw_custom_color_presets(BONEWIDGET_PT_bw_panel, bpy.types.Panel):
|
||||
bl_idname = "BONEWIDGET_PT_bw_custom_color_presets"
|
||||
bl_parent_id = "BONEWIDGET_PT_bw_panel_main"
|
||||
bl_label = "Custom Color Presets"
|
||||
bl_options = {'DEFAULT_CLOSED'}
|
||||
|
||||
@classmethod
|
||||
def poll(self, context):
|
||||
return bpy.app.version >= (4, 0, 0)
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
row = layout.row()
|
||||
row.template_list("BONEWIDGET_UL_colorset_items", "", context.window_manager, "custom_color_presets",
|
||||
context.window_manager, "colorset_list_index")
|
||||
|
||||
col = row.column(align=True)
|
||||
col.operator("bonewidget.add_default_custom_colorset",
|
||||
icon='ADD', text="")
|
||||
col.operator("bonewidget.remove_custom_item", icon='REMOVE', text="")
|
||||
col.separator()
|
||||
col.menu("BONEWIDGET_MT_bw_color_presets_specials",
|
||||
icon="DOWNARROW_HLT", text="")
|
||||
col.separator()
|
||||
col.operator("bonewidget.move_custom_item_up", icon="TRIA_UP", text="")
|
||||
col.operator("bonewidget.move_custom_item_down",
|
||||
icon="TRIA_DOWN", text="")
|
||||
row = layout.row()
|
||||
row.operator("bonewidget.add_colorset_to_bone",
|
||||
text="Apply To Selected Bones")
|
||||
|
||||
|
||||
class BONEWIDGET_UL_colorset_items(bpy.types.UIList):
|
||||
def draw_item(self, context, layout, data, item, icon, active_data, active_property, index):
|
||||
# set the size of each color set field
|
||||
split = layout.split(factor=0.58)
|
||||
split.prop(item, "name", text="", emboss=False)
|
||||
|
||||
row = split.row(align=True)
|
||||
row.prop(item, "normal", text="")
|
||||
row.prop(item, "select", text="")
|
||||
row.prop(item, "active", text="")
|
||||
|
||||
|
||||
classes = (
|
||||
BONEWIDGET_PT_bw_panel_main,
|
||||
BONEWIDGET_PT_bw_custom_color_presets,
|
||||
BONEWIDGET_UL_colorset_items,
|
||||
)
|
||||
|
||||
|
||||
def register():
|
||||
if not hasattr(bpy.types.WindowManager, "widget_list"):
|
||||
create_preview_collection()
|
||||
|
||||
bpy.types.WindowManager.toggle_preview = bpy.props.BoolProperty(
|
||||
name="Preview Panel",
|
||||
default=get_preview_default(),
|
||||
description="Show thumbnail previews"
|
||||
)
|
||||
|
||||
bpy.utils.register_class(PresetColorSetItem)
|
||||
bpy.types.WindowManager.custom_color_presets = bpy.props.CollectionProperty(
|
||||
type=PresetColorSetItem)
|
||||
bpy.types.WindowManager.colorset_list_index = bpy.props.IntProperty(
|
||||
name="Index", default=0)
|
||||
bpy.types.WindowManager.turn_off_colorset_save = bpy.props.BoolProperty(
|
||||
name="Turn Off ColorSet Save",
|
||||
description="Disable automatic saving of color sets",
|
||||
default=False
|
||||
)
|
||||
bpy.types.WindowManager.load_presets_on_startup = bpy.props.BoolProperty(
|
||||
name="Load Presets on Startup",
|
||||
description="Load color presets when Blender starts",
|
||||
default=True
|
||||
)
|
||||
|
||||
from bpy.utils import register_class
|
||||
for cls in classes:
|
||||
try:
|
||||
register_class(cls)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def unregister():
|
||||
if hasattr(bpy.types.WindowManager, "widget_list"):
|
||||
del bpy.types.WindowManager.widget_list
|
||||
|
||||
del bpy.types.WindowManager.toggle_preview
|
||||
del bpy.types.WindowManager.custom_color_presets
|
||||
del bpy.types.WindowManager.colorset_list_index
|
||||
del bpy.types.WindowManager.turn_off_colorset_save
|
||||
del bpy.types.WindowManager.load_presets_on_startup
|
||||
|
||||
bpy.utils.unregister_class(PresetColorSetItem)
|
||||
|
||||
for pcoll in preview_collections.values():
|
||||
bpy.utils.previews.remove(pcoll)
|
||||
preview_collections.clear()
|
||||
|
||||
from bpy.utils import unregister_class
|
||||
for cls in classes:
|
||||
try:
|
||||
unregister_class(cls)
|
||||
except:
|
||||
pass
|
||||
@@ -0,0 +1,203 @@
|
||||
import bpy
|
||||
from bpy.types import AddonPreferences
|
||||
from bpy.props import StringProperty, BoolProperty, FloatProperty, EnumProperty
|
||||
|
||||
from .panels import BONEWIDGET_PT_bw_panel_main
|
||||
from .operators import BONEWIDGET_OT_reset_default_images, BONEWIDGET_OT_user_data_filebrowser
|
||||
|
||||
|
||||
class BoneWidget_preferences(AddonPreferences):
|
||||
bl_idname = __package__
|
||||
|
||||
# Use Rigify Defaults
|
||||
use_rigify_defaults: BoolProperty(
|
||||
name="Use Rigify Defaults",
|
||||
description="Use the same naming convention for widget creation (disable if you prefer your naming convention)",
|
||||
default=True,
|
||||
)
|
||||
|
||||
# widget prefix
|
||||
widget_prefix: StringProperty(
|
||||
name="Bone Widget prefix",
|
||||
description="Choose a prefix for the widget objects",
|
||||
default="WGT-",
|
||||
)
|
||||
|
||||
# symmetry suffix
|
||||
symmetry_suffix: StringProperty(
|
||||
name="Bone Widget symmetry suffix",
|
||||
description="Choose a naming convention for the symmetrical widgets, separate by semicolon.",
|
||||
default="L; R",
|
||||
)
|
||||
|
||||
# collection name
|
||||
bonewidget_collection_name: StringProperty(
|
||||
name="Bone Widget collection name",
|
||||
description="Choose a name for the collection the widgets will appear",
|
||||
default="WGTS",
|
||||
)
|
||||
|
||||
def panel_category_update_fn(self, context):
|
||||
has_panel = hasattr(bpy.types, BONEWIDGET_PT_bw_panel_main.bl_idname)
|
||||
if has_panel:
|
||||
try:
|
||||
bpy.utils.unregister_class(BONEWIDGET_PT_bw_panel_main)
|
||||
except:
|
||||
pass
|
||||
BONEWIDGET_PT_bw_panel_main.bl_category = self.panel_category
|
||||
bpy.utils.register_class(BONEWIDGET_PT_bw_panel_main)
|
||||
|
||||
panel_category: StringProperty(
|
||||
name="Panel Category",
|
||||
description="Category to show Bone-Widgets panel",
|
||||
default="Rigging",
|
||||
update=panel_category_update_fn,
|
||||
)
|
||||
|
||||
preview_panel_size: FloatProperty(
|
||||
name="Preview Panel Size",
|
||||
description="Size of the Preview Panel",
|
||||
default=6.0,
|
||||
min=1.0,
|
||||
max=10.0,
|
||||
precision=1,
|
||||
)
|
||||
|
||||
preview_popup_size: FloatProperty(
|
||||
name="Preview Popup Size",
|
||||
description="Size of the Preview Popup Thumbnails",
|
||||
default=3.5,
|
||||
min=1.0,
|
||||
max=10.0,
|
||||
precision=1,
|
||||
)
|
||||
|
||||
preview_default: BoolProperty(
|
||||
name="Default Preview State",
|
||||
description="Default state of preview panel",
|
||||
default=True,
|
||||
)
|
||||
|
||||
edit_bone_colors: EnumProperty(
|
||||
name="Edit Bone Colors",
|
||||
description="Behavior of Edit Bone colors",
|
||||
items=[
|
||||
('DEFAULT', "Default", "Set the Edit Bone color to the default colors"),
|
||||
('LINKED', "Linked",
|
||||
"Use the same colors for both the Edit bones and Pose bones"),
|
||||
('SEPARATE', "Separate",
|
||||
"Edit bones and Pose bones will have their own colors"),
|
||||
],
|
||||
default='DEFAULT'
|
||||
)
|
||||
|
||||
clear_both_modes: bpy.props.BoolProperty(
|
||||
name="Clear All Bone Color",
|
||||
description='When enabled, bone colors from Edit mode and Pose mode will be cleared. When disabled, only the color from the current mode will be cleared',
|
||||
default=True
|
||||
)
|
||||
|
||||
symmetrize_color: bpy.props.BoolProperty(
|
||||
name="Symmetrize Bone Colors",
|
||||
description='When enabled, bone colors will be copied when you symmetrize a widget. When disabled, only the shape will be symmetrized',
|
||||
default=True
|
||||
)
|
||||
|
||||
use_default_location: bpy.props.BoolProperty(
|
||||
name="Use default location",
|
||||
description='When enabled, user widgets and color sets will be saved to extensions/.user/{repository_name}/bone_widget/bone_widget_custom_data',
|
||||
default=True
|
||||
)
|
||||
|
||||
user_data_location: StringProperty(
|
||||
name="User Data Location",
|
||||
description="Choose a location where you want to save custom data",
|
||||
default="",
|
||||
)
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
box = layout.box()
|
||||
box.label(text="Widget Naming Convention:")
|
||||
box.prop(self, "use_rigify_defaults", text="Use Rigify Defaults")
|
||||
|
||||
box_row = box.row()
|
||||
box_col = box_row.column()
|
||||
box_col.prop(self, "widget_prefix", text="Widget Prefix")
|
||||
box_col.prop(self, "bonewidget_collection_name",
|
||||
text="Collection name")
|
||||
box_row.enabled = not self.use_rigify_defaults
|
||||
|
||||
box_row = box.row()
|
||||
box_row = box.row()
|
||||
box_row.prop(self, "symmetry_suffix", text="Symmetry suffix")
|
||||
|
||||
row = layout.row()
|
||||
|
||||
box = layout.box()
|
||||
box_col = box.column()
|
||||
box_col.label(text="Set the category to show Bone-Widgets panel:")
|
||||
box_col.prop(self, "panel_category")
|
||||
|
||||
# edit bone colors
|
||||
row = layout.row()
|
||||
box = layout.box()
|
||||
box.label(text="Bone Color Behavior:")
|
||||
row = box.row()
|
||||
row.prop(self, "edit_bone_colors")
|
||||
row = box.row()
|
||||
row.label(text="Clearing Colors:")
|
||||
row.prop(self, "clear_both_modes")
|
||||
row = box.row()
|
||||
row.label(text="Symmetrize Colors:")
|
||||
row.prop(self, "symmetrize_color")
|
||||
|
||||
# preview area
|
||||
row = layout.row()
|
||||
box = layout.box()
|
||||
|
||||
box.label(text="Thumbnail Previews:")
|
||||
box_row = box.row()
|
||||
box_row.prop(self, "preview_default",
|
||||
text="Display Previews by Default")
|
||||
|
||||
box_row = box.row()
|
||||
box_col = box_row.column()
|
||||
box_col.label(text="Preview Panel Size:")
|
||||
box_row.prop(self, "preview_panel_size", text="")
|
||||
|
||||
box_row = box.row()
|
||||
box_col = box_row.column()
|
||||
box_col.label(text="Preview Popup Size:")
|
||||
box_row.prop(self, "preview_popup_size", text="")
|
||||
|
||||
# custom data
|
||||
row = layout.row()
|
||||
box = layout.box()
|
||||
|
||||
box.label(text="Custom Data:")
|
||||
box_row = box.row()
|
||||
box_row.prop(self, "use_default_location", text="Use Default Location")
|
||||
|
||||
box_row = box.row()
|
||||
box_col = box_row.column()
|
||||
box_col.prop(self, "user_data_location", text="Custom Path")
|
||||
box_row.operator("bonewidget.user_data_filebrowser",
|
||||
icon="FILEBROWSER", text="")
|
||||
box_row.enabled = not self.use_default_location
|
||||
|
||||
# reset button
|
||||
layout.separator()
|
||||
row = layout.row()
|
||||
row = row.split(factor=.75)
|
||||
row.label(text="Reset Default Widget Thumbnails")
|
||||
row.operator("bonewidget.reset_default_images", icon="ERROR")
|
||||
|
||||
|
||||
def register():
|
||||
bpy.utils.register_class(BoneWidget_preferences)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.utils.unregister_class(BoneWidget_preferences)
|
||||
@@ -0,0 +1,197 @@
|
||||
import bpy
|
||||
from .functions.main_functions import (
|
||||
update_bone_color,
|
||||
bone_color_items_short,
|
||||
live_update_toggle
|
||||
)
|
||||
from bpy.types import PropertyGroup
|
||||
from bpy.props import BoolProperty, EnumProperty, PointerProperty
|
||||
|
||||
|
||||
class CustomColorSet(bpy.types.PropertyGroup):
|
||||
|
||||
name: bpy.props.StringProperty(name="Name", default="Untitled")
|
||||
|
||||
normal: bpy.props.FloatVectorProperty(
|
||||
name="Normal",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for the surface of bones",
|
||||
update=update_bone_color,
|
||||
)
|
||||
|
||||
select: bpy.props.FloatVectorProperty(
|
||||
name="Select",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for selected bones",
|
||||
update=update_bone_color,
|
||||
)
|
||||
|
||||
active: bpy.props.FloatVectorProperty(
|
||||
name="Active",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for active bones",
|
||||
update=update_bone_color,
|
||||
)
|
||||
|
||||
|
||||
class BW_Settings(PropertyGroup):
|
||||
live_update_on: BoolProperty(
|
||||
name="Live Update On",
|
||||
description="Enable live widget updates",
|
||||
default=False
|
||||
)
|
||||
live_update_toggle: BoolProperty(
|
||||
name="Live Update Toggle",
|
||||
description="Toggle live updates in the UI",
|
||||
default=False,
|
||||
update=live_update_toggle,
|
||||
)
|
||||
lock_colorset_color_changes: BoolProperty(
|
||||
name="Lock ColorSet Color Changes",
|
||||
description="Prevent modifying the current color set",
|
||||
default=False
|
||||
)
|
||||
# Blender's bone color themes
|
||||
bone_widget_colors: EnumProperty(
|
||||
name="Colors",
|
||||
description="Select a Bone Color",
|
||||
items=bone_color_items_short, # get the themes minus the blank ones
|
||||
default=1, # THEME01
|
||||
)
|
||||
|
||||
# Nested Property Groups
|
||||
custom_edit_color_set: PointerProperty(type=CustomColorSet)
|
||||
custom_pose_color_set: PointerProperty(type=CustomColorSet)
|
||||
|
||||
|
||||
save_timer = None
|
||||
|
||||
|
||||
def debounce_save(context):
|
||||
"""Schedule saving the color sets 1 second after the last change."""
|
||||
from .functions.json_functions import save_color_sets
|
||||
global save_timer
|
||||
|
||||
if save_timer is not None:
|
||||
try:
|
||||
bpy.app.timers.unregister(save_timer)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def delayed_save():
|
||||
save_color_sets(context)
|
||||
return None # stop the timer
|
||||
|
||||
save_timer = delayed_save
|
||||
bpy.app.timers.register(save_timer, first_interval=1.0)
|
||||
|
||||
|
||||
class PresetColorSetItem(bpy.types.PropertyGroup):
|
||||
|
||||
def update_colorset_list(self, context):
|
||||
if not context.window_manager.turn_off_colorset_save and not context.scene.bw_settings.lock_colorset_color_changes:
|
||||
debounce_save(context)
|
||||
|
||||
name: bpy.props.StringProperty(
|
||||
name="Name", default="Untitled", update=update_colorset_list)
|
||||
normal: bpy.props.FloatVectorProperty(
|
||||
name="Normal",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for the surface of bones",
|
||||
update=update_colorset_list,
|
||||
)
|
||||
select: bpy.props.FloatVectorProperty(
|
||||
name="Select",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for selected bones",
|
||||
update=update_colorset_list,
|
||||
)
|
||||
active: bpy.props.FloatVectorProperty(
|
||||
name="Active",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for active bones",
|
||||
update=update_colorset_list,
|
||||
)
|
||||
|
||||
|
||||
class ImportColorSet(bpy.types.PropertyGroup):
|
||||
|
||||
normal: bpy.props.FloatVectorProperty(
|
||||
name="Normal",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for the surface of bones",
|
||||
)
|
||||
|
||||
select: bpy.props.FloatVectorProperty(
|
||||
name="Select",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for selected bones",
|
||||
)
|
||||
|
||||
active: bpy.props.FloatVectorProperty(
|
||||
name="Active",
|
||||
subtype='COLOR_GAMMA',
|
||||
default=(0.0, 0.0, 0.0),
|
||||
size=3,
|
||||
min=0.0, max=1.0,
|
||||
description="Color used for active bones",
|
||||
)
|
||||
|
||||
|
||||
def get_import_options():
|
||||
return [
|
||||
("OVERWRITE", "Add/Overwrite", "Add or Overwrite existing item"),
|
||||
("SKIP", "Skip", "Skip item"),
|
||||
("RENAME", "Rename", "Rename item"),
|
||||
]
|
||||
|
||||
|
||||
class ImportItemData(bpy.types.PropertyGroup):
|
||||
|
||||
name: bpy.props.StringProperty(
|
||||
name="Unnamed",
|
||||
description="The name of the imported item"
|
||||
)
|
||||
|
||||
import_option: bpy.props.EnumProperty(
|
||||
name="Options",
|
||||
description="Choose an option",
|
||||
items=get_import_options(),
|
||||
default="SKIP"
|
||||
)
|
||||
|
||||
|
||||
def register():
|
||||
bpy.utils.register_class(CustomColorSet)
|
||||
bpy.utils.register_class(BW_Settings)
|
||||
bpy.types.Scene.bw_settings = bpy.props.PointerProperty(type=BW_Settings)
|
||||
|
||||
|
||||
def unregister():
|
||||
del bpy.types.Scene.bw_settings
|
||||
bpy.utils.unregister_class(BW_Settings)
|
||||
bpy.utils.unregister_class(CustomColorSet)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user