Skip to content

Commit 90bd4ba

Browse files
committed
ZBrush Python SDK inital commit.
0 parents  commit 90bd4ba

File tree

166 files changed

+3662
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

166 files changed

+3662
-0
lines changed

LICENSE

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Creative Commons Attribution-NoDerivatives 4.0 International
2+
3+
The license can also be found under https://creativecommons.org/licenses/by-nd/4.0.
4+
5+
By exercising the Licensed Rights (defined below), you accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, you are granted the Licensed Rights in consideration of your acceptance of these terms and conditions, and the Licensor grants you such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
6+
7+
Section 1 – Definitions
8+
9+
Adapted Material: Material subject to copyright and similar rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the copyright and similar rights held by the Licensor.
10+
Copyright and Similar Rights: Copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights.
11+
Effective Technological Measures: Measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
12+
Exceptions and Limitations: Fair use, fair dealing, and/or any other exception or limitation to copyright and similar rights that applies to your use of the Licensed Material.
13+
Licensed Material: The artistic or literary work, database, or other material to which the Licensor applied this Public License.
14+
Licensed Rights: The rights granted to you subject to the terms and conditions of this Public License, which are limited to all copyright and similar rights that apply to your use of the Licensed Material and that the Licensor has authority to license.
15+
Licensor: The individual(s) or entity(ies) granting rights under this Public License.
16+
Share: To provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation.
17+
Sui Generis Database Rights: Rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
18+
You: The individual or entity exercising the Licensed Rights under this Public License. "Your" has a corresponding meaning.
19+
20+
21+
Section 2 – Scope
22+
23+
License grant: Subject to the terms and conditions of this Public License, the Licensor hereby grants you a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to reproduce and share the Licensed Material, in whole or in part; and produce and reproduce, but not share, Adapted Material.
24+
Exceptions and Limitations: Where exceptions and limitations apply to your use, this Public License does not apply, and you do not need to comply with its terms and conditions.
25+
Term: The term of this Public License is specified in Section 6(a).
26+
Media and formats; technical modifications allowed: The Licensor authorizes you to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so.
27+
Downstream recipients: Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. You may not offer or impose any additional or different terms or conditions on, or apply any effective technological measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
28+
No endorsement: Nothing in this Public License constitutes or may be construed as permission to assert or imply that you are, or that your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution.
29+
Other rights: Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow you to exercise the Licensed Rights, but not otherwise. Patent and trademark rights are not licensed under this Public License. To the extent possible, the Licensor waives any right to collect royalties from you for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
30+
31+
32+
Section 3 – License Conditions
33+
34+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
35+
Attribution: If you share the Licensed Material, you must retain the following if it is supplied by the Licensor with the Licensed Material: identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); a copyright notice; a notice that refers to this Public License; a notice that refers to the disclaimer of warranties; a URI or hyperlink to the Licensed Material to the extent reasonably practicable. Indicate if you modified the Licensed Material and retain an indication of any previous modifications; and indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. For the avoidance of doubt, you do not have permission under this Public License to share Adapted Material.
36+
37+
38+
Section 4 – Sui Generis Database Rights
39+
40+
Where the Licensed Rights include Sui Generis Database Rights that apply to your use of the Licensed Material: Section 2(a)(1) grants you the right to extract, reuse, reproduce, and share all or a substantial portion of the contents of the database, provided you do not share Adapted Material; if you include all or a substantial portion of the database contents in a database in which you have Sui Generis Database Rights, then the database in which you have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and you must comply with the conditions in Section 3(a) if you share all or a substantial portion of the contents of the database. This Section 4 supplements and does not replace your obligations under this Public License where the Licensed Rights include other copyright and similar rights.
41+
42+
43+
Section 5 – Disclaimer of Warranties and Limitation of Liability
44+
45+
Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to you. To the extent possible, in no event will the Licensor be liable to you on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to you. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
46+
47+
48+
Section 6 – Term and Termination
49+
50+
This Public License applies for the term of the copyright and similar rights licensed here. However, if you fail to comply with this Public License, then your rights under this Public License terminate automatically. Where your right to use the Licensed Material has terminated under Section 6(a), it reinstates automatically as of the date the violation is cured, provided it is cured within 30 days of your discovery of the violation; or upon express reinstatement by the Licensor. This Section 6(b) does not affect any right the Licensor may have to seek remedies for your violations of this Public License. The Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
51+
52+
53+
Section 7 – Other Terms and Conditions
54+
55+
The Licensor shall not be bound by any additional or different terms or conditions communicated by you unless expressly agreed. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
56+
57+
58+
Section 8 – Interpretation
59+
60+
This Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or you, including from the legal processes of any jurisdiction or authority.

ex_hello_world.png

1.22 MB
Loading

ex_hello_world.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Demonstrates how to write a basic script to create an editable cube in the center of the canvas
2+
and sets up the view.
3+
"""
4+
5+
import zbrush.commands as zbc
6+
7+
def main() -> None:
8+
"""Runs when Zbrush executes this script.
9+
"""
10+
# We set ZBrush into its 2026 configuration state, to start with a known UI state.
11+
zbc.config(2026)
12+
13+
# We select the Cube 3D tool and convert it to a polymesh.
14+
zbc.press("Tool:Cube3D")
15+
zbc.press("Tool:Make PolyMesh3D")
16+
17+
# We draw a stroke on the canvas to place the cube. This string is a pre-recorded brush stroke.
18+
stroke: zbc.Stroke = zbc.Stroke(
19+
"(ZObjStrokeV03n27%p2377BA8p191C7ACPnA63An234Fn-BF76s100672Cs100672Cs100672Cz-7E6B=H231V219H230"
20+
"V216H22FV214h22E55v210AAH22Ev20C40h22D40v203C0H22Dv1F980H22DV1EEH22DV1E2h22D40v1D5C0h22DC0v1C9"
21+
"80h22E40v1BD40h22EC0v1B040H22Fv1A280H22Fv19380h22EC0v18480h22DC0v17640h22C40v16980h22A80v15F40"
22+
"h228C0v15740h227C0v15240h22740v14F40h226C0v14D80h22680v14C80h22640v14B80H226v14A80H226v149C0)")
23+
zbc.canvas_stroke(stroke)
24+
25+
# Now we enable edit mode to edit the cube.
26+
zbc.press("Transform: Edit")
27+
28+
# And finally, we rotate the camera into a 45°, 45° angle to get a better view on the cube, and
29+
# then frame the object in the view.
30+
zbc.set_transform(x_rotate=45, y_rotate=45, z_rotate=0)
31+
zbc.press("Transform:Fit Mesh To View")
32+
33+
34+
# This code, the "if _name__ ..." is called the main guard and ensures that the main() function
35+
# is only executed when this script is run directly, not when it is imported as a module.
36+
if __name__ == "__main__":
37+
main()

fragments/_example_parser.py

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
"""Contains a tool to extract code examples embedded in modules.
2+
"""
3+
import ast
4+
import os
5+
import typing
6+
import re
7+
8+
HEADER: str = '''"""Code fragment for {}.
9+
"""
10+
__author__ = "Ferdinand Hoppe"
11+
__date__ = "16/10/2025"
12+
__copyright__ = "Maxon Computer"
13+
'''
14+
15+
PATH_PREFIX: str = "/../../examples/fragments"
16+
17+
class PyExampleParser:
18+
"""A parser for extracting examples from Python code."""
19+
20+
def __init__(self, file: str, output_dir: str, prefix: str) -> None:
21+
"""Initializes the parser with the given Python file.
22+
"""
23+
self.file: str = str(file)
24+
self.output_dir: str = str(output_dir)
25+
self.prefix: str = str(prefix)
26+
if not os.path.isfile(self.file):
27+
raise FileNotFoundError(f"File not found: {self.file}")
28+
29+
if not os.path.isdir(self.output_dir):
30+
os.makedirs(self.output_dir)
31+
32+
with open(self.file, "r", encoding="utf-8") as f:
33+
self.code: str = self.preprocess_file(f.read())
34+
35+
self.out_file: str = self.file.replace(".py", "_parsed.py")
36+
self.tree: ast.Module = ast.parse(self.code)
37+
self.new_code: str = self.code
38+
self.lines: list[str] = self.code.splitlines()
39+
self.max_index: int = len(self.lines)
40+
41+
def preprocess_file(self, content: str) -> str:
42+
"""Preprocesses the file by removing leading/trailing empty lines in doc strings.
43+
"""
44+
return re.sub(r'"""\s*(?!\s*(?:def|class|\.\.\.))', r'"""', content)
45+
46+
def iter_items(self) -> typing.Iterator[tuple[str, str, ast.AST]]:
47+
"""Yields all relevant descriptions found in the AST with their entity names and nodes.
48+
"""
49+
node: ast.AST
50+
visited: set[ast.AST] = set()
51+
for node in ast.walk(self.tree):
52+
if node in visited:
53+
continue
54+
55+
visited.add(node)
56+
if isinstance(node, ast.ClassDef):
57+
for child in (c for c in node.body if isinstance(c, ast.FunctionDef)):
58+
visited.add(child)
59+
yield f"{node.name}.{child.name}", ast.get_docstring(child) or "", child
60+
elif isinstance(node, ast.FunctionDef):
61+
yield node.name, ast.get_docstring(node) or "", node
62+
63+
def process_description(self, entity_name: str, description: str, node: ast.AST) -> None:
64+
"""Processes a single description, potentially modifying it."""
65+
if not description:
66+
return
67+
68+
def find_example_ranges(index: int) -> typing.Iterator[tuple[int, int]]:
69+
"""Finds the scope of the example in the description.
70+
"""
71+
count: int = 0
72+
indent: int = 0
73+
start: int = -1
74+
75+
while index < self.max_index:
76+
line: str = self.lines[index].lower()
77+
line_strip: str = line.strip()
78+
if len(line_strip) == 0:
79+
index += 1
80+
continue
81+
82+
cur_indent: int = len(line) - len(line_strip)
83+
isCodeBlock: bool = line_strip.startswith(".. code-block:: python")
84+
isCommentEnd: bool = line_strip == '"""'
85+
86+
if isCodeBlock:
87+
start = index
88+
indent = cur_indent
89+
90+
if start != -1 and index != start and (cur_indent <= indent):
91+
yield count, start, index
92+
count += 1
93+
start = -1
94+
95+
if isCommentEnd:
96+
return
97+
98+
index += 1
99+
100+
def save_example(start: int, end: int, entity_name: str, count: int) -> None:
101+
"""Saves the example code to a separate file and modifies the original description.
102+
"""
103+
lines: list[str] = self.lines[start + 1:end]
104+
min_indent: int = min((len(line) - len(line.lstrip())
105+
for line in lines if line.strip()), default=0)
106+
entity_name: str = f"{self.prefix}.{entity_name}"
107+
header: str = HEADER.format(entity_name)
108+
code: str = header + "\n".join(line[min_indent:] if line else line for line in lines)
109+
110+
name: str = f"{entity_name}.{count}.py".lower()
111+
file: str = os.path.join(self.output_dir, name)
112+
if os.path.exists(file):
113+
raise FileExistsError(f"File already exists: {file}")
114+
115+
with open(file, "w", encoding="utf-8") as f:
116+
f.write(code)
117+
118+
indent: str = " " * (max(min_indent - 4, 0))
119+
old : str = "\n".join(self.lines[start:end])
120+
new: str = (f"{indent}.. literalinclude:: {PATH_PREFIX}/{name}\n{indent} :language: "
121+
f"python\n{indent} :lines: 7-\n")
122+
self.new_code = self.new_code.replace(old, new)
123+
124+
index: int = node.lineno
125+
for i, start, end in find_example_ranges(index):
126+
save_example(start, end, entity_name, i)
127+
128+
def run(self):
129+
"""Run the parser and print extracted information.
130+
"""
131+
for name, description, node in self.iter_items():
132+
self.process_description(name, description, node)
133+
134+
with open(self.out_file, "w", encoding="utf-8") as f:
135+
f.write(self.new_code)
136+
137+
if __name__ == "__main__":
138+
# Delete all existing fragments first.
139+
for f in os.listdir("/Users/f_hoppe/git/zbrush-sdk/examples/fragments/"):
140+
os.remove(os.path.join("/Users/f_hoppe/git/zbrush-sdk/examples/fragments/", f))
141+
142+
# Process all relevant files.
143+
for path, domain in [
144+
("/Users/f_hoppe/git/zbrush-sdk/api/zbrush/commands.py", "zbrush.commands"),
145+
("/Users/f_hoppe/git/zbrush-sdk/api/zbrush/utils.py", "zbrush.utils"),
146+
("/Users/f_hoppe/git/zbrush-sdk/api/zbrush/zscript_compatibility.py", "zbrush.zscript_compatibility")]:
147+
parser = PyExampleParser(path, "/Users/f_hoppe/git/zbrush-sdk/examples/fragments/", domain)
148+
parser.run()
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""Code fragment for zbrush.commands.add_button.
2+
"""
3+
__author__ = "Ferdinand Hoppe"
4+
__date__ = "16/10/2025"
5+
__copyright__ = "Maxon Computer"
6+
7+
from zbrush import commands as zbc
8+
9+
# A callback functions for multiple buttons which checks the item path of the raised item.
10+
def on_button_pressed(sender: str) -> None:
11+
if str(sender).endswith("Bar"):
12+
print("A button named 'Bar' was pressed.")
13+
else:
14+
print(f"Button pressed: {sender = }")
15+
16+
# Add a 'Foo' subpalette to the 'ZScript' palette if it doesn't exist.
17+
if not zbc.exists("ZScript:Foo"):
18+
zbc.add_subpalette("ZScript:Foo")
19+
20+
# Adds a button labeled 'Bar' to the 'ZScript:Foo' subpalette with the tooltip "Hello World!"
21+
# which invokes the callback #on_button_pressed when clicked.
22+
zbc.add_button("ZScript:Foo:Bar", "Hello World!", on_button_pressed)

0 commit comments

Comments
 (0)