├── .github └── workflows │ └── github_pages.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── absolute_path.py ├── api ├── arrange.py ├── node_mapper.py ├── state.py ├── static │ ├── attribute.py │ ├── curve.py │ ├── expression.py │ ├── input_group.py │ ├── repeat.py │ ├── sample_mode.py │ └── simulation.py ├── tree.py └── types.py ├── book ├── .gitignore ├── book.toml ├── src │ ├── SUMMARY.md │ ├── api │ │ ├── advanced-scripting.md │ │ ├── advanced-scripting │ │ │ ├── attributes.md │ │ │ ├── boolean-math.md │ │ │ ├── cube_grid.png │ │ │ ├── curves.md │ │ │ ├── drivers.md │ │ │ ├── float_curve.png │ │ │ ├── generators.md │ │ │ ├── geometry_generator.png │ │ │ ├── input-groups.md │ │ │ ├── instance_grid.png │ │ │ ├── mixed_generator.png │ │ │ ├── node-groups.md │ │ │ ├── repeat-zones.md │ │ │ └── simulation-zones.md │ │ ├── basics.md │ │ └── basics │ │ │ ├── capture_attribute_node.png │ │ │ ├── cube_node.png │ │ │ ├── cube_tree.png │ │ │ ├── cube_tree_int.png │ │ │ ├── cube_tree_mesh_to_volume.png │ │ │ ├── cube_tree_modifier.png │ │ │ ├── cube_tree_named_outputs.png │ │ │ ├── cube_tree_size.png │ │ │ ├── cube_tree_size_compare.png │ │ │ ├── cube_tree_size_components.png │ │ │ ├── cube_tree_size_double.png │ │ │ ├── cube_tree_size_input.png │ │ │ ├── math_wrap.png │ │ │ ├── modules.md │ │ │ ├── open_documentation.png │ │ │ ├── sockets.md │ │ │ ├── tree-functions.md │ │ │ └── using-nodes.md │ ├── images │ │ ├── addon_preferences.png │ │ ├── auto_resolve.png │ │ ├── example_generated_tree.png │ │ ├── geometry_nodes_modifier.png │ │ ├── ide_docs.png │ │ ├── live_edit.png │ │ ├── open_file.png │ │ ├── text_editor_new.png │ │ ├── text_editor_run_script.png │ │ ├── text_editor_space.png │ │ ├── vscode_code_completion.png │ │ ├── vscode_extra_paths.png │ │ └── wordmark.png │ ├── introduction.md │ ├── setup │ │ ├── external-editing.md │ │ ├── installation.md │ │ └── internal-editing-basics.md │ └── tutorials │ │ ├── city-builder.md │ │ ├── city_builder.gif │ │ ├── city_builder_nodes.png │ │ ├── monkey.png │ │ ├── monkey_points.png │ │ ├── monkey_volume.png │ │ ├── monkey_voxels.png │ │ ├── voxelize.md │ │ ├── voxelize_modifier.png │ │ └── voxelize_nodes.png └── style.css ├── docs └── .gitignore ├── examples ├── City Builder.py ├── Mesh to LEGO.py └── Repeat Grid.py ├── external.py ├── preferences.py └── typeshed └── .gitignore /.github/workflows/github_pages.yml: -------------------------------------------------------------------------------- 1 | name: github pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | concurrency: preview-${{ github.ref }} 10 | 11 | jobs: 12 | deploy: 13 | runs-on: ubuntu-20.04 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.ref }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - name: Setup mdBook 20 | uses: peaceiris/actions-mdbook@v1 21 | with: 22 | mdbook-version: 'latest' 23 | 24 | - run: mdbook build 25 | working-directory: book 26 | 27 | - name: Deploy 28 | uses: peaceiris/actions-gh-pages@v3 29 | if: ${{ github.ref == 'refs/heads/main' }} 30 | with: 31 | github_token: ${{ secrets.GITHUB_TOKEN }} 32 | publish_dir: ./book/book 33 | 34 | - name: Deploy preview 35 | uses: rossjrw/pr-preview-action@v1 36 | if: ${{ github.ref != 'refs/heads/main' }} 37 | with: 38 | source-dir: ./book/book -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | # For a library or package, you might want to ignore these files since the code is 89 | # intended to run in multiple environments; otherwise, check them in: 90 | # .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 101 | # This is especially recommended for binary packages to ensure reproducibility, and is more 102 | # commonly ignored for libraries. 103 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 104 | #poetry.lock 105 | 106 | # pdm 107 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 108 | #pdm.lock 109 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 110 | # in version control. 111 | # https://pdm.fming.dev/#use-with-ide 112 | .pdm.toml 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Geometry Script wordmark](book/src/images/wordmark.png) 2 | 3 | A scripting API for Blender's Geometry Nodes: 4 | 5 | 6 | 7 | 8 | 9 | 24 | 29 | 30 | 31 |
10 | 11 | ```python 12 | from geometry_script import * 13 | 14 | @tree("Repeat Grid") 15 | def repeat_grid(geometry: Geometry, width: Int, height: Int): 16 | g = grid( 17 | size_x=width, size_y=height, 18 | vertices_x=width, vertices_y=height 19 | ).mesh.mesh_to_points() 20 | return g.instance_on_points(instance=geometry) 21 | ``` 22 | 23 | 25 | 26 | ![Generated node tree](book/src/images/example_generated_tree.png) 27 | 28 |
32 | 33 | ## Installation 34 | 1. [Download the source code](https://github.com/carson-katri/geometry-script/archive/refs/heads/main.zip) 35 | 2. Open *Blender* > *Preferences* > *Add-ons* 36 | 3. Choose *Install...* and select the downloaded ZIP file 37 | 38 | Or you can get it from the [Blender Market](https://www.blendermarket.com/products/geometry-script). 39 | 40 | ## What is Geometry Script? 41 | *Geometry Script* is a robust yet easy to use Python API for creating Geometry Nodes with code. 42 | 43 | At a certain point, Geometry Node trees become unmanagably large. Creating node trees in Python enables quicker editing and reorganization of large, complex trees. 44 | 45 | *Geometry Script* has all of the performance and capabilities of Geometry Nodes, but in a more managable format. The scripts are converted directly to Geometry Node trees making them easy to tweak for others unfamiliar with scripting. 46 | 47 | ## [Documentation](https://carson-katri.github.io/geometry-script/) 48 | Read the documentation for more information on installation, syntax, and tutorials. 49 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # This program is free software; you can redistribute it and/or modify 2 | # it under the terms of the GNU General Public License as published by 3 | # the Free Software Foundation; either version 3 of the License, or 4 | # (at your option) any later version. 5 | # 6 | # This program is distributed in the hope that it will be useful, but 7 | # WITHOUT ANY WARRANTY; without even the implied warranty of 8 | # MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 9 | # General Public License for more details. 10 | # 11 | # You should have received a copy of the GNU General Public License 12 | # along with this program. If not, see . 13 | 14 | # Set the `geometry_script` module to the current module in case the folder is named differently. 15 | import sys 16 | sys.modules['geometry_script'] = sys.modules[__name__] 17 | 18 | import bpy 19 | import os 20 | import webbrowser 21 | 22 | from .api.tree import * 23 | from .preferences import GeometryScriptPreferences 24 | from .absolute_path import absolute_path 25 | 26 | bl_info = { 27 | "name" : "Geometry Script", 28 | "author" : "Carson Katri", 29 | "description" : "Python scripting for geometry nodes", 30 | "blender" : (3, 0, 0), 31 | "version" : (0, 1, 2), 32 | "location" : "", 33 | "warning" : "", 34 | "category" : "Node" 35 | } 36 | 37 | class TEXT_MT_templates_geometryscript(bpy.types.Menu): 38 | bl_label = "Geometry Script" 39 | 40 | def draw(self, _context): 41 | self.path_menu( 42 | [os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples")], 43 | "text.open", 44 | props_default={"internal": True}, 45 | filter_ext=lambda ext: (ext.lower() == ".py") 46 | ) 47 | 48 | class OpenDocumentation(bpy.types.Operator): 49 | bl_idname = "geometry_script.open_documentation" 50 | bl_label = "Open Documentation" 51 | 52 | def execute(self, context): 53 | webbrowser.open('file://' + absolute_path('docs/documentation.html')) 54 | return {'FINISHED'} 55 | 56 | class GeometryScriptSettings(bpy.types.PropertyGroup): 57 | auto_resolve: bpy.props.BoolProperty(name="Auto Resolve", default=False, description="If the file is edited externally, automatically accept the changes") 58 | 59 | class GeometryScriptMenu(bpy.types.Menu): 60 | bl_idname = "TEXT_MT_geometryscript" 61 | bl_label = "Geometry Script" 62 | 63 | def draw(self, context): 64 | layout = self.layout 65 | 66 | text = context.space_data.text 67 | if text and len(text.filepath) > 0: 68 | layout.prop(context.scene.geometry_script_settings, 'auto_resolve') 69 | layout.operator(OpenDocumentation.bl_idname) 70 | 71 | def templates_menu_draw(self, context): 72 | self.layout.menu(TEXT_MT_templates_geometryscript.__name__) 73 | 74 | def editor_header_draw(self, context): 75 | self.layout.menu(GeometryScriptMenu.bl_idname) 76 | 77 | def auto_resolve(): 78 | if bpy.context.scene.geometry_script_settings.auto_resolve: 79 | try: 80 | for area in bpy.context.screen.areas: 81 | for space in area.spaces: 82 | if space.type == 'TEXT_EDITOR': 83 | with bpy.context.temp_override(area=area, space=space): 84 | text = bpy.context.space_data.text 85 | if text and text.is_modified: 86 | bpy.ops.text.resolve_conflict(resolution='RELOAD') 87 | if bpy.context.space_data.use_live_edit: 88 | bpy.ops.text.run_script() 89 | except: 90 | pass 91 | return 1 92 | 93 | def register(): 94 | bpy.utils.register_class(TEXT_MT_templates_geometryscript) 95 | bpy.types.TEXT_MT_templates.append(templates_menu_draw) 96 | bpy.utils.register_class(GeometryScriptSettings) 97 | bpy.utils.register_class(GeometryScriptPreferences) 98 | bpy.utils.register_class(OpenDocumentation) 99 | bpy.utils.register_class(GeometryScriptMenu) 100 | 101 | bpy.types.TEXT_HT_header.append(editor_header_draw) 102 | 103 | bpy.types.Scene.geometry_script_settings = bpy.props.PointerProperty(type=GeometryScriptSettings) 104 | 105 | bpy.app.timers.register(auto_resolve, persistent=True) 106 | 107 | def unregister(): 108 | bpy.utils.unregister_class(TEXT_MT_templates_geometryscript) 109 | bpy.types.TEXT_MT_templates.remove(templates_menu_draw) 110 | bpy.utils.unregister_class(GeometryScriptSettings) 111 | bpy.utils.unregister_class(GeometryScriptPreferences) 112 | bpy.utils.unregister_class(OpenDocumentation) 113 | bpy.utils.unregister_class(GeometryScriptMenu) 114 | bpy.types.TEXT_HT_header.remove(editor_header_draw) 115 | try: 116 | bpy.app.timers.unregister(auto_resolve) 117 | except: 118 | pass 119 | -------------------------------------------------------------------------------- /absolute_path.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def absolute_path(component): 4 | """ 5 | Returns the absolute path to a file in the addon directory. 6 | 7 | Alternative to `os.abspath` that works the same on macOS and Windows. 8 | """ 9 | return os.path.join(os.path.dirname(os.path.realpath(__file__)), component) -------------------------------------------------------------------------------- /api/arrange.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import typing 3 | from collections import deque, Counter 4 | 5 | def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)): 6 | # Organize the nodes into columns based on their links. 7 | columns: typing.List[typing.List[typing.Any]] = [] 8 | 9 | def topo_sort(graph): 10 | in_degree = {u: 0 for u in graph} 11 | for u in graph: 12 | for v in graph[u]: 13 | in_degree[v] += 1 14 | queue = deque([u for u in in_degree if in_degree[u] == 0]) 15 | topo_order = [] 16 | while queue: 17 | u = queue.popleft() 18 | topo_order.append(u) 19 | for v in graph[u]: 20 | in_degree[v] -= 1 21 | if in_degree[v] == 0: 22 | queue.append(v) 23 | return topo_order 24 | 25 | graph = { node:set() for node in node_tree.nodes } 26 | node_input_link_count = Counter() 27 | for link in node_tree.links: 28 | graph[link.from_node].add(link.to_node) 29 | node_input_link_count[link.to_socket] += 1 30 | sorted_nodes = topo_sort(graph) 31 | 32 | column_index = {} 33 | for node in reversed(sorted_nodes): 34 | column_index[node] = max([ column_index[adj_node] for adj_node in graph[node] ], default=-1) + 1 35 | if column_index[node] == len(columns): 36 | columns.append([node]) 37 | else: 38 | columns[column_index[node]].append(node) 39 | columns = reversed(columns) 40 | 41 | # Arrange the columns, computing the size of the node manually so arrangement can be done without UI being visible. 42 | UI_SCALE = bpy.context.preferences.view.ui_scale 43 | NODE_HEADER_HEIGHT = 20 44 | NODE_LINK_HEIGHT = 28 45 | NODE_PROPERTY_HEIGHT = 28 46 | NODE_VECTOR_HEIGHT = 84 47 | x = 0 48 | for col in columns: 49 | largest_width = 0 50 | y = 0 51 | for node in col: 52 | node.update() 53 | input_count = len(list(filter(lambda i: i.enabled, node.inputs))) 54 | output_count = len(list(filter(lambda i: i.enabled, node.outputs))) 55 | parent_props = [prop.identifier for base in type(node).__bases__ for prop in base.bl_rna.properties] 56 | properties_count = len([prop for prop in node.bl_rna.properties if prop.identifier not in parent_props]) 57 | unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and node_input_link_count[i] == 0, node.inputs))) 58 | node_height = ( 59 | NODE_HEADER_HEIGHT \ 60 | + (output_count * NODE_LINK_HEIGHT) \ 61 | + (properties_count * NODE_PROPERTY_HEIGHT) \ 62 | + (input_count * NODE_LINK_HEIGHT) \ 63 | + (unset_vector_count * NODE_VECTOR_HEIGHT) 64 | ) * UI_SCALE 65 | if node.width > largest_width: 66 | largest_width = node.width 67 | node.location = (x, y) 68 | y -= node_height + padding[1] 69 | x += largest_width + padding[0] -------------------------------------------------------------------------------- /api/node_mapper.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import itertools 3 | import enum 4 | import re 5 | import os 6 | from .state import State 7 | from .types import * 8 | from .static.input_group import InputGroup 9 | from .static.curve import Curve 10 | from ..absolute_path import absolute_path 11 | 12 | class OutputsList(dict): 13 | __getattr__ = dict.get 14 | __setattr__ = dict.__setitem__ 15 | __delattr__ = dict.__delitem__ 16 | 17 | def set_or_create_link(x, node_input): 18 | if issubclass(type(x), Type): 19 | State.current_node_tree.links.new(x._socket, node_input) 20 | else: 21 | def link_constant(): 22 | constant = Type(value=x) 23 | State.current_node_tree.links.new(constant._socket, node_input) 24 | if node_input.hide_value: 25 | link_constant() 26 | else: 27 | try: 28 | node_input.default_value = x 29 | except: 30 | link_constant() 31 | 32 | def build_node(node_type): 33 | def build(_primary_arg=None, **kwargs): 34 | for k, v in kwargs.copy().items(): 35 | if isinstance(v, InputGroup): 36 | kwargs = { **kwargs, **v.__dict__ } 37 | del kwargs[k] 38 | if v is None: 39 | del kwargs[k] 40 | node = State.current_node_tree.nodes.new(node_type.__name__) 41 | if _primary_arg is not None: 42 | State.current_node_tree.links.new(_primary_arg._socket, node.inputs[0]) 43 | for prop in node.bl_rna.properties: 44 | argname = prop.identifier.lower().replace(' ', '_') 45 | if argname in kwargs: 46 | value = kwargs[argname] 47 | if isinstance(value, list) and len(value) > 0 and isinstance(value[0], Curve): 48 | for i, curve in enumerate(value): 49 | curve.apply(getattr(node, prop.identifier).curves[i]) 50 | continue 51 | if isinstance(value, Curve): 52 | value.apply(getattr(node, prop.identifier).curves[0]) 53 | continue 54 | if isinstance(value, enum.Enum): 55 | value = value.value 56 | setattr(node, prop.identifier, value) 57 | for node_input in (node.inputs[1:] if _primary_arg is not None else node.inputs): 58 | if not node_input.enabled: 59 | continue 60 | argname = node_input.name.lower().replace(' ', '_') 61 | all_with_name = [] 62 | for node_input2 in (node.inputs[1:] if _primary_arg is not None else node.inputs): 63 | if node_input2.name.lower().replace(' ', '_') == argname and node_input2.type == node_input.type: 64 | all_with_name.append(node_input2) 65 | if argname in kwargs: 66 | value = kwargs[argname] 67 | if isinstance(value, enum.Enum): 68 | value = value.value 69 | if node_input.is_multi_input and hasattr(value, '__iter__') and len(value) > 0 and issubclass(type(next(iter(value))), Type): 70 | for x in value: 71 | for node_input in all_with_name: 72 | State.current_node_tree.links.new(x._socket, node_input) 73 | elif len(all_with_name) > 1 and issubclass(type(value), tuple) and len(value) > 0: 74 | for i, x in enumerate(value): 75 | set_or_create_link(x, all_with_name[i]) 76 | else: 77 | for node_input in all_with_name: 78 | set_or_create_link(value, node_input) 79 | outputs = {} 80 | for node_output in node.outputs: 81 | if not node_output.enabled: 82 | continue 83 | outputs[node_output.name.lower().replace(' ', '_')] = Type(node_output) 84 | if len(outputs) == 1: 85 | return list(outputs.values())[0] 86 | else: 87 | return OutputsList(outputs) 88 | return build 89 | 90 | documentation = {} 91 | registered_nodes = set() 92 | def register_node(node_type, category_path=None): 93 | if node_type in registered_nodes: 94 | return 95 | snake_case_name = node_type.bl_rna.name.lower().replace(' ', '_') 96 | node_namespace_name = snake_case_name.replace('_', ' ').title().replace(' ', '') 97 | globals()[snake_case_name] = build_node(node_type) 98 | globals()[snake_case_name].bl_category_path = category_path 99 | globals()[snake_case_name].bl_node_type = node_type 100 | documentation[snake_case_name] = globals()[snake_case_name] 101 | def build_node_method(node_type): 102 | def build(self, *args, **kwargs): 103 | return build_node(node_type)(self, *args, **kwargs) 104 | return build 105 | setattr(Type, snake_case_name, build_node_method(node_type)) 106 | parent_props = [prop.identifier for base in node_type.__bases__ for prop in base.bl_rna.properties] 107 | for prop in node_type.bl_rna.properties: 108 | if not prop.identifier in parent_props and prop.type == 'ENUM': 109 | if node_namespace_name not in globals(): 110 | class NodeNamespace: pass 111 | NodeNamespace.__name__ = node_namespace_name 112 | globals()[node_namespace_name] = NodeNamespace 113 | enum_type_name = prop.identifier.replace('_', ' ').title().replace(' ', '') 114 | enum_type = enum.Enum(enum_type_name, { map_case_name(i): i.identifier for i in prop.enum_items }) 115 | setattr(globals()[node_namespace_name], enum_type_name, enum_type) 116 | registered_nodes.add(node_type) 117 | 118 | denylist = {'filter'} # some nodes should be excluded. 119 | class_denylist = {'CompositorNodeMath', 'TextureNodeMath'} 120 | node_types_to_register = [] 121 | for node_type_name in dir(bpy.types): 122 | node_type = getattr(bpy.types, node_type_name) 123 | if isinstance(node_type, type) and issubclass(node_type, bpy.types.Node): 124 | if node_type.is_registered_node_type() and node_type.bl_rna.name.lower() not in denylist and node_type.__name__ not in class_denylist: 125 | node_types_to_register.append(node_type) 126 | node_types_to_register.sort(key=lambda node_type: node_type.__name__.startswith("GeometryNode")) 127 | for node_type in node_types_to_register: 128 | register_node(node_type) 129 | 130 | def create_documentation(): 131 | temp_node_group = bpy.data.node_groups.new('temp_node_group', 'GeometryNodeTree') 132 | color_mappings = { 133 | 'INT': '#598C5C', 134 | 'FLOAT': '#A1A1A1', 135 | 'BOOLEAN': '#CCA6D6', 136 | 'GEOMETRY': '#00D6A3', 137 | 'VALUE': '#A1A1A1', 138 | 'VECTOR': '#6363C7', 139 | 'MATERIAL': '#EB7582', 140 | 'TEXTURE': '#9E4FA3', 141 | 'COLLECTION': '#F5F5F5', 142 | 'OBJECT': '#ED9E5C', 143 | 'STRING': '#70B2FF', 144 | 'RGBA': '#C7C729', 145 | } 146 | default_color = '#A1A1A1' 147 | docstrings = [] 148 | symbols = [] 149 | enums = {} 150 | skipped_nodes = [] 151 | for func in sorted(documentation.keys()): 152 | try: 153 | method = documentation[func] 154 | link = f"https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/{method.bl_category_path}/{func}.html" 155 | image = f"https://docs.blender.org/manual/en/latest/_images/node-types_{method.bl_node_type.__name__}" 156 | node_instance = temp_node_group.nodes.new(method.bl_node_type.__name__) 157 | props_inputs = {} 158 | symbol_inputs = {} 159 | parent_props = [prop.identifier for base in method.bl_node_type.__bases__ for prop in base.bl_rna.properties] 160 | node_namespace_name = func.replace('_', ' ').title().replace(' ', '') 161 | for prop in method.bl_node_type.bl_rna.properties: 162 | if not prop.identifier in parent_props: 163 | if prop.type == 'ENUM': 164 | enum_name = prop.identifier.replace('_', ' ').title().replace(' ', '') 165 | enum_cases = '\n '.join(map(lambda i: f"{map_case_name(i)} = '{i.identifier}'", prop.enum_items)) 166 | if node_namespace_name not in enums: 167 | enums[node_namespace_name] = [] 168 | enums[node_namespace_name].append(f""" class {enum_name}(enum.Enum): 169 | {enum_cases}""") 170 | props_inputs[prop.identifier] = {f"{node_namespace_name}.{enum_name}":1} 171 | symbol_inputs[prop.identifier] = {f"{node_namespace_name}.{enum_name}": 1} 172 | else: 173 | props_inputs[prop.identifier] = {f"{prop.type.title()}":1} 174 | symbol_inputs[prop.identifier] = {prop.type.title(): 1} 175 | primary_arg = None 176 | for node_input in node_instance.inputs: 177 | name = node_input.name.lower().replace(' ', '_') 178 | typename = type(node_input).__name__.replace('NodeSocket', '') 179 | if node_input.is_multi_input: 180 | typename = f"List[{typename}]" 181 | type_str = f"{typename}" 182 | if name in props_inputs: 183 | if type_str in props_inputs[name]: 184 | props_inputs[name][type_str] += 1 185 | symbol_inputs[name][typename] += 1 186 | else: 187 | props_inputs[name][type_str] = 1 188 | symbol_inputs[name][typename] = 1 189 | else: 190 | props_inputs[name] = {type_str: 1} 191 | symbol_inputs[name] = {typename: 1} 192 | if primary_arg is None: 193 | primary_arg = (name, list(props_inputs[name].keys())[0]) 194 | def collapse_inputs(inputs): 195 | for k, v in inputs.items(): 196 | values = [] 197 | for t, c in v.items(): 198 | for c in range(1, c + 1): 199 | value = "" 200 | if c > 1: 201 | value += "Tuple[" 202 | value += ', '.join(itertools.repeat(t, c)) 203 | if c > 1: 204 | value += "]" 205 | values.append(value) 206 | inputs[k] = ' | '.join(values) 207 | collapse_inputs(props_inputs) 208 | collapse_inputs(symbol_inputs) 209 | arg_docs = [] 210 | symbol_args = [] 211 | for name, value in props_inputs.items(): 212 | arg_docs.append(f"{name}: {value}") 213 | symbol_args.append(f"{name}: {symbol_inputs[name]} | None = None") 214 | outputs = {} 215 | symbol_outputs = {} 216 | for node_output in node_instance.outputs: 217 | output_name = node_output.name.lower().replace(' ', '_') 218 | output_type = type(node_output).__name__.replace('NodeSocket', '') 219 | outputs[output_name] = f"{output_type}" 220 | symbol_outputs[output_name] = output_type 221 | output_docs = [] 222 | output_symbols = [] 223 | for name, value in outputs.items(): 224 | output_docs.append(f"{name}: {value}") 225 | output_symbols.append(f"{name}: {symbol_outputs[name]}") 226 | outputs_doc = f"{{ {', '.join(output_docs)} }}" if len(output_docs) > 1 else ''.join(output_docs) 227 | arg_separator = ',\n ' 228 | def primary_arg_docs(): 229 | return f""" 230 |

Chain Syntax

231 |
{primary_arg[0]}: {primary_arg[1]} = ...
232 | {primary_arg[0]}.{func}(...)
233 | """ 234 | docstrings.append(f""" 235 |
236 | {func} - {method.bl_node_type.bl_rna.name} 237 |
238 | 239 |

Signature

240 |
{func}(
241 |   {arg_separator.join(arg_docs)}
242 | )
243 |

Result

244 |
{outputs_doc}
245 | {primary_arg_docs() if primary_arg is not None else ""} 246 |
247 |
248 | """) 249 | output_symbol_separator = '\n ' 250 | if len(output_symbols) > 1: 251 | if node_namespace_name not in enums: 252 | enums[node_namespace_name] = [] 253 | enums[node_namespace_name].append(f""" class Result: 254 | {output_symbol_separator.join(output_symbols)}""") 255 | return_type_hint = list(symbol_outputs.values())[0] if len(output_symbols) == 1 else f"{node_namespace_name}.Result" 256 | symbols.append(f"""def {func}({', '.join(symbol_args)}) -> {return_type_hint}: \"\"\"![]({image}.webp)\"\"\"""") 257 | except: 258 | skipped_nodes.append(documentation[func].bl_node_type.__name__) 259 | continue 260 | bpy.data.node_groups.remove(temp_node_group) 261 | html = f""" 262 | 263 | 264 | 284 | 285 | 286 |

Geometry Script

287 |

Nodes

288 | {''.join(docstrings)} 289 | 290 | 291 | """ 292 | with open(absolute_path('docs/documentation.html'), 'w') as f: 293 | f.write(html) 294 | with open(absolute_path('typeshed/geometry_script.pyi'), 'w') as fpyi, open(absolute_path('typeshed/geometry_script.py'), 'w') as fpy: 295 | newline = '\n' 296 | def type_symbol(t): 297 | return f"class {t.__name__}(Type): pass" 298 | def enum_namespace(k): 299 | return f"""class {k}: 300 | {newline.join(enums[k])}""" 301 | def add_self_arg(x): 302 | return re.sub('\(', '(self, ', x, 1) 303 | contents = f"""from typing import * 304 | import enum 305 | def tree(builder): 306 | \"\"\" 307 | Marks a function as a node tree. 308 | \"\"\" 309 | pass 310 | _SomeType = TypeVar('_SomeType', bound='Type') 311 | class Type: 312 | def __add__(self, other) -> Type: return self 313 | def __radd__(self, other) -> Type: return self 314 | def __sub__(self, other) -> Type: return self 315 | def __rsub__(self, other) -> Type: return self 316 | def __mul__(self, other) -> Type: return self 317 | def __rmul__(self, other) -> Type: return self 318 | def __truediv__(self, other) -> Type: return self 319 | def __rtruediv__(self, other) -> Type: return self 320 | def __mod__(self, other) -> Type: return self 321 | def __rmod__(self, other) -> Type: return self 322 | def __eq__(self, other) -> Type: return self 323 | def __ne__(self, other) -> Type: return self 324 | def __lt__(self, other) -> Type: return self 325 | def __le__(self, other) -> Type: return self 326 | def __gt__(self, other) -> Type: return self 327 | def __ge__(self, other) -> Type: return self 328 | def __invert__(self) -> Type: return self 329 | def __getitem__( 330 | self, 331 | subscript: _SomeType | slice | Tuple[_SomeType | slice, SampleMode] 332 | ) -> Type: return self 333 | x = Type() 334 | y = Type() 335 | z = Type() 336 | def capture(self, attribute: Type, **kwargs) -> (Geometry, Type): return Geometry(), Type() 337 | def transfer(self, attribute: Type, **kwargs) -> Type: return Type() 338 | {(newline + ' ').join(map(add_self_arg, filter(lambda x: x.startswith('def'), symbols)))} 339 | 340 | {newline.join(map(type_symbol, Type.__subclasses__()))} 341 | {newline.join(map(enum_namespace, enums.keys()))} 342 | {newline.join(symbols)}""" 343 | 344 | static_path = absolute_path('api/static') 345 | for path in os.listdir(static_path): 346 | if os.path.splitext(path)[-1] != '.py': 347 | continue 348 | with open(os.path.join(static_path, path), 'r') as static_api: 349 | contents += f"\n\n# {path}\n{static_api.read()}" 350 | 351 | fpyi.write(contents) 352 | fpy.write(contents) 353 | 354 | if len(skipped_nodes) > 0: 355 | pass # This could be reported later. 356 | 357 | def create_docs(): 358 | create_documentation() 359 | bpy.app.timers.register(create_docs) 360 | -------------------------------------------------------------------------------- /api/state.py: -------------------------------------------------------------------------------- 1 | # Tree generation state 2 | class State: 3 | current_node_tree = None -------------------------------------------------------------------------------- /api/static/attribute.py: -------------------------------------------------------------------------------- 1 | class Attribute: 2 | """ 3 | A class that represents named attributes, providing methods for accessing and storing them. 4 | 5 | Create an attribute with a name, data type, and optional domain. 6 | ```python 7 | height_level = Attribute( 8 | "height_level", 9 | NamedAttribute.DataType.FLOAT, 10 | StoreNamedAttribute.Domain.POINT # optional 11 | ) 12 | ``` 13 | 14 | Access the attribute value by calling the class instance. 15 | ```python 16 | height_level() 17 | ``` 18 | 19 | Store a value for the named attribute on some geometry with `store(...)`. 20 | ```python 21 | height_level.store(geometry, value) 22 | ``` 23 | 24 | Check if the attribute exists on some geometry with `exists()`. 25 | ```python 26 | selection = height_level.exists() 27 | ``` 28 | """ 29 | name: str 30 | data_type: 'NamedAttribute.DataType' 31 | domain: 'StoreNamedAttribute.Domain' 32 | 33 | def __init__( 34 | self, 35 | name: str, 36 | data_type: 'NamedAttribute.DataType', 37 | domain: 'StoreNamedAttribute.Domain' = 'POINT' 38 | ): 39 | self.name = name 40 | self.data_type = data_type 41 | self.domain = domain 42 | 43 | def __call__(self, *args, **kwargs): 44 | """ 45 | Creates a "Named Attribute" node with the correct arguments passed, and returns the "Attribute" socket. 46 | """ 47 | from geometry_script import named_attribute, Type 48 | result = named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs) 49 | # Handle Blender 3.5+, which includes an `exists` result. 50 | if isinstance(result, Type): 51 | return result 52 | else: 53 | return result.attribute 54 | 55 | def exists(self, *args, **kwargs): 56 | """ 57 | Creates a "Named Attribute" node with the correct arguments passed, and returns the "Exists" socket. 58 | 59 | > Only available in Blender 3.5+ 60 | """ 61 | from geometry_script import named_attribute 62 | return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).exists 63 | 64 | def store(self, geometry: 'Geometry', value, *args, **kwargs) -> 'Geometry': 65 | """ 66 | Creates a "Store Named Attribute" node with the correct arguments passed, and returns the modified `Geometry`. 67 | """ 68 | from geometry_script import store_named_attribute 69 | if 'domain' not in kwargs: 70 | kwargs['domain'] = self.domain 71 | return store_named_attribute( 72 | data_type=self.data_type, 73 | geometry=geometry, 74 | name=self.name, 75 | value=value, 76 | *args, 77 | **kwargs 78 | ) -------------------------------------------------------------------------------- /api/static/curve.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import enum 3 | 4 | class HandleType(enum.Enum): 5 | AUTO = 'AUTO' 6 | VECTOR = 'VECTOR' 7 | AUTO_CLAMPED = 'AUTO_CLAMPED' 8 | 9 | class Point: 10 | """ 11 | A single point on a curve 12 | """ 13 | 14 | x: float 15 | y: float 16 | handle_type: HandleType 17 | 18 | def __init__(self, x: float, y: float, handle_type: HandleType = HandleType.AUTO): 19 | self.x = x 20 | self.y = y 21 | self.handle_type = handle_type 22 | 23 | class Curve: 24 | """ 25 | A class that represents a curve. 26 | 27 | Create a curve from a set of `Point`s. 28 | ```python 29 | my_curve = Curve( 30 | Point(0, 0, Handle.AUTO_CLAMPED), 31 | Point(0.2, 0.3, Handle.AUTO), 32 | Point(1, 1, Handle.VECTOR) 33 | ) 34 | ``` 35 | """ 36 | 37 | points: List[Point] 38 | 39 | def __init__(self, *points: Point): 40 | if len(points) == 1 and isinstance(points[0], list): 41 | self.points = points[0] 42 | else: 43 | self.points = list(points) 44 | 45 | def apply(self, curve): 46 | """ 47 | Apply the points to a curve object. 48 | """ 49 | for i, point in enumerate(self.points): 50 | if len(curve.points) > i: 51 | curve.points[i].location = (point.x, point.y) 52 | curve.points[i].handle_type = point.handle_type.value 53 | else: 54 | curve.points.new(point.x, point.y).handle_type = point.handle_type.value -------------------------------------------------------------------------------- /api/static/expression.py: -------------------------------------------------------------------------------- 1 | def scripted_expression(scripted_expression: str) -> 'Type': 2 | from geometry_script import Type, State 3 | value_node = State.current_node_tree.nodes.new('ShaderNodeValue') 4 | fcurve = value_node.outputs[0].driver_add("default_value") 5 | fcurve.driver.expression = scripted_expression 6 | return Type(value_node.outputs[0]) -------------------------------------------------------------------------------- /api/static/input_group.py: -------------------------------------------------------------------------------- 1 | class _InputGroupMeta(type): 2 | def __getitem__(cls, args): 3 | if isinstance(args, str): 4 | class PrefixedInputGroup(InputGroup): 5 | prefix = args 6 | PrefixedInputGroup.__annotations__ = cls.__annotations__ 7 | return PrefixedInputGroup 8 | return cls 9 | 10 | class InputGroup(metaclass=_InputGroupMeta): 11 | """ 12 | A group of inputs that will be expanded in the node tree. 13 | 14 | All properties must be annotated: 15 | ```python 16 | class MyInputGroup(InputGroup): 17 | my_float: Float 18 | my_bool: Bool 19 | my_string # Invalid 20 | ``` 21 | """ 22 | 23 | def __init__(self, **kwargs): 24 | for p in dir(self): 25 | if p in kwargs: 26 | setattr(self, p, kwargs[p]) -------------------------------------------------------------------------------- /api/static/repeat.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import inspect 3 | import typing 4 | 5 | def repeat_zone(block: typing.Callable): 6 | """ 7 | Create a repeat input/output block. 8 | 9 | > Only available in Blender 4.0+. 10 | """ 11 | def wrapped(*args, **kwargs): 12 | from geometry_script.api.node_mapper import OutputsList, set_or_create_link 13 | from geometry_script.api.state import State 14 | from geometry_script.api.types import Type, socket_class_to_data_type 15 | 16 | signature = inspect.signature(block) 17 | 18 | # setup zone 19 | repeat_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatInput.__name__) 20 | repeat_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatOutput.__name__) 21 | repeat_in.pair_with_output(repeat_out) 22 | 23 | # clear state items 24 | for item in repeat_out.repeat_items: 25 | repeat_out.repeat_items.remove(item) 26 | 27 | # link the iteration count 28 | set_or_create_link(args[0], repeat_in.inputs[0]) 29 | 30 | # create state items from block signature 31 | repeat_items = {} 32 | for param in signature.parameters.values(): 33 | repeat_items[param.name] = (param.annotation, param.default, None, None) 34 | for i, arg in enumerate(repeat_items.items()): 35 | repeat_out.repeat_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title()) 36 | # skip the first index, which is reserved for the iteration count 37 | i = i + 1 38 | set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], repeat_in.inputs[i]) 39 | 40 | step = block(*[Type(o) for o in repeat_in.outputs[:-1]]) 41 | 42 | if isinstance(step, Type): 43 | step = (step,) 44 | for i, result in enumerate(step): 45 | set_or_create_link(result, repeat_out.inputs[i]) 46 | 47 | if len(repeat_out.outputs[:-1]) == 1: 48 | return Type(repeat_out.outputs[0]) 49 | else: 50 | return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in repeat_out.outputs[:-1]}) 51 | return wrapped -------------------------------------------------------------------------------- /api/static/sample_mode.py: -------------------------------------------------------------------------------- 1 | import enum 2 | 3 | class SampleMode(enum.IntEnum): 4 | INDEX = 0 5 | NEAREST_SURFACE = 1 6 | NEAREST = 2 -------------------------------------------------------------------------------- /api/static/simulation.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import inspect 3 | import typing 4 | 5 | def simulation_zone(block: typing.Callable): 6 | """ 7 | Create a simulation input/output block. 8 | 9 | In Blender 4.0+, you must return a boolean value for the "Skip" argument as the first element in the return tuple. 10 | 11 | > Only available in Blender 3.6+. 12 | """ 13 | def wrapped(*args, **kwargs): 14 | from geometry_script.api.node_mapper import OutputsList, set_or_create_link 15 | from geometry_script.api.state import State 16 | from geometry_script.api.types import Type, socket_class_to_data_type 17 | 18 | signature = inspect.signature(block) 19 | 20 | # setup zone 21 | simulation_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationInput.__name__) 22 | simulation_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationOutput.__name__) 23 | simulation_in.pair_with_output(simulation_out) 24 | 25 | # clear state items 26 | for item in simulation_out.state_items: 27 | simulation_out.state_items.remove(item) 28 | 29 | # create state items from block signature 30 | state_items = {} 31 | for param in [*signature.parameters.values()][1:]: 32 | state_items[param.name] = (param.annotation, param.default, None, None) 33 | for i, arg in enumerate(state_items.items()): 34 | simulation_out.state_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title()) 35 | set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], simulation_in.inputs[i]) 36 | 37 | step = block(*[Type(o) for o in simulation_in.outputs[:-1]]) 38 | 39 | if isinstance(step, Type): 40 | step = (step,) 41 | for i, result in enumerate(step): 42 | set_or_create_link(result, simulation_out.inputs[i]) 43 | 44 | if len(simulation_out.outputs[:-1]) == 1: 45 | return Type(simulation_out.outputs[0]) 46 | else: 47 | return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in simulation_out.outputs[:-1]}) 48 | return wrapped -------------------------------------------------------------------------------- /api/tree.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import inspect 3 | try: 4 | import node_arrange as node_arrange 5 | except: 6 | pass 7 | from .state import State 8 | from .types import * 9 | from .node_mapper import * 10 | from .static.attribute import * 11 | from .static.curve import * 12 | from .static.expression import * 13 | from .static.input_group import * 14 | from .static.repeat import * 15 | from .static.sample_mode import * 16 | from .static.simulation import * 17 | from .arrange import _arrange 18 | 19 | IS_BLENDER_4 = bpy.app.version[0] >= 4 20 | 21 | def _as_iterable(x): 22 | if isinstance(x, Type): 23 | return [x,] 24 | try: 25 | return iter(x) 26 | except TypeError: 27 | return [x,] 28 | 29 | def get_node_inputs(x): 30 | if IS_BLENDER_4: 31 | return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'INPUT'] 32 | else: 33 | return x.inputs 34 | def get_node_outputs(x): 35 | if IS_BLENDER_4: 36 | return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'OUTPUT'] 37 | else: 38 | return x.outputs 39 | 40 | def tree(name): 41 | tree_name = name 42 | def build_tree(builder): 43 | signature = inspect.signature(builder) 44 | 45 | # Locate or create the node group 46 | node_group = None 47 | if tree_name in bpy.data.node_groups: 48 | node_group = bpy.data.node_groups[tree_name] 49 | else: 50 | node_group = bpy.data.node_groups.new(tree_name, 'GeometryNodeTree') 51 | 52 | if IS_BLENDER_4: 53 | node_group.is_modifier = True 54 | 55 | # Clear the node group before building 56 | for node in node_group.nodes: 57 | node_group.nodes.remove(node) 58 | 59 | node_inputs = get_node_inputs(node_group) 60 | input_count = sum(map(lambda p: len(p.annotation.__annotations__) if issubclass(p.annotation, InputGroup) else 1, list(signature.parameters.values()))) 61 | for node_input in node_inputs[input_count:]: 62 | if IS_BLENDER_4: 63 | node_group.interface.remove(node_input) 64 | else: 65 | node_group.inputs.remove(node_input) 66 | 67 | for group_output in get_node_outputs(node_group): 68 | if IS_BLENDER_4: 69 | node_group.interface.remove(group_output) 70 | else: 71 | node_group.outputs.remove(group_output) 72 | 73 | # Setup the group inputs 74 | group_input_node = node_group.nodes.new('NodeGroupInput') 75 | group_output_node = node_group.nodes.new('NodeGroupOutput') 76 | 77 | # Collect the inputs 78 | inputs = {} 79 | def validate_param(param): 80 | if param.annotation == inspect.Parameter.empty: 81 | raise Exception(f"Tree input '{param.name}' has no type specified. Please annotate with a valid node input type.") 82 | if not issubclass(param.annotation, Type): 83 | raise Exception(f"Type of tree input '{param.name}' is not a valid 'Type' subclass.") 84 | for param in signature.parameters.values(): 85 | if issubclass(param.annotation, InputGroup): 86 | instance = param.annotation() 87 | prefix = (param.annotation.prefix + "_") if hasattr(param.annotation, "prefix") else "" 88 | for group_param, annotation in param.annotation.__annotations__.items(): 89 | default = getattr(instance, group_param, None) 90 | inputs[prefix + group_param] = (annotation, inspect.Parameter.empty if default is None else default, param.name, prefix) 91 | else: 92 | validate_param(param) 93 | inputs[param.name] = (param.annotation, param.default, None, None) 94 | 95 | # Create the input sockets and collect input values. 96 | node_inputs = get_node_inputs(node_group) 97 | for i, node_input in enumerate(node_inputs): 98 | if node_input.bl_socket_idname != list(inputs.values())[i][0].socket_type: 99 | for ni in node_inputs: 100 | if IS_BLENDER_4: 101 | node_group.interface.remove(ni) 102 | else: 103 | node_group.inputs.remove(ni) 104 | break 105 | builder_inputs = {} 106 | 107 | node_inputs = get_node_inputs(node_group) 108 | for i, arg in enumerate(inputs.items()): 109 | input_name = arg[0].replace('_', ' ').title() 110 | if len(node_inputs) > i: 111 | node_inputs[i].name = input_name 112 | node_input = node_inputs[i] 113 | else: 114 | if IS_BLENDER_4: 115 | node_input = node_group.interface.new_socket(socket_type=arg[1][0].socket_type, name=input_name, in_out='INPUT') 116 | else: 117 | node_input = node_group.inputs.new(arg[1][0].socket_type, input_name) 118 | if arg[1][1] != inspect.Parameter.empty: 119 | node_input.default_value = arg[1][1] 120 | if arg[1][2] is not None: 121 | if arg[1][2] not in builder_inputs: 122 | builder_inputs[arg[1][2]] = signature.parameters[arg[1][2]].annotation() 123 | setattr(builder_inputs[arg[1][2]], arg[0].replace(arg[1][3], ''), arg[1][0](group_input_node.outputs[i])) 124 | else: 125 | builder_inputs[arg[0]] = arg[1][0](group_input_node.outputs[i]) 126 | 127 | # Run the builder function 128 | State.current_node_tree = node_group 129 | if inspect.isgeneratorfunction(builder): 130 | generated_outputs = [*builder(**builder_inputs)] 131 | if all(map(lambda x: issubclass(type(x), Type) and x._socket.type == 'GEOMETRY', generated_outputs)): 132 | outputs = join_geometry(geometry=generated_outputs) 133 | else: 134 | outputs = generated_outputs 135 | else: 136 | outputs = builder(**builder_inputs) 137 | 138 | # Create the output sockets 139 | if isinstance(outputs, dict): 140 | # Use a dict to name each return value 141 | for i, (k, v) in enumerate(outputs.items()): 142 | if not issubclass(type(v), Type): 143 | v = Type(value=v) 144 | if IS_BLENDER_4: 145 | node_group.interface.new_socket(socket_type=v.socket_type, name=k, in_out='OUTPUT') 146 | else: 147 | node_group.outputs.new(v.socket_type, k) 148 | node_group.links.new(v._socket, group_output_node.inputs[i]) 149 | else: 150 | for i, result in enumerate(_as_iterable(outputs)): 151 | if not issubclass(type(result), Type): 152 | result = Type(value=result) 153 | # raise Exception(f"Return value '{result}' is not a valid 'Type' subclass.") 154 | if IS_BLENDER_4: 155 | node_group.interface.new_socket(socket_type=result.socket_type, name='Result', in_out='OUTPUT') 156 | else: 157 | node_group.outputs.new(result.socket_type, 'Result') 158 | node_group.links.new(result._socket, group_output_node.inputs[i]) 159 | 160 | _arrange(node_group) 161 | 162 | # Return a function that creates a NodeGroup node in the tree. 163 | # This lets @trees be used in other @trees via simple function calls. 164 | def group_reference(*args, **kwargs): 165 | if IS_BLENDER_4: 166 | result = geometrynodegroup(node_tree=node_group, *args, **kwargs) 167 | else: 168 | result = group(node_tree=node_group, *args, **kwargs) 169 | group_outputs = [] 170 | for group_output in result._socket.node.outputs: 171 | group_outputs.append(Type(group_output)) 172 | if len(group_outputs) == 1: 173 | return group_outputs[0] 174 | else: 175 | return tuple(group_outputs) 176 | return group_reference 177 | if isinstance(name, str): 178 | return build_tree 179 | else: 180 | tree_name = name.__name__ 181 | return build_tree(name) -------------------------------------------------------------------------------- /api/types.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from bpy.types import NodeSocketStandard 3 | import nodeitems_utils 4 | import enum 5 | from .state import State 6 | from .static.sample_mode import SampleMode 7 | import geometry_script 8 | 9 | def map_case_name(i): 10 | return ('_' if not i.identifier[0].isalpha() else '') + i.identifier.replace(' ', '_').upper() 11 | 12 | def socket_type_to_data_type(socket_type): 13 | match socket_type: 14 | case 'VALUE': 15 | return 'FLOAT' 16 | case 'VECTOR': 17 | return 'FLOAT_VECTOR' 18 | case 'COLOR': 19 | return 'FLOAT_COLOR' 20 | case _: 21 | return socket_type 22 | 23 | def socket_class_to_data_type(socket_class_name): 24 | match socket_class_name: 25 | case 'NodeSocketGeometry': 26 | return 'GEOMETRY' 27 | case 'NodeSocketFloat': 28 | return 'FLOAT' 29 | case _: 30 | return socket_class_name 31 | 32 | # The base class all exposed socket types conform to. 33 | class _TypeMeta(type): 34 | def __getitem__(self, args): 35 | for s in filter(lambda x: isinstance(x, slice), args): 36 | if (isinstance(s.start, float) or isinstance(s.start, int)) and (isinstance(s.stop, float) or isinstance(s.stop, int)): 37 | print(f"minmax: ({s.start}, {s.stop})") 38 | elif isinstance(s.start, str): 39 | print(f"{s.start} = {s.stop}") 40 | return self 41 | 42 | class Type(metaclass=_TypeMeta): 43 | socket_type: str 44 | 45 | def __init__(self, socket: bpy.types.NodeSocket = None, value = None): 46 | if value is not None: 47 | input_nodes = { 48 | int: ('FunctionNodeInputInt', 'integer'), 49 | bool: ('FunctionNodeInputBool', 'boolean'), 50 | str: ('FunctionNodeInputString', 'string'), 51 | tuple: ('FunctionNodeInputVector', 'vector'), 52 | float: ('ShaderNodeValue', None), 53 | } 54 | if type(value) == int: 55 | print("Making an integer node?") 56 | if not type(value) in input_nodes: 57 | raise Exception(f"'{value}' cannot be expressed as a node.") 58 | input_node_info = input_nodes[type(value)] 59 | value_node = State.current_node_tree.nodes.new(input_node_info[0]) 60 | if input_node_info[1] is None: 61 | value_node.outputs[0].default_value = value 62 | else: 63 | setattr(value_node, input_node_info[1], value) 64 | socket = value_node.outputs[0] 65 | self._socket = socket 66 | self.socket_type = type(socket).__name__ 67 | 68 | def _math(self, other, operation, reverse=False): 69 | if other is None: 70 | vector_or_value = self 71 | else: 72 | vector_or_value = (other, self) if reverse else (self, other) 73 | 74 | if self._socket.type == 'VECTOR': 75 | return geometry_script.vector_math(operation=operation, vector=vector_or_value) 76 | else: 77 | return geometry_script.math(operation=operation, value=vector_or_value) 78 | 79 | def __add__(self, other): 80 | return self._math(other, 'ADD') 81 | 82 | def __radd__(self, other): 83 | return self._math(other, 'ADD', True) 84 | 85 | def __sub__(self, other): 86 | return self._math(other, 'SUBTRACT') 87 | 88 | def __rsub__(self, other): 89 | return self._math(other, 'SUBTRACT', True) 90 | 91 | def __mul__(self, other): 92 | return self._math(other, 'MULTIPLY') 93 | 94 | def __rmul__(self, other): 95 | return self._math(other, 'MULTIPLY', True) 96 | 97 | def __truediv__(self, other): 98 | return self._math(other, 'DIVIDE') 99 | 100 | def __rtruediv__(self, other): 101 | return self._math(other, 'DIVIDE', True) 102 | 103 | def __mod__(self, other): 104 | return self._math(other, 'MODULO') 105 | 106 | def __rmod__(self, other): 107 | return self._math(other, 'MODULO', True) 108 | 109 | def __floordiv__(self, other): 110 | return self._math(other, 'DIVIDE')._math(None,'FLOOR') 111 | 112 | def __rfloordiv__(self, other): 113 | return self._math(other, 'DIVIDE',True)._math(None,'FLOOR') 114 | 115 | def __pow__(self, other): 116 | return self._math(other, 'POWER') 117 | 118 | def __rpow__(self, other): 119 | return self._math(other, 'POWER', True) 120 | 121 | def __matmul__(self, other): 122 | return self._math(other, 'DOT_PRODUCT') 123 | 124 | def __rmatmul__(self, other): 125 | return self._math(other, 'DOT_PRODUCT', True) 126 | 127 | def __abs__(self): 128 | return self._math(None,'ABSOLUTE') 129 | 130 | def __neg__(self): 131 | return self._math(-1, 'MULTIPLY') 132 | 133 | def __pos__(self): 134 | return self 135 | 136 | def __round__(self): 137 | return self._math(None,'ROUND') 138 | 139 | def _compare(self, other, operation): 140 | return geometry_script.compare(operation=operation, a=self, b=other) 141 | 142 | def __eq__(self, other): 143 | if self._socket.type == 'BOOLEAN': 144 | return self._boolean_math(other, 'XNOR') 145 | else: 146 | return self._compare(other, 'EQUAL') 147 | 148 | def __ne__(self, other): 149 | if self._socket.type == 'BOOLEAN': 150 | return self._boolean_math(other, 'XOR') 151 | else: 152 | return self._compare(other, 'NOT_EQUAL') 153 | 154 | def __lt__(self, other): 155 | return self._compare(other, 'LESS_THAN') 156 | 157 | def __le__(self, other): 158 | return self._compare(other, 'LESS_EQUAL') 159 | 160 | def __gt__(self, other): 161 | return self._compare(other, 'GREATER_THAN') 162 | 163 | def __ge__(self, other): 164 | return self._compare(other, 'GREATER_EQUAL') 165 | 166 | def _boolean_math(self, other, operation, reverse=False): 167 | boolean_math_node = State.current_node_tree.nodes.new('FunctionNodeBooleanMath') 168 | boolean_math_node.operation = operation 169 | a = None 170 | b = None 171 | for node_input in boolean_math_node.inputs: 172 | if not node_input.enabled: 173 | continue 174 | elif a is None: 175 | a = node_input 176 | else: 177 | b = node_input 178 | State.current_node_tree.links.new(self._socket, a) 179 | if other is not None: 180 | if issubclass(type(other), Type): 181 | State.current_node_tree.links.new(other._socket, b) 182 | else: 183 | b.default_value = other 184 | return Type(boolean_math_node.outputs[0]) 185 | 186 | def __and__(self, other): 187 | return self._boolean_math(other, 'AND') 188 | 189 | def __rand__(self, other): 190 | return self._boolean_math(other, 'AND', reverse=True) 191 | 192 | def __or__(self, other): 193 | return self._boolean_math(other, 'OR') 194 | 195 | def __ror__(self, other): 196 | return self._boolean_math(other, 'OR', reverse=True) 197 | 198 | def __invert__(self): 199 | if self._socket.type == 'BOOLEAN': 200 | return self._boolean_math(None, 'NOT') 201 | else: 202 | return self._math((-1, -1, -1) if self._socket.type == 'VECTOR' else -1, 'MULTIPLY') 203 | 204 | def _get_xyz_component(self, component): 205 | if self._socket.type != 'VECTOR': 206 | raise Exception("`x`, `y`, `z` properties are not available on non-Vector types.") 207 | separate_node = State.current_node_tree.nodes.new('ShaderNodeSeparateXYZ') 208 | State.current_node_tree.links.new(self._socket, separate_node.inputs[0]) 209 | return Type(separate_node.outputs[component]) 210 | @property 211 | def x(self): 212 | return self._get_xyz_component(0) 213 | @property 214 | def y(self): 215 | return self._get_xyz_component(1) 216 | @property 217 | def z(self): 218 | return self._get_xyz_component(2) 219 | 220 | def capture(self, value, **kwargs): 221 | data_type = socket_type_to_data_type(value._socket.type) 222 | res = self.capture_attribute(data_type=data_type, value=value, **kwargs) 223 | return res.geometry, res.attribute 224 | def transfer(self, attribute, **kwargs): 225 | data_type = socket_type_to_data_type(attribute._socket.type) 226 | return self.transfer_attribute(data_type=data_type, attribute=attribute, **kwargs) 227 | 228 | def __getitem__(self, subscript): 229 | if self._socket.type == 'VECTOR' and isinstance(subscript, int): 230 | return self._get_xyz_component(subscript) 231 | if isinstance(subscript, tuple): 232 | accessor = subscript[0] 233 | args = subscript[1:] 234 | else: 235 | accessor = subscript 236 | args = [] 237 | sample_mode = SampleMode.INDEX if len(args) < 1 else args[0] 238 | domain = 'POINT' if len(args) < 2 else (args[1].value if isinstance(args[1], enum.Enum) else args[1]) 239 | sample_position = None 240 | sampling_index = None 241 | if isinstance(accessor, slice): 242 | data_type = socket_type_to_data_type(accessor.start._socket.type) 243 | value = accessor.start 244 | match sample_mode: 245 | case SampleMode.INDEX: 246 | sampling_index = accessor.stop 247 | case SampleMode.NEAREST_SURFACE: 248 | sample_position = accessor.stop 249 | case SampleMode.NEAREST: 250 | sample_position = accessor.stop 251 | if accessor.step is not None: 252 | domain = accessor.step.value if isinstance(accessor.step, enum.Enum) else accessor.step 253 | else: 254 | data_type = socket_type_to_data_type(accessor._socket.type) 255 | value = accessor 256 | match sample_mode: 257 | case SampleMode.INDEX: 258 | return self.sample_index( 259 | data_type=data_type, 260 | domain=domain, 261 | value=value, 262 | index=sampling_index or geometry_script.index() 263 | ) 264 | case SampleMode.NEAREST_SURFACE: 265 | return self.sample_nearest_surface( 266 | data_type=data_type, 267 | value=value, 268 | sample_position=sample_position or geometry_script.position() 269 | ) 270 | case SampleMode.NEAREST: 271 | return self.sample_index( 272 | data_type=data_type, 273 | value=value, 274 | index=self.sample_nearest(domain=domain, sample_position=sample_position or geometry_script.position()) 275 | ) 276 | 277 | for standard_socket in list(filter(lambda x: 'NodeSocket' in x, dir(bpy.types))): 278 | name = standard_socket.replace('NodeSocket', '') 279 | if len(name) < 1: 280 | continue 281 | globals()[name] = type(name, (Type,), { 'socket_type': standard_socket, '__module__': Type.__module__ }) 282 | if name == 'Int': 283 | class IntIterator: 284 | def __init__(self, integer): 285 | self.integer = integer 286 | self.points = State.current_node_tree.nodes.new('GeometryNodePoints') 287 | State.current_node_tree.links.new(self.integer._socket, self.points.inputs[0]) 288 | self.index = State.current_node_tree.nodes.new('GeometryNodeInputIndex') 289 | self._did_iterate = False 290 | def __next__(self): 291 | if not self._did_iterate: 292 | self._did_iterate = True 293 | return Type(self.index.outputs[0]), Type(self.points.outputs[0]) 294 | else: 295 | raise StopIteration() 296 | globals()[name].__iter__ = lambda self: IntIterator(self) -------------------------------------------------------------------------------- /book/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /book/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Carson Katri"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "Geometry Script" 7 | 8 | [output.html] 9 | default-theme = "coal" 10 | preferred-dark-theme = "coal" 11 | additional-css = ["style.css"] -------------------------------------------------------------------------------- /book/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | [Introduction](./introduction.md) 4 | 5 | # Setup 6 | 7 | - [Installation](./setup/installation.md) 8 | - [Internal Editing Basics](./setup/internal-editing-basics.md) 9 | - [External Editing](./setup/external-editing.md) 10 | 11 | # API 12 | 13 | - [Basics](./api/basics.md) 14 | - [Modules](./api/basics/modules.md) 15 | - [Tree Functions](./api/basics/tree-functions.md) 16 | - [Sockets](./api/basics/sockets.md) 17 | - [Using Nodes](./api/basics/using-nodes.md) 18 | - [Advanced Scripting](./api/advanced-scripting.md) 19 | - [Node Groups](./api/advanced-scripting/node-groups.md) 20 | - [Generators](./api/advanced-scripting/generators.md) 21 | - [Input Groups](./api/advanced-scripting/input-groups.md) 22 | - [Attributes](./api/advanced-scripting/attributes.md) 23 | - [Boolean Math](./api/advanced-scripting/boolean-math.md) 24 | - [Curves](./api/advanced-scripting/curves.md) 25 | - [Drivers](./api/advanced-scripting/drivers.md) 26 | - [Simulation Zones](./api/advanced-scripting/simulation-zones.md) 27 | - [Repeat Zones](./api/advanced-scripting/repeat-zones.md) 28 | 29 | # Tutorials 30 | 31 | - [Voxelize](./tutorials/voxelize.md) 32 | - [City Builder](./tutorials/city-builder.md) -------------------------------------------------------------------------------- /book/src/api/advanced-scripting.md: -------------------------------------------------------------------------------- 1 | # Advanced Scripting 2 | 3 | Now that we've covered the basics, let's take a look at some more advanced scripting techniques. -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/attributes.md: -------------------------------------------------------------------------------- 1 | # Attributes 2 | 3 | An important concept in Geometry Nodes is attributes. Many trees capture attributes or transfer them from one domain to another. 4 | 5 | When using these methods, the `data_type` argument must be correctly specified for the transfer to work as intended. 6 | 7 | ```python 8 | @tree("Skin") 9 | def skin(): 10 | # Create a cube 11 | c = cube() 12 | # Create a sphere 13 | sphere = uv_sphere() 14 | # Transfer the position to the sphere 15 | transferred_position = c.transfer_attribute( 16 | data_type=TransferAttribute.DataType.FLOAT_VECTOR, 17 | attribute=position() 18 | ) 19 | # Make the sphere conform to the shape of the cube 20 | return sphere.set_position(position=transferred_position) 21 | ``` 22 | 23 | To improve the usability of these nodes, `capture(...)` and `transfer(...)` methods are provided on `Geometry` that simply take the attribute and any other optional arguments. 24 | 25 | ```python 26 | @tree("Skin") 27 | def skin(): 28 | # Create a cube 29 | c = cube() 30 | # Create a sphere 31 | sphere = uv_sphere() 32 | # Make the sphere conform to the shape of the cube 33 | return sphere.set_position(position=c.transfer(position())) 34 | ``` 35 | 36 | The same is available for `capture(...)`. 37 | 38 | ```python 39 | geometry_with_attribute, attribute = c.capture(position()) 40 | ``` 41 | 42 | > You must use the `Geometry` returned from `capture(...)` for the anonymous attribute it creates to be usable. 43 | 44 | Any additional keyword arguments can be passed as normal. 45 | 46 | ```python 47 | c.transfer(position(), mapping=TransferAttribute.Mapping.INDEX) 48 | ``` 49 | 50 | ## Named Attributes 51 | 52 | Custom attributes can be created by name. 53 | The safest way to use named attributes is with the `Attribute` class. 54 | 55 | Create a named attribute with a data type and optional domain, then use the `store(...)`, `exists()`, and `__call__(...)` methods to use it. 56 | 57 | ```python 58 | # Create the attribute 59 | my_custom_attribute = Attribute( 60 | "my_custom_attribute", 61 | NamedAttribute.DataType.FLOAT, # declare the data type once 62 | StoreNamedAttribute.Domain.INSTANCE # optional 63 | ) 64 | # Store a value 65 | geometry = my_custom_attribute.store(geometry, 0.5) 66 | # Use the value by calling the attribute 67 | geometry = geometry.set_position(offset=my_custom_attribute()) 68 | ``` 69 | 70 | ## Attribute Sampling 71 | In Blender 3.4+, transfer attribute was replaced with a few separate nodes: *Sample Index*, *Sample Nearest*, and *Sample Nearest Surface*. 72 | 73 | To avoid inputting data types and geometry manually, you can use the custom `Geometry` subscript. 74 | 75 | The structure for these subscripts is: 76 | 77 | ```python 78 | geometry[value : index or sample position : domain, mode, domain] 79 | ``` 80 | 81 | Only the value argument is required. Other arguments can be supplied as needed. 82 | 83 | ```python 84 | geometry[value] 85 | geometry[value : sample_position, SampleMode.NEAREST] 86 | geometry[value : index() + 1 : SampleIndex.Domain.EDGE] 87 | ``` 88 | 89 | Try passing different arguments and see how the resulting nodes are created. -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/boolean-math.md: -------------------------------------------------------------------------------- 1 | # Boolean Math 2 | 3 | The *Boolean Math* node gives access to common boolean operations, such as `AND`, `NOT`, `XOR`, etc. 4 | 5 | However, it can be cumbersome to use the `boolean_math` function in complex boolean expressions. 6 | 7 | ```python 8 | # Check if the two values equal, or if the first is true. 9 | x = False 10 | y = True 11 | return boolean_math( 12 | operation=BooleanMath.Operation.OR 13 | boolean=( 14 | boolean_math( 15 | operation=BooleanMath.Operation.XNOR # Equal 16 | boolean=(x, y) 17 | ), 18 | x 19 | ) 20 | ) 21 | ``` 22 | 23 | A few operators are available to make boolean math easier and more readable. 24 | 25 | ```python 26 | # Check if the two values equal, or if the first is true. 27 | x = False 28 | y = True 29 | return (x == y) | x 30 | ``` 31 | 32 | The operators available are: 33 | 34 | * `==` - `XNOR` 35 | * `!=` - `XOR` 36 | * `|` - `OR` 37 | * `&` - `AND` 38 | * `~` - `NOT` 39 | 40 | > You *cannot* use the built-in Python keywords `and`, `or`, and `not`. You must use the custom operators above to create *Boolean Math* nodes. -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/cube_grid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/advanced-scripting/cube_grid.png -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/curves.md: -------------------------------------------------------------------------------- 1 | # Curves 2 | 3 | Some nodes, such as *Float Curve* take a curve as a property. You can create a curve with the `Curve` class. 4 | 5 | ```python 6 | float_curve( 7 | mapping=Curve( 8 | Point(0, 0), 9 | Point(0.5, 0.25), 10 | Point(1, 1, HandleType.VECTOR), # Optionally specify a handle type, such as `AUTO`, `VECTOR`, or `AUTO_CLAMPED`. 11 | ) 12 | ) 13 | ``` 14 | 15 | ![](./float_curve.png) 16 | 17 | You can also pass the points as a list to `Curve`. 18 | 19 | ```python 20 | points = [Point(0, 0), Point(1, 1)] 21 | float_curve( 22 | mapping=Curve(points) 23 | ) 24 | ``` 25 | 26 | If a node has multiple curve properties, such as the *Vector Curves* node, pass a list of curves to the node. 27 | 28 | ```python 29 | vector_curves( 30 | mapping=[x_curve, y_curve, z_curve] 31 | ) 32 | ``` -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/drivers.md: -------------------------------------------------------------------------------- 1 | # Drivers 2 | 3 | Drivers can be used with geometry nodes. To create a scripted expression driver, use the `scripted_expression` convenience function. 4 | 5 | This can be used to get information like the current frame number in a Geometry Script. 6 | 7 | ```python 8 | frame_number = scripted_expression("frame") 9 | frame_number_doubled = scripted_expression("frame * 2") 10 | ``` -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/float_curve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/advanced-scripting/float_curve.png -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/generators.md: -------------------------------------------------------------------------------- 1 | # Generators 2 | 3 | Python has support for [generators](https://wiki.python.org/moin/Generators) using the `yield` keyword. 4 | 5 | Geometry Script tree functions can be represented as generators to output multiple values. If every generated value is `Geometry`, the values are automatically connected to a *Join Geometry* node and output as a single mesh. 6 | 7 | ```python 8 | @tree("Primitive Shapes") 9 | def primitive_shapes(): 10 | yield cube() 11 | yield uv_sphere() 12 | yield cylinder().mesh 13 | ``` 14 | 15 | ![](./geometry_generator.png) 16 | 17 | However, if any of the outputs is not `Geometry`, separate sockets are created for each output. 18 | 19 | ```python 20 | @tree("Primitive Shapes and Integer") 21 | def primitive_shapes(): 22 | yield cube() 23 | yield uv_sphere() 24 | yield cylinder().mesh 25 | yield 5 # Not a geometry socket type 26 | ``` 27 | 28 | ![](./mixed_generator.png) 29 | 30 | > The first output is always displayed when using a *Geometry Nodes* modifier. Ensure it is a `Geometry` socket type, unless you are using the function as a node group. -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/geometry_generator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/advanced-scripting/geometry_generator.png -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/input-groups.md: -------------------------------------------------------------------------------- 1 | # Input Groups 2 | 3 | Some geometry node trees need a lot of arguments. 4 | 5 | ```python 6 | @tree("Terrain Generator") 7 | def terrain_generator( 8 | width: Float 9 | height: Float 10 | resolution: Int 11 | scale: Float 12 | w: Float 13 | ): 14 | ... 15 | ``` 16 | 17 | There are a couple of problems with this. Firstly, the function signature is getting long. This can make it harder to visually parse the script. And, if we want to use the same arguments in another tree and pass them through to `terrain`, we need to make sure to keep everything up to date. 18 | 19 | This is where input groups come in. An input group is class that contains properties annotated with valid socket types. 20 | 21 | To create an input group, declare a new class that derives from `InputGroup`. 22 | 23 | ```python 24 | class TerrainInputs(InputGroup): 25 | width: Float 26 | height: Float 27 | resolution: Int 28 | scale: Float 29 | w: Float 30 | ``` 31 | 32 | Then annotate an argument in your tree function with this class. 33 | 34 | ```python 35 | @tree("Terrain Generator") 36 | def terrain_generator( 37 | inputs: TerrainInputs 38 | ): 39 | ... 40 | ``` 41 | 42 | This will create a node tree with the exact same structure as the original implementation. The inputs can be accessed with dot notation. 43 | 44 | ```python 45 | size = combine_xyz(x=input.width, y=input.height) 46 | ``` 47 | 48 | And now passing the inputs through from another function is much simpler. 49 | 50 | ```python 51 | def point_terrain( 52 | terrain_inputs: TerrainInputs, 53 | radius: Float 54 | ): 55 | return terrain_generator( 56 | inputs=terrain_inputs 57 | ).mesh_to_points(radius=radius) 58 | ``` 59 | 60 | ## Instantiating Input Groups 61 | 62 | If you nest calls to tree functions, you can instantiate the `InputGroup` subclass to pass the correct inputs. 63 | 64 | ```python 65 | def point_terrain(): 66 | return terrain_generator( 67 | inputs=TerrainInputs( 68 | width=5, 69 | height=5, 70 | resolution=10, 71 | scale=1, 72 | w=0 73 | ) 74 | ).mesh_to_points() 75 | ``` 76 | 77 | ## Input Group Prefix 78 | 79 | If you use the same `InputGroup` multiple times, you need to provide a prefix. Otherwise, inputs with duplicate names will be created on your tree. 80 | 81 | To do this, use square brackets next to the annotation with a string for the prefix. 82 | 83 | ```python 84 | def mountain_or_canyon( 85 | mountain_inputs: TerrainInputs["Mountain"], # Prefixed with 'Mountain' 86 | canyon_inputs: TerrainInputs["Canyon"], # Prefixed with 'Canyon' 87 | is_mountain: Bool 88 | ): 89 | return terrain_generator( 90 | inputs=switch(switch=is_mountain, true=mountain_inputs, false=canyon_inputs) 91 | ) 92 | ``` -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/instance_grid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/advanced-scripting/instance_grid.png -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/mixed_generator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/advanced-scripting/mixed_generator.png -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/node-groups.md: -------------------------------------------------------------------------------- 1 | # Node Groups 2 | 3 | A Geometry Script can have more than one tree function. Each tree function is a node group, and tree functions can be used in other tree functions to create *Node Group* nodes. 4 | 5 | ```python 6 | @tree("Instance Grid") 7 | def instance_grid(instance: Geometry): 8 | """ Instance the input geometry on a grid """ 9 | return grid().mesh_to_points().instance_on_points(instance=instance) 10 | 11 | @tree("Cube Grid") 12 | def cube_grid(): 13 | """ Create a grid of cubes """ 14 | return instance_grid(instance=cube(size=0.2)) 15 | ``` 16 | 17 | The *Cube Grid* tree uses the *Instance Grid* node group by calling the `instance_grid` function: 18 | 19 | ![](./cube_grid.png) 20 | 21 | The *Instance Grid* node group uses the passed in `instance` argument to create a grid of instances: 22 | 23 | ![](./instance_grid.png) 24 | 25 | This concept can scale to complex interconnected node trees, while keeping everything neatly organized in separate functions. 26 | 27 | ## Functions vs Node Groups 28 | 29 | You do not have to mark a function with `@tree(...)`. If you don't, function calls are treated as normal in Python. No checks are made against the arguments. Any nodes created in the callee will be placed in the caller's tree. 30 | 31 | ```python 32 | def instance_grid(instance: Geometry): # Not marked with `@tree(...)` 33 | return grid().mesh_to_points().instance_on_points(instance=instance) 34 | 35 | @tree("Cube Grid") 36 | def cube_grid(): # Marked with `@tree(...)` 37 | return instance_grid(instance=cube(size=0.2)) 38 | ``` 39 | 40 | The above example would place the *Grid*, *Mesh to Points*, and *Instance on Points* nodes in the main "Cube Grid" tree. It could be rewritten as: 41 | 42 | ```python 43 | @tree("Cube Grid") 44 | def cube_grid(): 45 | return grid().mesh_to_points().instance_on_points(instance=cube(size=0.2)) 46 | ``` -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/repeat-zones.md: -------------------------------------------------------------------------------- 1 | # Repeat Zones 2 | 3 | Blender 4.0 introduced repeat zones. 4 | 5 | Using a *Repeat Input* and *Repeat Output* node, you can loop a block of nodes for a specific number of iterations. 6 | 7 | You must use the `@repeat_zone` decorator to create these special linked nodes. 8 | 9 | ```python 10 | from geometry_script import * 11 | 12 | @tree 13 | def test_loop(geometry: Geometry): 14 | @repeat_zone 15 | def doubler(value: Float): 16 | return value * 2 17 | return points(count=doubler(5, 1)) # double the input value 5 times. 18 | ``` 19 | 20 | The function should modify the input values and return them in the same order. 21 | 22 | When calling the repeat zone, pass the *Iterations* argument first, then any other arguments the function accepts. 23 | 24 | For example: 25 | 26 | ```python 27 | def doubler(value: Float) -> Float 28 | ``` 29 | 30 | would be called as: 31 | 32 | ```python 33 | doubler(iteration_count, value) 34 | ``` 35 | 36 | When a repeat zone has multiple arguments, return a tuple from the zone. 37 | 38 | ```python 39 | @repeat_zone 40 | def multi_doubler(value1: Float, value2: Float): 41 | return (value1 * 2, value2 * 2) 42 | ``` -------------------------------------------------------------------------------- /book/src/api/advanced-scripting/simulation-zones.md: -------------------------------------------------------------------------------- 1 | # Simulation Zones 2 | 3 | Blender 3.6 includes simulation nodes. 4 | 5 | Using a *Simulation Input* and *Simulation Output* node, you can create effects that change over time. 6 | 7 | As a convenience, the `@simulation_zone` decorator is provided to make simulation node blocks easier to create. 8 | 9 | ```python 10 | from geometry_script import * 11 | 12 | @tree 13 | def test_sim(geometry: Geometry): 14 | @simulation_zone 15 | def my_sim(delta_time, geometry: Geometry, value: Float): 16 | return (geometry, value) 17 | return my_sim(geometry, 0.26).value 18 | ``` 19 | 20 | The first argument should always be `delta_time`. Any other arguments must also be returned as a tuple with their modified values. 21 | Each frame, the result from the previous frame is passed into the zone's inputs. 22 | The initial call to `my_sim` in `test_sim` provides the initial values for the simulation. 23 | 24 | ## Blender 4.0+ 25 | 26 | A "Skip" argument was added to the *Simulation Output* node in Blender 4.0. 27 | 28 | Return a boolean value first from any simulation zone to determine whether the step should be skipped. 29 | 30 | The simplest way to migrate existing node trees is by adding `False` to the return tuple. 31 | 32 | ```python 33 | @simulation_zone 34 | def my_sim(delta_time, geometry: Geometry, value: Float): 35 | return (False, geometry, value) 36 | ``` 37 | 38 | You can pass any boolean value as the skip output. -------------------------------------------------------------------------------- /book/src/api/basics.md: -------------------------------------------------------------------------------- 1 | # Basics 2 | Creating Geometry Scripts can be as easy or complex as you want for your project. 3 | Throughout this guide, scripts will be displayed alongside the generated nodes to provide context on how a script relates to the underlying nodes. 4 | 5 | Setting up an editor for [external editing](../setup/external-editing.md) is recommended when writing scripts, but [internal editing inside Blender](../setup/internal-editing-basics.md) will suffice for the simple examples shown here. -------------------------------------------------------------------------------- /book/src/api/basics/capture_attribute_node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/capture_attribute_node.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_node.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_int.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_int.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_mesh_to_volume.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_mesh_to_volume.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_modifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_modifier.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_named_outputs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_named_outputs.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_size.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_size.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_size_compare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_size_compare.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_size_components.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_size_components.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_size_double.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_size_double.png -------------------------------------------------------------------------------- /book/src/api/basics/cube_tree_size_input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/cube_tree_size_input.png -------------------------------------------------------------------------------- /book/src/api/basics/math_wrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/math_wrap.png -------------------------------------------------------------------------------- /book/src/api/basics/modules.md: -------------------------------------------------------------------------------- 1 | # Modules 2 | 3 | The first step when writing is script is importing the `geometry_script` module. There a are a few ways of doing this: 4 | 5 | ## Import All Names (Recommended) 6 | This will import every type and function available into your script. It can make it easy to discover what's available with code completion, and makes the scripts more terse. 7 | ```python 8 | from geometry_script import * 9 | 10 | cube(...) # Available globally 11 | my_geo: Geometry # All types available as well 12 | ``` 13 | 14 | ## Import Specific Names 15 | This will import only the specified names from the module: 16 | ```python 17 | from geometry_script import cube, Geometry 18 | 19 | cube(...) # Available from import 20 | my_geo: Geometry 21 | ``` 22 | 23 | ## Namespaced Import 24 | This will import every type and function, and place them behind the namespace. You can use the module name, or provide your own. 25 | ```python 26 | import geometry_script 27 | 28 | geometry_script.cube(...) # Prefix with the namespace 29 | my_geo: geometry_script.Geometry 30 | ``` 31 | ```python 32 | import geometry_script as gs 33 | 34 | gs.cube(...) # Prefix with the custom name 35 | my_geo: gs.Geometry 36 | ``` 37 | 38 | Now that you have Geometry Script imported in some way, let's create a tree. -------------------------------------------------------------------------------- /book/src/api/basics/open_documentation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/api/basics/open_documentation.png -------------------------------------------------------------------------------- /book/src/api/basics/sockets.md: -------------------------------------------------------------------------------- 1 | # Sockets 2 | Because scripts are converted to Geometry Node trees, you typically cannot use default Python types as arguments. In some cases, they will be automatically converted for you, but in general you will be dealing with socket types. 3 | 4 | ## What is a socket? 5 | A socket is any input or output on a node. Take the *Cube* node for example: 6 | 7 | ![](./cube_node.png) 8 | 9 | This node has 4 input sockets, and 1 output socket. 10 | 11 | * Input Sockets 12 | * Size: `Vector` 13 | * Vertices X: `Int` 14 | * Vertices Y: `Int` 15 | * Vertices Z: `Int` 16 | * Output Sockets 17 | * Mesh: `Geometry` 18 | 19 | A socket does not represent a value itself. For example, the `Size` socket does not necessarily represent the value `(1, 1, 1)`. Instead, it can be connected to another node as an input, giving it a dynamic value. 20 | 21 | When we write scripts, we typically deal with socket types, not concrete values like `(1, 1, 1)`. Take this script for example: 22 | 23 | ```python 24 | @tree("Cube Tree") 25 | def cube_tree(size: Vector): 26 | return cube(size=size) 27 | ``` 28 | 29 | The `size` argument creates a input socket with the type `Vector`. This is then connected to the `size` socket of the *Cube* node. 30 | 31 | ![](./cube_tree_size.png) 32 | 33 | Our script does not run every time the node tree is evaluated. It only runs once to create the node tree. Therefore, we have no way of knowing what value `size` has when the script runs, because it is dynamic. 34 | 35 | ## What sockets *can* do 36 | 37 | Sockets are great for passing values between nodes. A socket type like `Geometry` does not represent concrete vertices, edges, and faces. Instead, it represents the input or output socket of a node. This lets us use it to create connections between different nodes, by passing the output of one node to the input of another. 38 | 39 | ## What sockets *cannot* do 40 | 41 | Sockets cannot be read for their concrete value. A `Float` socket type does not equal `5` or `10` or `3.14` to our script. It only represents the socket of a node. If you try to `print(...)` a socket, you will receive a generic reference type with no underlying value. 42 | 43 | ## Why use sockets? 44 | 45 | You might be wondering, "if you can't access the value of a socket, what can you do with it?" 46 | 47 | Geometry Script provides many helpful additions that make working with sockets about as easy as working with a concrete value. 48 | 49 | ## Socket Math 50 | 51 | Socket types can be used to perform math operations. The proper *Math* node will be created automatically for you, so you can focus on writing a script and not thinking about sockets. If you use `Float` or `Int` it will create a *Math* node, and if you use a `Vector` it will create a *Vector Math* node. 52 | 53 | ```python 54 | @tree("Cube Tree") 55 | def cube_tree(size: Vector): 56 | doubled = size * (2, 2, 2) # Multiply each component by 2 57 | return cube(size=doubled) 58 | ``` 59 | ![](./cube_tree_size_double.png) 60 | 61 | Several common math operations are available, such as: 62 | * Add (`socket + 2`) 63 | * Subtract (`socket - 2`) 64 | * Multiply (`socket * 2`) 65 | * Divide (`socket / 2`) 66 | * Modulo (`socket % 2`) 67 | 68 | ## Socket Comparison 69 | 70 | Socket types can be compared with Python comparison operators. A *Compare* node will be created with the correct inputs and options specified. 71 | 72 | ```python 73 | @tree("Cube Tree") 74 | def cube_tree(size: Vector): 75 | show_cube = size > (2, 2, 2) # Check if each component is greater than 2 76 | return cube(size=show_cube) 77 | ``` 78 | ![](./cube_tree_size_compare.png) 79 | 80 | Several common comparison operators are supported, such as: 81 | * Equal To (`socket == 2`) 82 | * Not Equal To (`socket != 2`) 83 | * Less Than (`socket < 2`) 84 | * Less Than Or Equal To (`socket <= 2`) 85 | * Greater Than (`socket > 2`) 86 | * Greater Than Or Equal To (`socket >= 2`) 87 | 88 | ## Vector Component Properties 89 | 90 | While the `Vector` type does not equate to three concrete components, such as `(1, 2, 3)`, you can still access the `x`, `y`, and `z` components as sockets. A *Separate XYZ* node will be created with the correct inputs and outputs specified. 91 | 92 | ```python 93 | @tree("Cube Tree") 94 | def cube_tree(size: Vector): 95 | height = size.z # Access the Z component 96 | # Multiply the height by 2 but leave the other components unchanged. 97 | return cube(size=combine_xyz(x=size.x, y=size.y, z=height * 2)) 98 | ``` 99 | 100 | For each component access, a *Separate XYZ* node is created. 101 | 102 | ![](./cube_tree_size_components.png) 103 | 104 | ## Chained Calls 105 | 106 | Any node function can be called on a socket type. This will automatically connect the socket to the first input of the node. 107 | 108 | ```python 109 | @tree("Cube Tree") 110 | def cube_tree(size: Vector): 111 | return cube(size=size).mesh_to_volume() 112 | ``` 113 | 114 | The output of the *Cube* node (a `Geometry` socket type) is connected to the first input of the *Mesh to Volume* node. 115 | 116 | ![](./cube_tree_mesh_to_volume.png) 117 | 118 | The same script without chaining calls is written more verbosely as: 119 | 120 | ```python 121 | @tree("Cube Tree") 122 | def cube_tree(size: Vector): 123 | return mesh_to_volume(mesh=cube(size=size)) 124 | ``` 125 | 126 | ### Spanning Multiple Lines 127 | 128 | Often times you want each chained calls to be on a separate line. There are a few ways to do this in Python: 129 | 130 | 1. Newlines around arguments 131 | 132 | ```python 133 | cube( 134 | size=size 135 | ).mesh_to_volume() 136 | ``` 137 | 138 | 2. Parentheses 139 | 140 | ```python 141 | (cube(size=size) 142 | .mesh_to_volume()) 143 | ``` 144 | 145 | 3. Line continuation 146 | 147 | ```python 148 | cube(size=size) \ 149 | .mesh_to_volume() 150 | ``` -------------------------------------------------------------------------------- /book/src/api/basics/tree-functions.md: -------------------------------------------------------------------------------- 1 | # Tree Functions 2 | 3 | Node trees are created by decorating a function with `@tree`. Let's try creating a simple tree function. 4 | 5 | > The code samples for the rest of the book assume you are importing all names with `from geometry_script import *`. However, if you are using a namespaced import, simply prefix the functions and types with `geometry_script` or your custom name. 6 | 7 | ```python 8 | @tree 9 | def cube_tree(): 10 | ... 11 | ``` 12 | 13 | By default, the name of your function will be used as the name of the generated node tree. However, you can specify a custom name by passing a string to `@tree`: 14 | 15 | ```python 16 | @tree("Cube Tree") 17 | def cube_tree(): 18 | ... 19 | ``` 20 | 21 | ## Group Output 22 | Every node tree is **required** to return `Geometry` as the first output. Let's try returning a simple cube. 23 | 24 | ```python 25 | @tree("Cube Tree") 26 | def cube_tree(): 27 | return cube() 28 | ``` 29 | 30 | Here we call the `cube(...)` function, which creates a *Cube* node and connects it to the *Group Output*. 31 | 32 | ![](./cube_tree.png) 33 | 34 | You can also return multiple values. However, `Geometry` must always be returned first for a tree to be valid. 35 | 36 | ```python 37 | @tree("Cube Tree") 38 | def cube_tree(): 39 | return cube(), 5 40 | ``` 41 | 42 | ![](./cube_tree_int.png) 43 | 44 | By default, each output is named 'Result'. To customize the name, return a dictionary. 45 | 46 | ```python 47 | @tree("Cube Tree") 48 | def cube_tree(): 49 | return { 50 | "My Cube": cube(), 51 | "Scale Constant": 5 52 | } 53 | ``` 54 | 55 | ![](./cube_tree_named_outputs.png) 56 | 57 | ## Group Input 58 | All arguments in a tree function must be annotated with a valid socket type. These types are provided by Geometry Script, and are not equivalent to Python's built-in types. Let's add a size argument to our Cube Tree. 59 | 60 | ```python 61 | @tree("Cube Tree") 62 | def cube_tree(size: Vector): 63 | return cube(size=size) 64 | ``` 65 | 66 | This creates a *Size* socket on the *Group Input* node and connects it to our cube. 67 | 68 | ![](./cube_tree_size.png) 69 | 70 | The option is available on the Geometry Nodes modifier. 71 | 72 | ![](./cube_tree_modifier.png) 73 | 74 | The available socket types match those in the UI. Here are some common ones: 75 | 76 | * `Geometry` 77 | * `Float` 78 | * `Int` 79 | * `Vector` 80 | 81 | > You *cannot* use Python's built-in types in place of these socket types. 82 | 83 | In the next chapter, we'll take a closer look at how socket types work, and what you can and cannot do with them. 84 | 85 | ### Default Values 86 | You can specify a default for any argument, and it will be set on the modifier when added: 87 | 88 | ```python 89 | @tree("Cube Tree") 90 | def cube_tree(size: Vector = (1, 1, 1)): 91 | return cube(size=size) 92 | ``` 93 | ![](./cube_tree_size_input.png) -------------------------------------------------------------------------------- /book/src/api/basics/using-nodes.md: -------------------------------------------------------------------------------- 1 | # Using Nodes 2 | 3 | Node functions are automatically generated for the Blender version you are using. This means every node will be available from geometry script. 4 | 5 | This means that when future versions of Blender add new nodes, they will all be available in Geometry Script without updating the add-on. 6 | 7 | To see all of the node functions available in your Blender version, open the *Geometry Script* menu in the *Text Editor* and click *Open Documentation*. 8 | 9 | ![](./open_documentation.png) 10 | 11 | This will open the automatically generated docs page with a list of every available node and it's inputs and outputs. 12 | 13 | ## How nodes are mapped 14 | All nodes are mapped to functions in the same way, so even without the documentation you can decifer what a node will equate to. Using an [IDE with code completion](../../setup/external-editing.md) makes this even easier. 15 | 16 | The general process is: 17 | 1. Convert the node name to snake case. 18 | 2. Add a keyword argument (in snake case) for each property and input. 19 | 3. If the node has a single output, return the socket type, otherwise return an object with properties for each output name. 20 | 21 | > Properties and inputs are different types of argument. A property is a value that cannot be connected to a socket. These are typically enums (displayed in the UI as a dropdown), with specific string values expected. Check the documentation for a node to see what the possible values are for a property. 22 | 23 | ## Enum Properties 24 | 25 | Many nodes have enum properties. For example, the math node lets you choose which operation to perform. You can pass a string to specify the enum case to use. But a safer way to set these values is with the autogenerated enum types. The enums are namespaced to the name of the node in PascalCase: 26 | 27 | ```python 28 | # Access it by Node.Enum Name.Case 29 | math(operation=Math.Operation.ADD) 30 | math(operation=Math.Operation.SUBTRACT) 31 | math(operation='MULTIPLY') # Or manually pass a string 32 | ``` 33 | 34 | Internally, this type is generated as: 35 | 36 | ```python 37 | import enum 38 | class Math: 39 | class Operation(enum.Enum): 40 | ADD = 'ADD' 41 | SUBTRACT = 'SUBTRACT' 42 | MULTIPLY = 'MULTIPLY' 43 | ... 44 | ... 45 | ``` 46 | 47 | The cases will appear in code completion if you setup an [external editor](../../setup/external-editing.md). 48 | 49 | ## Duplicate Names 50 | 51 | Some nodes use the same input name multiple times. For example, the *Math* node has three inputs named `value`. To specify each value, pass a tuple for the input: 52 | 53 | ```python 54 | math(operation=Math.Operation.WRAP, value=(0.5, 1, 0)) # Pass all 3 55 | math(operation=Math.Operation.WRAP, value=(0.5, 1)) # Only pass 2/3 56 | math(operation=Math.Operation.WRAP, value=0.5) # Only pass 1/3 57 | ``` 58 | 59 | ![](./math_wrap.png) 60 | 61 | ## Examples 62 | 63 | Here are two examples to show how a node maps to a function. 64 | 65 | ### Cube 66 | 67 | ![](./cube_node.png) 68 | 69 | 1. Name: `Cube` -> `cube` 70 | 2. Keyword Arguments 71 | * `size: Vector` 72 | * `vertices_x: Int` 73 | * `vertices_y: Int` 74 | * `vertices_z: Int` 75 | 3. Return `Geometry` 76 | 77 | The node can now be used as a function: 78 | 79 | ```python 80 | cube() # All arguments are optional 81 | cube(size=(1, 1, 1), vertices_x=3) # Optionally specify keyword arguments 82 | cube_geo: Geometry = cube() # Returns a Geometry socket type 83 | ``` 84 | 85 | The generated documentation will show the signature, result type, and [chain syntax](./sockets.md#chained-calls). 86 | 87 | #### Signature 88 | ```python 89 | cube( 90 | size: VectorTranslation, 91 | vertices_x: Int, 92 | vertices_y: Int, 93 | vertices_z: Int 94 | ) 95 | ``` 96 | 97 | #### Result 98 | ```python 99 | mesh: Geometry 100 | ``` 101 | 102 | #### Chain Syntax 103 | ```python 104 | size: VectorTranslation = ... 105 | size.cube(...) 106 | ``` 107 | 108 | ### Capture Attribute 109 | 110 | ![](./capture_attribute_node.png) 111 | 112 | 1. Name `Capture Attribute` -> `capture_attribute` 113 | 2. Keyword Arguments 114 | * Properties 115 | * `data_type: CaptureAttribute.DataType` 116 | * `domain: CaptureAttribute.Domain` 117 | * Inputs 118 | * `geometry: Geometry` 119 | * `value: Vector | Float | Color | Bool | Int` 120 | 3. Return `{ geometry: Geometry, attribute: Int }` 121 | 122 | The node can now be used as a function: 123 | 124 | ```python 125 | result = capture_attribute(data_type=CaptureAttribute.DataType.BOOLEAN, geometry=cube_geo) # Specify a property and an input 126 | result.geometry # Access the geometry 127 | result.attribute # Access the attribute 128 | ``` 129 | 130 | The generated documentation will show the signature, result type, and [chain syntax](./sockets.md#chained-calls). 131 | 132 | #### Signature 133 | ```python 134 | capture_attribute( 135 | data_type: CaptureAttribute.DataType, 136 | domain: CaptureAttribute.Domain, 137 | geometry: Geometry, 138 | value: Vector | Float | Color | Bool | Int 139 | ) 140 | ``` 141 | 142 | #### Result 143 | ```python 144 | { geometry: Geometry, attribute: Int } 145 | ``` 146 | 147 | #### Chain Syntax 148 | ```python 149 | geometry: Geometry = ... 150 | geometry.capture_attribute(...) 151 | ``` -------------------------------------------------------------------------------- /book/src/images/addon_preferences.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/addon_preferences.png -------------------------------------------------------------------------------- /book/src/images/auto_resolve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/auto_resolve.png -------------------------------------------------------------------------------- /book/src/images/example_generated_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/example_generated_tree.png -------------------------------------------------------------------------------- /book/src/images/geometry_nodes_modifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/geometry_nodes_modifier.png -------------------------------------------------------------------------------- /book/src/images/ide_docs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/ide_docs.png -------------------------------------------------------------------------------- /book/src/images/live_edit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/live_edit.png -------------------------------------------------------------------------------- /book/src/images/open_file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/open_file.png -------------------------------------------------------------------------------- /book/src/images/text_editor_new.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/text_editor_new.png -------------------------------------------------------------------------------- /book/src/images/text_editor_run_script.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/text_editor_run_script.png -------------------------------------------------------------------------------- /book/src/images/text_editor_space.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/text_editor_space.png -------------------------------------------------------------------------------- /book/src/images/vscode_code_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/vscode_code_completion.png -------------------------------------------------------------------------------- /book/src/images/vscode_extra_paths.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/vscode_extra_paths.png -------------------------------------------------------------------------------- /book/src/images/wordmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/images/wordmark.png -------------------------------------------------------------------------------- /book/src/introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | **Geometry Script** is a scripting API for Blender's Geometry Nodes. 4 | It makes complicated node trees more managable and easy to share. 5 | 6 | * [Full coverage of nodes](./api/basics/using-nodes.md) available in your Blender version 7 | * Clean, easy to use [Python API](./api/basics.md) 8 | * External [IDE integration](./setup/external-editing.md) for better completions and hot reload 9 | 10 | Here's a simple example of what's possible with a short script: 11 | 12 | ### Geometry Script 13 | 14 | ```python 15 | from geometry_script import * 16 | 17 | @tree("Repeat Grid") 18 | def repeat_grid(geometry: Geometry, width: Int, height: Int): 19 | g = grid( 20 | size_x=width, size_y=height, 21 | vertices_x=width, vertices_y=height 22 | ).mesh_to_points() 23 | return g.instance_on_points(instance=geometry) 24 | ``` 25 | 26 | ### Generated Node Tree 27 | 28 | ![Generated node tree](images/example_generated_tree.png) -------------------------------------------------------------------------------- /book/src/setup/external-editing.md: -------------------------------------------------------------------------------- 1 | # External Editing 2 | 3 | Blender's *Text Editor* leaves a lot to be desired. Writing scripts without code completion can be tough. 4 | Using an external code editor is one way to improve the editing experience. 5 | 6 | This guide will show how to setup [Visual Studio Code](https://code.visualstudio.com/) to edit Geometry Scripts. However, the same concepts apply to other IDEs. 7 | 8 | > This guide assumes you have already installed Visual Studio Code and setup the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python). If not, please setup those tools before continuing. 9 | 10 | ## Code Completion 11 | When the Geometry Script add-on starts, it generates a Python typeshed file that can be used to provide code completion. 12 | All we have to do is add the right path to the Python extension's configuration: 13 | 14 | 1. Open Blender preferences and expand the *Geometry Script* preferences 15 | 2. Copy the *Typeshed Path* 16 | 17 | ![A screenshot of the Geometry Script preferences](../images/addon_preferences.png) 18 | 19 | 3. In VS Code, open the Settings UI (`Shift+CTRL+P` or `Shift+CMD+P` > `Preferences > Open Settings (UI)`) 20 | 4. Find the setting `Python > Analysis: Extra Paths` 21 | 5. Click *Add Item*, then paste in the path copied from Blender and click *OK* 22 | 23 | ![A screenshot of the Python > Analysis: Extra Paths setting with the path pasted in](../images/vscode_extra_paths.png) 24 | 25 | 6. Create a new Python file, such as `Repeat Grid.py` and start writing a script. As you type, you should get helpful suggestions for every available node. 26 | 27 | ![A screenshot of a script with the documentation for `instance_on_points` appearing as the user types.](../images/vscode_code_completion.png) 28 | 29 | ## Linking with Blender 30 | Writing a script is great, but we want to see it run in Blender. Thankfully, Blender's Text Editor lets us link with an external file, and a simple tool from Geometry Script can make the process more seamless: 31 | 32 | 1. Open a *Text Editor* space. 33 | 2. Click the open button in the top of the editor, and navigate to your Python file. 34 | 3. Click the gear icon or press *N*, and uncheck *Make Internal*. This will ensure that changes made outside of Blender can be easily brought in. 35 | 4. Click *Open Text*. 36 | 37 | ![A screenshot of Blender's file picker, with the Make Internal checkbox unchecked.](../images/open_file.png) 38 | 39 | 5. At the top right of the Text Editor, open the *Geometry Script* menu and enable *Auto Resolve*. Enabling this feature will make the text data-block in Blender update every time you save the file outside of Blender. 40 | 41 | ![A screenshot of the Geometry Script menu with Auto Resolve checked](../images/auto_resolve.png) 42 | 43 | 6. To enable hot reload, open the *Text* menu and enable *Live Edit*. This will re-run your Geometry Script whenever it changes, updating the node tree live. 44 | 45 | ![A screenshot of the Text menu with Live Edit checked](../images/live_edit.png) 46 | 47 | And that's it! You're setup to start writing scripts. In the next section we'll take a look at the API, and all of the things you can do with it. -------------------------------------------------------------------------------- /book/src/setup/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | The add-on is available on GitHub and Blender Market. 4 | Choose where you want to get it from and follow the steps below: 5 | 6 | ## From GitHub 7 | 1. [Download the source code](https://github.com/carson-katri/geometry-script/archive/refs/heads/main.zip) 8 | 2. Open *Blender* > *Preferences* > *Add-ons* 9 | 3. Choose *Install...* and select the downloaded ZIP file 10 | 11 | ## From Blender Market 12 | 1. After [purchasing the add-on](https://www.blendermarket.com/), download the ZIP file 13 | 2. Open *Blender* > *Preferences* > *Add-ons* 14 | 3. Choose *Install...* and select the downloaded ZIP file -------------------------------------------------------------------------------- /book/src/setup/internal-editing-basics.md: -------------------------------------------------------------------------------- 1 | # Internal Editing Basics 2 | 3 | The fastest way to get up and running is with Blender's built-in *Text Editor*. 4 | You can edit and execute your scripts right inside of Blender: 5 | 6 | 1. Open a *Text Editor* space. 7 | 8 | ![A screenshot of the available spaces, with the Text Editor space highlighted](../images/text_editor_space.png) 9 | 10 | 2. Create a new text data-block with the *New* button. 11 | 12 | ![A screenshot of the Text Editor space with the new button](../images/text_editor_new.png) 13 | 14 | 3. Start writing a Geometry Script. As an example, you can paste in the script below. More detailed instructions on writing scripts are in later chapters. 15 | 16 | ```python 17 | from geometry_script import * 18 | 19 | @tree("Repeat Grid") 20 | def repeat_grid(geometry: Geometry, width: Int, height: Int): 21 | g = grid( 22 | size_x=width, size_y=height, 23 | vertices_x=width, vertices_y=height 24 | ).mesh_to_points() 25 | return g.instance_on_points(instance=geometry) 26 | ``` 27 | 28 | 4. Click the run button to execute the script. This will create a Geometry Nodes tree named *Repeat Grid*. 29 | 30 | ![A screenshot of the Text Editor space with the Run Script button](../images/text_editor_run_script.png) 31 | 32 | 5. Create a *Geometry Nodes* modifier on any object in your scene and select the *Repeat Grid* tree. 33 | 34 | ![A screenshot of the Blender window with a 3x3 grid of cubes on the left and a Geometry Nodes modifier with the Repeat Grid tree selected on the right](../images/geometry_nodes_modifier.png) -------------------------------------------------------------------------------- /book/src/tutorials/city-builder.md: -------------------------------------------------------------------------------- 1 | # City Builder 2 | 3 | In this tutorial we'll create a dense grid of buildings, then cut away from them to place roads with curves. We'll also make use of a [generator](../api/advanced-scripting/generators.md) to combine the buildings with the roads. 4 | 5 | ![](./city_builder.gif) 6 | 7 | ## Setting Up 8 | Create a Bezier Curve object. You can enter edit mode and delete the default curve it creates. 9 | 10 | Then create a new script. Setting up an [external editor](../setup/external-editing.md) is recommended. 11 | 12 | Import Geometry Script, and create a basic tree builder function. We'll add a few arguments to configure the buildings. 13 | 14 | ```python 15 | from geometry_script import * 16 | 17 | @tree("City Builder") 18 | def city_builder( 19 | geometry: Geometry, 20 | seed: Int, 21 | road_width: Float = 0.25, 22 | size_x: Float = 5, size_y: Float = 5, density: Float = 10, 23 | building_size_min: Vector = (0.1, 0.1, 0.2), 24 | building_size_max: Vector = (0.3, 0.3, 1), 25 | ): 26 | return geometry 27 | ``` 28 | 29 | Run the script to create the tree, then add a *Geometry Nodes* modifier to your curve object and select the *City Builder* node group. 30 | 31 | ## Buildings 32 | Let's start with the buildings. We'll distribute points on a grid with `size_x` and `size_y`. 33 | 34 | ```python 35 | def city_builder(...): 36 | building_points = grid(size_x=size_x, size_y=size_y).distribute_points_on_faces(density=density, seed=seed).points 37 | return building_points 38 | ``` 39 | 40 | Next, we'll instance cubes on these points to serve as our buildings. We move the cube object up half its height so the buildings sit flat on the grid, and scale them randomly between the min and max sizes. 41 | 42 | ```python 43 | def city_builder(...): 44 | ... 45 | return building_points.instance_on_points( 46 | instance=cube().transform(translation=(0, 0, 0.5)), 47 | scale=random_value(data_type=RandomValue.DataType.FLOAT_VECTOR, min=building_size_min, max=building_size_max, seed=seed), 48 | ) 49 | ``` 50 | 51 | ## Roads 52 | Using `curve_to_mesh`, we can turn the input curve into a flat mesh. We'll use the `yield` keyword to join the curve mesh and the building mesh automatically. Change the `building_points.instance_on_points` line to use `yield` for this to work. 53 | 54 | ```python 55 | def city_builder(...): 56 | yield geometry.curve_to_mesh(profile_curve=curve_line( 57 | start=combine_xyz(x=road_width * -0.5), 58 | end=combine_xyz(x=road_width * 0.5) 59 | )) 60 | ... 61 | yield building_points.instance_on_points(...) 62 | ``` 63 | 64 | But now the buildings are overlapping the road. We need to remove any point that falls within the road curve. We'll use `geometry_proximity` and `delete_geometry` to find and remove these invalid points. 65 | 66 | ```python 67 | def city_builder(...): 68 | ... 69 | building_points = ... 70 | road_points = geometry.curve_to_points(mode=CurveToPoints.Mode.EVALUATED).points 71 | building_points = building_points.delete_geometry( 72 | domain=DeleteGeometry.Domain.POINT, 73 | selection=geometry_proximity(target_element=GeometryProximity.TargetElement.POINTS, target=road_points, source_position=position()).distance < road_width 74 | ) 75 | ... 76 | ``` 77 | 78 | ## Drawing Roads 79 | Enter edit mode and select the *Draw* tool. Simply draw roads onto your city to see the buildings and meshes update. 80 | 81 | ![](./city_builder.gif) 82 | 83 | ## Final Script 84 | 85 | ```python 86 | from geometry_script import * 87 | 88 | @tree("City Builder") 89 | def city_builder( 90 | geometry: Geometry, 91 | seed: Int, 92 | road_width: Float = 0.25, 93 | size_x: Float = 5, size_y: Float = 5, density: Float = 10, 94 | building_size_min: Vector = (0.1, 0.1, 0.2), 95 | building_size_max: Vector = (0.3, 0.3, 1), 96 | ): 97 | # Road mesh 98 | yield geometry.curve_to_mesh(profile_curve=curve_line( 99 | start=combine_xyz(x=road_width * -0.5), 100 | end=combine_xyz(x=road_width * 0.5) 101 | )) 102 | # Building points 103 | building_points = grid(size_x=size_x, size_y=size_y).distribute_points_on_faces(density=density, seed=seed).points 104 | road_points = geometry.curve_to_points(mode=CurveToPoints.Mode.EVALUATED).points 105 | # Delete points within the curve 106 | building_points = building_points.delete_geometry( 107 | domain=DeleteGeometry.Domain.POINT, 108 | selection=geometry_proximity(target_element=GeometryProximity.TargetElement.POINTS, target=road_points, source_position=position()).distance < road_width 109 | ) 110 | # Building instances 111 | yield building_points.instance_on_points( 112 | instance=cube().transform(translation=(0, 0, 0.5)), 113 | scale=random_value(data_type=RandomValue.DataType.FLOAT_VECTOR, min=building_size_min, max=building_size_max, seed=seed), 114 | ) 115 | ``` 116 | 117 | ## Generated Node Tree 118 | 119 | ![](./city_builder_nodes.png) -------------------------------------------------------------------------------- /book/src/tutorials/city_builder.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/city_builder.gif -------------------------------------------------------------------------------- /book/src/tutorials/city_builder_nodes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/city_builder_nodes.png -------------------------------------------------------------------------------- /book/src/tutorials/monkey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/monkey.png -------------------------------------------------------------------------------- /book/src/tutorials/monkey_points.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/monkey_points.png -------------------------------------------------------------------------------- /book/src/tutorials/monkey_volume.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/monkey_volume.png -------------------------------------------------------------------------------- /book/src/tutorials/monkey_voxels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/monkey_voxels.png -------------------------------------------------------------------------------- /book/src/tutorials/voxelize.md: -------------------------------------------------------------------------------- 1 | # Voxelize 2 | 3 | This tutorial walks you through creating a script that turns any mesh into voxels. 4 | 5 | > This tutorial requires Blender 3.4+ for the *Distribute Points In Volume* node. 6 | 7 | ## Setting Up 8 | Create a base mesh. I'll be using a Monkey primitive. 9 | 10 | ![](./monkey.png) 11 | 12 | Next, create a new script. Setting up an [external editor](../setup/external-editing.md) is recommended. 13 | 14 | Import Geometry Script, and create a basic tree builder function. We'll add a `geometry` argument and annotate it with the `Geometry` type to receive our base mesh (in this case, a monkey). 15 | 16 | ```python 17 | from geometry_script import * 18 | 19 | @tree("Voxelize") 20 | def voxelize(geometry: Geometry): 21 | return geometry 22 | ``` 23 | 24 | Run the script to create the tree, then add a *Geometry Nodes* modifier to your mesh and select the *Voxelize* node group. 25 | 26 | ![](./voxelize_modifier.png) 27 | 28 | ## Arguments 29 | Add a new argument `resolution: Float`. Give it a default value of `0.2`. This value will be used throughout the script to configure spacing and voxel density. 30 | 31 | ```python 32 | def voxelize(geometry: Geometry, resolution: Float = 0.2): 33 | ... 34 | ``` 35 | 36 | ## Mesh to Volume 37 | We want to convert the mesh to a hollow volume, so only the outside of the mesh has voxel instances. This will improve the performance of our script. 38 | 39 | Use the `mesh_to_volume` function on the base mesh to convert it to a volume. 40 | 41 | ```python 42 | def voxelize(geometry: Geometry, resolution: Float = 0.2): 43 | return geometry.mesh_to_volume( # Hollow mesh volume 44 | interior_band_width=resolution, 45 | fill_volume=False 46 | ) 47 | ``` 48 | 49 | ![](./monkey_volume.png) 50 | 51 | ## Volume to Points 52 | Next, we need to create points to instance each voxel cube on. Use `distribute_points_in_volume` with the mode set to `DENSITY_GRID` to create a uniform distribution of points. 53 | 54 | ```python 55 | def voxelize(geometry: Geometry, resolution: Float = 0.2): 56 | return geometry.mesh_to_volume( 57 | interior_band_width=resolution, 58 | fill_volume=False 59 | ).distribute_points_in_volume( # Uniform grid distribution 60 | mode=DistributePointsInVolume.Mode.DENSITY_GRID, 61 | spacing=resolution 62 | ) 63 | ``` 64 | 65 | ![](./monkey_points.png) 66 | 67 | ## Instance Cubes 68 | Finally, use `instance_on_points` with a cube of size `resolution` to instance a cube on each point created from our mesh. 69 | 70 | ```python 71 | def voxelize(geometry: Geometry, resolution: Float = 0.2): 72 | return geometry.mesh_to_volume( 73 | interior_band_width=resolution, 74 | fill_volume=False 75 | ).distribute_points_in_volume( 76 | mode=DistributePointsInVolume.Mode.DENSITY_GRID, 77 | spacing=resolution 78 | ).instance_on_points( # Cube instancing 79 | instance=cube(size=resolution) 80 | ) 81 | ``` 82 | 83 | ![](./monkey_voxels.png) 84 | 85 | You can lower the resolution to get smaller, more detailed voxels, or raise it to get larger voxels. 86 | 87 | ## Final Script 88 | 89 | ```python 90 | # NOTE: This example requires Blender 3.4+ 91 | 92 | from geometry_script import * 93 | 94 | @tree("Voxelize") 95 | def voxelize(geometry: Geometry, resolution: Float = 0.2): 96 | return geometry.mesh_to_volume( 97 | interior_band_width=resolution, 98 | fill_volume=False 99 | ).distribute_points_in_volume( 100 | mode=DistributePointsInVolume.Mode.DENSITY_GRID, 101 | spacing=resolution 102 | ).instance_on_points( 103 | instance=cube(size=resolution) 104 | ) 105 | ``` 106 | 107 | ## Generated Node Tree 108 | 109 | ![](./voxelize_nodes.png) -------------------------------------------------------------------------------- /book/src/tutorials/voxelize_modifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/voxelize_modifier.png -------------------------------------------------------------------------------- /book/src/tutorials/voxelize_nodes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carson-katri/geometry-script/96a1b293cc7f737c0a940c57072aa35568e21164/book/src/tutorials/voxelize_nodes.png -------------------------------------------------------------------------------- /book/style.css: -------------------------------------------------------------------------------- 1 | .coal { 2 | --bg: #1C1C1C !important; 3 | } -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !*.gitignore -------------------------------------------------------------------------------- /examples/City Builder.py: -------------------------------------------------------------------------------- 1 | # Create a curve object as the base. 2 | # In Edit Mode, use the Draw tool to create new roads in the city. 3 | 4 | from geometry_script import * 5 | 6 | @tree("City Builder") 7 | def city_builder( 8 | geometry: Geometry, 9 | building_size_min: Vector = (0.1, 0.1, 0.2), 10 | building_size_max: Vector = (0.3, 0.3, 1), 11 | size_x: Float = 5.0, 12 | size_y: Float = 5.0, 13 | road_width: Float = 0.25, 14 | seed: Int = 0, 15 | resolution: Int = 60 16 | ): 17 | # Road geometry from input curves 18 | road_points = geometry.curve_to_points().points 19 | yield geometry.curve_to_mesh( 20 | profile_curve=curve_line( 21 | start=combine_xyz(x=road_width * -0.5), 22 | end=combine_xyz(x=road_width / 2) 23 | ) 24 | ) 25 | 26 | # Randomly distribute buildings on a grid 27 | building_points = grid( 28 | size_x=size_x, size_y=size_y, 29 | vertices_x=resolution, vertices_y=resolution 30 | ).distribute_points_on_faces( 31 | seed=seed 32 | # Delete invalid building points based on proximity to a road 33 | ).points.delete_geometry( 34 | domain=DeleteGeometry.Domain.POINT, 35 | selection=road_points.geometry_proximity(target_element=GeometryProximity.TargetElement.POINTS, source_position=position()).distance < road_width * 2 36 | ) 37 | random_scale = random_value(data_type=RandomValue.DataType.FLOAT_VECTOR, min=building_size_min, max=building_size_max, seed=seed + id()) 38 | yield building_points.instance_on_points( 39 | instance=cube(size=(1, 1, 1)).transform(translation=(0, 0, 0.5)), 40 | scale=random_scale 41 | ) -------------------------------------------------------------------------------- /examples/Mesh to LEGO.py: -------------------------------------------------------------------------------- 1 | # NOTE: This example requires Blender 3.4+ 2 | 3 | from geometry_script import * 4 | 5 | @tree("LEGO") 6 | def lego(size: Vector, stud_radius: Float, stud_depth: Float, count_x: Int, count_y: Int): 7 | base = cube(size=size) 8 | stud_shape = cylinder(fill_type=Cylinder.FillType.NGON, radius=stud_radius, depth=stud_depth, vertices=8).mesh 9 | stud = stud_shape.transform(translation=combine_xyz(z=(stud_depth / 2) + (size.z / 2))) 10 | hole = stud_shape.transform(translation=combine_xyz(z=(stud_depth / 2) - (size.z / 2))) 11 | segment = mesh_boolean( 12 | operation=MeshBoolean.Operation.DIFFERENCE, 13 | mesh_1=mesh_boolean(operation=MeshBoolean.Operation.UNION, mesh_2=[base, stud]).mesh, 14 | mesh_2=hole 15 | ).mesh 16 | return mesh_line(count=count_x, offset=(1, 0, 0)).instance_on_points( 17 | instance=mesh_line(count=count_y, offset=(0, 1, 0)).instance_on_points(instance=segment) 18 | ).realize_instances().merge_by_distance() 19 | 20 | @tree("Mesh to LEGO") 21 | def mesh_to_lego(geometry: Geometry, resolution: Float=0.2): 22 | return geometry.mesh_to_volume(interior_band_width=resolution, fill_volume=False).distribute_points_in_volume( 23 | mode=DistributePointsInVolume.Mode.DENSITY_GRID, 24 | spacing=resolution 25 | ).instance_on_points( 26 | instance=lego(size=resolution, stud_radius=resolution / 3, stud_depth=resolution / 8, count_x=1, count_y=1) 27 | ).realize_instances().merge_by_distance() -------------------------------------------------------------------------------- /examples/Repeat Grid.py: -------------------------------------------------------------------------------- 1 | from geometry_script import * 2 | 3 | @tree("Repeat Grid") 4 | def repeat_grid(geometry: Geometry, width: Int, height: Int): 5 | g = grid( 6 | size_x=width, size_y=height, 7 | vertices_x=width, vertices_y=height 8 | ).mesh_to_points() 9 | return g.instance_on_points(instance=geometry) -------------------------------------------------------------------------------- /external.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | 4 | def load(filename): 5 | """ 6 | Execute an external script. 7 | """ 8 | filepath = os.path.join(os.path.dirname(bpy.data.filepath), filename) 9 | global_namespace = {"__file__": filepath, "__name__": "__main__"} 10 | with open(filepath, 'rb') as file: 11 | exec(compile(file.read(), filepath, 'exec'), global_namespace) -------------------------------------------------------------------------------- /preferences.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import sys 3 | import os 4 | 5 | class GeometryScriptPreferences(bpy.types.AddonPreferences): 6 | bl_idname = __package__ 7 | 8 | typeshed_path: bpy.props.StringProperty( 9 | name="Typeshed Path", 10 | get=lambda self: os.path.join(os.path.dirname(__file__), 'typeshed'), 11 | set=lambda self, _: None 12 | ) 13 | 14 | def draw(self, context): 15 | layout = self.layout 16 | box = layout.box() 17 | box.label(text="External Editing", icon="CONSOLE") 18 | box.label(text="Add the following path to the module lookup paths in your IDE of choice:") 19 | box.prop(self, "typeshed_path") 20 | vscode = box.box() 21 | vscode.label(text="Visual Studio Code", icon="QUESTION") 22 | vscode.label(text="Setup instructions for the Visual Studio Code:") 23 | ctrl_cmd = 'CMD' if sys.platform == 'darwin' else 'CTRL' 24 | vscode.label(text=f"1. Press {ctrl_cmd}+Shift+P") 25 | vscode.label(text=f"2. Search for 'Preferences: Open Settings (UI)'") 26 | vscode.label(text=f"3. Search for 'Python > Analysis: Extra Paths") 27 | vscode.label(text=f"4. Click 'Add Item'") 28 | vscode.label(text=f"5. Paste the typeshed path from above") 29 | -------------------------------------------------------------------------------- /typeshed/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !*.gitignore --------------------------------------------------------------------------------