2025-12-01
This commit is contained in:
@@ -0,0 +1,674 @@
|
||||
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,5 @@
|
||||
# Lattice Magic
|
||||
|
||||
Lattice Magic is an add-on that adds two lattice-based deformation tools to Blender; The first one lets you smear meshes in an area of influence, and the other lets you deform them using a camera-space grid.
|
||||
|
||||
You can find the documentation [here](https://studio.blender.org/tools/addons/lattice_magic).
|
||||
@@ -0,0 +1,64 @@
|
||||
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
bl_info = {
|
||||
"name": "Lattice Magic",
|
||||
"author": "Demeter Dzadik",
|
||||
"version": (0, 1, 3),
|
||||
"blender": (2, 90, 0),
|
||||
"location": "View3D > Sidebar > Lattice Magic",
|
||||
"description": "Various Lattice-based tools to smear or adjust geometry.",
|
||||
"category": "Rigging",
|
||||
"doc_url": "https://gitlab.com/blender/lattice_magic/-/wikis/home",
|
||||
"tracker_url": "https://gitlab.com/blender/lattice_magic/-/issues/new",
|
||||
}
|
||||
|
||||
import importlib
|
||||
import bpy
|
||||
|
||||
from . import (
|
||||
camera_lattice,
|
||||
tweak_lattice,
|
||||
operators,
|
||||
utils,
|
||||
prefs,
|
||||
)
|
||||
|
||||
modules = [camera_lattice, tweak_lattice, operators, utils, prefs]
|
||||
|
||||
|
||||
def register_unregister_modules(modules, register: bool):
|
||||
"""Recursively register or unregister modules by looking for either
|
||||
un/register() functions or lists named `registry` which should be a list of
|
||||
registerable classes.
|
||||
"""
|
||||
register_func = bpy.utils.register_class if register else bpy.utils.unregister_class
|
||||
|
||||
for m in modules:
|
||||
if register:
|
||||
importlib.reload(m)
|
||||
if hasattr(m, 'registry'):
|
||||
for c in m.registry:
|
||||
try:
|
||||
register_func(c)
|
||||
except Exception as e:
|
||||
un = 'un' if not register else ''
|
||||
print(f"Warning: Failed to {un}register class: {c.__name__}")
|
||||
print(e)
|
||||
|
||||
if hasattr(m, 'modules'):
|
||||
register_unregister_modules(m.modules, register)
|
||||
|
||||
if register and hasattr(m, 'register'):
|
||||
m.register()
|
||||
elif hasattr(m, 'unregister'):
|
||||
m.unregister()
|
||||
|
||||
|
||||
def register():
|
||||
register_unregister_modules(modules, True)
|
||||
|
||||
|
||||
def unregister():
|
||||
register_unregister_modules(modules, False)
|
||||
@@ -0,0 +1,19 @@
|
||||
schema_version = "1.0.0"
|
||||
|
||||
id = "latticemagic"
|
||||
version = "1.0.0"
|
||||
name = "Lattice Magic"
|
||||
tagline = "Lattice-based deforming tools"
|
||||
maintainer = "Demeter Dzadik <demeter@blender.org>"
|
||||
type = "add-on"
|
||||
website = "https://studio.blender.org/tools/addons/lattice_magic"
|
||||
tags = ["Rigging", "Animation"]
|
||||
|
||||
blender_version_min = "4.2.0"
|
||||
|
||||
license = [
|
||||
"SPDX:GPL-3.0-or-later",
|
||||
]
|
||||
copyright = [
|
||||
"2019-2024 Demeter Dzadik & Blender Studio",
|
||||
]
|
||||
@@ -0,0 +1,640 @@
|
||||
# SPDX-FileCopyrightText: 2015 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# Inspired by https://animplay.wordpress.com/2015/11/18/smear-frame-script-maya/.
|
||||
|
||||
# This addon allows the user to specify a camera and a collection,
|
||||
# and create a 2D lattice that fills the camera's view,
|
||||
# to deform the mesh objects in that collection.
|
||||
|
||||
import bpy
|
||||
import math
|
||||
from bpy.app.handlers import persistent
|
||||
from mathutils import Vector
|
||||
from bpy.props import (
|
||||
BoolProperty,
|
||||
PointerProperty,
|
||||
CollectionProperty,
|
||||
IntProperty,
|
||||
EnumProperty,
|
||||
FloatProperty,
|
||||
)
|
||||
from mathutils.geometry import intersect_point_line
|
||||
|
||||
from .utils import bounding_box_center_of_objects
|
||||
from .prefs import get_addon_prefs
|
||||
|
||||
|
||||
class CAMLAT_UL_lattice_slots(bpy.types.UIList):
|
||||
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
|
||||
lattice_slots = context.scene.lattice_slots
|
||||
active_slot = lattice_slots[context.scene.active_lattice_index]
|
||||
current_slot = item
|
||||
|
||||
if self.layout_type in {'DEFAULT', 'COMPACT'}:
|
||||
if current_slot.collection:
|
||||
row = layout.row()
|
||||
icon = 'OUTLINER_COLLECTION' if current_slot.enabled else 'COLLECTION_COLOR_07'
|
||||
row.prop(current_slot.collection, 'name', text="", emboss=False, icon=icon)
|
||||
row.enabled = current_slot.enabled
|
||||
|
||||
layout.prop(current_slot, 'strength', text="", slider=True, emboss=False)
|
||||
|
||||
icon = 'CHECKBOX_HLT' if current_slot.enabled else 'CHECKBOX_DEHLT'
|
||||
layout.prop(current_slot, 'enabled', text="", icon=icon, emboss=False)
|
||||
else:
|
||||
layout.label(text="", translate=False, icon='COLLECTION_NEW')
|
||||
elif self.layout_type in {'GRID'}:
|
||||
layout.alignment = 'CENTER'
|
||||
layout.label(text="", icon_value=icon)
|
||||
|
||||
|
||||
class LatticeSlot(bpy.types.PropertyGroup):
|
||||
enabled: BoolProperty(
|
||||
name="Enabled", description="Whether the Lattice has an effect or not", default=True
|
||||
)
|
||||
strength: FloatProperty(
|
||||
name="Strength", description="Strength of the lattice effect", min=0, max=1, default=1
|
||||
)
|
||||
lattice: PointerProperty(
|
||||
name="Lattice",
|
||||
type=bpy.types.Object,
|
||||
description="Lattice object generated by this LatticeSlot. This cannot be specified manually, use the Generate or Delete operator below",
|
||||
)
|
||||
|
||||
def is_camera(self, obj):
|
||||
return obj.type == 'CAMERA'
|
||||
|
||||
camera: PointerProperty(
|
||||
name="Camera",
|
||||
type=bpy.types.Object,
|
||||
description="Camera used by this LatticeSlot",
|
||||
poll=is_camera,
|
||||
)
|
||||
collection: PointerProperty(
|
||||
name="Collection",
|
||||
type=bpy.types.Collection,
|
||||
description="Collection affected by this LatticeSlot",
|
||||
)
|
||||
|
||||
resolution: IntProperty(
|
||||
name="Resolution",
|
||||
description="Resolution of the lattice grid",
|
||||
min=5,
|
||||
max=64,
|
||||
default=10,
|
||||
options=set(),
|
||||
)
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_add(bpy.types.Operator):
|
||||
"""Add a Camera Lattice Slot"""
|
||||
|
||||
bl_idname = "lattice.add_slot"
|
||||
bl_label = "Add Lattice Slot"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
lattice_slots = scene.lattice_slots
|
||||
active_index = scene.active_lattice_index
|
||||
to_index = active_index + 1
|
||||
if len(lattice_slots) == 0:
|
||||
to_index = 0
|
||||
|
||||
scene.lattice_slots.add()
|
||||
scene.lattice_slots.move(len(scene.lattice_slots) - 1, to_index)
|
||||
scene.active_lattice_index = to_index
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_remove(bpy.types.Operator):
|
||||
"""Remove Lattice Slot along with its Lattice object, animation and modifiers"""
|
||||
|
||||
bl_idname = "lattice.remove_slot"
|
||||
bl_label = "Remove Lattice Slot"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
index: IntProperty()
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
scene = context.scene
|
||||
if len(scene.lattice_slots) > 0:
|
||||
return True
|
||||
|
||||
cls.poll_message_set("No slots to remove.")
|
||||
return False
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
lattice_slots = scene.lattice_slots
|
||||
active_index = scene.active_lattice_index
|
||||
# This behaviour is inconsistent with other UILists in Blender, but I am right and they are wrong!
|
||||
active_slot = lattice_slots[active_index]
|
||||
if active_slot.lattice:
|
||||
bpy.ops.lattice.delete_lattice_from_slot()
|
||||
to_index = active_index
|
||||
if to_index > len(lattice_slots) - 2:
|
||||
to_index = len(lattice_slots) - 2
|
||||
|
||||
scene.lattice_slots.remove(self.index)
|
||||
scene.active_lattice_index = to_index
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_move(bpy.types.Operator):
|
||||
"""Move Lattice Slot"""
|
||||
|
||||
bl_idname = "lattice.move_slot"
|
||||
bl_label = "Move Lattice Slot"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
direction: EnumProperty(
|
||||
name="Direction",
|
||||
items=[
|
||||
('UP', 'UP', 'UP'),
|
||||
('DOWN', 'DOWN', 'DOWN'),
|
||||
],
|
||||
default='UP',
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
scene = context.scene
|
||||
if len(scene.lattice_slots) > 1:
|
||||
return True
|
||||
|
||||
cls.poll_message_set("No slots to re-order.")
|
||||
return False
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
lattice_slots = scene.lattice_slots
|
||||
active_index = scene.active_lattice_index
|
||||
to_index = active_index + (1 if self.direction == 'DOWN' else -1)
|
||||
|
||||
if to_index > len(lattice_slots) - 1:
|
||||
to_index = 0
|
||||
if to_index < 0:
|
||||
to_index = len(lattice_slots) - 1
|
||||
|
||||
scene.lattice_slots.move(active_index, to_index)
|
||||
scene.active_lattice_index = to_index
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_generate(bpy.types.Operator):
|
||||
"""Generate a lattice to smear the selected collection from the selected camera"""
|
||||
|
||||
bl_idname = "lattice.generate_lattice_for_slot"
|
||||
bl_label = "Generate Lattice"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
|
||||
if not active_slot.collection:
|
||||
cls.poll_message_set("A collection must be selected above.")
|
||||
return False
|
||||
if not active_slot.camera:
|
||||
cls.poll_message_set("A camera must be selected above.")
|
||||
return False
|
||||
if active_slot.lattice:
|
||||
cls.poll_message_set("This slot already has a lattice generated for it. You can delete it above if you wish to re-generate it.")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
|
||||
collection = active_slot.collection
|
||||
camera = active_slot.camera
|
||||
resolution = active_slot.resolution
|
||||
|
||||
if context.active_object and context.active_object.mode != 'OBJECT':
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
|
||||
# Create a lattice object.
|
||||
lattice_name = "Lattice_" + collection.name
|
||||
lattice = bpy.data.lattices.new(lattice_name)
|
||||
lattice_ob = bpy.data.objects.new(lattice_name, lattice)
|
||||
scene.collection.objects.link(lattice_ob)
|
||||
active_slot.lattice = lattice_ob
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
context.view_layer.objects.active = lattice_ob
|
||||
lattice_ob.select_set(True)
|
||||
|
||||
# Align to camera (not really needed).
|
||||
lattice_ob.rotation_euler = camera.matrix_world.to_euler()
|
||||
|
||||
# Parent to camera.
|
||||
lattice_ob.parent = camera
|
||||
lattice_ob.matrix_parent_inverse = camera.matrix_world.inverted()
|
||||
# Constrain to camera.
|
||||
constraint = lattice_ob.constraints.new('DAMPED_TRACK')
|
||||
constraint.target = camera
|
||||
constraint.track_axis = 'TRACK_Z'
|
||||
|
||||
### Placing the Lattice in the center of the camera's view, at the bounding box center of the collection's objects.
|
||||
# Find the bounding box center of the collection of objects
|
||||
all_meshes = [o for o in collection.all_objects if o.type == 'MESH']
|
||||
center = bounding_box_center_of_objects(all_meshes)
|
||||
|
||||
# Define a line from the camera towards the camera's view direction
|
||||
cam_vec = Vector((0, 0, -1)) # Default aim vector of a camera (they point straight down)
|
||||
# Rotate the default vector by the camera's rotation
|
||||
cam_vec.rotate(camera.matrix_world.to_euler())
|
||||
cam_world_pos = camera.matrix_world.to_translation()
|
||||
cam_target_pos = cam_world_pos + cam_vec
|
||||
|
||||
# Find the nearest point on this line to the bounding box center
|
||||
intersect = intersect_point_line(center, cam_world_pos, cam_target_pos)[0]
|
||||
|
||||
# This is where the Lattice is placed!
|
||||
lattice_ob.location = intersect
|
||||
|
||||
# Scale the lattice so that it fills up the camera's view
|
||||
# based on the distance of this point from the camera and the scene's aspect ratio.
|
||||
# https://fullpipeumbrella.com/en/blender-python-script-how-to-position/
|
||||
distance = (intersect - cam_world_pos).length
|
||||
fov = camera.data.angle
|
||||
|
||||
scale_x = distance * math.sin(fov / 2) / math.cos(fov / 2) * 2
|
||||
aspect_ratio = (scene.render.resolution_x * scene.render.pixel_aspect_x) / (
|
||||
scene.render.resolution_y * scene.render.pixel_aspect_y
|
||||
)
|
||||
scale_y = scale_x / aspect_ratio
|
||||
lattice_ob.scale = [scale_x, scale_y, 1]
|
||||
|
||||
# Set lattice resolution
|
||||
lattice.points_u = resolution
|
||||
lattice.points_v = round(resolution / aspect_ratio)
|
||||
lattice.points_w = 1
|
||||
|
||||
# Create two shape keys.
|
||||
bpy.ops.lattice.smear_add_shape()
|
||||
bpy.ops.lattice.smear_add_shape()
|
||||
|
||||
# Add Lattice modifiers
|
||||
for ob in all_meshes:
|
||||
# Skip those meshes which are already being deformed by another mesh in the same collection.
|
||||
skip = False
|
||||
for m in ob.modifiers:
|
||||
if m.type == 'MESH_DEFORM' and m.object in all_meshes:
|
||||
skip = True
|
||||
break
|
||||
if m.type == 'SURFACE_DEFORM' and m.target in all_meshes:
|
||||
skip = True
|
||||
break
|
||||
if not ob.visible_get():
|
||||
skip = True
|
||||
if skip:
|
||||
continue
|
||||
|
||||
mod = ob.modifiers.new(name=lattice_ob.name, type='LATTICE')
|
||||
mod.object = lattice_ob
|
||||
# Add drivers for easy disabling
|
||||
index = len(scene.lattice_slots) - 1
|
||||
|
||||
driver = ob.driver_add(f'modifiers["{lattice_ob.name}"].strength').driver
|
||||
driver.type = 'SUM'
|
||||
var = driver.variables.new()
|
||||
var.targets[0].id_type = 'SCENE'
|
||||
var.targets[0].id = scene
|
||||
var.targets[0].data_path = f'lattice_slots[{index}].strength'
|
||||
|
||||
driver = ob.driver_add(f'modifiers["{lattice_ob.name}"].show_viewport').driver
|
||||
driver.type = 'SUM'
|
||||
var = driver.variables.new()
|
||||
var.targets[0].id_type = 'SCENE'
|
||||
var.targets[0].id = scene
|
||||
var.targets[0].data_path = f'lattice_slots[{index}].enabled'
|
||||
|
||||
driver = ob.driver_add(f'modifiers["{lattice_ob.name}"].show_render').driver
|
||||
driver.type = 'SUM'
|
||||
var = driver.variables.new()
|
||||
var.targets[0].id_type = 'SCENE'
|
||||
var.targets[0].id = scene
|
||||
var.targets[0].data_path = f'lattice_slots[{index}].enabled'
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_delete(bpy.types.Operator):
|
||||
"""Delete Lattice object, its animation and modifiers that target it in the selected collection's objects"""
|
||||
|
||||
bl_idname = "lattice.delete_lattice_from_slot"
|
||||
bl_label = "Delete Lattice"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
|
||||
if not active_slot.lattice:
|
||||
cls.poll_message_set("This slot has no lattice to delete.")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
lattice_ob = active_slot.lattice
|
||||
lattice = lattice_ob.data
|
||||
|
||||
# Delete modifiers and their drivers
|
||||
collection = active_slot.collection
|
||||
for ob in collection.all_objects:
|
||||
if not ob.type == 'MESH':
|
||||
continue
|
||||
for m in ob.modifiers[:]:
|
||||
if not (m.type == 'LATTICE' and m.object == lattice_ob):
|
||||
continue
|
||||
ob.driver_remove(f'modifiers["{m.name}"].strength')
|
||||
ob.driver_remove(f'modifiers["{m.name}"].show_viewport')
|
||||
ob.driver_remove(f'modifiers["{m.name}"].show_render')
|
||||
ob.modifiers.remove(m)
|
||||
|
||||
# Delete animation datablocks
|
||||
datablocks = [lattice, lattice_ob, lattice.shape_keys]
|
||||
for datablock in datablocks:
|
||||
if not datablock:
|
||||
continue
|
||||
if not datablock.animation_data:
|
||||
continue
|
||||
if not datablock.animation_data.action:
|
||||
continue
|
||||
bpy.data.actions.remove(datablock.animation_data.action)
|
||||
|
||||
# Delte Lattice datablock
|
||||
bpy.data.objects.remove(lattice_ob)
|
||||
|
||||
# Delete Object datablock
|
||||
bpy.data.lattices.remove(lattice)
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_shapekey_add(bpy.types.Operator):
|
||||
"""Add a shape key to the active Lattice Slot's lattice, named after the current frame number"""
|
||||
|
||||
bl_idname = "lattice.smear_add_shape"
|
||||
bl_label = "Add Smear Shape"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
lattice_ob = active_slot.lattice
|
||||
lattice = lattice_ob.data
|
||||
|
||||
name = "Basis"
|
||||
if lattice.shape_keys:
|
||||
name = "Frame " + str(scene.frame_current)
|
||||
lattice_ob.shape_key_add(name=name, from_mix=False)
|
||||
lattice_ob.active_shape_key_index = len(lattice.shape_keys.key_blocks) - 1
|
||||
block = lattice.shape_keys.key_blocks[-1]
|
||||
block.value = 1
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
def shape_key_poll(context):
|
||||
ob = context.object
|
||||
if not ob or ob.type != 'LATTICE':
|
||||
return False
|
||||
if not ob.data.shape_keys or len(ob.data.shape_keys.key_blocks) < 2:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_zero_all(bpy.types.Operator):
|
||||
"""Set all shape key values to 0"""
|
||||
|
||||
bl_idname = "lattice.shape_keys_zero_all"
|
||||
bl_label = "Zero All Shape Keys"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
return shape_key_poll(context)
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
lattice_ob = active_slot.lattice
|
||||
lattice = lattice_ob.data
|
||||
|
||||
for sk in lattice.shape_keys.key_blocks:
|
||||
sk.value = 0
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_camlattice_keyframe_all(bpy.types.Operator):
|
||||
"""Insert a keyframe on the current frame for all shape key values"""
|
||||
|
||||
bl_idname = "lattice.shape_keys_keyframe_all"
|
||||
bl_label = "Keyframe All Shape Keys"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
return shape_key_poll(context)
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
lattice_ob = active_slot.lattice
|
||||
lattice = lattice_ob.data
|
||||
|
||||
for sk in lattice.shape_keys.key_blocks:
|
||||
sk.keyframe_insert('value')
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class VIEW3D_PT_camlattice_panel(bpy.types.Panel):
|
||||
bl_space_type = 'VIEW_3D'
|
||||
bl_region_type = 'UI'
|
||||
bl_category = 'Lattice Magic'
|
||||
bl_label = "Camera Lattice"
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
return True
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.use_property_split = True
|
||||
layout.use_property_decorate = False
|
||||
scene = context.scene
|
||||
active_index = scene.active_lattice_index
|
||||
|
||||
row = layout.row()
|
||||
row.template_list(
|
||||
'CAMLAT_UL_lattice_slots',
|
||||
'',
|
||||
scene,
|
||||
'lattice_slots',
|
||||
scene,
|
||||
'active_lattice_index',
|
||||
)
|
||||
|
||||
col = row.column()
|
||||
col.operator(OBJECT_OT_camlattice_add.bl_idname, text="", icon='ADD')
|
||||
remove_op = col.operator(OBJECT_OT_camlattice_remove.bl_idname, text="", icon='REMOVE')
|
||||
remove_op.index = active_index
|
||||
col.separator()
|
||||
move_up_op = col.operator(OBJECT_OT_camlattice_move.bl_idname, text="", icon='TRIA_UP')
|
||||
move_up_op.direction = 'UP'
|
||||
move_down_op = col.operator(OBJECT_OT_camlattice_move.bl_idname, text="", icon='TRIA_DOWN')
|
||||
move_down_op.direction = 'DOWN'
|
||||
|
||||
if len(scene.lattice_slots) == 0:
|
||||
return
|
||||
|
||||
active_slot = scene.lattice_slots[scene.active_lattice_index]
|
||||
|
||||
col = layout.column()
|
||||
if active_slot.lattice:
|
||||
col.enabled = False
|
||||
row = col.row()
|
||||
if not active_slot.collection:
|
||||
row.alert = True
|
||||
row.prop(active_slot, 'collection')
|
||||
row = col.row()
|
||||
if not active_slot.camera:
|
||||
row.alert = True
|
||||
row.prop(active_slot, 'camera', icon='OUTLINER_OB_CAMERA')
|
||||
col.prop(active_slot, 'resolution')
|
||||
|
||||
layout.separator()
|
||||
|
||||
if not active_slot.lattice:
|
||||
layout.operator(OBJECT_OT_camlattice_generate.bl_idname, icon='OUTLINER_OB_LATTICE')
|
||||
else:
|
||||
layout.operator(OBJECT_OT_camlattice_delete.bl_idname, icon='TRASH')
|
||||
|
||||
row = layout.row()
|
||||
row.enabled = False
|
||||
row.prop(active_slot, 'lattice')
|
||||
|
||||
if not active_slot.lattice:
|
||||
return
|
||||
|
||||
lattice_ob = active_slot.lattice
|
||||
lattice = lattice_ob.data
|
||||
|
||||
col = layout.column()
|
||||
|
||||
row = layout.row(align=True)
|
||||
row.operator(OBJECT_OT_camlattice_zero_all.bl_idname, text="", icon='RADIOBUT_OFF')
|
||||
row.operator(OBJECT_OT_camlattice_keyframe_all.bl_idname, text="", icon='HANDLETYPE_FREE_VEC')
|
||||
row.separator()
|
||||
prefs = get_addon_prefs(context)
|
||||
row.prop(prefs, 'update_active_shape_key', toggle=True, text="", icon='TIME')
|
||||
|
||||
row = layout.row()
|
||||
|
||||
# Display the lattice's Shape Keys in a less cluttered way than in the Properties editor.
|
||||
row.template_list(
|
||||
'MESH_UL_shape_keys',
|
||||
'',
|
||||
lattice.shape_keys,
|
||||
'key_blocks',
|
||||
lattice_ob,
|
||||
'active_shape_key_index',
|
||||
)
|
||||
|
||||
col = row.column()
|
||||
col.operator(OBJECT_OT_camlattice_shapekey_add.bl_idname, text="", icon='ADD')
|
||||
remove_op = col.operator('object.shape_key_remove', text="", icon='REMOVE')
|
||||
|
||||
col.separator()
|
||||
col.menu("MESH_MT_shape_key_context_menu", icon='DOWNARROW_HLT', text="")
|
||||
|
||||
col.separator()
|
||||
move_up_op = col.operator('object.shape_key_move', text="", icon='TRIA_UP')
|
||||
move_up_op.type = 'UP'
|
||||
move_down_op = col.operator('object.shape_key_move', text="", icon='TRIA_DOWN')
|
||||
move_down_op.type = 'DOWN'
|
||||
|
||||
|
||||
@persistent
|
||||
def camera_lattice_frame_change(scene):
|
||||
"""On frame change, set the active shape key of the active lattice object to the most recent frame
|
||||
|
||||
(Assuming the shape keys are named after the frame on which they are used)
|
||||
"""
|
||||
|
||||
# I wonder why this function doesn't recieve a context... should it not be relied on from here? o.0
|
||||
context = bpy.context
|
||||
|
||||
prefs = get_addon_prefs(context)
|
||||
if not prefs.update_active_shape_key:
|
||||
return
|
||||
|
||||
ob = context.object
|
||||
if not shape_key_poll(context):
|
||||
return
|
||||
|
||||
key_blocks = ob.data.shape_keys.key_blocks
|
||||
|
||||
current_frame = scene.frame_current
|
||||
most_recent_number = 0
|
||||
most_recent_index = 1
|
||||
for i, kb in enumerate(key_blocks):
|
||||
if not kb.name.startswith('Frame '):
|
||||
continue
|
||||
number_str = kb.name[5:].split(".")[0]
|
||||
if number_str == "":
|
||||
continue
|
||||
number = int(number_str)
|
||||
if number <= current_frame and number >= most_recent_number:
|
||||
most_recent_number = number
|
||||
most_recent_index = i
|
||||
if most_recent_number == current_frame:
|
||||
break
|
||||
|
||||
if ob.active_shape_key_index != most_recent_index:
|
||||
ob.active_shape_key_index = most_recent_index
|
||||
|
||||
|
||||
registry = [
|
||||
LatticeSlot,
|
||||
CAMLAT_UL_lattice_slots,
|
||||
OBJECT_OT_camlattice_add,
|
||||
OBJECT_OT_camlattice_remove,
|
||||
OBJECT_OT_camlattice_move,
|
||||
OBJECT_OT_camlattice_generate,
|
||||
OBJECT_OT_camlattice_delete,
|
||||
OBJECT_OT_camlattice_shapekey_add,
|
||||
OBJECT_OT_camlattice_zero_all,
|
||||
OBJECT_OT_camlattice_keyframe_all,
|
||||
VIEW3D_PT_camlattice_panel,
|
||||
]
|
||||
|
||||
|
||||
def register():
|
||||
bpy.types.Scene.lattice_slots = CollectionProperty(type=LatticeSlot)
|
||||
bpy.types.Scene.active_lattice_index = IntProperty()
|
||||
bpy.app.handlers.frame_change_post.append(camera_lattice_frame_change)
|
||||
|
||||
|
||||
def unregister():
|
||||
del bpy.types.Scene.lattice_slots
|
||||
del bpy.types.Scene.active_lattice_index
|
||||
|
||||
bpy.app.handlers.frame_change_post.remove(camera_lattice_frame_change)
|
||||
@@ -0,0 +1,104 @@
|
||||
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import bpy
|
||||
from bpy.props import FloatProperty
|
||||
from .utils import get_lattice_point_original_position
|
||||
|
||||
|
||||
class LATTICE_OT_reset(bpy.types.Operator):
|
||||
"""Reset selected lattice points to their default position"""
|
||||
|
||||
bl_idname = "lattice.reset_points"
|
||||
bl_label = "Reset Lattice Points"
|
||||
bl_options = {'REGISTER', 'UNDO'}
|
||||
|
||||
factor: FloatProperty(name="Factor", min=0, max=1, default=1)
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
return len(context.selected_objects) > 0
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.use_property_split = True
|
||||
layout.prop(self, 'factor', slider=True)
|
||||
|
||||
def execute(self, context):
|
||||
org_mode = context.active_object.mode
|
||||
check_selection = False
|
||||
if org_mode != 'OBJECT':
|
||||
if org_mode == 'EDIT':
|
||||
check_selection = True
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
|
||||
for ob in context.selected_objects:
|
||||
if ob.type != 'LATTICE':
|
||||
continue
|
||||
|
||||
# Resetting shape key or Basis shape
|
||||
if ob.data.shape_keys:
|
||||
active_index = ob.active_shape_key_index
|
||||
key_blocks = ob.data.shape_keys.key_blocks
|
||||
active_block = key_blocks[active_index]
|
||||
basis_block = key_blocks[0]
|
||||
if active_index > 0:
|
||||
for i, skp in enumerate(active_block.data):
|
||||
if check_selection and not ob.data.points[i].select:
|
||||
continue
|
||||
skp.co = skp.co.lerp(basis_block.data[i].co, self.factor)
|
||||
continue
|
||||
else:
|
||||
for i, skp in enumerate(active_block.data):
|
||||
if check_selection and not ob.data.points[i].select:
|
||||
continue
|
||||
base = get_lattice_point_original_position(ob.data, i)
|
||||
# Resetting the Basis shape
|
||||
mix = basis_block.data[i].co.lerp(base, self.factor)
|
||||
basis_block.data[i].co = mix
|
||||
continue
|
||||
|
||||
# Otherwise, reset the actual points.
|
||||
for i in range(len(ob.data.points)):
|
||||
point = ob.data.points[i]
|
||||
if not point.select:
|
||||
continue
|
||||
base = get_lattice_point_original_position(ob.data, i)
|
||||
mix = point.co_deform.lerp(base, self.factor)
|
||||
point.co_deform = mix
|
||||
|
||||
if org_mode != 'OBJECT':
|
||||
bpy.ops.object.mode_set(mode=org_mode)
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
def draw_shape_key_reset(self, context):
|
||||
layout = self.layout
|
||||
ob = context.object
|
||||
if ob.type == 'MESH' and ob.data and ob.data.shape_keys:
|
||||
op = layout.operator('mesh.blend_from_shape', text='Reset Shape Key', icon='FILE_REFRESH')
|
||||
# op.shape = ob.data.shape_keys.key_blocks[0].name
|
||||
op.blend = 1
|
||||
op.add = False
|
||||
else:
|
||||
layout.operator(LATTICE_OT_reset.bl_idname, text="Reset Shape Key", icon='FILE_REFRESH')
|
||||
|
||||
|
||||
def draw_lattice_reset(self, context):
|
||||
self.layout.operator(
|
||||
LATTICE_OT_reset.bl_idname, text="Reset Point Positions", icon='FILE_REFRESH'
|
||||
)
|
||||
|
||||
|
||||
registry = [LATTICE_OT_reset]
|
||||
|
||||
|
||||
def register():
|
||||
bpy.types.MESH_MT_shape_key_context_menu.append(draw_shape_key_reset)
|
||||
bpy.types.VIEW3D_MT_edit_lattice.append(draw_lattice_reset)
|
||||
|
||||
|
||||
def unregister():
|
||||
bpy.types.MESH_MT_shape_key_context_menu.remove(draw_shape_key_reset)
|
||||
bpy.types.VIEW3D_MT_edit_lattice.remove(draw_lattice_reset)
|
||||
@@ -0,0 +1,23 @@
|
||||
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from bpy.types import AddonPreferences
|
||||
from bpy.props import BoolProperty
|
||||
from . import __package__ as base_package
|
||||
|
||||
class LatticeMagicPreferences(AddonPreferences):
|
||||
bl_idname = base_package
|
||||
|
||||
update_active_shape_key: BoolProperty(
|
||||
name='Update Active Shape Key',
|
||||
description="Update the active shape key on frame change based on the current frame and the shape key's name",
|
||||
default=False,
|
||||
)
|
||||
|
||||
|
||||
def get_addon_prefs(context=None):
|
||||
return context.preferences.addons[base_package].preferences
|
||||
|
||||
|
||||
registry = [LatticeMagicPreferences]
|
||||
@@ -0,0 +1,867 @@
|
||||
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# Inspired by https://twitter.com/soyposmoderno/status/1307222594047758337
|
||||
|
||||
# This lets you create an empty hooked up to a Lattice to deform all selected
|
||||
# objects. A root empty is also created that can be (manually) parented to a
|
||||
# rig in order to use this for animation.
|
||||
|
||||
import bpy
|
||||
from bpy.props import (
|
||||
FloatProperty,
|
||||
IntVectorProperty,
|
||||
PointerProperty,
|
||||
StringProperty,
|
||||
EnumProperty,
|
||||
)
|
||||
from bpy.types import (
|
||||
Operator,
|
||||
Object,
|
||||
Lattice,
|
||||
VertexGroup,
|
||||
Scene,
|
||||
Collection,
|
||||
Modifier,
|
||||
Panel,
|
||||
PropertyGroup,
|
||||
)
|
||||
from typing import List, Tuple
|
||||
|
||||
from mathutils import Matrix, Vector, kdtree
|
||||
from math import *
|
||||
|
||||
from rna_prop_ui import rna_idprop_ui_create
|
||||
|
||||
from .utils import clamp, get_lattice_vertex_index, simple_driver, bounding_box_center_of_objects
|
||||
|
||||
TWEAKLAT_COLL_NAME = 'Tweak Lattices'
|
||||
|
||||
FALLOFF_TYPES = {
|
||||
# Since these expressions manipulate the shape of the lattice,
|
||||
# which then manipulates the shape of the mesh,
|
||||
# it's hard to come up with these functions in any meaningful way.
|
||||
# So, it was done more so with artistic trial and error.
|
||||
'LINEAR': lambda x: x + x * 0.1,
|
||||
'CONSTANT': lambda x: 1,
|
||||
'SHARP': lambda x: pow(x, 2) * 1.25,
|
||||
'ROOT': lambda x: pow(x, 0.5) * 1.05,
|
||||
'SMOOTH': lambda x: (1 - cos(x * pi)) / 2,
|
||||
'SPHERE': lambda x: sin(pow(x, 0.5)) * 1.25,
|
||||
'DONUT': lambda x: (sin(pow(x, 0.5)) - pow(x, 2)) * 2.5,
|
||||
}
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_create(Operator):
|
||||
"""Create a lattice setup to deform selected objects"""
|
||||
|
||||
bl_idname = "lattice.create_tweak_lattice"
|
||||
bl_label = "Create Tweak Lattice"
|
||||
bl_options = {'REGISTER', 'UNDO'}
|
||||
|
||||
name: StringProperty(
|
||||
name="Name",
|
||||
description="A unique name to identify this tweak lattice. Used in helper objects and modifiers",
|
||||
default="Tweak",
|
||||
)
|
||||
|
||||
resolution: IntVectorProperty(name="Resolution", default=(25, 25, 25), min=6, max=64)
|
||||
|
||||
location: EnumProperty(
|
||||
name="Location",
|
||||
items=[
|
||||
('CURSOR', "3D Cursor", "Create at the location and orientation of the 3D cursor."),
|
||||
('CENTER', "Center", "Create at the bounding box center of all selected objects."),
|
||||
('PARENT', "Parent", "Create at the location of the parent object or bone."),
|
||||
],
|
||||
)
|
||||
radius: FloatProperty(
|
||||
name="Radius",
|
||||
description="Radius of influence of this lattice. Can be changed later",
|
||||
default=0.1,
|
||||
min=0.0001,
|
||||
max=1000,
|
||||
soft_max=2,
|
||||
)
|
||||
|
||||
parent_method: EnumProperty(
|
||||
name="Parent Method",
|
||||
description="How to parent the tweak lattice",
|
||||
items=[
|
||||
(
|
||||
'AUTO',
|
||||
'Automatic',
|
||||
"Parent using an Armature constraint which mimics the deformation of the nearest vertex to the cursor",
|
||||
),
|
||||
(
|
||||
'MANUAL',
|
||||
'Manual',
|
||||
"Manually select a single object or bone as the tweak lattice parent",
|
||||
),
|
||||
],
|
||||
default='AUTO',
|
||||
)
|
||||
parent_bone: StringProperty(name="Bone", description="Bone to use as parent")
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
for ob in context.selected_objects:
|
||||
if ob.type == 'MESH':
|
||||
return True
|
||||
|
||||
cls.poll_message_set("No selected mesh objects.")
|
||||
return False
|
||||
|
||||
def invoke(self, context, _event):
|
||||
parent_obj = context.object
|
||||
for m in parent_obj.modifiers:
|
||||
if m.type == 'ARMATURE' and m.object:
|
||||
parent_obj = m.object
|
||||
if self.parent_bone not in parent_obj.data.bones:
|
||||
self.parent_bone = ""
|
||||
break
|
||||
|
||||
context.scene.tweak_lattice_parent_ob = parent_obj
|
||||
|
||||
wm = context.window_manager
|
||||
return wm.invoke_props_dialog(self, width=400)
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.use_property_split = True
|
||||
layout.use_property_decorate = False
|
||||
|
||||
layout.prop(self, 'name')
|
||||
layout.separator()
|
||||
|
||||
layout.prop(self, 'location', expand=True)
|
||||
layout.prop(self, 'radius', slider=True)
|
||||
layout.separator()
|
||||
|
||||
layout.prop(self, 'parent_method', expand=True)
|
||||
|
||||
if self.parent_method == 'MANUAL':
|
||||
col = layout.column(align=True)
|
||||
col.prop(context.scene, 'tweak_lattice_parent_ob')
|
||||
|
||||
scene = context.scene
|
||||
if scene.tweak_lattice_parent_ob and scene.tweak_lattice_parent_ob.type == 'ARMATURE':
|
||||
col.prop_search(self, 'parent_bone', scene.tweak_lattice_parent_ob.data, 'bones')
|
||||
|
||||
def execute(self, context):
|
||||
scene = context.scene
|
||||
|
||||
# Ensure a collection to organize all our objects in.
|
||||
coll = ensure_tweak_lattice_collection(context.scene)
|
||||
|
||||
# Create a lattice object at the 3D cursor.
|
||||
lattice_name = f"LTC-{self.name}"
|
||||
lattice = bpy.data.lattices.new(lattice_name)
|
||||
lattice_ob = bpy.data.objects.new(lattice_name, lattice)
|
||||
coll.objects.link(lattice_ob)
|
||||
|
||||
# Set resolution
|
||||
set_lattice_resolution(lattice_ob, *self.resolution)
|
||||
lattice_ob.hide_viewport = True
|
||||
|
||||
# Create a falloff vertex group.
|
||||
vg = ensure_falloff_vgroup(lattice_ob, vg_name="Hook", func=FALLOFF_TYPES['SMOOTH'])
|
||||
|
||||
# Create the Hook Empty.
|
||||
hook_name = "Hook_" + lattice_ob.name
|
||||
hook = bpy.data.objects.new(hook_name, None)
|
||||
hook.empty_display_type = 'SPHERE'
|
||||
hook.empty_display_size = 0.5
|
||||
coll.objects.link(hook)
|
||||
|
||||
# Create some custom properties.
|
||||
hook['Lattice'] = lattice_ob
|
||||
lattice_ob['Hook'] = hook
|
||||
hook['Strength'] = 1.0
|
||||
|
||||
rna_idprop_ui_create(
|
||||
hook,
|
||||
"Influence",
|
||||
default=1.0,
|
||||
min=0,
|
||||
max=1,
|
||||
description="Influence of this lattice on all of its target objects",
|
||||
)
|
||||
rna_idprop_ui_create(
|
||||
hook,
|
||||
"Radius",
|
||||
default=self.radius,
|
||||
min=0,
|
||||
soft_max=0.2,
|
||||
max=100,
|
||||
description="Size of the influenced area",
|
||||
)
|
||||
|
||||
# Create a Root Empty to parent both the hook and the lattice to.
|
||||
# This will allow pressing Alt+G/R/S on the hook to reset its transforms.
|
||||
root_name = "Root_" + hook.name
|
||||
root = bpy.data.objects.new(root_name, None)
|
||||
root['Hook'] = hook
|
||||
root.empty_display_type = 'CUBE'
|
||||
root.empty_display_size = 0.5
|
||||
coll.objects.link(root)
|
||||
hook['Root'] = root
|
||||
|
||||
self.set_parent_and_transform(context, root)
|
||||
|
||||
# Disable the root from view.
|
||||
# NOTE: This must be done AFTER any reliance on view_layer.update() calls!
|
||||
# They don't work when the object is disabled!
|
||||
root.hide_viewport = True
|
||||
|
||||
# Parent lattice and hook to root.
|
||||
lattice_ob.parent = root
|
||||
hook.parent = root
|
||||
|
||||
# Add Hook modifier to the lattice.
|
||||
hook_mod = lattice_ob.modifiers.new(name="Hook", type='HOOK')
|
||||
hook_mod.object = hook
|
||||
hook_mod.vertex_group = vg.name
|
||||
|
||||
# Add Lattice modifier to the selected objects
|
||||
add_objects_to_lattice(hook, context.selected_objects)
|
||||
|
||||
# Set up Radius control.
|
||||
add_radius_constraint(hook, hook, root)
|
||||
add_radius_constraint(lattice_ob, hook, root)
|
||||
|
||||
root_drv = simple_driver(root, 'empty_display_size', hook, '["Radius"]')
|
||||
root_drv.expression = 'var/2'
|
||||
|
||||
# Deselect everything, select the hook and make it active
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
hook.select_set(True)
|
||||
context.view_layer.objects.active = hook
|
||||
|
||||
# Clear the parent selector helper property.
|
||||
scene.tweak_lattice_parent_ob = None
|
||||
return {'FINISHED'}
|
||||
|
||||
def set_parent_and_transform(self, context, root):
|
||||
scene = context.scene
|
||||
depsgraph = context.evaluated_depsgraph_get()
|
||||
|
||||
matrix_of_parent = self.get_lattice_parent_matrix(context)
|
||||
|
||||
root.matrix_world = matrix_of_parent.copy()
|
||||
context.view_layer.update()
|
||||
mat_pre_arm_con = root.matrix_world.copy()
|
||||
|
||||
if self.parent_method == 'AUTO':
|
||||
# Parent to the nearest deforming vertex.
|
||||
nearest_vertex = get_nearest_evaluated_vertex(
|
||||
dg=depsgraph,
|
||||
coord=matrix_of_parent.copy().to_translation(),
|
||||
objs=context.selected_objects,
|
||||
)
|
||||
obj, eval_obj, vert_idx, _vert_co = nearest_vertex
|
||||
|
||||
root.parent = obj.find_armature() or obj
|
||||
weights = get_deforming_weights(obj, eval_obj, vert_idx)
|
||||
else:
|
||||
root.parent = scene.tweak_lattice_parent_ob
|
||||
weights = {}
|
||||
if self.parent_bone:
|
||||
weights = {self.parent_bone: 1.0}
|
||||
|
||||
if weights:
|
||||
arm_con = root.constraints.new(type='ARMATURE')
|
||||
for bone_name, weight in weights.items():
|
||||
tgt = arm_con.targets.new()
|
||||
tgt.target = root.parent
|
||||
tgt.subtarget = bone_name
|
||||
tgt.weight = weight
|
||||
|
||||
context.view_layer.update()
|
||||
mat_post_arm_con = root.matrix_world.copy()
|
||||
|
||||
delta = mat_pre_arm_con.inverted() @ mat_post_arm_con
|
||||
|
||||
root.matrix_world = matrix_of_parent @ delta.inverted()
|
||||
|
||||
if self.parent_method != 'AUTO' or self.location != 'CURSOR':
|
||||
root.rotation_euler = 0, 0, 0
|
||||
|
||||
def get_lattice_parent_matrix(self, context):
|
||||
location = self.location
|
||||
parent_bone = self.parent_bone
|
||||
scene = context.scene
|
||||
|
||||
if location == 'CENTER':
|
||||
meshes = [o for o in context.selected_objects if o.type == 'MESH']
|
||||
mat = Matrix.Identity((4))
|
||||
mat.translation = bounding_box_center_of_objects(meshes)
|
||||
return mat
|
||||
elif location == 'CURSOR':
|
||||
return context.scene.cursor.matrix.copy()
|
||||
elif location == 'PARENT':
|
||||
ob_mat = scene.tweak_lattice_parent_ob.matrix_world
|
||||
if parent_bone:
|
||||
bone_mat = scene.tweak_lattice_parent_ob.pose.bones[parent_bone].matrix
|
||||
return ob_mat @ bone_mat
|
||||
else:
|
||||
return ob_mat
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_duplicate(Operator):
|
||||
"""Duplicate this Tweak Lattice set-up"""
|
||||
|
||||
bl_idname = "lattice.duplicate_tweak_setup"
|
||||
bl_label = "Duplicate Tweak Lattice"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
def execute(self, context):
|
||||
hook, lattice, root = get_tweak_setup(context.object)
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
|
||||
affected_objects = get_objects_of_lattice(hook)
|
||||
|
||||
visibilities = {}
|
||||
for ob in [hook, lattice, root]:
|
||||
ob.hide_set(False)
|
||||
visibilities[ob] = ob.hide_viewport
|
||||
ob.hide_viewport = False
|
||||
if not ob.visible_get():
|
||||
self.report({'ERROR'}, f'Object "{ob.name}" could not be made visible, cancelling.')
|
||||
return {'CANCELLED'}
|
||||
ob.select_set(True)
|
||||
|
||||
context.view_layer.objects.active = hook
|
||||
|
||||
bpy.ops.object.duplicate()
|
||||
new_hook, new_lattice, new_root = get_tweak_setup(context.object)
|
||||
|
||||
for key, value in list(new_hook.items()):
|
||||
if key.startswith("object_"):
|
||||
del new_hook[key]
|
||||
|
||||
add_objects_to_lattice(new_hook, affected_objects)
|
||||
|
||||
# Restore visibilities
|
||||
for ob, new_ob in zip((hook, lattice, root), (new_hook, new_lattice, new_root)):
|
||||
ob.hide_viewport = new_ob.hide_viewport = visibilities[ob]
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class TweakLatticeProperties(PropertyGroup):
|
||||
def update_falloff(self, context):
|
||||
falloff_func = FALLOFF_TYPES[self.falloff_type]
|
||||
|
||||
hook, lattice, _root = get_tweak_setup(context.active_object)
|
||||
ensure_falloff_vgroup(lattice, 'Hook', multiplier=self.strength, func=falloff_func)
|
||||
hook['Strength'] = self.strength
|
||||
|
||||
strength: FloatProperty(
|
||||
name="Strength",
|
||||
description="A multiplier on the weight values",
|
||||
default=1,
|
||||
update=update_falloff,
|
||||
min=0,
|
||||
soft_max=2,
|
||||
)
|
||||
falloff_type: EnumProperty(
|
||||
name="Falloff Shape",
|
||||
description="Choose shape of influence for this lattice",
|
||||
items=[
|
||||
('LINEAR', 'Linear', 'Linear'),
|
||||
('CONSTANT', 'Constant', 'Constant'),
|
||||
('SHARP', 'Sharp', 'Sharp'),
|
||||
('ROOT', 'Root', 'Root'),
|
||||
('SMOOTH', 'Smooth', 'Smooth'),
|
||||
('SPHERE', 'Sphere', 'Sphere'),
|
||||
('DONUT', 'Donut', 'Donut'),
|
||||
],
|
||||
default='SMOOTH',
|
||||
update=update_falloff,
|
||||
)
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_delete(Operator):
|
||||
"""Delete a tweak lattice setup with all its helper objects, drivers, etc"""
|
||||
|
||||
bl_idname = "lattice.delete_tweak_lattice"
|
||||
bl_label = "Delete Tweak Lattice"
|
||||
bl_options = {'REGISTER', 'UNDO'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
hook, lattice, root = get_tweak_setup(context.object)
|
||||
if hook and lattice and root:
|
||||
return True
|
||||
|
||||
cls.poll_message_set("Tweak Lattice set-up is incomplete. Some objects were manually deleted.")
|
||||
return False
|
||||
|
||||
def execute(self, context):
|
||||
hook, lattice, root = get_tweak_setup(context.object)
|
||||
|
||||
# Remove Lattice modifiers and their drivers.
|
||||
remove_all_objects_from_lattice(hook)
|
||||
|
||||
# Remove hook Action if exists.
|
||||
if hook.animation_data and hook.animation_data.action:
|
||||
bpy.data.actions.remove(hook.animation_data.action)
|
||||
|
||||
# Remove objects and Lattice datablock.
|
||||
bpy.data.objects.remove(hook)
|
||||
lattice_data = lattice.data
|
||||
bpy.data.objects.remove(lattice)
|
||||
bpy.data.lattices.remove(lattice_data)
|
||||
bpy.data.objects.remove(root)
|
||||
|
||||
# Remove the collection if it's empty.
|
||||
coll = bpy.data.collections.get(TWEAKLAT_COLL_NAME)
|
||||
if coll and len(coll.all_objects) == 0:
|
||||
bpy.data.collections.remove(coll)
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_objects_add(Operator):
|
||||
"""Add selected objects to this tweak lattice"""
|
||||
|
||||
bl_idname = "lattice.add_selected_objects"
|
||||
bl_label = "Add Selected Objects"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
if not hook:
|
||||
cls.poll_message_set("Cannot find hook object of this Tweak Lattice set-up. Perhaps it was deleted?")
|
||||
return False
|
||||
|
||||
values = hook.values()
|
||||
for sel_o in context.selected_objects:
|
||||
if sel_o == hook or sel_o.type != 'MESH':
|
||||
continue
|
||||
if sel_o not in values:
|
||||
return True
|
||||
|
||||
cls.poll_message_set("No selected objects to add to this Tweak Lattice.")
|
||||
return False
|
||||
|
||||
def execute(self, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
|
||||
# Add Lattice modifier to the selected objects
|
||||
add_objects_to_lattice(hook, context.selected_objects)
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_objects_remove(Operator):
|
||||
"""Remove selected objects from this tweak lattice"""
|
||||
|
||||
bl_idname = "lattice.remove_selected_objects"
|
||||
bl_label = "Remove Selected Objects"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
if not hook:
|
||||
cls.poll_message_set("Cannot find hook object of this Tweak Lattice set-up. Perhaps it was deleted?")
|
||||
return False
|
||||
|
||||
values = hook.values()
|
||||
for sel_o in context.selected_objects:
|
||||
if sel_o == hook or sel_o.type != 'MESH':
|
||||
continue
|
||||
if sel_o in values:
|
||||
return True
|
||||
|
||||
cls.poll_message_set("No selected objects to remove from this Tweak Lattice.")
|
||||
return False
|
||||
|
||||
def execute(self, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
|
||||
# Add Lattice modifier to the selected objects
|
||||
remove_objects_from_lattice(hook, context.selected_objects)
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class OBJECT_OT_tweaklattice_object_remove_single(Operator):
|
||||
"""Remove this object from the tweak lattice"""
|
||||
|
||||
bl_idname = "lattice.remove_object"
|
||||
bl_label = "Remove Object"
|
||||
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
|
||||
|
||||
ob_pointer_prop_name: StringProperty(
|
||||
description="Name of the custom property that references the object that should be removed"
|
||||
)
|
||||
|
||||
def execute(self, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
target = hook[self.ob_pointer_prop_name]
|
||||
|
||||
# Add Lattice modifier to the selected objects
|
||||
remove_objects_from_lattice(hook, [target])
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class VIEW3D_PT_tweak_lattice(Panel):
|
||||
bl_space_type = 'VIEW_3D'
|
||||
bl_region_type = 'UI'
|
||||
bl_category = 'Lattice Magic'
|
||||
bl_label = "Tweak Lattice"
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
hook, _lattice, _root = get_tweak_setup(context.object)
|
||||
|
||||
return context.object and context.object.type == 'MESH' or hook
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.use_property_split = True
|
||||
layout.use_property_decorate = False
|
||||
|
||||
hook, lattice, root = get_tweak_setup(context.object)
|
||||
|
||||
layout = layout.column()
|
||||
if not hook:
|
||||
layout.operator(OBJECT_OT_tweaklattice_create.bl_idname, icon='OUTLINER_OB_LATTICE')
|
||||
return
|
||||
|
||||
layout.prop(hook, '["Influence"]', slider=True, text="Influence")
|
||||
layout.prop(hook["Lattice"].data.lattice_magic, 'strength')
|
||||
layout.separator()
|
||||
|
||||
layout.prop(hook["Lattice"].data.lattice_magic, 'falloff_type')
|
||||
layout.prop(hook, '["Radius"]', slider=True)
|
||||
|
||||
layout.separator()
|
||||
layout.operator(
|
||||
OBJECT_OT_tweaklattice_delete.bl_idname, text='Delete Tweak Lattice', icon='TRASH'
|
||||
)
|
||||
layout.operator(
|
||||
OBJECT_OT_tweaklattice_duplicate.bl_idname,
|
||||
text='Duplicate Tweak Lattice',
|
||||
icon='DUPLICATE',
|
||||
)
|
||||
|
||||
layout.separator()
|
||||
layout.label(text="Helper Objects")
|
||||
lattice_row = layout.row()
|
||||
lattice_row.prop(hook, '["Lattice"]', text="Lattice")
|
||||
lattice_row.prop(lattice, 'hide_viewport', text="", emboss=False)
|
||||
|
||||
root_row = layout.row()
|
||||
root_row.prop(hook, '["Root"]', text="Root")
|
||||
root_row.prop(root, 'hide_viewport', text="", emboss=False)
|
||||
|
||||
layout.separator()
|
||||
layout.label(text="Parenting")
|
||||
col = layout.column()
|
||||
col.enabled = False
|
||||
col.prop(root, 'parent')
|
||||
if root.parent and root.parent.type == 'ARMATURE':
|
||||
col.prop(root, 'parent_bone', icon='BONE_DATA')
|
||||
|
||||
layout.separator()
|
||||
layout.label(text="Affected Objects")
|
||||
|
||||
num_to_add = 0
|
||||
for o in context.selected_objects:
|
||||
if o == hook or o.type != 'MESH':
|
||||
continue
|
||||
if o in hook.values():
|
||||
continue
|
||||
num_to_add += 1
|
||||
if num_to_add == 1:
|
||||
text = f"Add {o.name}"
|
||||
if num_to_add:
|
||||
if num_to_add > 1:
|
||||
text = f"Add {num_to_add} Objects"
|
||||
layout.operator(OBJECT_OT_tweaklattice_objects_add.bl_idname, icon='ADD', text=text)
|
||||
|
||||
layout.separator()
|
||||
num_to_remove = False
|
||||
for o in context.selected_objects:
|
||||
if o == hook or o.type != 'MESH':
|
||||
continue
|
||||
if o not in hook.values():
|
||||
continue
|
||||
num_to_remove += 1
|
||||
if num_to_remove == 1:
|
||||
text = f"Remove {o.name}"
|
||||
if num_to_remove:
|
||||
if num_to_remove > 1:
|
||||
text = f"Remove {num_to_remove} Objects"
|
||||
layout.operator(
|
||||
OBJECT_OT_tweaklattice_objects_remove.bl_idname, icon='REMOVE', text=text
|
||||
)
|
||||
|
||||
objects_and_keys = [(hook[key], key) for key in hook.keys() if "object_" in key]
|
||||
objects_and_keys.sort(key=lambda o_and_k: o_and_k[1])
|
||||
for ob, key in objects_and_keys:
|
||||
row = layout.row(align=True)
|
||||
row.prop(hook, f'["{key}"]', text="")
|
||||
mod = get_lattice_modifier_of_object(ob, lattice)
|
||||
if not mod:
|
||||
continue
|
||||
row.prop_search(mod, 'vertex_group', ob, 'vertex_groups', text="", icon='GROUP_VERTEX')
|
||||
op = row.operator(
|
||||
OBJECT_OT_tweaklattice_object_remove_single.bl_idname, text="", icon='X'
|
||||
)
|
||||
op.ob_pointer_prop_name = key
|
||||
|
||||
|
||||
def set_lattice_resolution(lat_ob: Object, res_u, res_v=None, res_w=None):
|
||||
assert lat_ob.type == 'LATTICE', f"This isn't a lattice object: {lat_ob.name}"
|
||||
|
||||
if not res_v:
|
||||
res_v = res_u
|
||||
if not res_w:
|
||||
res_w = res_u
|
||||
|
||||
lat_ob.data.points_u = res_u
|
||||
lat_ob.data.points_v = res_v
|
||||
lat_ob.data.points_w = res_w
|
||||
|
||||
|
||||
def build_kdtree(obj):
|
||||
# Get the vertices of the mesh in world coordinates
|
||||
vertices = [obj.matrix_world @ v.co for v in obj.data.vertices]
|
||||
|
||||
# Build KD-Tree from the vertices
|
||||
size = len(vertices)
|
||||
kd = kdtree.KDTree(size)
|
||||
|
||||
for i, vertex in enumerate(vertices):
|
||||
kd.insert(vertex, i)
|
||||
|
||||
kd.balance()
|
||||
return kd
|
||||
|
||||
|
||||
def get_nearest_evaluated_vertex(
|
||||
dg, coord: Vector, objs: list[Object]
|
||||
) -> tuple[Object, int, Vector]:
|
||||
"""Get nearest EVALUATED vertex to a coordinate out of a list of passed mesh objects.
|
||||
Return the original object, and the evaluated object, vertex index, and coordinate.
|
||||
"""
|
||||
nearest_vertex = None
|
||||
nearest_distance = float('inf')
|
||||
|
||||
for obj in objs:
|
||||
if obj.type != 'MESH':
|
||||
continue
|
||||
|
||||
eval_ob = obj.evaluated_get(dg)
|
||||
|
||||
kd = build_kdtree(eval_ob)
|
||||
|
||||
# Find the nearest vertex to the 3D cursor
|
||||
|
||||
eval_co, eval_idx, dist = kd.find(coord)
|
||||
|
||||
# If this vertex is closer than any previously found, store it
|
||||
if dist < nearest_distance:
|
||||
nearest_distance = dist
|
||||
nearest_vertex = (obj, eval_ob, eval_idx, eval_co)
|
||||
|
||||
return nearest_vertex
|
||||
|
||||
|
||||
def get_deforming_weights(obj: Object, eval_obj, vert_idx: int) -> dict[str, float] | None:
|
||||
armature = obj.find_armature()
|
||||
|
||||
if not armature:
|
||||
return
|
||||
|
||||
vertex = eval_obj.data.vertices[vert_idx]
|
||||
|
||||
weights = {}
|
||||
|
||||
# Loop through the vertex groups the vertex belongs to
|
||||
for group in vertex.groups:
|
||||
group_index = group.group
|
||||
group_weight = group.weight
|
||||
group_name = obj.vertex_groups[group_index].name
|
||||
pbone = armature.pose.bones.get(group_name)
|
||||
if pbone and pbone.bone.use_deform:
|
||||
weights[group_name] = group_weight
|
||||
|
||||
return weights
|
||||
|
||||
|
||||
def get_tweak_setup(obj: Object) -> Tuple[Object, Object, Object]:
|
||||
"""Based on either the hook, lattice or root, return all three."""
|
||||
if not obj:
|
||||
return [None, None, None]
|
||||
|
||||
if obj.type == 'EMPTY':
|
||||
if 'Root' and 'Lattice' in obj:
|
||||
return obj, obj['Lattice'], obj['Root']
|
||||
elif 'Hook' in obj:
|
||||
return obj['Hook'], obj['Hook']['Lattice'], obj
|
||||
elif obj.type == 'LATTICE' and 'Hook' in obj:
|
||||
return obj['Hook'], obj, obj['Hook']['Root']
|
||||
|
||||
return [None, None, None]
|
||||
|
||||
|
||||
def ensure_tweak_lattice_collection(scene: Scene) -> Collection:
|
||||
coll = bpy.data.collections.get(TWEAKLAT_COLL_NAME)
|
||||
if not coll:
|
||||
coll = bpy.data.collections.new(TWEAKLAT_COLL_NAME)
|
||||
scene.collection.children.link(coll)
|
||||
|
||||
return coll
|
||||
|
||||
|
||||
def ensure_falloff_vgroup(
|
||||
lattice_ob: Object, vg_name="Group", multiplier=1, func=lambda x: x
|
||||
) -> VertexGroup:
|
||||
lattice = lattice_ob.data
|
||||
res_x, res_y, res_z = lattice.points_u, lattice.points_v, lattice.points_w
|
||||
|
||||
vg = lattice_ob.vertex_groups.get(vg_name)
|
||||
|
||||
center = Vector((res_x - 1, res_y - 1, res_z - 1)) / 2
|
||||
max_res = max(res_x, res_y, res_z)
|
||||
|
||||
if not vg:
|
||||
vg = lattice_ob.vertex_groups.new(name=vg_name)
|
||||
for x in range(res_x - 4):
|
||||
for y in range(res_y - 4):
|
||||
for z in range(res_z - 4):
|
||||
index = get_lattice_vertex_index(lattice, (x + 2, y + 2, z + 2))
|
||||
|
||||
coord = Vector((x + 2, y + 2, z + 2))
|
||||
distance_from_center = (coord - center).length
|
||||
distance_factor = clamp(1 - (distance_from_center / max_res * 2), 0, 1)
|
||||
influence = func(distance_factor)
|
||||
|
||||
vg.add([index], influence * multiplier, 'REPLACE')
|
||||
return vg
|
||||
|
||||
|
||||
def add_radius_constraint(obj, hook, target):
|
||||
trans_con = obj.constraints.new(type='TRANSFORM')
|
||||
trans_con.name += " (Radius Scaling)"
|
||||
trans_con.target = target
|
||||
trans_con.map_to = 'SCALE'
|
||||
trans_con.mix_mode_scale = 'MULTIPLY'
|
||||
for prop in ['to_min_x_scale', 'to_min_y_scale', 'to_min_z_scale']:
|
||||
simple_driver(trans_con, prop, hook, '["Radius"]')
|
||||
return trans_con
|
||||
|
||||
|
||||
def get_objects_of_lattice(hook: Object) -> List[Object]:
|
||||
objs = []
|
||||
for key, value in hook.items():
|
||||
if key.startswith("object_") and value:
|
||||
objs.append(value)
|
||||
|
||||
return objs
|
||||
|
||||
|
||||
def get_lattice_modifier_of_object(obj, lattice) -> Modifier:
|
||||
"""Find the lattice modifier on the object that uses this lattice"""
|
||||
if not obj:
|
||||
return
|
||||
for m in obj.modifiers:
|
||||
if m.type == 'LATTICE' and m.object == lattice:
|
||||
return m
|
||||
|
||||
|
||||
def add_objects_to_lattice(hook: Object, objects: List[Object]):
|
||||
lattice_ob = hook['Lattice']
|
||||
|
||||
for i, obj in enumerate(objects):
|
||||
obj.select_set(False)
|
||||
if obj.type != 'MESH' or obj in hook.values():
|
||||
continue
|
||||
|
||||
# Make sure overridden object is editable.
|
||||
if obj.override_library:
|
||||
obj.override_library.is_system_override = False
|
||||
|
||||
mod = obj.modifiers.new(name=lattice_ob.name, type='LATTICE')
|
||||
mod.object = lattice_ob
|
||||
|
||||
# Make sure the property name is available.
|
||||
offset = 0
|
||||
while "object_" + str(offset) in hook:
|
||||
offset += 1
|
||||
hook["object_" + str(i + offset)] = obj
|
||||
|
||||
# Add driver to the modifier influence.
|
||||
simple_driver(mod, 'strength', hook, '["Influence"]')
|
||||
|
||||
|
||||
def remove_object_from_lattice(hook: Object, obj: Object):
|
||||
"""Cleanly remove an object from a Tweak Lattice set-up's influence."""
|
||||
hook, lattice, root = get_tweak_setup(hook)
|
||||
|
||||
# Remove the custom property pointing from the Hook to the Object.
|
||||
for key, value in list(hook.items()):
|
||||
if value == obj:
|
||||
del hook[key]
|
||||
break
|
||||
|
||||
# Remove the Lattice modifier (and its driver) deforming the Object.
|
||||
for m in obj.modifiers:
|
||||
if m.type != 'LATTICE':
|
||||
continue
|
||||
if m.object == lattice:
|
||||
m.driver_remove('strength')
|
||||
obj.modifiers.remove(m)
|
||||
break
|
||||
|
||||
|
||||
def remove_objects_from_lattice(hook: Object, objects_to_remove: List[Object]) -> List[Object]:
|
||||
"""Cleanly remove several objects from a Tweak Lattice set-up's influence."""
|
||||
objs_removed = []
|
||||
for key, value in list(hook.items()):
|
||||
if value in objects_to_remove:
|
||||
remove_object_from_lattice(hook, value)
|
||||
objs_removed.append(value)
|
||||
|
||||
return objs_removed
|
||||
|
||||
|
||||
def remove_all_objects_from_lattice(hook: Object) -> List[Object]:
|
||||
"""Cleanly remove all objects from a Tweak Lattice set-up's influence."""
|
||||
objs_to_remove = []
|
||||
for key, value in list(hook.items()):
|
||||
if key.startswith("object_"):
|
||||
objs_to_remove.append(value)
|
||||
|
||||
return remove_objects_from_lattice(hook, objs_to_remove)
|
||||
|
||||
|
||||
registry = [
|
||||
OBJECT_OT_tweaklattice_create,
|
||||
OBJECT_OT_tweaklattice_duplicate,
|
||||
OBJECT_OT_tweaklattice_delete,
|
||||
OBJECT_OT_tweaklattice_objects_add,
|
||||
OBJECT_OT_tweaklattice_objects_remove,
|
||||
OBJECT_OT_tweaklattice_object_remove_single,
|
||||
VIEW3D_PT_tweak_lattice,
|
||||
TweakLatticeProperties,
|
||||
]
|
||||
|
||||
|
||||
def register():
|
||||
Scene.tweak_lattice_parent_ob = PointerProperty(type=Object, name="Parent")
|
||||
Lattice.lattice_magic = PointerProperty(type=TweakLatticeProperties)
|
||||
|
||||
|
||||
def unregister():
|
||||
del Scene.tweak_lattice_parent_ob
|
||||
del Lattice.lattice_magic
|
||||
@@ -0,0 +1,121 @@
|
||||
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import bpy
|
||||
from mathutils import Vector
|
||||
from typing import List, Tuple
|
||||
|
||||
|
||||
def clamp(val, _min=0, _max=1) -> float or int:
|
||||
if val < _min:
|
||||
return _min
|
||||
if val > _max:
|
||||
return _max
|
||||
return val
|
||||
|
||||
|
||||
def get_lattice_vertex_index(lattice: bpy.types.Lattice, xyz: List[int], do_clamp=True) -> int:
|
||||
"""Get the index of a lattice vertex based on its position on the XYZ axes."""
|
||||
|
||||
# The lattice vertex indicies start in the -Y, -X, -Z corner,
|
||||
# increase on X+, then moves to the next row on Y+, then moves up on Z+.
|
||||
res_x, res_y, res_z = lattice.points_u, lattice.points_v, lattice.points_w
|
||||
x, y, z = xyz[:]
|
||||
if do_clamp:
|
||||
x = clamp(x, 0, res_x)
|
||||
y = clamp(y, 0, res_y)
|
||||
z = clamp(z, 0, res_z)
|
||||
|
||||
assert x < res_x and y < res_y and z < res_z, "Error: Lattice vertex xyz index out of bounds"
|
||||
|
||||
index = (z * res_y * res_x) + (y * res_x) + x
|
||||
return index
|
||||
|
||||
|
||||
def get_lattice_vertex_xyz_position(lattice: bpy.types.Lattice, index: int) -> (int, int, int):
|
||||
res_x, res_y, res_z = lattice.points_u, lattice.points_v, lattice.points_w
|
||||
|
||||
x = 0
|
||||
remaining = index
|
||||
z = int(remaining / (res_x * res_y))
|
||||
remaining -= z * (res_x * res_y)
|
||||
y = int(remaining / res_x)
|
||||
remaining -= y * res_x
|
||||
x = remaining # Maybe need to add or subtract 1 here?
|
||||
|
||||
return (x, y, z)
|
||||
|
||||
|
||||
def get_lattice_point_original_position(lattice: bpy.types.Lattice, index: int) -> Vector:
|
||||
"""Reset a lattice vertex to its original position."""
|
||||
start_vec = Vector((-0.5, -0.5, -0.5))
|
||||
if lattice.points_u == 1:
|
||||
start_vec[0] = 0
|
||||
if lattice.points_v == 1:
|
||||
start_vec[1] = 0
|
||||
if lattice.points_w == 1:
|
||||
start_vec[2] = 0
|
||||
|
||||
unit_u = 1 / (lattice.points_u - 0.99)
|
||||
unit_v = 1 / (lattice.points_v - 0.99)
|
||||
unit_w = 1 / (lattice.points_w - 0.99)
|
||||
|
||||
unit_vec = Vector((unit_u, unit_v, unit_w))
|
||||
xyz_vec = Vector(get_lattice_vertex_xyz_position(lattice, index))
|
||||
|
||||
return start_vec + xyz_vec * unit_vec
|
||||
|
||||
|
||||
def simple_driver(
|
||||
owner: bpy.types.ID,
|
||||
driver_path: str,
|
||||
target_ob: bpy.types.Object,
|
||||
data_path: str,
|
||||
array_index=-1,
|
||||
) -> bpy.types.Driver:
|
||||
if array_index > -1:
|
||||
owner.driver_remove(driver_path, array_index)
|
||||
driver = owner.driver_add(driver_path, array_index).driver
|
||||
else:
|
||||
owner.driver_remove(driver_path)
|
||||
driver = owner.driver_add(driver_path).driver
|
||||
|
||||
driver.expression = 'var'
|
||||
var = driver.variables.new()
|
||||
var.targets[0].id = target_ob
|
||||
var.targets[0].data_path = data_path
|
||||
|
||||
return driver
|
||||
|
||||
|
||||
def bounding_box(points) -> Tuple[Vector, Vector]:
|
||||
"""Return two vectors representing the lowest and highest coordinates of
|
||||
a the bounding box of the passed points.
|
||||
"""
|
||||
|
||||
lowest = points[0].copy()
|
||||
highest = points[0].copy()
|
||||
for p in points:
|
||||
for i in range(len(p)):
|
||||
if p[i] < lowest[i]:
|
||||
lowest[i] = p[i]
|
||||
if p[i] > highest[i]:
|
||||
highest[i] = p[i]
|
||||
|
||||
return lowest, highest
|
||||
|
||||
|
||||
def bounding_box_center(points) -> Vector:
|
||||
"""Find the bounding box center of some points."""
|
||||
bbox_low, bbox_high = bounding_box(points)
|
||||
return bbox_low + (bbox_high - bbox_low) / 2
|
||||
|
||||
|
||||
def bounding_box_center_of_objects(objects) -> Vector:
|
||||
"""Find the bounding box center of some objects."""
|
||||
all_points = []
|
||||
for o in objects:
|
||||
for p in o.bound_box:
|
||||
all_points.append(o.matrix_world @ Vector(p))
|
||||
return bounding_box_center(all_points)
|
||||
Reference in New Issue
Block a user