Brushstroke Tools: Initial Version #328

Merged
Simon Thommes merged 229 commits from SimonThommes/blender-studio-tools:brushstroke_tools-initial-version into main 2024-11-06 15:03:47 +01:00
25 changed files with 3818 additions and 0 deletions

View File

@ -0,0 +1 @@
<!--@include: ../../scripts-blender/addons/brushstroke_tools/README.md-->

View File

@ -0,0 +1 @@
*.txt~

View File

@ -0,0 +1,183 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

View File

@ -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

View File

@ -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()

View File

@ -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

View File

@ -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 <simon@blender.org>"
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"

View File

@ -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

View File

@ -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()

BIN
scripts-blender/addons/brushstroke_tools/icons/random.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -0,0 +1,447 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
height="16000"
viewBox="0 0 16000 16000"
width="16000"
version="1.1"
id="svg3"
sodipodi:docname="random.svg"
inkscape:version="1.3.2 (091e20ef0f, 2023-11-25)"
inkscape:export-filename="random.png"
inkscape:export-xdpi="1"
inkscape:export-ydpi="1"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs3">
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect17"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,96.61328,0,1 @ F,0,0,1,0,87.894951,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,96.130535,0,1 @ F,0,0,1,0,136.84977,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect16"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect14"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,38.11328,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect13"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,306.22768,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect22"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect21"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect20"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,43.247149,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,21.653685,0,1 @ F,0,0,1,0,36.44727,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect19"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,80.166317,0,1 @ F,0,0,1,0,42.114857,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powerclip"
id="path-effect18"
is_visible="true"
lpeversion="1"
inverse="true"
flatten="false"
hide_clip="false"
message="Use fill-rule evenodd on &lt;b&gt;fill and stroke&lt;/b&gt; dialog if no flatten result after convert clip to paths." />
<inkscape:path-effect
effect="powerclip"
id="path-effect15"
is_visible="true"
lpeversion="1"
inverse="true"
flatten="false"
hide_clip="false"
message="Use fill-rule evenodd on &lt;b&gt;fill and stroke&lt;/b&gt; dialog if no flatten result after convert clip to paths." />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect6"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,159.98102,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect5"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,131.34073,0,1 @ F,0,0,1,0,133.0127,0,1 @ F,0,0,1,0,133.01271,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect4"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,204.97527,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,218.37273,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,208.56511,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect12"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect12"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect11"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,223.48671,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect10"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect10"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect8"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,231.93627,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect7"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect7"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="powermask"
id="path-effect2"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect2"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect9"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,60.467422,0,1 @ F,0,0,1,0,61.371837,0,1 @ F,0,0,1,0,63.489488,0,1 @ F,0,0,1,0,61.238588,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<filter
id="mask-powermask-path-effect4_inverse"
inkscape:label="filtermask-powermask-path-effect4"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect4_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect4_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
<filter
id="mask-powermask-path-effect13_inverse"
inkscape:label="filtermask-powermask-path-effect13"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect13_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect13_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
<filter
id="mask-powermask-path-effect17_inverse"
inkscape:label="filtermask-powermask-path-effect17"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect17_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect17_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
</defs>
<sodipodi:namedview
pagecolor="#303030"
showgrid="true"
id="namedview1"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="0.0625"
inkscape:cx="7040"
inkscape:cy="7808"
inkscape:window-width="2560"
inkscape:window-height="1358"
inkscape:window-x="0"
inkscape:window-y="32"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
id="grid5"
units="px"
spacingx="100"
spacingy="100"
color="#4772b3"
opacity="0.2"
visible="true"
originx="0"
originy="0" />
</sodipodi:namedview>
<g
fill="#ffffff"
id="g3"
style="display:none">
<g
id="g5">
<g
id="g4">
<g
enable-background="new"
opacity="0.99"
transform="matrix(100,0,0,100,-48800,-19899.963)"
id="g2">
<path
d="M 495.49219,199.99219 A 0.50005,0.50005 0 0 0 495,200.5 v 6.79297 l -3.85352,3.85351 a 0.50005,0.50005 0 1 0 0.70704,0.70704 L 495.70703,208 H 502.5 a 0.50005,0.50005 0 1 0 0,-1 H 496 v -6.5 a 0.50005,0.50005 0 0 0 -0.50781,-0.50781 z"
opacity="1"
id="path1" />
<path
d="m 499.49023,202.99609 a 0.50005,0.50005 0 0 0 -0.34375,0.15039 l -2,2 a 0.50005,0.50005 0 1 0 0.70704,0.70704 l 2,-2 a 0.50005,0.50005 0 0 0 -0.36329,-0.85743 z M 489.5,207 a 0.50005,0.50005 0 1 0 0,1 h 3.25 a 0.50005,0.50005 0 1 0 0,-1 z m 5.99219,2.74219 A 0.50005,0.50005 0 0 0 495,210.25 v 3.25 a 0.50005,0.50005 0 1 0 1,0 v -3.25 a 0.50005,0.50005 0 0 0 -0.50781,-0.50781 z"
opacity="0.6"
id="path2" />
</g>
</g>
</g>
</g>
<g
inkscape:groupmode="layer"
id="layer1"
inkscape:label="Layer 1">
<path
id="path3"
style="color:#000000;display:none;fill:#ffffff;fill-opacity:0.6;stroke-linejoin:round;-inkscape-stroke:none"
d="m 500,100 c -220.32124,0 -400,179.67876 -400,400 0,131.59237 64.13891,248.62332 162.72034,321.57873 22.18264,16.41632 45.30496,4.85701 54.36188,-21.19654 0.22088,-0.63538 0.44382,-1.26977 0.66883,-1.90317 9.23262,-25.98976 1.38973,-57.26331 -19.07836,-75.75221 C 238.01459,667.93412 200,588.61487 200,500 200,333.72266 333.72266,200 500,200 c 114.00907,0 212.65908,62.88761 263.42614,156.01778 21.12726,38.75714 46.45545,43.58478 68.59301,5.24196 l 3.34702,-5.79711 c 11.62982,-20.14315 12.65529,-53.4221 -0.0293,-72.90553 C 763.8993,172.82969 640.22189,100 500,100 Z"
inkscape:original-d="m 500,100 c -220.32124,0 -400,179.67876 -400,400 0,149.4376 82.71418,280.09665 204.65234,348.75391 5.86588,-34.27979 17.34855,-66.54493 33.73828,-95.75 C 255.06192,699.834 200,606.64908 200,500 200,333.72266 333.72266,200 500,200 c 142.38957,0 260.8216,98.09404 291.93555,230.68555 L 856.42383,318.99023 C 790.16805,189.24325 655.22057,100 500,100 Z"
inkscape:path-effect="#path-effect19" />
<g
id="path7"
inkscape:transform-center-y="-175.00286" />
<path
id="rect1"
style="fill:#ffffff;fill-opacity:0.6;stroke-width:979.022;stroke-linejoin:round;stroke-opacity:0.8"
d="m 6184.7961,1000 c -523.7731,0 -998.143,204.0121 -1348.2993,537.2416 -1524.5715,1450.8733 -1133.7259,1083.5981 -1994.5161,1968.3924 -400.6935,411.8671 -262.7586,742.7614 311.8659,742.7614 H 9998.66 a 2296.6616,2296.6616 0 0 0 1618.245,-666.9561 l 1378.483,-1368.786 c 101.339,-100.6267 238.505,-156.873 381.318,-156.3643 142.807,0.5062 279.562,57.7207 380.184,159.0566 209.529,211.0226 208.323,551.9455 -2.692,761.4813 l -1250.367,1241.5744 a 2486.9119,2486.9119 0 0 0 -734.6,1764.7027 v 6396.65 c 0,813.938 466.274,1006.895 1041.271,430.81 1022.07,-1024.006 1369.084,-1371.996 1591.49,-1585.979 369.022,-355.046 598.008,-854.484 598.008,-1409.3808 V 2954.0263 C 15000,1871.4958 14128.505,1000 13045.973,1000 Z M 8000.0004,2076.9231 A 1615.3846,538.46153 0 0 1 9615.385,2615.3846 1615.3846,538.46153 0 0 1 8000.0004,3153.8461 1615.3846,538.46153 0 0 1 6384.6158,2615.3846 1615.3846,538.46153 0 0 1 8000.0004,2076.9231 Z m 5923.0776,1615.3846 a 538.46153,1615.3846 0 0 1 538.461,1615.3845 538.46153,1615.3846 0 0 1 -538.461,1615.3847 538.46153,1615.3846 0 0 1 -538.462,-1615.3847 538.46153,1615.3846 0 0 1 538.462,-1615.3845 z m -1076.923,4846.1538 a 538.46153,1615.3846 0 0 1 538.46,1615.3845 538.46153,1615.3846 0 0 1 -538.46,1615.385 538.46153,1615.3846 0 0 1 -538.461,-1615.385 538.46153,1615.3846 0 0 1 538.461,-1615.3845 z" />
<path
id="rect6"
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:969.226;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1"
d="m 2907.1639,5307.6922 c -1056.5657,0 -1907.1634,850.5979 -1907.1634,1907.1635 v 5877.9803 c 0,1056.566 850.5977,1907.164 1907.1634,1907.164 h 5877.9808 c 1056.5657,0 1907.1633,-850.598 1907.1633,-1907.164 V 7214.8557 c 0,-1056.5656 -850.5976,-1907.1635 -1907.1633,-1907.1635 z m 785.1443,1076.9231 A 1615.3846,1615.3846 0 0 1 5307.6927,7999.9999 1615.3846,1615.3846 0 0 1 3692.3082,9615.3845 1615.3846,1615.3846 0 0 1 2076.9236,7999.9999 1615.3846,1615.3846 0 0 1 3692.3082,6384.6153 Z m 4307.6922,0 A 1615.3846,1615.3846 0 0 1 9615.385,7999.9999 1615.3846,1615.3846 0 0 1 8000.0004,9615.3845 1615.3846,1615.3846 0 0 1 6384.6158,7999.9999 1615.3846,1615.3846 0 0 1 8000.0004,6384.6153 Z M 3692.3082,10692.307 a 1615.3846,1615.3846 0 0 1 1615.3845,1615.386 1615.3846,1615.3846 0 0 1 -1615.3845,1615.384 1615.3846,1615.3846 0 0 1 -1615.3846,-1615.384 1615.3846,1615.3846 0 0 1 1615.3846,-1615.386 z m 4307.6922,0 A 1615.3846,1615.3846 0 0 1 9615.385,12307.693 1615.3846,1615.3846 0 0 1 8000.0004,13923.077 1615.3846,1615.3846 0 0 1 6384.6158,12307.693 1615.3846,1615.3846 0 0 1 8000.0004,10692.307 Z" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 18 KiB

File diff suppressed because it is too large Load Diff

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)