diff --git a/docs/addons/brushstroke_tools.md b/docs/addons/brushstroke_tools.md new file mode 100644 index 00000000..a5f99866 --- /dev/null +++ b/docs/addons/brushstroke_tools.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/.gitignore b/scripts-blender/addons/brushstroke_tools/.gitignore new file mode 100644 index 00000000..c0a38d10 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/.gitignore @@ -0,0 +1 @@ +*.txt~ \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/LICENSE b/scripts-blender/addons/brushstroke_tools/LICENSE new file mode 100644 index 00000000..d69b6157 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/LICENSE @@ -0,0 +1,183 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/README.md b/scripts-blender/addons/brushstroke_tools/README.md new file mode 100644 index 00000000..38139c0f --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/README.md @@ -0,0 +1,27 @@ +# Brushstroke Tools + +Set of tools for a painterly brushstroke stylization workflow of 3D assets developed by the Blender Studio + +## Getting Started +- UI navigation +- draw modes + - surface fill + - surface draw +- flow curves +- draw tool +- color options + +## Advanced Functionality +- stable surface deformation +- animated drawing/flow + +## Customization Options + +### Material +- add more FX layers +- replace surface shader + +### Brush Texture +- atlas setup +- node-group setup +- default file integration \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/__init__.py b/scripts-blender/addons/brushstroke_tools/__init__.py new file mode 100644 index 00000000..6022a56c --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/__init__.py @@ -0,0 +1,29 @@ +from . import utils, icons, settings, preferences, ui, draw_tool, ops +import tomllib as toml +import bpy + +modules = [utils, icons, settings, preferences, ui, draw_tool, ops] + +def register(): + # register modules + for m in modules: + m.register() + + # read addon meta-data + with open(f"{utils.get_addon_directory()}/blender_manifest.toml", 'rb') as f: + manifest = toml.load(f) + utils.addon_version = tuple([int(i) for i in manifest['version'].split('.')]) + + # Add addon asset library + utils.register_asset_lib() + + # Get available brush styles + #utils.refresh_brushstroke_styles() + +def unregister(): + # un-register modules + for m in reversed(modules): + m.unregister() + + # Remove addon asset library + utils.unregister_asset_lib() \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/assets/blender_assets.cats.txt b/scripts-blender/addons/brushstroke_tools/assets/blender_assets.cats.txt new file mode 100644 index 00000000..2b997012 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/assets/blender_assets.cats.txt @@ -0,0 +1,10 @@ +# This is an Asset Catalog Definition file for Blender. +# +# Empty lines and lines starting with `#` will be ignored. +# The first non-ignored line should be the version indicator. +# Other lines are of the format "UUID:catalog/path/for/assets:simple catalog name" + +VERSION 1 + +39d602da-9c11-471c-a99f-996e474e8e9a:Edge:Edge +4cee84fd-9d34-4ad1-b8f0-a6369e473f0d:Face:Face diff --git a/scripts-blender/addons/brushstroke_tools/assets/brushstroke_tools-resources.blend b/scripts-blender/addons/brushstroke_tools/assets/brushstroke_tools-resources.blend new file mode 100644 index 00000000..4634c0e0 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/brushstroke_tools-resources.blend differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_01.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_01.exr new file mode 100644 index 00000000..6d5edeea Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_01.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_02.painted.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_02.painted.exr new file mode 100644 index 00000000..3d4ac76b Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_02.painted.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_03.painted.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_03.painted.exr new file mode 100644 index 00000000..99320263 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_03.painted.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_04.painted_dry.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_04.painted_dry.exr new file mode 100644 index 00000000..411b7a59 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_04.painted_dry.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_floaters.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_floaters.exr new file mode 100644 index 00000000..b837989c Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_floaters.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_tiles_01.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_tiles_01.exr new file mode 100644 index 00000000..a9e59c89 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/brush_atlas_tiles_01.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/maps/canvas-linen_01.exr b/scripts-blender/addons/brushstroke_tools/assets/maps/canvas-linen_01.exr new file mode 100644 index 00000000..b2f28ae7 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/maps/canvas-linen_01.exr differ diff --git a/scripts-blender/addons/brushstroke_tools/assets/styles/brushstroke_tools-oil_brushes.blend b/scripts-blender/addons/brushstroke_tools/assets/styles/brushstroke_tools-oil_brushes.blend new file mode 100644 index 00000000..d6fba376 Binary files /dev/null and b/scripts-blender/addons/brushstroke_tools/assets/styles/brushstroke_tools-oil_brushes.blend differ diff --git a/scripts-blender/addons/brushstroke_tools/blender_manifest.toml b/scripts-blender/addons/brushstroke_tools/blender_manifest.toml new file mode 100644 index 00000000..7a9a27db --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/blender_manifest.toml @@ -0,0 +1,30 @@ +schema_version = "1.0.0" + +id = "brushstroke_tools" +version = "1.0.1" +name = "Brushstroke Tools" +tagline = "Brushstroke painting tools by the Blender Studio" +maintainer = "Simon Thommes " +type = "add-on" + +# Optional link to documentation, support, source files, etc +# website = "https://studio.blender.org/tools/addons/brushstroke_tools" + +# Optional list defined by Blender and server, see: +# https://docs.blender.org/manual/en/dev/advanced/extensions/tags.html +tags = ["Geometry Nodes", "Grease Pencil", "Node", ] + +blender_version_min = "4.2.0" + +# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix) +# https://docs.blender.org/manual/en/dev/advanced/extensions/licenses.html +license = [ + "SPDX:GPL-3.0-or-later", +] +# Optional: required by some licenses. +# copyright = [ +# "2024 Blender Foundation", +# ] + +# [permissions] +# files = "Read/write brushstroke asset resources from/to disk" \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/draw_tool.py b/scripts-blender/addons/brushstroke_tools/draw_tool.py new file mode 100644 index 00000000..38af37e7 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/draw_tool.py @@ -0,0 +1,204 @@ +import bpy +from . import utils +from mathutils import Vector +from bpy.types import WorkSpaceTool + +def preserve_draw_settings(context, restore=False): + props_list = ['curve_type', + 'depth_mode', + 'use_pressure_radius', + 'use_project_only_selected', + 'radius_taper_start', + 'radius_taper_end', + 'radius_min', + 'radius_max', + 'surface_offset', + 'use_offset_absolute', + 'use_stroke_endpoints',] + if restore: + draw_settings_dict = context.scene['BSBST-TMP-draw_settings_dict'] + for k, v in draw_settings_dict.items(): + setattr(context.tool_settings.curve_paint_settings, k, v) + del context.scene['BSBST-TMP-draw_settings_dict'] + else: + draw_settings_dict = dict() + for item in props_list: + draw_settings_dict[item] = getattr(context.tool_settings.curve_paint_settings, item) + context.scene['BSBST-TMP-draw_settings_dict'] = draw_settings_dict + +class BSBST_tool_settings(bpy.types.PropertyGroup): + brush_color: bpy.props.FloatVectorProperty(name='Brush Color', + size=3, + subtype='COLOR', + default=(0.,.5,1.), + soft_min=0, + soft_max=1, + update=None, + ) + radius_taper_start: bpy.props.FloatProperty(name='Taper Start', default=0, min=0, max=1, subtype='FACTOR') + radius_taper_end: bpy.props.FloatProperty(name='Taper End', default=0, min=0, max=1, subtype='FACTOR') + radius_min: bpy.props.FloatProperty(name='Radius Min', default=0, min=0, soft_max=10) + radius_max: bpy.props.FloatProperty(name='Radius Max', default=1, min=0, soft_max=10) + surface_offset: bpy.props.FloatProperty(name='Surface Offset', default=0, soft_max=10) + use_project_only_selected: bpy.props.BoolProperty(name='Project Onto Selected', + default=True, + description='Project the strokes only on selected objects if applicable.') + use_pressure_radius: bpy.props.BoolProperty(name='Use Pressure', + default=True, + description='Map tablet pressure to curve radius',) + use_offset_absolute: bpy.props.BoolProperty(name='Absolute Offset', + default=False, + description="Apply a fixed offset. (Don't scale by the radius.)") + +class BSBST_OT_draw(bpy.types.Macro): + """ + Custom draw operation for hair curves + """ + bl_idname = "brushstroke_tools.draw" + bl_label = "Custom Draw" + bl_options = {'REGISTER', 'UNDO'} + +class BSBST_OT_pre_process_brushstroke(bpy.types.Operator): + """ + Set up custom draw tool for curve drawing + """ + bl_idname = "brushstroke_tools.pre_process_brushstroke" + bl_label = "Custom Draw Pre Process" + bl_options = {'REGISTER', 'UNDO'} + + def execute(self, context): + tool_settings = context.scene.BSBST_tool_settings + + preserve_draw_settings(context) + + # fix some settings + context.tool_settings.curve_paint_settings.curve_type = 'POLY' + context.tool_settings.curve_paint_settings.depth_mode = 'SURFACE' + context.tool_settings.curve_paint_settings.use_stroke_endpoints = False + + is_other_object_selected = len(set(context.selected_objects) - {context.object}) > 0 + context.tool_settings.curve_paint_settings.use_project_only_selected = is_other_object_selected and tool_settings.use_project_only_selected + + # propagate some settings from custom tool + props_list = ['use_pressure_radius', + 'radius_taper_start', + 'radius_taper_end', + 'radius_min', + 'radius_max', + 'surface_offset', + 'use_offset_absolute',] + for prop in props_list: + setattr(context.tool_settings.curve_paint_settings, prop, getattr(tool_settings, prop)) + + return {'FINISHED'} + +class BSBST_OT_post_process_brushstroke(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.post_process_brushstroke" + bl_label = "Custom Draw Post Process" + bl_options = {'REGISTER', 'UNDO'} + + ng_process = None + gp = None + + def execute(self, context): + if not self.ng_process: + preserve_draw_settings(context, restore=True) + return {'CANCELLED'} + tool_settings = context.scene.BSBST_tool_settings + + self.ng_process.nodes['settings.color'].value = [*tool_settings.brush_color, 1.] + self.ng_process.nodes['view_vector'].vector = context.space_data.region_3d.view_rotation @ Vector((0.0, 0.0, 1.0)) + self.ng_process.nodes['new_key'].boolean = context.scene.tool_settings.use_keyframe_insert_auto + self.ng_process.nodes['deform'].boolean = utils.get_deformable(context.object) + if 'BSBST_surface_object' in context.object.keys(): + if context.object['BSBST_surface_object']: + self.ng_process.nodes['surface_object'].inputs[0].default_value = context.object['BSBST_surface_object'] + bpy.ops.geometry.execute_node_group(name="set_brush_stroke_color", session_uid=self.ng_process.session_uid) + + preserve_draw_settings(context, restore=True) + return {'FINISHED'} + + def invoke(self, context, event): + utils.ensure_resources() + self.gp = None + self.ng_process = bpy.data.node_groups['.brushstroke_tools.draw_processing'] + return self.execute(context) + +def register_custom_draw_macro(): + op = BSBST_OT_draw.define("brushstroke_tools.pre_process_brushstroke") + op = BSBST_OT_draw.define("curves.draw") + op.properties.wait_for_input = False + op = BSBST_OT_draw.define("brushstroke_tools.post_process_brushstroke") + +class BrushstrokesCurves(WorkSpaceTool): + bl_space_type = 'VIEW_3D' + bl_context_mode = 'EDIT_CURVES' + + bl_idname = "brushstroke_tools.draw" + bl_label = "Brushstroke Draw" + bl_description = ( + "Brushstrokes on the visible surface" + ) + bl_icon = "brush.sculpt.paint" + bl_widget = None + bl_keymap = ( + ("brushstroke_tools.draw", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, + {"properties": []}), + ) + + def draw_settings(context, layout, tool, *, extra=False): + props = tool.operator_properties("brushstroke_tools.draw") + tool_settings = context.scene.BSBST_tool_settings + region_type = context.region.type + + if region_type == 'TOOL_HEADER': + if not extra: + layout.prop(tool_settings , "radius_max") + layout.prop(tool_settings , "surface_offset") + layout.prop(tool_settings, "brush_color") + layout.popover("TOPBAR_PT_tool_settings_extra", text="...") + return + + layout.use_property_split = True + layout.use_property_decorate = False + + col = layout.column(align=False) + col.template_color_picker(tool_settings, 'brush_color', value_slider=True) + col.prop(tool_settings, 'brush_color', text='') + + col = layout.column(align=True) + col.prop(tool_settings, "radius_taper_start", text="Taper Start", slider=True) + col.prop(tool_settings, "radius_taper_end", text="End", slider=True) + col = layout.column(align=True) + col.prop(tool_settings, "radius_min", text="Radius Min") + col.prop(tool_settings, "radius_max", text="Max") + col.prop(tool_settings, "use_pressure_radius", icon='STYLUS_PRESSURE', emboss=True) + + layout.separator() + + col = layout.column() + col.prop(tool_settings, "use_project_only_selected") + col.prop(tool_settings, "surface_offset") + col.prop(tool_settings, "use_offset_absolute") + +classes = [ + BSBST_tool_settings, + BSBST_OT_pre_process_brushstroke, + BSBST_OT_post_process_brushstroke, + BSBST_OT_draw, +] + +def register(): + for c in classes: + bpy.utils.register_class(c) + bpy.types.Scene.BSBST_tool_settings = bpy.props.PointerProperty(type=BSBST_tool_settings) + register_custom_draw_macro() + bpy.utils.register_tool(BrushstrokesCurves, after={"builtin.draw"}, group=True) + +def unregister(): + for c in reversed(classes): + bpy.utils.unregister_class(c) + bpy.utils.unregister_tool(BrushstrokesCurves) + del bpy.types.Scene.BSBST_tool_settings \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/icons.py b/scripts-blender/addons/brushstroke_tools/icons.py new file mode 100644 index 00000000..7a0c70d6 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/icons.py @@ -0,0 +1,23 @@ +import bpy +import bpy.utils.previews +import os + +icon_previews = {} + +def register(): + # register custom icons + dir = os.path.join(os.path.dirname(__file__), "icons") + pcoll = bpy.utils.previews.new() + for entry in os.scandir(dir): + if entry.name.endswith(".png"): + name = os.path.splitext(entry.name)[0] + pcoll.load(name.upper(), entry.path, "IMAGE") + global icon_previews + icon_previews["main"] = pcoll + +def unregister(): + # unregister custom icons + global icon_previews + for pcoll in icon_previews.values(): + bpy.utils.previews.remove(pcoll) + icon_previews.clear() diff --git a/scripts-blender/addons/brushstroke_tools/icons/random.png b/scripts-blender/addons/brushstroke_tools/icons/random.png new file mode 100644 index 00000000..a0fd2196 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/icons/random.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06b3fb4e80b0048572b99723a702f24180a9d9c5633d36b040b16fcdd7d9c7c0 +size 1922 diff --git a/scripts-blender/addons/brushstroke_tools/icons/random.svg b/scripts-blender/addons/brushstroke_tools/icons/random.svg new file mode 100644 index 00000000..96bb7a43 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/icons/random.svg @@ -0,0 +1,447 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts-blender/addons/brushstroke_tools/ops.py b/scripts-blender/addons/brushstroke_tools/ops.py new file mode 100644 index 00000000..062d2eaf --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/ops.py @@ -0,0 +1,1205 @@ +import bpy +import random +from . import utils, settings +import mathutils + +class BSBST_OT_new_brushstrokes(bpy.types.Operator): + """ Create new object according to method and type. + Link to correct collection. + Attach to selection context if applicable. + Assign selected modifier setup. Enter correct context for editing. + """ + bl_idname = "brushstroke_tools.new_brushstrokes" + bl_label = "New Brushstrokes" + bl_description = "Create new brushstrokes object of selected type with all the necessary setup in place" + bl_options = {"REGISTER", "UNDO"} + + method: bpy.props.StringProperty(default='SURFACE_FILL') + + @classmethod + def poll(cls, context): + surface_object = utils.get_active_context_surface_object(context) + return bool(surface_object) + + def new_brushstrokes_object(self, context, name): + settings = context.scene.BSBST_settings + settings.brushstroke_method = self.method + + if settings.curve_mode == 'GP': + bpy.ops.object.grease_pencil_add(type='EMPTY') + context.object.name = name + context.object.data.name = name + brushstrokes_object = context.object + else: + if settings.curve_mode == 'CURVE': + brushstrokes_data = bpy.data.curves.new(name, type='CURVE') + brushstrokes_data.dimensions = '3D' + elif settings.curve_mode == 'CURVES': + brushstrokes_data = bpy.data.hair_curves.new(name) + brushstrokes_object = bpy.data.objects.new(name, brushstrokes_data) + context.collection.objects.link(brushstrokes_object) + brushstrokes_object.visible_shadow = False + brushstrokes_object['BSBST_version'] = utils.addon_version + utils.set_deformable(brushstrokes_object, settings.deforming_surface) + utils.set_animated(brushstrokes_object, settings.animated) + return brushstrokes_object + + def new_flow_object(self, context, name, surface_object): + settings = context.scene.BSBST_settings + if settings.curve_mode == 'GP': + bpy.ops.object.grease_pencil_add(type='EMPTY') + context.object.name = name + context.object.data.name = name + flow_object = context.object + else: + if settings.curve_mode == 'CURVE': + flow_data = bpy.data.curves.new(name, type='CURVE') + flow_data.dimensions = '3D' + elif settings.curve_mode == 'CURVES': + flow_data = bpy.data.hair_curves.new(name) + flow_object = bpy.data.objects.new(name, flow_data) + context.collection.objects.link(flow_object) + + visibility_options = [ + 'visible_camera', + 'visible_diffuse', + 'visible_glossy', + 'visible_transmission', + 'visible_volume_scatter', + 'visible_shadow', + ] + for vis in visibility_options: + setattr(flow_object, vis, False) + + ## add pre-processing modifier + mod = flow_object.modifiers.new('Pre-Processing', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.pre_processing'] + + mod_info = flow_object.modifier_info.add() + mod_info.name = mod.name + + utils.mark_socket_context_type(mod_info, 'Socket_2', 'SURFACE_OBJECT') + + mod['Socket_2'] = surface_object + mod['Socket_3'] = False + + utils.set_deformable(flow_object, settings.deforming_surface) + utils.set_animated(flow_object, settings.animated) + return flow_object + + def main(self, context): + settings = context.scene.BSBST_settings + + utils.ensure_resources() + if not context.mode == 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + + surface_object = utils.get_active_context_surface_object(context) + flow_object = None + + if not surface_object.data.uv_layers.active: + self.report({"ERROR"}, "Surface Object needs an available UV Map") + return {"CANCELLED"} + + name = f'{surface_object.name} - Brushstrokes' + brushstrokes_object = self.new_brushstrokes_object(context, name) + flow_is_required = settings.brushstroke_method == 'SURFACE_FILL' + if flow_is_required: + flow_object = None + if settings.reuse_flow: + if settings.context_brushstrokes: + bs = bpy.data.objects.get(settings.context_brushstrokes[settings.active_context_brushstrokes_index].name) + if 'BSBST_flow_object' in bs.keys(): + flow_object = bs['BSBST_flow_object'] + if not flow_object: + flow_object = self.new_flow_object(context, utils.flow_name(name), surface_object) + + # attach surface object pointer + if surface_object: + utils.set_surface_object(brushstrokes_object, surface_object) + if flow_object: + brushstrokes_object['BSBST_flow_object'] = flow_object + brushstrokes_object['BSBST_active'] = True + brushstrokes_object['BSBST_method'] = settings.brushstroke_method + + if surface_object: + surface_object.add_rest_position_attribute = True # TODO report if library data + brushstrokes_object.parent = surface_object + if flow_object: + flow_object.parent = surface_object + + if not settings.preset_object: + bpy.ops.brushstroke_tools.init_preset() + + # assign preset material + preset_material = getattr(settings.preset_object, '["BSBST_material"]', None) + + if preset_material: + override = context.copy() + override['object'] = brushstrokes_object + with context.temp_override(**override): + bpy.ops.object.material_slot_add() + brushstrokes_object.material_slots[0].material = preset_material + settings.context_material = preset_material + brushstrokes_object['BSBST_material'] = settings.context_material + + # transfer preset modifiers to new brushstrokes TODO: refactor to deduplicate + for mod in settings.preset_object.modifiers: + utils.transfer_modifier(mod.name, brushstrokes_object, settings.preset_object) + + for v in mod.node_group.interface.items_tree.values(): + if type(v) not in utils.linkable_sockets: + continue + if not settings.preset_object.modifier_info[mod.name].socket_info[v.identifier].link_context: + continue + # initialize linked context parameters + link_context_type = settings.preset_object.modifier_info[mod.name].socket_info[v.identifier].link_context_type + if link_context_type=='SURFACE_OBJECT': + brushstrokes_object.modifiers[mod.name][f'{v.identifier}'] = surface_object + elif link_context_type=='FLOW_OBJECT': + brushstrokes_object.modifiers[mod.name][f'{v.identifier}'] = flow_object + elif link_context_type=='MATERIAL': + brushstrokes_object.modifiers[mod.name][f'{v.identifier}'] = settings.context_material + elif link_context_type=='UVMAP': + if type(brushstrokes_object.modifiers[mod.name][f'{v.identifier}']) == str: + brushstrokes_object.modifiers[mod.name][f'{v.identifier}'] = surface_object.data.uv_layers.active.name + else: + brushstrokes_object.modifiers[mod.name][f'{v.identifier}_use_attribute'] = True + brushstrokes_object.modifiers[mod.name][f'{v.identifier}_attribute_name'] = surface_object.data.uv_layers.active.name + elif link_context_type=='RANDOM': + vmin = v.min_value + vmax = v.max_value + val = vmin + random.random() * (vmax - vmin) + brushstrokes_object.modifiers[mod.name][f'{v.identifier}_use_attribute'] = False + brushstrokes_object.modifiers[mod.name][f'{v.identifier}'] = type(brushstrokes_object.modifiers[mod.name][f'{v.identifier}'])(val) + + # transfer modifier info data from preset to brush strokes + utils.deep_copy_mod_info(settings.preset_object, brushstrokes_object) + + # estimate dimensions + + if settings.estimate_dimensions: + bb_min = mathutils.Vector(surface_object.bound_box[0]) + bb_max = mathutils.Vector(surface_object.bound_box[6]) + bb_radius = mathutils.Vector([abs(co) for co in bb_max-bb_min]).length * 0.5 + + surf_est = 4 * 3.142 * bb_radius**2 + + mod = brushstrokes_object.modifiers['Brushstrokes'] + if settings.brushstroke_method == 'SURFACE_FILL': + # set density + mod['Socket_7'] = utils.round_n((1000 / surf_est) ** 0.5, 2) + # set length + mod['Socket_11'] = utils.round_n(bb_radius * 0.5, 2) + # set width + mod['Socket_13'] = utils.round_n(bb_radius * 0.05, 2) + elif settings.brushstroke_method == 'SURFACE_DRAW': + # set width + mod['Socket_5'] = utils.round_n(bb_radius * 0.05, 2) + + # refresh UI + for mod in brushstrokes_object.modifiers: + mod.node_group.interface_update(context) + + if settings.assign_materials: + for mod in brushstrokes_object.modifiers: + for v in mod.node_group.interface.items_tree.values(): + if type(v) != bpy.types.NodeTreeInterfaceSocketMaterial: + continue + mat = mod[v.identifier] + if not mat: + continue + if mat in [m_slot.material for m_slot in brushstrokes_object.material_slots]: + continue + override = context.copy() + override['object'] = brushstrokes_object + with context.temp_override(**override): + bpy.ops.object.material_slot_add() + brushstrokes_object.material_slots[-1].material = mat + + # set deformable + set_brushstrokes_deformable(brushstrokes_object, settings.deforming_surface) + + # set animated + set_brushstrokes_animated(brushstrokes_object, settings.animated) + + for mod in brushstrokes_object.modifiers: + mod.show_group_selector = False + + # update brushstroke context + utils.find_context_brushstrokes(None) + for i, name in enumerate([bs.name for bs in settings.context_brushstrokes]): + if name == brushstrokes_object.name: + settings.active_context_brushstrokes_index = i + break + + utils.edit_active_brushstrokes(context) + return {"FINISHED"} + + def execute(self, context): + settings = context.scene.BSBST_settings + settings.silent_switch = True + state = self.main(context) + + settings.silent_switch = False + return state + +class BSBST_OT_edit_brushstrokes(bpy.types.Operator): + """ + Enter the editing context for the active context brushstrokes. + """ + bl_idname = "brushstroke_tools.edit_brushstrokes" + bl_label = "Edit Brushstrokes" + bl_description = " Enter the editing context for the active context brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + settings.silent_switch = True + state = utils.edit_active_brushstrokes(context) + + settings.silent_switch = False + return state + +class BSBST_OT_delete_brushstrokes(bpy.types.Operator): + """ + Delete the active context brushstrokes + """ + bl_idname = "brushstroke_tools.delete_brushstrokes" + bl_label = "Delete Brushstrokes" + bl_description = "Delete the active context brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + + edit_toggle = settings.edit_toggle + settings.edit_toggle = False + + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + settings.edit_toggle = edit_toggle + return {"CANCELLED"} + + surface_object = utils.get_surface_object(bs_ob) + flow_object = utils.get_flow_object(bs_ob) + + if context.active_object: + if context.mode != 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + bpy.data.objects.remove(bs_ob) + settings.active_context_brushstrokes_index = max(0, settings.active_context_brushstrokes_index-1) + + if surface_object: + context.view_layer.objects.active = surface_object + bs_ob = utils.get_active_context_brushstrokes_object(context) + if bs_ob: + context.view_layer.objects.active = bs_ob + bs_ob.select_set(True) + + if not flow_object: + settings.edit_toggle = edit_toggle + return {"FINISHED"} + + # delete controller objects + if flow_object.users <= 1: + bpy.data.objects.remove(flow_object) + + settings.edit_toggle = edit_toggle + return {'FINISHED'} + +class BSBST_OT_duplicate_brushstrokes(bpy.types.Operator): + """ + Duplicate the active context brushstrokes + """ + bl_idname = "brushstroke_tools.duplicate_brushstrokes" + bl_label = "Duplicate Brushstrokes" + bl_description = "Duplicate the active context brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + return {"CANCELLED"} + + if not bs_ob.visible_get(view_layer=context.view_layer): + self.report({"WARNING"}, f"Skipped Brushstroke layer '{bs_ob.name}' because it is invisible in this context") + return {"CANCELLED"} + + flow_object = utils.get_flow_object(bs_ob) + + if context.mode != 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + + bpy.context.view_layer.objects.active = bs_ob + if context.mode != 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + for ob in bpy.data.objects: + ob.select_set(False) + bs_ob.select_set(True) + if flow_object and not settings.reuse_flow: + flow_object.select_set(True) + bpy.ops.object.duplicate_move() + + # reshuffle seed + for ob in context.selected_editable_objects: + for mod in ob.modifiers: + if not mod.type=='NODES': + continue + if not mod.node_group: + continue + for v in mod.node_group.interface.items_tree.values(): + if type(v) not in utils.linkable_sockets: + continue + if not ob.modifier_info[mod.name].socket_info[v.identifier].link_context: + continue + # initialize linked context parameters + link_context_type = ob.modifier_info[mod.name].socket_info[v.identifier].link_context_type + if link_context_type=='RANDOM': + vmin = v.min_value + vmax = v.max_value + val = vmin + random.random() * (vmax - vmin) + mod[f'{v.identifier}'] = type(ob.modifiers[mod.name][f'{v.identifier}'])(val) + + return {'FINISHED'} + +class BSBST_OT_copy_brushstrokes(bpy.types.Operator): + """ + Copy the active context brushstrokes to the selected surface objects + """ + bl_idname = "brushstroke_tools.copy_brushstrokes" + bl_label = "Copy Brushstrokes to Selected" + bl_description = "Copy the active context brushstrokes to the selected surface objects" + bl_options = {"REGISTER", "UNDO"} + + copy_all: bpy.props.BoolProperty(default=False) + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + + active_surface_object = utils.get_surface_object(utils.get_active_context_brushstrokes_object(context)) + + surface_objects = [ob for ob in context.selected_objects + if ob.type=='MESH' + and not utils.is_brushstrokes_object(ob) + and not ob==active_surface_object] + if not surface_objects: + return {"CANCELLED"} + + if self.copy_all: + bs_objects = [bpy.data.objects.get(bs.name) for bs in settings.context_brushstrokes] + bs_objects = [bs for bs in bs_objects if bs] + else: + bs_objects = [utils.get_active_context_brushstrokes_object(context)] + if not bs_objects: + return {"CANCELLED"} + + if context.mode != 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + for surface_object in surface_objects: + for ob in bpy.data.objects: + ob.select_set(False) + for bs_ob in bs_objects: + if not bs_ob.visible_get(view_layer=context.view_layer): + self.report({"WARNING"}, f"Skipped Brushstroke layer '{bs_ob.name}' because it is invisible in this context") + continue + bs_ob.select_set(True) + flow_object = utils.get_flow_object(bs_ob) + if not flow_object: + continue + flow_object.select_set(True) + + all_obj = set(bpy.data.objects[:]) + context.view_layer.depsgraph.update() + bpy.ops.object.duplicate_move() + new_bs = list(set(bpy.data.objects[:]) - all_obj) + del all_obj + + # remap surface pointers and context linked data TODO: refactor to deduplicate + for ob in new_bs: + ob.parent = surface_object + utils.set_surface_object(ob, surface_object) + + for mod in ob.modifiers: + if not mod.type: + continue + if not mod.node_group: + continue + mod_info = ob.modifier_info.get(mod.name) + if not mod_info: + continue + for v in mod.node_group.interface.items_tree.values(): + if type(v) not in utils.linkable_sockets: + continue + if not mod_info.socket_info[v.identifier].link_context: + continue + # re-initialize linked context parameters + link_context_type = ob.modifier_info[mod.name].socket_info[v.identifier].link_context_type + if link_context_type=='SURFACE_OBJECT': + ob.modifiers[mod.name][f'{v.identifier}'] = surface_object + elif link_context_type=='UVMAP': + if type(ob.modifiers[mod.name][f'{v.identifier}']) == str: + ob.modifiers[mod.name][f'{v.identifier}'] = surface_object.data.uv_layers.active.name + else: + ob.modifiers[mod.name][f'{v.identifier}_use_attribute'] = True + ob.modifiers[mod.name][f'{v.identifier}_attribute_name'] = surface_object.data.uv_layers.active.name + elif link_context_type=='RANDOM': + vmin = v.min_value + vmax = v.max_value + val = vmin + random.random() * (vmax - vmin) + ob.modifiers[mod.name][f'{v.identifier}_use_attribute'] = False + ob.modifiers[mod.name][f'{v.identifier}'] = type(ob.modifiers[mod.name][f'{v.identifier}'])(val) + + + # enable rest position + surface_object.add_rest_position_attribute = True + + return {'FINISHED'} + +class BSBST_OT_select_surface(bpy.types.Operator): + """ + Select the surface object for the active context brushstrokes. + """ + bl_idname = "brushstroke_tools.select_surface" + bl_label = "Select Surface" + bl_description = "Select the surface object for the active context brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + return {"CANCELLED"} + surface_object = getattr(bs_ob, '["BSBST_surface_object"]', None) + if not surface_object: + return {"CANCELLED"} + + bpy.context.view_layer.objects.active = surface_object + if not context.mode == 'OBJECT': + bpy.ops.object.mode_set(mode='OBJECT') + for ob in bpy.data.objects: + ob.select_set(False) + surface_object.select_set(True) + + return {"FINISHED"} + +class BSBST_OT_assign_surface(bpy.types.Operator): + """ + Assign a surface object for the active context brushstrokes. + """ + bl_idname = "brushstroke_tools.assign_surface" + bl_label = "Assign Surface" + bl_description = "Assign a surface object for the active context brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + surface_object: bpy.props.StringProperty() + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + return {"CANCELLED"} + + surface_object = bpy.data.objects.get(self.surface_object) + + if not surface_object: + return {"CANCELLED"} + + # TODO handle parenting with keep transform as default option + utils.set_surface_object(bs_ob, surface_object) + return {"FINISHED"} + + def draw(self, context): + layout = self.layout + layout.prop_search(self, 'surface_object', bpy.data, 'objects') + + def invoke(self, context, event): + bs_ob = utils.get_active_context_brushstrokes_object(context) + surf_ob = utils.get_surface_object(bs_ob) + if surf_ob: + self.surface_object = surf_ob.name + return context.window_manager.invoke_props_dialog(self) + +def set_brushstrokes_deformable(bs_ob, deformable): + flow_ob = utils.get_flow_object(bs_ob) + + for mod in bs_ob.modifiers: + if not mod.type == 'NODES': + continue + if not mod.node_group: + continue + if mod.node_group.name == '.brushstroke_tools.pre_processing': + mod['Socket_3'] = deformable + elif mod.node_group.name == '.brushstroke_tools.surface_fill': + mod['Socket_27'] = deformable + elif mod.node_group.name == '.brushstroke_tools.surface_draw': + mod['Socket_15'] = deformable + + mod.node_group.interface_update(bpy.context) + utils.set_deformable(bs_ob, deformable) + if not flow_ob: + return + utils.set_deformable(flow_ob, deformable) + +def set_brushstrokes_animated(bs_ob, animated): + flow_ob = utils.get_flow_object(bs_ob) + + if flow_ob: + ob = flow_ob + else: + ob = bs_ob + mod = ob.modifiers.get('Animation') + if animated: + if not mod: + mod = ob.modifiers.new('Animation', 'NODES') + mod.node_group = utils.ensure_node_group('.brushstroke_tools.animation') + + mod_info = ob.modifier_info.get(mod.name) + if not mod_info: + mod_info = ob.modifier_info.add() + mod_info.name = mod.name + + # ui visibility settings + mod_info.hide_ui = True + else: + mod['Socket_5'] = True + mod.node_group.interface_update(bpy.context) + with bpy.context.temp_override(object=ob): + bpy.ops.object.modifier_move_to_index(modifier=mod.name, index=0) + else: + if mod: + ob.modifiers.remove(mod) + utils.set_animated(bs_ob, animated) + if not flow_ob: + return + utils.set_animated(flow_ob, animated) + +class BSBST_OT_copy_flow(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.copy_flow" + bl_label = "Copy Flow from Existing" + bl_description = "Copy the flow object from another brushstroke layer." + bl_options = {"REGISTER", "UNDO"} + + source_bs: bpy.props.StringProperty(name="Brushstroke Layers") + bs_list: bpy.props.CollectionProperty(type=settings.BSBST_context_brushstrokes) + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + bs_ob = utils.get_active_context_brushstrokes_object(context) + flow_ob_old = utils.get_flow_object(bs_ob) + if not bs_ob: + return {"CANCELLED"} + + # get source + + source_ob = bpy.data.objects.get(self.source_bs) + flow_ob = utils.get_flow_object(source_ob) + if not source_ob or not flow_ob: + return {"CANCELLED"} + + # set flow object + + utils.set_flow_object(bs_ob, flow_ob) + + # delete old flow if unused necessary + + if not flow_ob_old: + return {"FINISHED"} + for bs in self.bs_list: + flow_ob = utils.get_flow_object(source_ob) + if not flow_ob: + continue + if flow_ob.name == flow_ob_old.name: + return {"FINISHED"} + + bpy.data.objects.remove(flow_ob_old) + + return {"FINISHED"} + + def draw(self, context): + layout = self.layout + layout.prop_search(self, 'source_bs', self, 'bs_list', icon='OUTLINER_OB_FORCE_FIELD') + + def invoke(self, context, event): + settings = context.scene.BSBST_settings + + bs_ob = utils.get_active_context_brushstrokes_object(context) + + for i in range(len(self.bs_list)): + self.bs_list.remove(0) + + for bs in settings.context_brushstrokes: + if not bs.method=='SURFACE_FILL': + continue + if bs.name==bs_ob.name: + continue + bs_new = self.bs_list.add() + bs_new.name = bs.name + bs_new.hide_viewport_base = bs.hide_viewport_base + + if self.bs_list: + self.source_bs = self.bs_list[0].name + return context.window_manager.invoke_props_dialog(self) + +class BSBST_OT_switch_deformable(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.switch_deformable" + bl_label = "Switch Deformable" + bl_description = "Switch the deformable state of the brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + deformable: bpy.props.BoolProperty( default=True, + name="Deformable",) + switch_all: bpy.props.BoolProperty( default=False, + name="All Brushstrokes", + description="Switch all Brushstroke Layers of Current Surface Object.") + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + + if self.switch_all: + bs_objects = [bpy.data.objects.get(bs.name) for bs in settings.context_brushstrokes] + bs_objects = [bs for bs in bs_objects if bs] + else: + bs_objects = [utils.get_active_context_brushstrokes_object(context)] + if not bs_objects: + return {"CANCELLED"} + + for ob in bs_objects: + set_brushstrokes_deformable(ob, self.deformable) + + context.view_layer.depsgraph.update() + + return {"FINISHED"} + +class BSBST_OT_switch_animated(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.switch_animated" + bl_label = "Switch Animated" + bl_description = "Switch the atnimated state of the brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + animated: bpy.props.BoolProperty( default=True, + name="Animated",) + switch_all: bpy.props.BoolProperty( default=False, + name="All Brushstrokes", + description="Switch all Brushstroke Layers of Current Surface Object.") + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return bool(settings.context_brushstrokes) + + def execute(self, context): + settings = context.scene.BSBST_settings + + if self.switch_all: + bs_objects = [bpy.data.objects.get(bs.name) for bs in settings.context_brushstrokes] + bs_objects = [bs for bs in bs_objects if bs] + else: + bs_objects = [utils.get_active_context_brushstrokes_object(context)] + if not bs_objects: + return {"CANCELLED"} + + for ob in bs_objects: + set_brushstrokes_animated(ob, self.animated) + + context.view_layer.depsgraph.update() + + return {"FINISHED"} + +class BSBST_OT_init_preset(bpy.types.Operator): + """ + Initialize the preset to define a modifier stack applied to new brushstrokess. + """ + bl_idname = "brushstroke_tools.init_preset" + bl_label = "Initialize Preset" + bl_description = "Initialize the preset environment to setup a predefined modifier stack for new brushstrokess" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return settings.preset_object is None + + def init_fill(self, context): + settings = context.scene.BSBST_settings + + preset_object = settings.preset_object + + # add modifiers + ## input + mod = preset_object.modifiers.new('Surface Input', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.geometry_input'] + + mod_info = settings.preset_object.modifier_info.get(mod.name) + if not mod_info: + mod_info = settings.preset_object.modifier_info.add() + mod_info.name = mod.name + + # context link settings + utils.mark_socket_context_type(mod_info, 'Socket_2', 'SURFACE_OBJECT') + + # ui visibility settings + mod_info.hide_ui = True + + mod_info.default_closed = True + + ## masking + mod = preset_object.modifiers.new('Masking', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.mask_surface'] + + mod_info = settings.preset_object.modifier_info.get(mod.name) + if not mod_info: + mod_info = settings.preset_object.modifier_info.add() + mod_info.name = mod.name + + mod_info.default_closed = True + + # ui visibility settings + hide_sockets =[ + 'Socket_5', + ] + for s in hide_sockets: + utils.mark_socket_hidden(mod_info, s) + + ## brushstrokes + mod = preset_object.modifiers.new('Brushstrokes', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.surface_fill'] + + mod_info = settings.preset_object.modifier_info.get(mod.name) + if not mod_info: + mod_info = settings.preset_object.modifier_info.add() + mod_info.name = mod.name + + # set fill custom defaults + + mod['Socket_59'] = 1 # color method: curves + + # context link settings + utils.mark_socket_context_type(mod_info, 'Socket_2', 'FLOW_OBJECT') + utils.mark_socket_context_type(mod_info, 'Socket_3', 'UVMAP') + utils.mark_socket_context_type(mod_info, 'Socket_9', 'RANDOM') + utils.mark_socket_context_type(mod_info, 'Socket_12', 'MATERIAL') + utils.mark_socket_context_type(mod_info, 'Socket_60', 'FLOW_OBJECT') + + # ui visibility settings + hide_sockets =[ + 'Socket_2', + 'Socket_3', + #'Socket_9', # seed + 'Socket_12', + 'Socket_15', + 'Socket_27', + 'Socket_37', + 'Socket_40', + 'Socket_62', + 'Socket_67', # mesh loops + ] + for s in hide_sockets: + utils.mark_socket_hidden(mod_info, s) + + hide_panels = [ + 'Stroke Culling', + 'Lighting Influence', + 'Offset Override', + 'Debug', + ] + for p in hide_panels: + utils.mark_panel_hidden(mod_info, p) + + def init_draw(self, context): + settings = context.scene.BSBST_settings + + preset_object = settings.preset_object + + # add modifiers + ## add pre-processing modifier + mod = preset_object.modifiers.new('Pre-Processing', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.pre_processing'] + + mod_info = settings.preset_object.modifier_info.get(mod.name) + if not mod_info: + mod_info = settings.preset_object.modifier_info.add() + mod_info.name = mod.name + + utils.mark_socket_context_type(mod_info, 'Socket_2', 'SURFACE_OBJECT') + + # ui visibility settings + mod_info.hide_ui = True + + ## brushstrokes + mod = preset_object.modifiers.new('Brushstrokes', 'NODES') + mod.node_group = bpy.data.node_groups['.brushstroke_tools.surface_draw'] + + mod_info = settings.preset_object.modifier_info.get(mod.name) + if not mod_info: + mod_info = settings.preset_object.modifier_info.add() + mod_info.name = mod.name + + utils.mark_socket_context_type(mod_info, 'Socket_2', 'SURFACE_OBJECT') + utils.mark_socket_context_type(mod_info, 'Socket_4', 'MATERIAL') + utils.mark_socket_context_type(mod_info, 'Socket_6', 'RANDOM') + utils.mark_socket_context_type(mod_info, 'Socket_12', 'UVMAP') + + # ui visibility settings + hide_sockets =[ + 'Socket_2', + 'Socket_3', + 'Socket_4', + #'Socket_6', # seed + 'Socket_12', + 'Socket_15', + 'Socket_24', + 'Socket_35', # mesh loops + ] + for s in hide_sockets: + utils.mark_socket_hidden(mod_info, s) + + hide_panels = [ + 'Debug', + ] + for p in hide_panels: + utils.mark_panel_hidden(mod_info, p) + + def execute(self, context): + + settings = context.scene.BSBST_settings + + utils.ensure_resources() + preset_name = f'BSBST-PRESET_{settings.brushstroke_method}' + preset_object = bpy.data.objects.new(preset_name, bpy.data.hair_curves.new(preset_name)) + settings.preset_object = preset_object + + if settings.brushstroke_method == "SURFACE_FILL": + self.init_fill(context) + elif settings.brushstroke_method == "SURFACE_DRAW": + self.init_draw(context) + + # select preset material + mat = bpy.data.materials.get('Brush Material') + if not mat: + mat = utils.import_brushstroke_material() + settings.context_material = mat + preset_object['BSBST_material'] = settings.context_material + + return {"FINISHED"} + +class BSBST_OT_make_preset(bpy.types.Operator): + """ + Make the current brushstrokes style specification the active preset. + """ + bl_idname = "brushstroke_tools.make_preset" + bl_label = "Make Preset" + bl_description = "Make the current brushstrokes style specification the active preset" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + return bool(utils.get_active_context_brushstrokes_object(context)) + + def execute(self, context): + + settings = context.scene.BSBST_settings + + if not settings.preset_object: + preset_name = f'BSBST-PRESET_{settings.brushstroke_method}' + settings.preset_object = bpy.data.objects.new(preset_name, bpy.data.hair_curves.new(preset_name)) + else: + for mod in settings.preset_object.modifiers[:]: + settings.preset_object.modifiers.remove(mod) + + # transfer brushstrokes modifiers to preset + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + return {"CANCELLED"} + for mod in bs_ob.modifiers: + utils.transfer_modifier(mod.name, settings.preset_object, bs_ob) + utils.refresh_preset(None) + + for mod in settings.preset_object.modifiers: + # refresh UI + mod.node_group.interface_update(context) + + # identify linked sockets + for v in mod.node_group.interface.items_tree.values(): + if type(v) not in utils.linkable_sockets: + continue + if not settings.preset_object.modifier_info[mod.name].socket_info[v.identifier]: + continue + if type(v) == bpy.types.NodeTreeInterfaceSocketObject: + if bs_ob['BSBST_surface_object']==mod[v.identifier]: + mod[v.identifier] = None + settings.preset_object.modifier_info[mod.name].socket_info[v.identifier].link_context = True + elif type(v) == bpy.types.NodeTreeInterfaceSocketMaterial: + pass # TODO: figure out material preset linking + return {"FINISHED"} + +class BSBST_OT_preset_add_mod(bpy.types.Operator): + """ + Add a modifier to the preset stack. + """ + bl_idname = "brushstroke_tools.preset_add_mod" + bl_label = "Add Preset Modifier" + bl_description = "Add a modifier to the preset" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return settings.preset_object + + def execute(self, context): + + settings = context.scene.BSBST_settings + settings.preset_object.modifiers.new('Brushstrokes Style', type='NODES') + + return {"FINISHED"} + +class BSBST_OT_preset_remove_mod(bpy.types.Operator): + """ + Remove a modifier from the preset stack. + """ + bl_idname = "brushstroke_tools.preset_remove_mod" + bl_label = "Remove Preset Modifier" + bl_description = "Remove a modifier from the preset" + bl_options = {"REGISTER", "UNDO"} + + modifier: bpy.props.StringProperty(default='') + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return settings.preset_object + + def execute(self, context): + + settings = context.scene.BSBST_settings + with context.temp_override(object=settings.preset_object): + bpy.ops.object.modifier_remove(modifier=self.modifier) + + return {"FINISHED"} + +class BSBST_OT_preset_toggle_attribute(bpy.types.Operator): + """ + Toggle use_attribute property for a socket on a specific object's modifier. + (Workaround due to how these are actually stored as integer in Blender) + """ + bl_idname = "brushstroke_tools.preset_toggle_attribute" + bl_label = "Toggle Attribute" + bl_description = "Toggle using a named attribute for this input" + bl_options = {"REGISTER", "UNDO"} + + modifier_name: bpy.props.StringProperty(default='GeometryNodes') + input_name: bpy.props.StringProperty(default='Socket_2') + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return settings.preset_object + + def execute(self, context): + settings = context.scene.BSBST_settings + override = context.copy() + override['object'] = settings.preset_object + with context.temp_override(**override): + bpy.ops.object.geometry_nodes_input_attribute_toggle(input_name=self.input_name, + modifier_name=self.modifier_name) + return {"FINISHED"} + +class BSBST_OT_brushstrokes_toggle_attribute(bpy.types.Operator): + """ + Toggle use_attribute property for a socket on a specific object's modifier. + (Workaround due to how these are actually stored as integer in Blender) + """ + bl_idname = "brushstroke_tools.brushstrokes_toggle_attribute" + bl_label = "Toggle Attribute" + bl_description = "Toggle using a named attribute for this input" + bl_options = {"REGISTER", "UNDO"} + + modifier_name: bpy.props.StringProperty(default='GeometryNodes') + input_name: bpy.props.StringProperty(default='Socket_2') + + @classmethod + def poll(cls, context): + settings = context.scene.BSBST_settings + return settings.preset_object + + def execute(self, context): + settings = context.scene.BSBST_settings + + edit_toggle = settings.edit_toggle + settings.edit_toggle = False + + bs_ob = utils.get_active_context_brushstrokes_object(context) + if not bs_ob: + settings.edit_toggle = edit_toggle + return {"CANCELLED"} + + override = context.copy() + override['object'] = bs_ob + with context.temp_override(**override): + bpy.ops.object.geometry_nodes_input_attribute_toggle(input_name=self.input_name, + modifier_name=self.modifier_name) + return {"FINISHED"} + +class BSBST_OT_render_setup(bpy.types.Operator): + """ + Set up render settings. + """ + bl_idname = "brushstroke_tools.render_setup" + bl_label = "Render Setup" + bl_description = "Set up render settings" + bl_options = {"REGISTER", "UNDO"} + + render_engine: bpy.props.EnumProperty(name='Render Engine', + items = [ + ('ALL', 'All', 'Set up for all available render engines', '', 0), + ('CYCLES', 'Cycles', 'Set up for Cycles', '', 1), + ('EEVEE', 'Eevee', 'Set up for Eevee', '', 2), + ] + ) + trans_pass_toggle: bpy.props.BoolProperty(default=True) + trans_pass: bpy.props.IntProperty(name='Transparency Passes', default=256, min=0, soft_max=1024) + + prop_map = { + 'CYCLES':['trans_pass', + ], + 'EEVEE':[ + ] + } + + def draw(self, context): + layout = self.layout + layout.prop(self, 'render_engine', text='') + for k, v in self.prop_map.items(): + if self.render_engine not in [k, 'ALL']: + continue + layout.label(text=k.capitalize()) + for prop in v: + split = layout.split(factor=.1) + split.prop(self, f'{prop}_toggle', icon_only=True) + split.active = getattr(self, f'{prop}_toggle', False) + split.prop(self, prop) + + def execute(self, context): + settings = context.scene.BSBST_settings + if self.render_engine in ['CYCLES', 'ALL']: + if self.trans_pass_toggle: + context.scene.cycles.transparent_max_bounces = self.trans_pass + return {"FINISHED"} + + def invoke(self, context, event): + return context.window_manager.invoke_props_dialog(self) + +class BSBST_OT_view_all(bpy.types.Operator): + """ + Enable/disable all brushstrokes for the viewport. + """ + bl_idname = "brushstroke_tools.view_all" + bl_label = "Enable/Disable All" + bl_description = "Enable/disable all brushstrokes for the viewport" + bl_options = {"REGISTER", "UNDO"} + + disable: bpy.props.BoolProperty(default=False) + + def execute(self, context): + for ob in bpy.data.objects: + if not utils.is_brushstrokes_object(ob): + continue + if ob.hide_viewport == self.disable: + continue + else: + ob.hide_viewport = self.disable + return {"FINISHED"} + +class BSBST_OT_new_material(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.new_material" + bl_label = "New Brushstrokes Material" + bl_description = "Create new material for the current brushstrokes" + bl_options = {"REGISTER", "UNDO"} + + @classmethod + def poll(cls, context): + return bool(utils.context_brushstrokes(context)) + + def execute(self, context): + settings = context.scene.BSBST_settings + mat = utils.import_brushstroke_material() + settings.context_material = mat + return {"FINISHED"} + +classes = [ + BSBST_OT_new_brushstrokes, + BSBST_OT_edit_brushstrokes, + BSBST_OT_delete_brushstrokes, + BSBST_OT_duplicate_brushstrokes, + BSBST_OT_copy_brushstrokes, + BSBST_OT_copy_flow, + BSBST_OT_switch_deformable, + BSBST_OT_switch_animated, + BSBST_OT_select_surface, + BSBST_OT_assign_surface, + BSBST_OT_init_preset, + BSBST_OT_make_preset, + BSBST_OT_preset_add_mod, + BSBST_OT_preset_remove_mod, + BSBST_OT_preset_toggle_attribute, + BSBST_OT_brushstrokes_toggle_attribute, + BSBST_OT_view_all, + BSBST_OT_render_setup, + BSBST_OT_new_material, + ] + +def register(): + for c in classes: + bpy.utils.register_class(c) + +def unregister(): + for c in reversed(classes): + bpy.utils.unregister_class(c) \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/preferences.py b/scripts-blender/addons/brushstroke_tools/preferences.py new file mode 100644 index 00000000..79542c8a --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/preferences.py @@ -0,0 +1,157 @@ +import bpy +from bpy.app.handlers import persistent +from . import utils +import os + +@persistent +def load_handler(dummy): + utils.refresh_brushstroke_styles() + +def update_resource_path(self, context): + utils.update_asset_lib_path() + +class BSBST_OT_refresh_brushstroke_styles(bpy.types.Operator): + """ + """ + bl_idname = "brushstroke_tools.refresh_styles" + bl_label = "Refresh Brushstroke Styles" + bl_description = "Refresh available brushstroke styles from library." + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + utils.refresh_brushstroke_styles() + return {"FINISHED"} +class BSBST_OT_copy_resources_to_path(bpy.types.Operator): + """ + Copy Resources to Directory. + """ + bl_idname = "brushstroke_tools.copy_resources" + bl_label = "Copy Resources" + bl_description = "Copy addon resources to local directory" + bl_options = {"REGISTER", "UNDO"} + + update: bpy.props.BoolProperty(default=False) + + @classmethod + def poll(cls, context): + addon_prefs = context.preferences.addons[__package__].preferences + return os.path.isdir(addon_prefs.resource_path) + + def execute(self, context): + utils.copy_resources_to_dir() + return {"FINISHED"} + + def invoke(self, context, event): + wm = context.window_manager + return wm.invoke_props_dialog(self) + + def draw(self, context): + layout = self.layout + layout.label(text='This will overwrite files in the target directory!', icon='ERROR') + layout.label(text=utils.get_resource_directory()) + +class BSBST_brush_style(bpy.types.PropertyGroup): + name: bpy.props.StringProperty(default='') + filepath: bpy.props.StringProperty(default='') + +class BSBST_UL_brush_styles(bpy.types.UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname): + resource_dir = utils.get_resource_directory() + if self.layout_type in {'DEFAULT', 'COMPACT'}: + split = layout.split(factor=0.4) + split.label(text=item.name) + row = split.row() + row.active = False + row.label(text=item.filepath.replace(resource_dir, '{LIB}/'), icon='FILE_FOLDER') + elif self.layout_type == 'GRID': + layout.label(text=item.name) + + def draw_filter(self, context, layout): + return + +class BSBST_preferences(bpy.types.AddonPreferences): + bl_idname = __package__ + + resource_path: bpy.props.StringProperty(name='Resource Directory', subtype='DIR_PATH', update=update_resource_path) + import_relative_path: bpy.props.BoolProperty(name='Relative Path', default=True) + import_method: bpy.props.EnumProperty(name='Import Method', default='APPEND', + items= [('APPEND', 'Append', 'Append data-blocks and pack image data as local to this file.', 'APPEND_BLEND', 0),\ + ('LINK', 'Link', 'Link data-blocks from resource directory.', 'LINK_BLEND', 1), + ]) + brush_styles: bpy.props.CollectionProperty(type=BSBST_brush_style) + active_brush_style_index: bpy.props.IntProperty() + + def draw(self, context): + layout = self.layout + row = layout.row() + row.label(text='Brushstrokes Library', icon='ASSET_MANAGER') + layout.prop(self, 'import_method') + if self.import_method == 'LINK': + layout.prop(self, 'import_relative_path') + row = layout.row() + col = row.column() + dir_exists = os.path.isdir(utils.get_resource_directory()) + resources_available = os.path.isfile(f"{utils.get_resource_directory()}brushstroke_tools-resources.blend") + if not dir_exists or not resources_available: + col.alert = True + col.prop(self, 'resource_path', placeholder=utils.get_resource_directory()) + + split = layout.split(factor=0.25) + split.column() + col = split.column() + if not dir_exists: + col.alert = True + row = col.row() + row.label(text='The selected directory does not exist.', icon='ERROR') + elif not resources_available: + col.alert = True + split = col.split(factor=0.75) + split.label(text='The required resources were not found at the specified directory.', icon='ERROR') + op = split.operator('brushstroke_tools.copy_resources', icon='IMPORT') + op.update = False + elif self.resource_path: + lib_version = utils.read_lib_version() + version_comp = utils.compare_versions(lib_version, utils.addon_version) + if bool(version_comp): + col.label(text=f"Version mismatch: Local Data ({'.'.join([str(i) for i in lib_version])}) {'>' if version_comp>0 else '<'} Addon ({'.'.join([str(i) for i in utils.addon_version])})", icon='ERROR') + if abs(version_comp) in [1,2]: + split = col.split(factor=0.75) + if version_comp>0: + split.label(text="Consider upgrading the addon or re-copying the data.") + else: + split.label(text="Consider upgrading re-copying the data.") + op = split.operator('brushstroke_tools.copy_resources', icon='IMPORT') + op.update = False + + if self.import_method == 'LINK' and not self.resource_path: + col.label(text='Linking the resources from the default addon directory is not recommended.', icon='ERROR') + + style_box = layout.box() + style_box_header = style_box.row(align=True) + style_box_header.label(text=f'Brush Styles ({len(self.brush_styles)} loaded)', icon='BRUSHES_ALL') + style_box_header.operator('brushstroke_tools.refresh_styles', text='', icon='FILE_REFRESH') + if not self.brush_styles: + style_box.label(text='No Brush styles found in library directory', icon='ERROR') + else: + style_box.template_list('BSBST_UL_brush_styles', "", self, "brush_styles", + self, "active_brush_style_index", rows=3, maxrows=5, sort_lock=True) + + + +classes = [ + BSBST_brush_style, + BSBST_UL_brush_styles, + BSBST_preferences, + BSBST_OT_copy_resources_to_path, + BSBST_OT_refresh_brushstroke_styles, +] + +def register(): + for c in classes: + bpy.utils.register_class(c) + bpy.app.handlers.load_post.append(load_handler) + +def unregister(): + for c in classes: + bpy.utils.unregister_class(c) + bpy.app.handlers.load_post.remove(load_handler) \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/settings.py b/scripts-blender/addons/brushstroke_tools/settings.py new file mode 100644 index 00000000..ec9bd2eb --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/settings.py @@ -0,0 +1,283 @@ +import bpy +from . import utils, icons + +def update_active_brushstrokes(self, context): + settings = context.scene.BSBST_settings + for i, el in enumerate(settings.context_brushstrokes): + ob = bpy.data.objects.get(el.name) + if not ob: + continue + is_active = i == settings.active_context_brushstrokes_index + ob['BSBST_active'] = is_active + if 'BSBST_material' in ob.keys() and is_active: + settings.context_material = ob['BSBST_material'] + +def update_brushstroke_method(self, context): + settings = context.scene.BSBST_settings + + preset_name = f'BSBST-PRESET_{settings.brushstroke_method}' + preset_object = bpy.data.objects.get(preset_name) + settings.preset_object = preset_object + + style_object = utils.get_active_context_brushstrokes_object(context) + if not style_object: + style_object = preset_object + + if not style_object: + settings.context_material = None + return + if 'BSBST_material' in style_object.keys(): + settings.context_material = style_object['BSBST_material'] + else: + settings.context_material = None + +def update_context_material(self, context): + settings = context.scene.BSBST_settings + + style_object = utils.get_active_context_brushstrokes_object(context) + if not style_object: + style_object = settings.preset_object + if not style_object: + return + utils.set_brushstroke_material(style_object, self.context_material) + ng = bpy.data.node_groups.get(f'BSBST-BS.{self.context_material.brush_style}') + if not ng: + utils.set_preview(None) + return + if ng.preview: + utils.set_preview(ng.preview.image_pixels_float, ng.preview.image_size[:], ng.name) + else: + utils.set_preview(None) + +def update_link_context_type(self, context): + self.link_context = True + +def get_brushstroke_name(self): + return self["name"] + +def set_brushstroke_name(self, value): + prev_name = self.get('name') + self["name"] = value + if not prev_name: + return + ob = bpy.data.objects.get(prev_name) + if not ob: + return + ob.name = value + ob.data.name = value + flow_ob = utils.get_flow_object(ob) + if flow_ob: + flow_name = utils.flow_name(value) + flow_ob.name = flow_name + flow_ob.data.name = flow_name + +def get_modifier_name(self): + return self["name"] + +def set_modifier_name(self, value): + prev_name = self.get('name') + if not prev_name: + self["name"] = value + return + ob = self.id_data.modifiers.get(prev_name) + ob.name = value + self["name"] = ob.name + +def get_hide_viewport_base(self): + return self["hide_viewport_base"] + +def set_hide_viewport_base(self, value): + self["hide_viewport_base"] = value + ob = bpy.data.objects.get(self.name) + if not ob: + return + ob.hide_set(value) + +def get_active_context_brushstrokes_index(self): + if not self.get('active_context_brushstrokes_index'): + return 0 + return self["active_context_brushstrokes_index"] + +def set_active_context_brushstrokes_index(self, value): + settings = bpy.context.scene.BSBST_settings + if not settings.context_brushstrokes: + if not settings.preset_object: + return + if 'BSBST_material' in settings.preset_object.keys(): + settings.context_material = settings.preset_object['BSBST_material'] + prev = self.get('active_context_brushstrokes_index') + if prev == abs(value): + return + self["active_context_brushstrokes_index"] = abs(value) + bs_ob = bpy.data.objects.get(self.context_brushstrokes[value].name) + if settings.silent_switch: + return + if not bs_ob: + return + if not bpy.context.object: + return + view_layer = bpy.context.view_layer + if bpy.context.object.visible_get(view_layer = view_layer): + bpy.ops.object.mode_set(mode='OBJECT') + bpy.context.view_layer.objects.active = bs_ob + if bs_ob.visible_get(view_layer = view_layer): + bpy.ops.object.mode_set(mode='OBJECT') + for ob in bpy.data.objects: + ob.select_set(False) + if utils.is_brushstrokes_object(ob): + ob['BSBST_active'] = False + bs_ob.select_set(True) + bs_ob['BSBST_active'] = True + if settings.edit_toggle and bs_ob.visible_get(view_layer = view_layer): + utils.edit_active_brushstrokes(bpy.context) + if 'BSBST_material' in bs_ob.keys(): + settings.context_material = bs_ob['BSBST_material'] + +def get_brush_style(self): + name = self.node_tree.nodes['Brush Style'].node_tree.name + return '.'.join(name.split('.')[1:]) + +def set_brush_style(self, value): + addon_prefs = bpy.context.preferences.addons[__package__].preferences + ng_name = f'BSBST-BS.{value}' + ng = utils.ensure_node_group(ng_name, [bs for bs in addon_prefs.brush_styles if bs.name==value][0].filepath) + + if ng.preview: + utils.set_preview(ng.preview.image_pixels_float, ng.preview.image_size[:], ng.name) + else: + utils.set_preview(None) + + node = self.node_tree.nodes['Brush Style'] + node_prev_inputs = [input.name for input in node.inputs] + node.node_tree = ng + for in_new in node.inputs: + if in_new.name in node_prev_inputs: + continue + in_new.default_value = ng.interface.items_tree[in_new.name].default_value + self["brush_style"] = value + +def link_context_type_items(self, context): + items = [ + ('SURFACE_OBJECT', 'Surface Object', 'Link socket preset to context surface object', 'OUTLINER_OB_SURFACE', 1),\ + ('FLOW_OBJECT', 'Flow Object', 'Link socket preset to context flow object', 'FORCE_WIND', 11), + ('MATERIAL', 'Material', 'Link socket preset to context material', 'MATERIAL', 101), + ('UVMAP', 'UV Map', 'Link socket preset to active context UVMap', 'UV', 201), + ('RANDOM', 'Random', 'Randomize input value', icons.icon_previews['main']["RANDOM"].icon_id, 501), + ] + return items + +def icon_from_link_type(link_type): + items = link_context_type_items(None, bpy.context) + for enum_item in items: + if enum_item[0]==link_type: + icon = enum_item[3] + if type(icon) == int: + return icon + else: + return {k : i for i, k in enumerate(bpy.types.UILayout.bl_rna.functions["prop"].parameters["icon"].enum_items.keys())}[icon] + +class BSBST_socket_info(bpy.types.PropertyGroup): + name: bpy.props.StringProperty(default='') + link_context: bpy.props.BoolProperty(default=False, name='Link to Context') + link_context_type: bpy.props.EnumProperty(default=1, name='Link to Context', update=update_link_context_type, + items=link_context_type_items) + hide_ui: bpy.props.BoolProperty(default=False) + +class BSBST_modifier_info(bpy.types.PropertyGroup): + name: bpy.props.StringProperty(default='', get=get_modifier_name, set=set_modifier_name) + hide_ui: bpy.props.BoolProperty(default=False) + default_closed: bpy.props.BoolProperty(default=False) + socket_info: bpy.props.CollectionProperty(type=BSBST_socket_info) + +class BSBST_context_brushstrokes(bpy.types.PropertyGroup): + name: bpy.props.StringProperty(default='', get=get_brushstroke_name, set=set_brushstroke_name) + method: bpy.props.StringProperty(default='') + hide_viewport_base: bpy.props.BoolProperty(default=False, get=get_hide_viewport_base, set=set_hide_viewport_base) + +class BSBST_Settings(bpy.types.PropertyGroup): + attach_to_active_selection: bpy.props.BoolProperty(default=True) + preset_object: bpy.props.PointerProperty(type=bpy.types.Object, name="Default/Preset Object") + assign_materials: bpy.props.BoolProperty(name='Assign Modifier Materials', default=True) + brushstroke_method: bpy.props.EnumProperty(default='SURFACE_FILL', update=update_brushstroke_method, + items= [('SURFACE_FILL', 'Fill', 'Use surface fill method for new brushstroke object', 'OUTLINER_OB_FORCE_FIELD', 0),\ + ('SURFACE_DRAW', 'Draw', 'Use surface draw method for new brushstroke object', 'LINE_DATA', 1), + ]) + style_context: bpy.props.EnumProperty(default='BRUSHSTROKES', + name='Context', + items= [ + ('PRESET', 'Default', 'Specify the style of the current default used for new brushstrokes', 'SETTINGS', 0),\ + ('BRUSHSTROKES', 'Brushstrokes', 'Specify the style of the currently active brushstrokes', 'BRUSH_DATA', 1), + ('AUTO', 'Auto', 'Specify the style of either the active brushstrokes or the preset depending on the context', 'AUTO', 2), + ]) + view_tab: bpy.props.EnumProperty(default='SHAPE', + name='Context', + items= [ + ('SHAPE', 'Shape', 'View Modifiers Settings', 'MODIFIER', 0), + ('MATERIAL', 'Material', 'View Material Settings', 'MATERIAL', 1), + ('SETTINGS', 'Settings', 'View Additional Settings', 'PREFERENCES', 2), + ]) + + try: + gpv3 = bpy.context.preferences.experimental.use_grease_pencil_version3 + except: + v0, v1, v3 = bpy.app.version + gpv3 = v0 >= 4 and v1 >= 3 + curve_mode: bpy.props.EnumProperty(default='CURVES', + items= [('CURVE', 'Legacy', 'Use legacy curve type (Limited Support)', 'CURVE_DATA', 0),\ + ('CURVES', 'Curves', 'Use hair curves (Fully supported)', 'CURVES_DATA', 1), + ('GP', 'Grease Pencil', 'Use Grease Pencil (Limited Support)', 'OUTLINER_OB_GREASEPENCIL', 2), + ] if gpv3 else + [('CURVE', 'Legacy', 'Use legacy curve type (Limited Support)', 'CURVE_DATA', 0),\ + ('CURVES', 'Curves', 'Use hair curves (Full Support)', 'CURVES_DATA', 1), + ]) + context_brushstrokes: bpy.props.CollectionProperty(type=BSBST_context_brushstrokes) + context_material: bpy.props.PointerProperty(type=bpy.types.Material, name="Material", update=update_context_material) + active_context_brushstrokes_index: bpy.props.IntProperty( default = 0, + update=update_active_brushstrokes, + get=get_active_context_brushstrokes_index, + set=set_active_context_brushstrokes_index) + ui_options: bpy.props.BoolProperty(default=False, + name='UI Options', + description="Show advanced UI options to customize exposed parameters") + reuse_flow: bpy.props.BoolProperty(default=False, + name='Re-use Flow Object', + description="Re-use flow object from active brushstrokes when creating new brushstrokes") + deforming_surface: bpy.props.BoolProperty(default=False, + name='Deforming Surface', + description='Create brushstrokes layer for a deforming surface') + animated: bpy.props.BoolProperty(default=False, + name='Animated', + description='Create brushstrokes layer for animated brushstrokes/flow') + edit_toggle: bpy.props.BoolProperty(default=False, + name='Edit on Selection', + description="Jump into the corresponding edit mode when selecting a brushstrokes layer") + estimate_dimensions: bpy.props.BoolProperty(default=True, + name='Estimate Dimensions', + description="Estimate the length, width and distribution density of the brush strokes based on the bounding box to provide a reasonable starting point regardless of scale") + + silent_switch: bpy.props.BoolProperty(default=False) + preview_texture: bpy.props.PointerProperty(type=bpy.types.Texture) + +classes = [ + BSBST_socket_info, + BSBST_modifier_info, + BSBST_context_brushstrokes, + BSBST_Settings, +] + +def register(): + for c in classes: + bpy.utils.register_class(c) + bpy.types.Scene.BSBST_settings = bpy.props.PointerProperty(type=BSBST_Settings) + bpy.types.Object.modifier_info = bpy.props.CollectionProperty(type=BSBST_modifier_info) + bpy.types.Material.brush_style = bpy.props.StringProperty(get=get_brush_style, set=set_brush_style, search_options={'SORT'}) + + bpy.app.handlers.depsgraph_update_post.append(utils.find_context_brushstrokes) + +def unregister(): + for c in reversed(classes): + bpy.utils.unregister_class(c) + del bpy.types.Scene.BSBST_settings + del bpy.types.Object.modifier_info + + bpy.app.handlers.depsgraph_update_post.remove(utils.find_context_brushstrokes) \ No newline at end of file diff --git a/scripts-blender/addons/brushstroke_tools/ui.py b/scripts-blender/addons/brushstroke_tools/ui.py new file mode 100644 index 00000000..f3cb32f4 --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/ui.py @@ -0,0 +1,577 @@ +import bpy +from . import utils +from . import settings as settings_py + +warning_icons_dict = { + 'ERROR': 'CANCEL', + 'WARNING': 'ERROR', + 'INFO': 'INFO', +} + +def draw_panel_ui_recursive(panel, panel_name, mod, items, display_mode, hide_panel=False): + + scene = bpy.context.scene + settings = scene.BSBST_settings + + is_preset = mod.id_data == settings.preset_object and mod.id_data + + if not panel: + return + + mod_info = mod.id_data.modifier_info.get(mod.name) + + icon_dict = { + bpy.types.NodeTreeInterfaceSocketObject: 'OBJECT_DATA', + bpy.types.NodeTreeInterfaceSocketMaterial: 'MATERIAL', + bpy.types.NodeTreeInterfaceSocketImage: 'IMAGE_DATA', + bpy.types.NodeTreeInterfaceSocketCollection: 'OUTLINER_COLLECTION', + } + + data_dict = { + bpy.types.NodeTreeInterfaceSocketMaterial: 'materials', + bpy.types.NodeTreeInterfaceSocketImage: 'images', + bpy.types.NodeTreeInterfaceSocketCollection: 'collections', + } + + mode_compare = [] + for k, v in items: + if type(v) == bpy.types.NodeTreeInterfacePanel: + + v_id = f'Panel_{v.index}' # TODO: replace with panel identifier once that is exposed in Blender 4.3 + + if not mod_info: + continue + s = mod_info.socket_info.get(v_id) + if not s: + continue + if display_mode == 0: + if s.hide_ui: + continue + + subpanel_header, subpanel = panel.panel(k, default_closed = v.default_closed) + subpanel_header.label(text=k) + if display_mode != 0: + col = subpanel_header.column() + col.active = not (mod_info.hide_ui or hide_panel) + col.prop(s, 'hide_ui', icon_only=True, icon='UNPINNED' if s.hide_ui else 'PINNED', emboss=False) + draw_panel_ui_recursive(subpanel, k, mod, v.interface_items.items(), display_mode, s.hide_ui) + mode_compare = [] + else: + if v.parent.name != panel_name: + continue + if f'{v.identifier}' not in mod.keys(): + continue + if not mod_info: + continue + + if type(v) == bpy.types.NodeTreeInterfaceSocketMenu: + for item in mod.id_properties_ui(f'{v.identifier}').as_dict()['items']: + if item[4] == mod[f'{v.identifier}']: + continue + mode_compare += [item[0]] + + s = mod_info.socket_info.get(v.identifier) + if not s: + continue + if display_mode == 0: + comp_match = False + for c in mode_compare: + comp_match = c in v.name + if comp_match: + break + if comp_match: + continue + if s.hide_ui: + continue + row = panel.row(align=True) + row.active = not (mod_info.hide_ui or hide_panel or s.hide_ui) + + col = row.column() + input_row = col.row(align=True) + attribute_toggle = False + if f'{v.identifier}_use_attribute' in mod.keys() and not v.force_non_field: + attribute_toggle = mod[f'{v.identifier}_use_attribute'] + if attribute_toggle: + input_row.prop(mod, f'["{v.identifier}_attribute_name"]', text=k) + else: + input_row.prop(mod, f'["{v.identifier}"]', text=k) + if is_preset: + toggle = input_row.operator('brushstroke_tools.preset_toggle_attribute', + text='', + depress=mod[f'{v.identifier}_use_attribute'], + icon='SPREADSHEET') + else: + toggle = input_row.operator('brushstroke_tools.brushstrokes_toggle_attribute', + text='', + depress=mod[f'{v.identifier}_use_attribute'], + icon='SPREADSHEET') + toggle.modifier_name = mod.name + toggle.input_name = v.identifier + else: + if type(v) in icon_dict.keys(): + icon = icon_dict[type(v)] + else: + icon='NONE' + if type(v) in data_dict.keys(): + input_row.prop_search(mod, f'["{v.identifier}"]', bpy.data, data_dict[type(v)], text=k, icon=icon) + else: + input_row.prop(mod, f'["{v.identifier}"]', text=k, icon=icon) + if type(v) in utils.linkable_sockets: + col.active = not s.link_context + icon = settings_py.icon_from_link_type(s.link_context_type) + row.alignment = 'EXPAND' + if s.link_context: + row.prop(s, 'link_context', text='', icon_value=icon) + else: + if display_mode == -1: + row.prop(s, 'link_context_type', text='', emboss=True, icon='LINKED', icon_only=True) + if display_mode != 0: + col = row.column() + col.active = not (mod_info.hide_ui or hide_panel) + col.prop(s, 'hide_ui', icon_only=True, icon='UNPINNED' if s.hide_ui else 'PINNED', emboss=False) + +def draw_material_settings(layout, material, surface_object=None): + addon_prefs = bpy.context.preferences.addons[__package__].preferences + settings = bpy.context.scene.BSBST_settings + + material_row = layout.row(align=True) + material_row.template_ID(settings, 'context_material') + + material_header, material_panel = layout.panel("brushstrokes_material", default_closed=False) + material_header.label(text='Properties', icon='MATERIAL') + if material_panel: + # draw color options + try: + n1 = material.node_tree.nodes['Color Attribute'] + n2 = material.node_tree.nodes['Color Texture'] + n3 = material.node_tree.nodes['Color'] + n4 = material.node_tree.nodes['Image Texture'] + n5 = material.node_tree.nodes['UV Map'] + n6 = material.node_tree.nodes['Color Variation'] + + box = material_panel.box() + box.prop(n1, 'mute', text='Use Brush Color', invert_checkbox=True) + if n1.mute: + row = box.row(align=True) + if n2.mute: + row.prop(n3.outputs[0], 'default_value', text ='') + else: + col = row.column() + col.template_node_inputs(n4) + row.prop(n2, 'mute', icon_only=True, invert_checkbox=True, icon='IMAGE') + if not n2.mute: + if not surface_object: + box.prop(n5, 'uv_map', icon='UV') + else: + box.prop_search(n5, 'uv_map', surface_object.data, 'uv_layers', icon='UV') + box.prop(n6.inputs[0], 'default_value', text='Color Variation') + except: + pass + + # draw opacity options + try: + n1 = material.node_tree.nodes.get('Use Strength') + n2 = material.node_tree.nodes.get('Opacity') + n3 = material.node_tree.nodes.get('Backface Culling') + + box = material_panel.box() + if n1: + box.prop(n1, 'mute', text='Use Brush Strength', invert_checkbox=True) + if n2: + box.prop(n2.inputs[0], 'default_value', text='Opacity') + if n3: + box.prop(n3, 'mute', text='Backface Culling', invert_checkbox=True) + except: + pass + + # draw BSDF options + try: + n1 = material.node_tree.nodes['Principled BSDF'] + n2 = material.node_tree.nodes['Bump'] + + box = material_panel.box() + box.prop(n1.inputs[1], 'default_value', text='Metallic') + box.prop(n1.inputs[2], 'default_value', text='Roughness') + box.prop(n2, 'mute', text='Bump', invert_checkbox=True) + row = box.row() + if n2.mute: + row.active = False + row.prop(n2.inputs[0], 'default_value', text='Bump Strength') + except: + pass + + # draw translucency options + try: + n1 = material.node_tree.nodes['Translucency Add'] + n2 = material.node_tree.nodes['Translucency Strength'] + n3 = material.node_tree.nodes['Translucency Tint'] + + box = material_panel.box() + box.prop(n1, 'mute', text='Translucency', invert_checkbox=True) + box.prop(n2.inputs[0], 'default_value', text='Translucency Strength') + box.prop(n3.inputs[7], 'default_value', text='Translucency Tint') + except: + pass + + material_panel.prop(material, 'diffuse_color', text='Viewport Color') + + # draw brush style options + try: + n1 = material.node_tree.nodes['Brush Style'] + n2 = material.node_tree.nodes['Brush Curve'] + + brush_header, brush_panel = layout.panel('brush_panel', default_closed = True) + brush_header.label(text='Brush Style', icon='BRUSHES_ALL') + if brush_panel: + if settings.preview_texture: + row = brush_panel.row(align=True) + row.template_preview(settings.preview_texture, show_buttons=False, preview_id='brushstroke_preview') + + row = brush_panel.row(align=True) + row.prop_search(material, 'brush_style', addon_prefs, 'brush_styles', text='', icon='BRUSHES_ALL') + row.operator('brushstroke_tools.refresh_styles', text='', icon='FILE_REFRESH') + if n1.inputs: + for in_s in n1.inputs: + brush_panel.prop(in_s, 'default_value', text=f"{in_s.name}") + brush_panel.template_node_inputs(n2) + except: + pass + + # draw effects options + try: + n1 = material.node_tree.nodes['Effects In'] + + effects_header, effects_panel = layout.panel('effects_panel', default_closed = True) + effects_header.label(text='Effects', icon='SHADERFX') + if effects_panel: + draw_effect_panel_recursive(effects_panel, material, n1) + except: + pass + +def draw_effect_panel_recursive(effects_panel, material, prev_node): + if not prev_node: + return + if not prev_node.outputs[0].links: + return + node = prev_node.outputs[0].links[0].to_node + if node.name == 'Effects Out': + return + header, panel = effects_panel.panel(f'{node.name}_panel', default_closed = True) + header.alignment = 'LEFT' + header.prop(node, 'mute', invert_checkbox=True, icon_only=True) + header.label(text=node.label if node.label else node.name) + if panel: + if node.mute: + panel.active = False + for input in node.inputs[1:]: + panel.prop(input, 'default_value', text=input.name) + + draw_effect_panel_recursive(effects_panel, material, node) + +def draw_advanced_settings(layout, settings): + new_advanced_header, new_advanced_panel = layout.panel("new_advanced", default_closed=True) + new_advanced_header.label(text='Advanced') + if not new_advanced_panel: + return + new_advanced_panel.row().prop(settings, 'curve_mode', expand=True) + if settings.curve_mode in ['CURVE', 'GP']: + new_advanced_panel.label(text='Curve mode does not support drawing on deformed geometry', icon='ERROR') + + new_advanced_panel.prop(settings, 'animated') + new_advanced_panel.prop(settings, 'deforming_surface') + new_advanced_panel.prop(settings, 'assign_materials') + new_advanced_panel.prop(settings, 'reuse_flow') + new_advanced_panel.prop(settings, 'estimate_dimensions') + new_advanced_panel.prop(settings, 'style_context') + new_advanced_panel.operator('brushstroke_tools.render_setup') + +def draw_shape_properties(layout, settings, style_object, is_preset, display_mode): + if not style_object: + return + for mod in style_object.modifiers: + mod_info = mod.id_data.modifier_info.get(mod.name) + if not mod_info: + continue + if display_mode == 0: + if mod_info.hide_ui: + continue + + mod_header, mod_panel = layout.panel(mod.name, default_closed = mod_info.default_closed) + row = mod_header.row(align=True) + row.label(text='', icon='GEOMETRY_NODES') + row.prop(mod_info, 'name', text='', emboss=False) + + if display_mode != 0: + mod_header.prop(mod_info, 'hide_ui', icon_only=True, icon='UNPINNED' if mod_info.hide_ui else 'PINNED', emboss=False) + if is_preset: + op = row.operator('brushstroke_tools.preset_remove_mod', text='', icon='X') + else: + op = row.operator('object.modifier_remove', text='', icon='X') + # TODO Implement operator to remove modifier on brushstroke object, even when not active + op.modifier = mod.name + + if not mod_panel: + continue + + if not mod.type == 'NODES': + mod_panel.label(text="Only 'Nodes' modifiers supported") + continue + + # show settings for nodes modifiers + if mod.show_group_selector: + mod_panel.prop(mod, 'node_group') + if not mod.node_group: + continue + + draw_panel_ui_recursive(mod_panel, + '', + mod, + mod.node_group.interface.items_tree.items(), + display_mode) + + draw_mod_warnings(layout, mod) + +def draw_material_properties(layout, settings, surface_object): + if settings.context_material: + draw_material_settings(layout, settings.context_material, surface_object=surface_object) + else: + material_row = layout.row(align=True) + material_row.template_ID(settings, 'context_material', new='brushstroke_tools.new_material') + +def draw_settings_properties(layout, settings, style_object): + deform = utils.get_deformable(style_object) + op = layout.operator('brushstroke_tools.switch_deformable', text='Deforming Surface', depress=deform, icon='MOD_SIMPLEDEFORM') + op.deformable = not deform + + anim = utils.get_animated(style_object) + op = layout.operator('brushstroke_tools.switch_animated', text='Animated Strokes', depress=anim, icon='GP_MULTIFRAME_EDITING') + op.animated = not anim + + layout.prop(style_object, 'visible_shadow', icon='LIGHT', emboss=True) + +def draw_properties_panel(layout, settings, style_object, surface_object, is_preset, display_mode): + + layout.separator(type='LINE') + row = layout.row(align=True) + row.prop(settings, 'view_tab', expand=True) + layout.separator(factor=.0, type='SPACE') + + if settings.view_tab == 'MATERIAL': + draw_material_properties(layout, settings, surface_object) + elif settings.view_tab == 'SHAPE': + draw_shape_properties(layout, settings, style_object, is_preset, display_mode) + + # expose add modifier operator for preset context + if is_preset: + layout.operator('brushstroke_tools.preset_add_mod', icon='ADD') + elif settings.view_tab == 'SETTINGS': + draw_settings_properties(layout, settings, style_object) + +def draw_mod_warnings(layout, mod): + if utils.compare_versions(bpy.app.version, (4,3,0)) < 0: + return + if mod.node_warnings: + warnings_header, warnings_panel = layout.panel(mod.name+'_warnings', default_closed = True) + warnings_header.label(text=f'Warnings ({len(mod.node_warnings)})') + if warnings_panel: + for warning in mod.node_warnings: # TODO sort warnings by type and alphabet + warnings_panel.label(text=warning.message,icon=warning_icons_dict[warning.type]) + +class BSBST_UL_brushstroke_objects(bpy.types.UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname): + settings = data + context_brushstroke = item + if self.layout_type in {'DEFAULT', 'COMPACT'}: + if context_brushstroke: + method_icon = 'BRUSH_DATA' + method_icon = settings.bl_rna.properties['brushstroke_method'].enum_items[context_brushstroke.method].icon + col = layout.column() + row = col.row(align=True) + row.prop(context_brushstroke, 'name', text='', emboss=False, icon=method_icon) + bs_ob = bpy.data.objects.get(item.name) + if not bs_ob: + return + row.prop(context_brushstroke, 'hide_viewport_base', icon_only=True, emboss=False, icon='HIDE_ON' if context_brushstroke.hide_viewport_base else 'HIDE_OFF') + row.prop(bs_ob, 'hide_viewport', icon_only=True, emboss=False) + row.prop(bs_ob, 'hide_render', icon_only=True, emboss=False) + else: + layout.label(text="", translate=False, icon_value=icon) + elif self.layout_type == 'GRID': + layout.label(text="", icon_value=icon) + + def draw_filter(self, context, layout): + return + +class BSBST_MT_bs_context_menu(bpy.types.Menu): + bl_label = "Brushstroke Specials" + + def draw(self, _context): + layout = self.layout + + op = layout.operator('brushstroke_tools.copy_brushstrokes', text='Copy to Selected Objects') + op.copy_all = False + + op = layout.operator('brushstroke_tools.copy_brushstrokes', text='Copy All to Selected Objects') + op.copy_all = True + + op = layout.operator('brushstroke_tools.switch_deformable') + op.switch_all = False + + op = layout.operator('brushstroke_tools.copy_flow') + + op = layout.operator("brushstroke_tools.assign_surface") + +class BSBST_PT_brushstroke_tools_panel(bpy.types.Panel): + bl_space_type = 'VIEW_3D' + bl_region_type = 'UI' + bl_label = "Brushstroke Tools" + bl_category = "Brushstroke Tools" + + def draw_header_preset(self,context): + layout = self.layout + row = layout.row(align=True) + + op = row.operator('brushstroke_tools.view_all', icon='RESTRICT_VIEW_OFF', text='') + op.disable = False + op = row.operator('brushstroke_tools.view_all', icon='RESTRICT_VIEW_ON', text='') + op.disable = True + + def draw(self, context): + layout = self.layout + + settings = context.scene.BSBST_settings + surface_object = utils.get_active_context_surface_object(context) + + surface_row = layout.row() + if surface_object: + surface_row.label(text=f'{surface_object.name}', icon='OUTLINER_OB_SURFACE') + else: + surface_row.alert = True + surface_row.label(text='No Valid Surface Object', icon='OUTLINER_OB_SURFACE') + + row = layout.row(align=True) + op = row.operator("brushstroke_tools.new_brushstrokes", text='Fill', icon='OUTLINER_OB_FORCE_FIELD') + op.method = 'SURFACE_FILL' + op = row.operator("brushstroke_tools.new_brushstrokes", text='Draw', icon='LINE_DATA') + op.method = 'SURFACE_DRAW' + + draw_advanced_settings(layout, settings) + + # identify style context + style_object = context.object if settings.style_context=='BRUSHSTROKES' else settings.preset_object + if settings.style_context=='PRESET': + style_object = settings.preset_object + else: + if utils.is_brushstrokes_object(context.object): + style_object = context.object + else: + if settings.context_brushstrokes: + bs_name = settings.context_brushstrokes[settings.active_context_brushstrokes_index].name + context_bs = bpy.data.objects.get(bs_name) + if context_bs: + style_object = context_bs + + is_preset = style_object == settings.preset_object + + display_mode = settings.ui_options + if is_preset: + display_mode = -1 + + style_header, style_panel = layout.panel("brushstrokes_style", default_closed=False) + + if is_preset: + style_header.label(text="Default Settings", icon='SETTINGS') + else: + style_header.label(text="Brushstroke Settings", icon='BRUSH_DATA') + #style_header.operator('brushstroke_tools.make_preset', text='', icon='DECORATE_OVERRIDE') + style_header.row().prop(settings, 'ui_options', icon='OPTIONS', icon_only=True) + + if style_panel: + if settings.style_context=='BRUSHSTROKES' and not utils.is_brushstrokes_object(style_object): + style_panel.label(text='No Brushstroke Context Found') + return + if not is_preset and len(settings.context_brushstrokes)>0: + row = style_panel.row() + row.template_list("BSBST_UL_brushstroke_objects", "", settings, "context_brushstrokes", + settings, "active_context_brushstrokes_index", rows=3, maxrows=5, sort_lock=True) + column = row.column(align=True) + column.operator('brushstroke_tools.duplicate_brushstrokes', text='', icon='DUPLICATE') + column.operator('brushstroke_tools.delete_brushstrokes', text='', icon='TRASH') + column.menu('BSBST_MT_bs_context_menu', text='', icon = 'DOWNARROW_HLT') + + row = style_panel.row() + row_edit = row.row(align=True) + row_edit.operator('brushstroke_tools.select_surface', icon='OUTLINER_OB_SURFACE', text='') + bs_ob = utils.get_active_context_brushstrokes_object(context) + text = 'Edit Flow' if getattr(bs_ob, '["BSBST_method"]', None)=='SURFACE_FILL' else 'Edit Brushstrokes' + row_edit.operator('brushstroke_tools.edit_brushstrokes', icon='GREASEPENCIL', text = text) + row_edit.prop(settings, 'edit_toggle', icon='RESTRICT_SELECT_OFF' if settings.edit_toggle else 'RESTRICT_SELECT_ON', icon_only=True) + + + if not settings.preset_object and is_preset: + layout.operator("brushstroke_tools.init_preset", icon='MODIFIER') + else: + draw_properties_panel(style_panel, settings, style_object, surface_object, is_preset, display_mode) + +class BSBST_MT_PIE_brushstroke_data_marking(bpy.types.Menu): + bl_idname= "BSBST_MT_PIE_brushstroke_data_marking" + bl_label = "Mark Brushstroke Flow" + + items = { + "Brush Flow - Mark": ['FORCE_WIND'], + "Brush Flow - Clear": ['NONE'], + "Brush Break - Mark": ['MOD_PHYSICS'], + "Brush Break - Clear": ['NONE'], + "Brush Ignore - Mark": ['X'], + "Brush Ignore - Clear": ['NONE'], + } + + def draw(self, context): + layout = self.layout + + pie = layout.menu_pie() + + for name, info in self.items.items(): + pie.alert=True + op = pie.operator("geometry.execute_node_group", text=name, icon=info[0]) + op.asset_library_type='CUSTOM' + op.asset_library_identifier=utils.asset_lib_name + op.relative_asset_identifier=f"brushstroke_tools-resources.blend/NodeTree/{name}" + +class BSBST_OT_brushstroke_data_marking(bpy.types.Operator): + """ + Call pie menu for operators to mark brushstroke data on the surface mesh + """ + bl_idname = "brushstroke_tools.data_marking" + bl_label = "Mark Brushstroke Data" + bl_description = " Call pie menu for operators to mark brushstroke data on the surface mesh" + + @classmethod + def poll(cls, context): + return context.mode == 'EDIT_MESH' + + def execute(self, context): + bpy.ops.wm.call_menu_pie('INVOKE_DEFAULT', name=BSBST_MT_PIE_brushstroke_data_marking.bl_idname) + return {'FINISHED'} + +classes = [ + BSBST_UL_brushstroke_objects, + BSBST_MT_bs_context_menu, + BSBST_PT_brushstroke_tools_panel, + BSBST_MT_PIE_brushstroke_data_marking, + BSBST_OT_brushstroke_data_marking, +] + +def register(): + for c in classes: + bpy.utils.register_class(c) + + # Register UI shortcuts + wm = bpy.context.window_manager + if wm.keyconfigs.addon is not None: + km = wm.keyconfigs.addon.keymaps.new(name="Mesh") + kmi = km.keymap_items.new("brushstroke_tools.data_marking","F", "PRESS",shift=False, ctrl=True, alt=True) + +def unregister(): + for c in reversed(classes): + bpy.utils.unregister_class(c) diff --git a/scripts-blender/addons/brushstroke_tools/utils.py b/scripts-blender/addons/brushstroke_tools/utils.py new file mode 100644 index 00000000..c528061d --- /dev/null +++ b/scripts-blender/addons/brushstroke_tools/utils.py @@ -0,0 +1,638 @@ +import os, ast +import bpy +from bpy.app.handlers import persistent +import math, shutil, errno, numpy +from bpy.app.handlers import persistent + +addon_version = (0,0,0) + +preview_name = '.BSBST-preview' + +ng_list = [ + ".brushstroke_tools.draw_processing", + ".brushstroke_tools.pre_processing", + ".brushstroke_tools.animation", + ".brushstroke_tools.surface_fill", + ".brushstroke_tools.surface_draw", + ".brushstroke_tools.geometry_input", + ".brushstroke_tools.mask_surface", +] + +linkable_sockets = [ + bpy.types.NodeTreeInterfaceSocketObject, + bpy.types.NodeTreeInterfaceSocketMaterial, + bpy.types.NodeTreeInterfaceSocketVector, + bpy.types.NodeTreeInterfaceSocketFloat, + bpy.types.NodeTreeInterfaceSocketInt, + bpy.types.NodeTreeInterfaceSocketString, +] + +asset_lib_name = 'Brushstroke Tools Library' + +@persistent +def find_context_brushstrokes(dummy): + context = bpy.context + settings = context.scene.BSBST_settings + + edit_toggle = settings.edit_toggle + settings.edit_toggle = False + len_prev = len(settings.context_brushstrokes) + name_prev = settings.context_brushstrokes[settings.active_context_brushstrokes_index].name if len_prev else '' + idx = settings.active_context_brushstrokes_index + # identify context brushstrokes + for el in range(len(settings.context_brushstrokes)): + settings.context_brushstrokes.remove(0) + context_object = context.object + if not is_brushstrokes_object(context_object): + bs_ob = is_flow_object(context_object) + if bs_ob: + context_object = bs_ob + else: + bs_ob = context_object + surf_ob = get_surface_object(context_object) + if surf_ob: + context_object = surf_ob + for ob in bpy.data.objects: + if not is_brushstrokes_object(ob): + continue + surf_ob = get_surface_object(ob) + flow_ob = get_flow_object(ob) + if not surf_ob: + if not flow_ob: + continue + if not surf_ob == context_object: + if not flow_ob == context_object: + continue + bs = settings.context_brushstrokes.add() + bs.name = ob.name + bs.method = ob['BSBST_method'] + bs.hide_viewport_base = ob.hide_get() + if name_prev == ob.name: + idx = len(settings.context_brushstrokes)-1 + if not settings.context_brushstrokes: + settings.edit_toggle = edit_toggle + return + if bs_ob: + for i, bs in enumerate(settings.context_brushstrokes): + if bs.name == bs_ob.name: + if name_prev != bs.name: + settings.ui_options = False + + settings.silent_switch = True + settings.active_context_brushstrokes_index = i + settings.silent_switch = False + elif len_prev == len(settings.context_brushstrokes): + settings.silent_switch = True + settings.active_context_brushstrokes_index = idx + settings.silent_switch = False + + settings.active_context_brushstrokes_index = max(min(settings.active_context_brushstrokes_index, len(settings.context_brushstrokes)-1), 0) + settings.edit_toggle = edit_toggle + +@persistent +def refresh_preset(dummy): + context = bpy.context + settings = context.scene.BSBST_settings + if not settings: + return + for ob in [settings.preset_object, get_active_context_brushstrokes_object(context)]: + if not ob: + continue + for mod in ob.modifiers: + mod_info = ob.modifier_info.get(mod.name) + if not mod_info: + mod_info = ob.modifier_info.add() + mod_info.name = mod.name + if not mod.type == 'NODES': + continue + if not mod.node_group: + continue + for v in mod.node_group.interface.items_tree.values(): + if type(v) is bpy.types.NodeTreeInterfacePanel: + v_id = f'Panel_{v.index}' # TODO: replace with panel identifier once that is exposed in Blender 4.3 + else: + v_id = v.identifier + if v_id in [s.name for s in mod_info.socket_info]: + continue + n = mod_info.socket_info.add() + n.name = v_id + # TODO: clean up old settings + +def mark_socket_context_type(mod_info, socket_name, link_type): + socket_info = mod_info.socket_info.get(socket_name) + if not socket_info: + socket_info = mod_info.socket_info.add() + socket_info.name = socket_name + socket_info.link_context_type = link_type + +def mark_socket_hidden(mod_info, socket_name, hide=True): + socket_info = mod_info.socket_info.get(socket_name) + if not socket_info: + socket_info = mod_info.socket_info.add() + socket_info.name = socket_name + socket_info.hide_ui = hide + +def mark_panel_hidden(mod_info, panel_name, hide=True): + mod = mod_info.id_data.modifiers.get(mod_info.name) + if not mod: + return + if not mod.type == 'NODES': + return + ng = mod.node_group + if not ng: + return + v_id = '' + for k, v in ng.interface.items_tree.items(): + if type(v) != bpy.types.NodeTreeInterfacePanel: + continue + if v.name == panel_name: + v_id = f'Panel_{v.index}' + break + if not v_id: + return + socket_info = mod_info.socket_info.get(v_id) + if not socket_info: + socket_info = mod_info.socket_info.add() + socket_info.name = v_id + socket_info.hide_ui = hide + +def set_brushstroke_material(ob, material): + prev_mat = None + if 'BSBST_material' in ob.keys(): + if ob['BSBST_material'] == material: + return + else: + prev_mat = ob['BSBST_material'] + ob['BSBST_material'] = material + for mod in ob.modifiers: + mod_info = ob.modifier_info.get(mod.name) + if not mod_info: + continue + for s in mod_info.socket_info: + if not s.link_context: + continue + if not s.link_context_type == 'MATERIAL': + continue + mod[s.name] = material + ob.update_tag() + + if ob.type == 'EMPTY': + return + if not ob.material_slots: + override = bpy.context.copy() + override['object'] = ob + with bpy.context.temp_override(**override): + bpy.ops.object.material_slot_add() + ob.material_slots[0].material = material + else: + for m_slot in ob.material_slots: + if m_slot.material == prev_mat: + m_slot.material = material + +def deep_copy_mod_info(source_object, target_object): + for mod_info in source_object.modifier_info: + mod_info_tgt = target_object.modifier_info.add() + for attr in mod_info.keys(): + if attr == 'socket_info': + continue + setattr(mod_info_tgt, attr, getattr(mod_info, attr)) + for socket_info in mod_info.socket_info: + socket_info_tgt = mod_info_tgt.socket_info.add() + for attr in socket_info.keys(): + setattr(socket_info_tgt, attr, getattr(socket_info, attr)) + +def get_addon_directory() -> str: + """ + Returns the path of the addon directory. + """ + return bpy.path.abspath(os.path.dirname(os.path.realpath(__file__))) + +def get_resource_directory() -> str: + """ + Returns the path to be used to append resource data-blocks. + """ + addon_prefs = bpy.context.preferences.addons[__package__].preferences + resource_path = addon_prefs.resource_path + if not resource_path: + resource_path = f'{get_addon_directory()}/assets/' + return resource_path + +def import_resources(ng_names = ng_list): + """ + Imports the necessary blend data resources required by the addon. + """ + addon_prefs = bpy.context.preferences.addons[__package__].preferences + + path = get_resource_directory() + + with bpy.data.libraries.load(f'{path}brushstroke_tools-resources.blend', link=addon_prefs.import_method=='LINK', relative=addon_prefs.import_relative_path) as (data_src, data_dst): + data_dst.node_groups = ng_names + if addon_prefs.import_method=='APPEND': + # pack imported resources + for img in bpy.data.images: + if not img.library_weak_reference: + continue + if img.packed_file: + continue + if 'brushstroke_tools-resources.blend' in img.library_weak_reference.filepath: + img.pack() + +def read_lib_version(): + resource_dir = f'{get_resource_directory()}' + with open(f"{resource_dir}.version", "r") as file: + version = ast.literal_eval(file.read()) + return version + +def write_lib_version(): + resource_dir = f'{get_resource_directory()}' + with open(f"{resource_dir}.version", "w") as file: + file.write(str(addon_version)) + +def copy_resources_to_dir(tgt_dir = ''): + resource_dir = f'{get_addon_directory()}/assets/' + if not tgt_dir: + tgt_dir = get_resource_directory() + + try: + shutil.copytree(resource_dir, tgt_dir, dirs_exist_ok=True) + write_lib_version() + except OSError as err: + # error caused if the source was not a directory + if err.errno == errno.ENOTDIR: + shutil.copy2(resource_dir, tgt_dir) + write_lib_version() + else: + print("Error: % s" % err) + +def compare_versions(v1: tuple, v2: tuple): + """ Returns n when v1 > v2, 0 when v1 == v2, -n when v1 < v2, while n = 'Index of first significant version tuple element' + 1. + e.g. (0,2,0), (0,2,1) -> -3 + """ + c = 1 + for e1, e2 in zip(v1, v2): + if e1 > e2: + return c + elif e1 < e2: + return -c + c += 1 + return 0 + +def import_brushstroke_material(): + name = 'Brush Material' + path = f"{get_resource_directory()}/brushstroke_tools-resources.blend" + addon_prefs = bpy.context.preferences.addons[__package__].preferences + + mats_pre = set(bpy.data.materials) + ng_pre = set(bpy.data.node_groups) + with bpy.data.libraries.load(path, link=addon_prefs.import_method=='LINK', relative=addon_prefs.import_relative_path) as (data_src, data_dst): + data_dst.materials = [name] + mats_new = list(set(bpy.data.materials) - mats_pre) + + # de-duplicate imported node-groups + ng_new = list(set(bpy.data.node_groups) - ng_pre) + ng_remove = [] + for ng in ng_new: + ng_name_elements = ng.name.split('.') + if len(ng_name_elements) == 1: + continue + root_ng = bpy.data.node_groups.get('.'.join(ng_name_elements[:-1])) + if not root_ng: + continue + ng.user_remap(root_ng) + ng_remove += [ng] + for ng in reversed(ng_remove): + bpy.data.node_groups.remove(ng) + + # return imported material + if mats_new: + return mats_new[0] + else: + return bpy.data.materials.get(name) + +def ensure_node_group(name, path=''): + ng = bpy.data.node_groups.get(name) + if ng: + return ng + + addon_prefs = bpy.context.preferences.addons[__package__].preferences + if not path: + path=f'{get_resource_directory()}/brushstroke_tools-resources.blend' + + with bpy.data.libraries.load(path, link=addon_prefs.import_method=='LINK', relative=addon_prefs.import_relative_path) as (data_src, data_dst): + data_dst.node_groups = [name] + if addon_prefs.import_method=='APPEND': + # pack imported resources + for img in bpy.data.images: + if not img.library_weak_reference: + continue + if path in img.library_weak_reference.filepath: + img.pack() + ng = bpy.data.node_groups.get(name) + + return ng + +def ensure_resources(): + ng_missing = set() + + for n in ng_list: + if not bpy.data.node_groups.get(n): + ng_missing.add(n) + + if ng_missing: + import_resources(list(ng_missing)) + +def register_asset_lib(): + asset_libs = bpy.context.preferences.filepaths.asset_libraries + if asset_lib_name in [a.name for a in asset_libs]: + return asset_libs[asset_lib_name] + lib = asset_libs.new() + lib.name = asset_lib_name + lib.path = get_resource_directory() + lib.use_relative_path = False + +def unregister_asset_lib(): + asset_libs = bpy.context.preferences.filepaths.asset_libraries + lib = asset_libs.get(asset_lib_name) + if not lib: + return + asset_libs.remove(lib) + +def update_asset_lib_path(): + asset_libs = bpy.context.preferences.filepaths.asset_libraries + if asset_lib_name not in [a.name for a in asset_libs]: + register_asset_lib() + return + lib = asset_libs[asset_lib_name] + lib.path = get_resource_directory() + +def refresh_brushstroke_styles(): + addon_prefs = bpy.context.preferences.addons[__package__].preferences + + for a in range(len(addon_prefs.brush_styles)): + addon_prefs.brush_styles.remove(0) + + lib_path = get_resource_directory() + add_brush_styles_from_directory(lib_path) + +def add_brush_styles_from_directory(path): + addon_prefs = bpy.context.preferences.addons[__package__].preferences + subdirs = [f.path for f in os.scandir(path) if f.is_dir()] + files = [f.path for f in os.scandir(path) if not f.is_dir()] + + for filepath in files: + if not filepath.endswith('.blend'): + continue + + names = [] + with bpy.data.libraries.load(filepath) as (data_from, data_to): + names = [name for name in data_from.node_groups if name.startswith('BSBST-BS')] + + for ng_name in names: + b_style = addon_prefs.brush_styles.add() + b_style.name = '.'.join(ng_name.split('.')[1:]) + b_style.filepath = filepath + + for dir in subdirs: + add_brush_styles_from_directory(dir) + +def transfer_modifier(modifier_name, target_obj, source_obj): + """ + Core taken from https://projects.blender.org/studio/blender-studio-pipeline + """ + + # create target mod + source_mod = source_obj.modifiers.get(modifier_name) + target_mod = target_obj.modifiers.new(source_mod.name, source_mod.type) + props = [p.identifier for p in source_mod.bl_rna.properties if not p.is_readonly] + for prop in props: + value = getattr(source_mod, prop) + setattr(target_mod, prop, value) + + if source_mod.type == 'NODES': + # Transfer geo node attributes + for key, value in source_mod.items(): + target_mod[key] = value + + # Transfer geo node bake settings + target_mod.bake_directory = source_mod.bake_directory + for index, target_bake in enumerate(target_mod.bakes): + source_bake = source_mod.bakes[index] + props = [p.identifier for p in source_bake.bl_rna.properties if not p.is_readonly] + for prop in props: + value = getattr(source_bake, prop) + setattr(target_bake, prop, value) + +def is_brushstrokes_object(object): + if not object: + return False + return 'BSBST_active' in object.keys() + +def is_surface_object(object): + if not object: + return False + for ob in bpy.data.objects: + if 'BSBST_surface_object' not in ob.keys(): + continue + if ob['BSBST_surface_object'] == object: + return True + return False + +def is_flow_object(object): + if not object: + return False + for ob in bpy.data.objects: + if 'BSBST_flow_object' not in ob.keys(): + continue + if ob['BSBST_flow_object'] == object: + return ob + return False + +def get_deformable(object): + if not object: + return False + if 'BSBST_deformable' in object.keys(): + return object['BSBST_deformable'] + return False + +def get_animated(object): + if not object: + return False + if 'BSBST_animated' in object.keys(): + return object['BSBST_animated'] + return False + +def set_deformable(object, deformable=True): + if not object: + return + object['BSBST_deformable'] = bool(deformable) + +def set_animated(object, animated=True): + if not object: + return + object['BSBST_animated'] = bool(animated) + +def get_surface_object(bs): + if not bs: + return None + if 'BSBST_surface_object' not in bs.keys(): + return None + return bs['BSBST_surface_object'] + +def set_surface_object(bs, surf_ob): + if not bs: + return + objects = [bs] + flow_ob = get_flow_object(bs) + if flow_ob: + objects += [flow_ob] + # assign surface pointer + for ob in objects: + for mod in bs.modifiers: + mod_info = bs.modifier_info.get(mod.name) + if not mod_info: + continue + for s in mod_info.socket_info: + if not s.link_context: + continue + if not s.link_context_type == 'SURFACE_OBJECT': + continue + mod[s.name] = surf_ob + ob.parent = surf_ob + ob.parent_type = 'OBJECT' + surf_ob.update_tag() + + if bs.type == 'CURVES': + bs.data.surface = surf_ob + bs.data.surface_uv_map = surf_ob.data.uv_layers.active.name + + bs['BSBST_surface_object'] = surf_ob + +def get_flow_object(bs): + if not bs: + return None + if 'BSBST_flow_object' not in bs.keys(): + return None + return bs['BSBST_flow_object'] + +def set_flow_object(bs, ob): + if not bs: + return + # assign flow pointer + for mod in bs.modifiers: + mod_info = bs.modifier_info.get(mod.name) + if not mod_info: + continue + for s in mod_info.socket_info: + if not s.link_context: + continue + if not s.link_context_type == 'FLOW_OBJECT': + continue + mod[s.name] = ob + ob.update_tag() + + bs['BSBST_flow_object'] = ob + +def context_brushstrokes(context): + settings = context.scene.BSBST_settings + return settings.context_brushstrokes + +def get_active_context_brushstrokes_object(context): + settings = context.scene.BSBST_settings + if not settings.context_brushstrokes: + return None + bs = settings.context_brushstrokes[settings.active_context_brushstrokes_index] + bs_ob = bpy.data.objects.get(bs.name) + return bs_ob + +def get_active_context_surface_object(context): + if not context.object: + return None + bs_ob = get_active_context_brushstrokes_object(context) + if bs_ob: + return get_surface_object(bs_ob) + if context.object.type == 'MESH': + return context.object + +def flow_name(name): + return f'{name}-FLOW' + +def edit_active_brushstrokes(context): + context.view_layer.depsgraph.update() + + bs_ob = get_active_context_brushstrokes_object(context) + if not bs_ob: + return {"CANCELLED"} + + flow_object = get_flow_object(bs_ob) + surface_object = get_surface_object(bs_ob) + active_object = bs_ob + if flow_object: + active_object = flow_object + if not active_object: + return {"CANCELLED"} + + context.view_layer.objects.active = active_object + for ob in bpy.data.objects: + ob.select_set(False) + surface_object.select_set(True) + active_object.select_set(True) + + # enter mode and tool context + if active_object.type=='GREASEPENCIL': + bpy.ops.object.mode_set(mode='PAINT_GREASE_PENCIL') + bpy.ops.wm.tool_set_by_id(name="builtin.draw") + context.scene.tool_settings.gpencil_stroke_placement_view3d = 'SURFACE' + else: + bpy.ops.object.mode_set(mode='EDIT') + bpy.ops.wm.tool_set_by_id(name="brushstroke_tools.draw") + return {'FINISHED'} + +def round_n(val, n): + """ Round value to n number of significant digits. + """ + return round(val, n-int(math.floor(math.log10(abs(val))))-1) + +def clear_preview(): + preview_img = bpy.data.images.get(preview_name) + preview_texture = bpy.data.textures.get(preview_name) + if preview_img: + bpy.data.images.remove(preview_img) + if preview_texture: + bpy.data.textures.remove(preview_texture) + +def set_preview(pixels, size = (256, 256), id=''): + preview_img = bpy.data.images.get(preview_name) + preview_texture = bpy.data.textures.get(preview_name) + if not pixels or compare_versions(bpy.app.version, (4,2,4)) < 0: + clear_preview() + return + if preview_img: + if id and id == preview_img['BSBST-id']: + return + if not len(preview_img.pixels) == len(pixels): + bpy.data.images.remove(preview_img) + preview_img = None + if not preview_img: + preview_img = bpy.data.images.new(preview_name, width=size[0], height=size[1]) + + if not preview_texture: + preview_texture = bpy.data.textures.new(name=preview_name, type="IMAGE") + settings = bpy.context.scene.BSBST_settings + settings.preview_texture = preview_texture + preview_texture.extension = 'EXTEND' + preview_texture.crop_max_x = size[1]/size[0] + preview_texture.image = preview_img + + preview_img.pixels.foreach_set(numpy.array(pixels, dtype=numpy.float32)) + preview_img['BSBST-id'] = id + + preview_img.pack() + + # TODO delete pre-save + # TODO set height of preview region + +def register(): + bpy.app.handlers.depsgraph_update_post.append(refresh_preset) + +def unregister(): + bpy.app.handlers.depsgraph_update_post.remove(refresh_preset) \ No newline at end of file