Add cutout shell and volume node assets for depth volume processing
- Implemented `cutout_shell.py` to build front normals and shell positions for balloon geometry. - Created `cutout_volume.py` to establish smooth center fields and manage balloon surface attributes. - Introduced `pisa_sr_export.py` for exporting PiSA-SR components with dependencies and asset finalization.
This commit is contained in:
202
tools/model_licenses/pisa-sr/LICENSE-APACHE.txt
Normal file
202
tools/model_licenses/pisa-sr/LICENSE-APACHE.txt
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
84
tools/model_licenses/pisa-sr/LICENSE-MODEL.txt
Normal file
84
tools/model_licenses/pisa-sr/LICENSE-MODEL.txt
Normal file
@@ -0,0 +1,84 @@
|
||||
Copyright (c) 2022 Stability AI and contributors
|
||||
|
||||
CreativeML Open RAIL++-M License
|
||||
dated November 24, 2022
|
||||
|
||||
Section I: PREAMBLE
|
||||
|
||||
Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
|
||||
|
||||
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
|
||||
|
||||
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
|
||||
|
||||
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
|
||||
|
||||
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
|
||||
|
||||
NOW THEREFORE, You and Licensor agree as follows:
|
||||
|
||||
1. Definitions
|
||||
|
||||
- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
|
||||
- "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
|
||||
- "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
|
||||
- "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
|
||||
- "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
|
||||
- "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
|
||||
- "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
|
||||
- "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
|
||||
- "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
|
||||
- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
|
||||
- "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
- "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
|
||||
|
||||
Section II: INTELLECTUAL PROPERTY RIGHTS
|
||||
|
||||
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
|
||||
|
||||
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
||||
|
||||
4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
|
||||
Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
|
||||
You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
|
||||
You must cause any modified files to carry prominent notices stating that You changed the files;
|
||||
You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
|
||||
5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
|
||||
6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
|
||||
|
||||
Section IV: OTHER PROVISIONS
|
||||
|
||||
7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
|
||||
8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
|
||||
9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
|
||||
10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
|
||||
|
||||
Attachment A
|
||||
|
||||
Use Restrictions
|
||||
|
||||
You agree not to use the Model or Derivatives of the Model:
|
||||
|
||||
- In any way that violates any applicable national, federal, state, local or international law or regulation;
|
||||
- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
|
||||
- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
|
||||
- To generate or disseminate personal identifiable information that can be used to harm an individual;
|
||||
- To defame, disparage or otherwise harass others;
|
||||
- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
|
||||
- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
|
||||
- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
|
||||
- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
|
||||
- To provide medical advice and medical results interpretation;
|
||||
- To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
|
||||
|
||||
21
tools/model_licenses/pisa-sr/NOTICE.txt
Normal file
21
tools/model_licenses/pisa-sr/NOTICE.txt
Normal file
@@ -0,0 +1,21 @@
|
||||
PiSA-SR ONNX models for AnyImage
|
||||
|
||||
PiSA-SR: Lingchen Sun and contributors, https://github.com/csslc/PiSA-SR
|
||||
Source commit: 9c76e12e261d1980148738a0cff41e5e27d18c9f
|
||||
PiSA-SR is released under Apache License 2.0; see LICENSE-APACHE.txt.
|
||||
|
||||
Stable Diffusion 2.1: Copyright (c) 2022 Stability AI and contributors.
|
||||
Base weights: sd2-community/stable-diffusion-2-1-base
|
||||
Revision: 4e63672c03103b6c636b8fb4119ba982469b2955
|
||||
Base weights and derivatives are subject to CreativeML Open RAIL++-M,
|
||||
including paragraph 5 and Attachment A use restrictions. All users must
|
||||
comply with these terms; see the accompanying LICENSE-MODEL.txt.
|
||||
License copy: sd2-community/stable-diffusion-2, LICENSE-MODEL.
|
||||
|
||||
AnyImage modifications: merged pixel and semantic LoRA adapters, FP16
|
||||
ONNX conversion, fixed empty prompt and timestep, VAE encoder/decoder
|
||||
separation. Runtime combines pixel/full predictions at semantic strength 0.7.
|
||||
noise.npy contains a fixed seed 42 latent noise field.
|
||||
|
||||
ONNX architecture derives from Hugging Face Diffusers and PiSA-SR.
|
||||
Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||
@@ -12,10 +12,9 @@ sys.path.insert(
|
||||
str(next((PROJECT_ROOT / "src" / "anyimage" / "wheels").glob("blendjob-*.whl"))),
|
||||
)
|
||||
|
||||
from build_cutout import (
|
||||
from build_cutout_modifiers import (
|
||||
CUTOUT_NODE_GROUP_NAMES,
|
||||
build_cutout_modifier_group,
|
||||
build_node_group,
|
||||
build_cutout_group,
|
||||
)
|
||||
from build_depth_plane import build_depth_plane_group
|
||||
from build_material_layers import build_material_layer_group
|
||||
@@ -38,11 +37,8 @@ def main():
|
||||
build_material_layer_group()
|
||||
build_material_layer_group(depth_plane=True)
|
||||
build_shadeless_group()
|
||||
shape_groups = {
|
||||
shape: build_node_group(shape)
|
||||
for shape in CUTOUT_NODE_GROUP_NAMES
|
||||
}
|
||||
build_cutout_modifier_group(shape_groups)
|
||||
for shape in CUTOUT_NODE_GROUP_NAMES:
|
||||
build_cutout_group(shape)
|
||||
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(OUTPUT_PATH), check_existing=False)
|
||||
|
||||
|
||||
252
tools/node_assets/build_cutout_modifiers.py
Normal file
252
tools/node_assets/build_cutout_modifiers.py
Normal file
@@ -0,0 +1,252 @@
|
||||
"""Build the three directly editable Cutout modifier assets."""
|
||||
import bpy
|
||||
from types import SimpleNamespace
|
||||
from mathutils import Matrix
|
||||
|
||||
from anyimage.operators.cutout_tool.shape import CUTOUT_NODE_GROUP_NAMES, CUTOUT_Z_TO_X, NORMAL_SCALE_ATTRIBUTE_NAME
|
||||
from cutout_shapes import (
|
||||
_socket, _float_input, _bool_input, _vector_input, _group_input, _math,
|
||||
_island_cleanup, _build_cutout, _build_balloon, _build_depth_balloon,
|
||||
_build_depth_surface, _shade_output,
|
||||
)
|
||||
from cutout_shape_layouts import LAYOUTS
|
||||
from cutout_depth_surface_layout import POSITIONS, INPUT_REGIONS, layout_geometry_references
|
||||
from cutout_layout import layout_stage, finish_layout
|
||||
from cutout_volume import build_volume_fields, shift_stage
|
||||
from cutout_rounding import build_volume_rounding
|
||||
from cutout_inflation import build_front_fields
|
||||
from cutout_shell import build_front_normals, build_shell_position
|
||||
from node_graph import expand_smooth
|
||||
|
||||
|
||||
def _menu(group, control, names, kind, location):
|
||||
selector = next((node for node in group.nodes if node.bl_idname == "GeometryNodeMenuSwitch" and node.inputs["Menu"].is_linked and node.inputs["Menu"].links[0].from_socket.name == control), None)
|
||||
if selector is None:
|
||||
selector = group.nodes.new("GeometryNodeMenuSwitch")
|
||||
selector.data_type = "BOOLEAN"
|
||||
selector.location = (location[0] - 240, location[1] + 450)
|
||||
for item, name in zip(selector.enum_items, names):
|
||||
item.name = name
|
||||
selector.inputs[names[0]].default_value = False
|
||||
selector.inputs[names[1]].default_value = True
|
||||
local = _group_input(group.nodes, (location[0] - 480, location[1] + 450), {control})
|
||||
group.links.new(local.outputs[control], selector.inputs["Menu"])
|
||||
node = group.nodes.new("GeometryNodeSwitch")
|
||||
node.input_type = kind
|
||||
node.location = location
|
||||
group.links.new(selector.outputs[0], node.inputs["Switch"])
|
||||
return SimpleNamespace(inputs={names[0]: node.inputs["False"], names[1]: node.inputs["True"]}, outputs=node.outputs)
|
||||
|
||||
|
||||
def _read(group, name, location):
|
||||
node = group.nodes.new("GeometryNodeInputNamedAttribute")
|
||||
node.data_type = "FLOAT"
|
||||
node.inputs["Name"].default_value = name
|
||||
node.location = location
|
||||
return node.outputs["Attribute"]
|
||||
|
||||
|
||||
def _store(group, geometry, name, value, location, domain="POINT"):
|
||||
node = group.nodes.new("GeometryNodeStoreNamedAttribute")
|
||||
node.domain, node.data_type = domain, "FLOAT"
|
||||
node.location = location
|
||||
node.inputs["Name"].default_value = name
|
||||
group.links.new(geometry, node.inputs["Geometry"])
|
||||
if isinstance(value, (int, float)):
|
||||
node.inputs["Value"].default_value = value
|
||||
else:
|
||||
group.links.new(value, node.inputs["Value"])
|
||||
return node.outputs["Geometry"]
|
||||
|
||||
|
||||
def _depth_volume(group, stage):
|
||||
"""Insert the volume field ahead of identity-based shell construction."""
|
||||
links = group.links
|
||||
projection = stage["Set Position"].outputs["Geometry"]
|
||||
shell_input = stage["Store Named Attribute.005"].inputs["Geometry"]
|
||||
for node in group.nodes:
|
||||
if node.location.x >= 4150:
|
||||
node.location.x += 5100
|
||||
projection = build_front_normals(group, projection)
|
||||
volume = build_volume_fields(group, projection, (4150, 0))
|
||||
shared = build_front_fields(group, volume.node.inputs["Geometry"].links[0].from_socket)
|
||||
links.new(shared, volume.node.inputs["Geometry"])
|
||||
uniform_control = _group_input(group.nodes, (8210, -330), {"Uniform Thickness"})
|
||||
uniform = _store(group, shared, "o_balloon_surface_thickness", uniform_control.outputs["Uniform Thickness"], (8490, -330))
|
||||
volume.node.location.x = uniform.node.location.x
|
||||
choose = _menu(group, "Mode", ("Balloon", "Uniform"), "GEOMETRY", (9000, 0))
|
||||
links.new(volume, choose.inputs["Balloon"])
|
||||
links.new(uniform, choose.inputs["Uniform"])
|
||||
links.new(choose.outputs[0], shell_input)
|
||||
thickness = _read(group, "o_balloon_surface_thickness", (12000, -1100))
|
||||
links.new(thickness, stage["Math.018"].inputs[1])
|
||||
control = _group_input(group.nodes, (13300, 700), {"Thickness", "Uniform Thickness"})
|
||||
amount = _menu(group, "Mode", ("Balloon", "Uniform"), "FLOAT", (13600, 500))
|
||||
links.new(control.outputs["Thickness"], amount.inputs["Balloon"])
|
||||
links.new(control.outputs["Uniform Thickness"], amount.inputs["Uniform"])
|
||||
links.new(amount.outputs[0], stage["Math.019"].inputs[0])
|
||||
identity_thickness = _read(group, "o_balloon_surface_thickness", (11100, 1500))
|
||||
positive = _math(group.nodes, "GREATER_THAN", (11340, 1500))
|
||||
positive.inputs[1].default_value = 1e-12
|
||||
links.new(identity_thickness, positive.inputs[0])
|
||||
layer = _math(group.nodes, "MULTIPLY", (11570, 1200))
|
||||
links.new(positive.outputs[0], layer.inputs[0])
|
||||
links.new(stage["Separate XYZ.006"].outputs["Z"], layer.inputs[1])
|
||||
links.new(layer.outputs[0], stage["Combine XYZ.002"].inputs["Z"])
|
||||
for node in group.nodes:
|
||||
if node.location.x >= 12070:
|
||||
node.location.x += 400
|
||||
for name in ("Flip Faces", "Flip Faces.001"):
|
||||
source = stage[name].outputs["Mesh"]
|
||||
outgoing = [link for link in links if link.from_socket == source]
|
||||
targets = [link.to_socket for link in outgoing]
|
||||
for link in outgoing:
|
||||
links.remove(link)
|
||||
masked = _store(group, source, NORMAL_SCALE_ATTRIBUTE_NAME, 0.0, (12100, stage[name].location.y), domain="FACE")
|
||||
for target in targets:
|
||||
links.new(masked, target)
|
||||
|
||||
for node in group.nodes:
|
||||
if node.location.x >= 8490:
|
||||
node.location.x += 3200
|
||||
volume.node.location.x = 8290
|
||||
rounded = build_volume_rounding(group, volume, (8600, 0))
|
||||
rounded.node.location.x = uniform.node.location.x + 40
|
||||
links.new(rounded, choose.inputs["Balloon"])
|
||||
restored = stage["Vector Math.004"].outputs[0]
|
||||
targets = [link.to_socket for link in restored.links]
|
||||
uniform_mode = choose.outputs[0].node.inputs["Switch"].links[0].from_socket
|
||||
oriented = build_shell_position(group, restored, uniform_mode, (14100, -2100))
|
||||
for target in targets:
|
||||
links.new(oriented, target)
|
||||
|
||||
|
||||
def build_cutout_group(shape):
|
||||
name = CUTOUT_NODE_GROUP_NAMES[shape]
|
||||
existing = bpy.data.node_groups.get(name)
|
||||
if existing is not None:
|
||||
return existing
|
||||
group = bpy.data.node_groups.new(name, "GeometryNodeTree")
|
||||
group.is_modifier, group.use_fake_user = True, True
|
||||
group.color_tag = "GEOMETRY"
|
||||
group["anyimage_asset_revision"] = 11
|
||||
depth = shape in {"DEPTH_SOLID", "DEPTH_BALLOON"}
|
||||
dual = shape != "DEPTH_BALLOON"
|
||||
_socket(group, "Geometry", "INPUT", "NodeSocketGeometry")
|
||||
if dual:
|
||||
_socket(group, "Mode", "INPUT", "NodeSocketMenu")
|
||||
_float_input(group, "Thickness", 1.0).description = "Balloon profile multiplier; zero returns the sheet"
|
||||
if dual:
|
||||
_float_input(group, "Uniform Thickness", 0.0, subtype="DISTANCE").description = "Distance used only by Uniform thickness mode"
|
||||
if depth:
|
||||
_float_input(group, "Depth Scale", 1.0)
|
||||
if shape == "DEPTH_BALLOON":
|
||||
_bool_input(group, "Double Sided", True)
|
||||
iterations = _socket(group, "Smooth", "INPUT", "NodeSocketInt")
|
||||
iterations.default_value = 0
|
||||
iterations.min_value, iterations.max_value = 0, 20
|
||||
options = group.interface.new_panel(name="Options", default_closed=True)
|
||||
_float_input(group, "Cleanup Threshold", 0.0, parent=options)
|
||||
if shape == "DEPTH_SOLID":
|
||||
_float_input(group, "Split Threshold", 0.0, maximum=1, subtype="FACTOR", parent=options)
|
||||
if depth:
|
||||
_float_input(group, "Reference Depth", 1.0, subtype="DISTANCE", parent=options)
|
||||
if shape == "DEPTH_SOLID":
|
||||
_float_input(group, "Edge Round", 0.2, maximum=1, subtype="FACTOR", parent=options)
|
||||
_float_input(group, "Front Inflation", 1.0, maximum=32, parent=options)
|
||||
normal_iterations = _socket(group, "Normal Smooth", "INPUT", "NodeSocketInt", options)
|
||||
normal_iterations.default_value = 50
|
||||
normal_iterations.min_value, normal_iterations.max_value = 0, 50
|
||||
_float_input(group, "Smooth Weight", 1.0, maximum=1, subtype="FACTOR", parent=options)
|
||||
if shape == "DEPTH_BALLOON":
|
||||
_vector_input(group, "Depth Direction", (0, 0, 1), subtype="DIRECTION", parent=options)
|
||||
data = group.interface.new_panel(name="Data", default_closed=True)
|
||||
_socket(group, "Inward Axis", "INPUT", "NodeSocketMenu", data).hide_in_modifier = True
|
||||
if depth:
|
||||
_float_input(group, "Uniform Scale", 1.0, parent=data).hide_in_modifier = True
|
||||
_socket(group, "Depth Image", "INPUT", "NodeSocketImage", data).hide_in_modifier = True
|
||||
_socket(group, "Geometry", "OUTPUT", "NodeSocketGeometry")
|
||||
controls = _group_input(group.nodes, (-5000, 0), set())
|
||||
previous = set(group.nodes)
|
||||
if shape == "DEPTH_SOLID":
|
||||
geometry = _build_depth_surface(group, controls.outputs["Geometry"], controls.outputs["Thickness"], controls.outputs["Depth Scale"], controls.outputs["Split Threshold"], controls.outputs["Uniform Scale"], controls.outputs["Reference Depth"], controls.outputs["Depth Image"])
|
||||
stage = layout_stage(group, previous, POSITIONS, INPUT_REGIONS)
|
||||
_depth_volume(group, stage)
|
||||
end = 18000
|
||||
elif shape == "DEPTH_BALLOON":
|
||||
geometry = _build_depth_balloon(group, controls.outputs["Geometry"], controls.outputs["Thickness"], controls.outputs["Depth Scale"], controls.outputs["Double Sided"], controls.outputs["Uniform Scale"], controls.outputs["Depth Direction"], controls.outputs["Depth Image"], controls.outputs["Reference Depth"])
|
||||
layout_stage(group, previous, *LAYOUTS["DEPTH_BALLOON"])
|
||||
end = 3000
|
||||
else:
|
||||
balloon = _build_balloon(group, controls.outputs["Geometry"], controls.outputs["Thickness"])
|
||||
layout_stage(group, previous, *LAYOUTS["BALLOON"])
|
||||
previous = set(group.nodes)
|
||||
uniform = _build_cutout(group, controls.outputs["Geometry"], controls.outputs["Uniform Thickness"])
|
||||
layout_stage(group, previous, *LAYOUTS["UNIFORM"], offset=(0, -2400))
|
||||
balloon.node.location.x = uniform.node.location.x
|
||||
choose = _menu(group, "Mode", ("Balloon", "Uniform"), "GEOMETRY", (3200, 0))
|
||||
group.links.new(balloon, choose.inputs["Balloon"])
|
||||
group.links.new(uniform, choose.inputs["Uniform"])
|
||||
geometry, end = choose.outputs[0], 3700
|
||||
planar_inputs = [link.to_socket for link in group.links if link.from_node.bl_idname == "NodeGroupInput" and link.from_socket.name == "Geometry"]
|
||||
base = _group_input(group.nodes, (-4800, 0), {"Geometry", "Cleanup Threshold"})
|
||||
area = _math(group.nodes, "MULTIPLY", (-4520, 500))
|
||||
area.inputs[1].default_value = 0.01
|
||||
group.links.new(base.outputs["Cleanup Threshold"], area.inputs[0])
|
||||
cleaned = _island_cleanup(group, base.outputs["Geometry"], area.outputs[0], (-4520, 0))
|
||||
if shape == "DEPTH_SOLID":
|
||||
cleaned = _store(group, cleaned, NORMAL_SCALE_ATTRIBUTE_NAME, 1.0, (-3540, 0), domain="FACE")
|
||||
for target in planar_inputs:
|
||||
group.links.new(cleaned, target)
|
||||
previous = set(group.nodes)
|
||||
geometry = expand_smooth(group, geometry, iterations_name="Smooth", weight_name="Smooth Weight")
|
||||
shift_stage(group, previous, (end, -550))
|
||||
end += 3450
|
||||
if shape == "DEPTH_SOLID":
|
||||
remove = group.nodes.new("GeometryNodeRemoveAttribute")
|
||||
remove.pattern_mode = "WILDCARD"
|
||||
remove.inputs["Name"].default_value = "o_balloon_surface_*"
|
||||
remove.location = (end, 0)
|
||||
group.links.new(geometry, remove.inputs["Geometry"])
|
||||
geometry, end = remove.outputs[0], end + 300
|
||||
else:
|
||||
profile = _read(group, "o_balloon", (end, 800))
|
||||
scale = profile
|
||||
if dual:
|
||||
amount = _group_input(group.nodes, (end, 1100), {"Thickness"})
|
||||
enabled = _math(group.nodes, "GREATER_THAN", (end + 250, 1100))
|
||||
enabled.inputs[1].default_value = 1e-6
|
||||
group.links.new(amount.outputs["Thickness"], enabled.inputs[0])
|
||||
inflated = group.nodes.new("GeometryNodeSwitch")
|
||||
inflated.input_type = "FLOAT"
|
||||
inflated.location = (end + 480, 800)
|
||||
inflated.inputs["False"].default_value = 1
|
||||
group.links.new(enabled.outputs[0], inflated.inputs["Switch"])
|
||||
group.links.new(profile, inflated.inputs["True"])
|
||||
mode = _menu(group, "Mode", ("Balloon", "Uniform"), "FLOAT", (end + 750, 800))
|
||||
mode.inputs["Uniform"].default_value = 1
|
||||
group.links.new(inflated.outputs[0], mode.inputs["Balloon"])
|
||||
scale = mode.outputs[0]
|
||||
geometry = _store(group, geometry, NORMAL_SCALE_ATTRIBUTE_NAME, scale, (end + 1050, 0))
|
||||
end += 1350
|
||||
orient = group.nodes.new("GeometryNodeTransform")
|
||||
orient.location = (end, -350)
|
||||
orient.inputs["Rotation"].default_value = Matrix(CUTOUT_Z_TO_X).to_euler()
|
||||
group.links.new(geometry, orient.inputs["Geometry"])
|
||||
axis = _menu(group, "Inward Axis", ("-Z", "+X"), "GEOMETRY", (end + 300, 0))
|
||||
group.links.new(geometry, axis.inputs["-Z"])
|
||||
group.links.new(orient.outputs[0], axis.inputs["+X"])
|
||||
_shade_output(group, axis.outputs[0], (end + 600, 0))
|
||||
if shape == "DEPTH_SOLID":
|
||||
layout_geometry_references(group, stage)
|
||||
finish_layout(group)
|
||||
for item in group.interface.items_tree:
|
||||
if item.item_type != "SOCKET" or item.in_out != "INPUT":
|
||||
continue
|
||||
if item.name == "Mode":
|
||||
item.default_value = "Balloon"
|
||||
elif item.name == "Inward Axis":
|
||||
item.default_value = "-Z"
|
||||
elif item.name == "Uniform Thickness":
|
||||
item.name = "Thickness"
|
||||
return group
|
||||
@@ -8,7 +8,6 @@ TEMPORARY_ATTRIBUTES = {
|
||||
"camera": ("FLOAT_VECTOR", "POINT"),
|
||||
"surface_position": ("FLOAT_VECTOR", "POINT"),
|
||||
"source_vertex": ("INT", "POINT"),
|
||||
"wall_layers": ("FLOAT", "POINT"),
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +49,7 @@ def _math(group, operation, a, b=None):
|
||||
return node.outputs[0]
|
||||
|
||||
|
||||
def split_depth_surface(group, geometry, image, strength, uniform, depth_scale):
|
||||
def split_depth_surface(group, geometry, image, strength, uniform):
|
||||
"""Keep each face's camera sample on its own corners before splitting."""
|
||||
nodes, links = group.nodes, group.links
|
||||
uv = nodes.new("GeometryNodeInputNamedAttribute")
|
||||
@@ -93,7 +92,6 @@ def split_depth_surface(group, geometry, image, strength, uniform, depth_scale):
|
||||
links.new(center, distance.inputs[index])
|
||||
delta = _math(group, "ABSOLUTE", _math(group, "SUBTRACT", *depths))
|
||||
scaled = _math(group, "MULTIPLY", delta, uniform)
|
||||
scaled = _math(group, "MULTIPLY", scaled, _math(group, "ABSOLUTE", depth_scale))
|
||||
# Cross multiplication avoids division and stays invariant under uniform scaling.
|
||||
selected = _math(
|
||||
group,
|
||||
@@ -171,7 +169,7 @@ def store_surface_camera(group, geometry, original, strength):
|
||||
|
||||
|
||||
def thicken_depth_surface(group, geometry, thickness):
|
||||
"""Connect caps and wall rings by source vertex and layer identity."""
|
||||
"""Connect caps with single quads by source vertex and cap identity."""
|
||||
nodes, links = group.nodes, group.links
|
||||
position = nodes.new("GeometryNodeInputPosition")
|
||||
geometry = _store(group, geometry, "surface_position", position.outputs[0])
|
||||
@@ -186,33 +184,7 @@ def thicken_depth_surface(group, geometry, thickness):
|
||||
geometry = _store(
|
||||
group, sheet.outputs["Geometry"], "source_vertex", index.outputs[0]
|
||||
)
|
||||
edge = nodes.new("GeometryNodeInputMeshEdgeVertices")
|
||||
length = nodes.new("ShaderNodeVectorMath")
|
||||
length.operation = "DISTANCE"
|
||||
links.new(edge.outputs["Position 1"], length.inputs[0])
|
||||
links.new(edge.outputs["Position 2"], length.inputs[1])
|
||||
neighbors = nodes.new("GeometryNodeInputMeshEdgeNeighbors")
|
||||
statistics = nodes.new("GeometryNodeAttributeStatistic")
|
||||
statistics.domain = "EDGE"
|
||||
statistics.data_type = "FLOAT"
|
||||
links.new(geometry, statistics.inputs["Geometry"])
|
||||
links.new(
|
||||
_math(group, "COMPARE", neighbors.outputs["Face Count"], 1.0),
|
||||
statistics.inputs["Selection"],
|
||||
)
|
||||
links.new(length.outputs["Value"], statistics.inputs["Attribute"])
|
||||
count = _math(
|
||||
group,
|
||||
"CEIL",
|
||||
_math(
|
||||
group,
|
||||
"DIVIDE",
|
||||
thickness,
|
||||
_math(group, "MAXIMUM", statistics.outputs["Median"], 1e-6),
|
||||
),
|
||||
)
|
||||
count = _math(group, "MINIMUM", _math(group, "MAXIMUM", count, 1.0), 128.0)
|
||||
saved = _store(group, geometry, "wall_layers", count)
|
||||
saved = geometry
|
||||
|
||||
# Weld in an integer identity grid, never in scene coordinates. Nearby cuts
|
||||
# retain distinct IDs; copies of one rim vertex share the same ID and layer.
|
||||
@@ -224,41 +196,26 @@ def thicken_depth_surface(group, geometry, thickness):
|
||||
links.new(_read(group, "source_vertex"), part.inputs[0])
|
||||
links.new(part.outputs[0], identity.inputs[axis])
|
||||
|
||||
repeat_output = nodes.new("GeometryNodeRepeatOutput")
|
||||
repeat_input = nodes.new("GeometryNodeRepeatInput")
|
||||
repeat_input.pair_with_output(repeat_output)
|
||||
repeat_output.repeat_items.clear()
|
||||
repeat_output.repeat_items.new("GEOMETRY", "Geometry")
|
||||
repeat_output.repeat_items.new("GEOMETRY", "Sides")
|
||||
links.new(count, repeat_input.inputs["Iterations"])
|
||||
links.new(saved, repeat_input.inputs["Geometry"])
|
||||
extrude = nodes.new("GeometryNodeExtrudeMesh")
|
||||
extrude.mode = "FACES"
|
||||
extrude.inputs["Individual"].default_value = False
|
||||
extrusion_offset = nodes.new("ShaderNodeCombineXYZ")
|
||||
extrusion_offset.inputs["Z"].default_value = -1.0
|
||||
links.new(extrusion_offset.outputs[0], extrude.inputs["Offset"])
|
||||
links.new(repeat_input.outputs["Geometry"], extrude.inputs["Mesh"])
|
||||
links.new(saved, extrude.inputs["Mesh"])
|
||||
sides = nodes.new("GeometryNodeSeparateGeometry")
|
||||
sides.domain = "FACE"
|
||||
links.new(extrude.outputs["Mesh"], sides.inputs["Geometry"])
|
||||
links.new(extrude.outputs["Side"], sides.inputs["Selection"])
|
||||
join_sides = nodes.new("GeometryNodeJoinGeometry")
|
||||
links.new(repeat_input.outputs["Sides"], join_sides.inputs["Geometry"])
|
||||
links.new(sides.outputs["Selection"], join_sides.inputs["Geometry"])
|
||||
links.new(sides.outputs["Inverted"], repeat_output.inputs["Geometry"])
|
||||
links.new(join_sides.outputs["Geometry"], repeat_output.inputs["Sides"])
|
||||
offset = nodes.new("ShaderNodeCombineXYZ")
|
||||
links.new(
|
||||
_math(group, "MULTIPLY", _read(group, "wall_layers"), -1.0), offset.inputs["Z"]
|
||||
)
|
||||
offset.inputs["Z"].default_value = -1.0
|
||||
back = nodes.new("GeometryNodeSetPosition")
|
||||
links.new(saved, back.inputs["Geometry"])
|
||||
links.new(offset.outputs[0], back.inputs["Offset"])
|
||||
flip_back = nodes.new("GeometryNodeFlipFaces")
|
||||
links.new(back.outputs["Geometry"], flip_back.inputs["Mesh"])
|
||||
flip_sides = nodes.new("GeometryNodeFlipFaces")
|
||||
links.new(repeat_output.outputs["Sides"], flip_sides.inputs["Mesh"])
|
||||
links.new(sides.outputs["Selection"], flip_sides.inputs["Mesh"])
|
||||
join = nodes.new("GeometryNodeJoinGeometry")
|
||||
for value in (
|
||||
saved,
|
||||
@@ -274,12 +231,11 @@ def thicken_depth_surface(group, geometry, thickness):
|
||||
merge.inputs["Distance"].default_value = 0.1
|
||||
links.new(encoded.outputs["Geometry"], merge.inputs["Geometry"])
|
||||
displacement = nodes.new("ShaderNodeCombineXYZ")
|
||||
step = _math(group, "DIVIDE", thickness, _read(group, "wall_layers"))
|
||||
layer_position = nodes.new("GeometryNodeInputPosition")
|
||||
layer_axes = nodes.new("ShaderNodeSeparateXYZ")
|
||||
links.new(layer_position.outputs[0], layer_axes.inputs[0])
|
||||
links.new(
|
||||
_math(group, "MULTIPLY", layer_axes.outputs["Z"], step),
|
||||
_math(group, "MULTIPLY", layer_axes.outputs["Z"], thickness),
|
||||
displacement.inputs["Z"],
|
||||
)
|
||||
restored = nodes.new("ShaderNodeVectorMath")
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""Arrange staggered calculation branches on both sides of the geometry path."""
|
||||
|
||||
from node_layout import arrange_nodes
|
||||
from cutout_layout import route_geometry
|
||||
|
||||
# Main geometry advances left to right. Local fields grow to either side of it;
|
||||
# a long calculation may start before the geometry input or span several stages.
|
||||
POSITIONS = {
|
||||
"Position": (0, 260),
|
||||
"Position": (-240, 110),
|
||||
"Store Named Attribute": (0, 0),
|
||||
"Store Named Attribute.001": (260, 0),
|
||||
"Store Named Attribute.002": (520, 0),
|
||||
@@ -13,9 +13,9 @@ POSITIONS = {
|
||||
"Split Edges": (1060, 0),
|
||||
"Switch": (1360, 0),
|
||||
# Face sampling stays near its stores; selection forms a dense field cluster.
|
||||
"Named Attribute": (-400, -320),
|
||||
"Evaluate on Domain": (-180, -320),
|
||||
"Image Texture": (20, -320),
|
||||
"Named Attribute": (-440, 380),
|
||||
"Evaluate on Domain": (-220, 380),
|
||||
"Image Texture": (20, 380),
|
||||
"Named Attribute.003": (260, 260),
|
||||
"Named Attribute.001": (-1090, 1060),
|
||||
"Separate XYZ": (-870, 1060),
|
||||
@@ -32,80 +32,55 @@ POSITIONS = {
|
||||
"Math": (-530, 1040),
|
||||
"Math.001": (-350, 1040),
|
||||
"Math.002": (-170, 1040),
|
||||
"Math.003": (-350, 830),
|
||||
"Math.004": (10, 1040),
|
||||
"Math.005": (190, 1040),
|
||||
"Math.006": (190, 790),
|
||||
"Math.007": (370, 980),
|
||||
"Math.008": (190, 620),
|
||||
"Math.009": (550, 910),
|
||||
"Math.003": (190, 1040),
|
||||
"Math.004": (190, 790),
|
||||
"Math.005": (370, 980),
|
||||
"Math.006": (190, 620),
|
||||
"Math.007": (550, 910),
|
||||
"Edge Neighbors": (370, 590),
|
||||
"Math.010": (550, 590),
|
||||
"Math.011": (730, 810),
|
||||
"Math.008": (550, 590),
|
||||
"Math.009": (730, 810),
|
||||
"Evaluate on Domain.001": (730, 670),
|
||||
"Evaluate on Domain.002": (910, 670),
|
||||
"Math.012": (1090, 670),
|
||||
"Math.013": (1360, 280),
|
||||
# Cleanup is a separate compact cluster before projection.
|
||||
"Face Area": (1460, 780),
|
||||
"Mesh Island": (1460, 580),
|
||||
"Accumulate Field": (1680, 780),
|
||||
"Math.014": (1900, 580),
|
||||
"Delete Geometry": (2120, 0),
|
||||
"Math.010": (1090, 670),
|
||||
"Math.011": (1360, 280),
|
||||
# Camera-ray reconstruction runs below; scene projection runs above.
|
||||
"Named Attribute.004": (1290, -440),
|
||||
"Image Texture.001": (1510, -440),
|
||||
"Separate XYZ.001": (1740, -440),
|
||||
"Named Attribute.005": (1510, -710),
|
||||
"Separate XYZ.002": (1740, -710),
|
||||
"Math.017": (1960, -440),
|
||||
"Math.014": (1960, -440),
|
||||
"Vector Math.001": (2180, -440),
|
||||
"Named Attribute.006": (1740, -940),
|
||||
"Math.015": (1510, -940),
|
||||
"Math.016": (1960, -940),
|
||||
"Math.012": (1510, -940),
|
||||
"Math.013": (1960, -940),
|
||||
"Switch.001": (2600, -240),
|
||||
"Store Named Attribute.004": (2920, 0),
|
||||
"Named Attribute.007": (2340, 1080),
|
||||
"Vector Math.002": (2560, 1080),
|
||||
"Separate XYZ.003": (2740, 1080),
|
||||
"Math.018": (3100, 730),
|
||||
"Math.019": (3280, 730),
|
||||
"Math.020": (2740, 910),
|
||||
"Math.015": (3100, 730),
|
||||
"Math.016": (3280, 730),
|
||||
"Math.017": (2740, 910),
|
||||
"Combine XYZ": (2920, 1040),
|
||||
"Position.001": (2920, 790),
|
||||
"Mix": (3100, 950),
|
||||
"Separate XYZ.004": (3280, 950),
|
||||
"Combine XYZ.001": (3460, 850),
|
||||
"Set Position": (3870, 0),
|
||||
# Short preparation fields sit above the axis; the long wall-count branch
|
||||
# sits below, reading geometry back from the source-vertex store.
|
||||
# Front and rear caps share a single extrusion along the geometry axis.
|
||||
"Position.002": (4560, 340),
|
||||
"Store Named Attribute.005": (4560, 0),
|
||||
"Vector Math.003": (4780, 340),
|
||||
"Set Position.001": (4780, 0),
|
||||
"Index": (5010, 340),
|
||||
"Store Named Attribute.006": (5010, 0),
|
||||
"Edge Vertices": (3470, -610),
|
||||
"Vector Math.004": (3700, -610),
|
||||
"Edge Neighbors.001": (3470, -850),
|
||||
"Math.021": (3700, -850),
|
||||
"Attribute Statistic": (3920, -610),
|
||||
"Math.022": (4150, -610),
|
||||
"Math.023": (4370, -610),
|
||||
"Math.024": (4590, -610),
|
||||
"Math.025": (4820, -610),
|
||||
"Math.026": (5040, -610),
|
||||
"Store Named Attribute.007": (5310, 0),
|
||||
"Repeat Input": (5620, 0),
|
||||
"Extrude Mesh": (5850, 0),
|
||||
"Combine XYZ.003": (5620, -340),
|
||||
"Separate Geometry": (6070, 0),
|
||||
"Join Geometry": (6300, -180),
|
||||
"Repeat Output": (6520, 0),
|
||||
"Flip Faces.001": (6740, 0),
|
||||
"Join Geometry.001": (6970, 0),
|
||||
"Named Attribute.010": (5620, -530),
|
||||
"Math.027": (5850, -530),
|
||||
"Extrude Mesh": (5500, 0),
|
||||
"Combine XYZ.003": (5260, 350),
|
||||
"Separate Geometry": (5780, 0),
|
||||
"Flip Faces.001": (6300, 0),
|
||||
"Join Geometry": (6970, 0),
|
||||
"Combine XYZ.004": (6070, -530),
|
||||
"Set Position.002": (6300, -320),
|
||||
"Flip Faces": (6740, -320),
|
||||
@@ -122,14 +97,12 @@ POSITIONS = {
|
||||
"Merge by Distance": (7640, 0),
|
||||
"Position.003": (6910, -950),
|
||||
"Separate XYZ.005": (7160, -950),
|
||||
"Named Attribute.011": (6900, -710),
|
||||
"Math.028": (7140, -580),
|
||||
"Math.029": (7380, -750),
|
||||
"Math.018": (7380, -750),
|
||||
"Combine XYZ.005": (7600, -680),
|
||||
"Named Attribute.012": (7600, -370),
|
||||
"Vector Math.005": (7830, -340),
|
||||
"Named Attribute.010": (7600, -370),
|
||||
"Vector Math.004": (7830, -340),
|
||||
"Set Position.004": (8080, 0),
|
||||
"Math.030": (8310, 260),
|
||||
"Math.019": (8310, 260),
|
||||
"Switch.002": (8310, 0),
|
||||
"Remove Named Attribute": (9000, 0),
|
||||
"Set Shade Smooth": (9220, 0),
|
||||
@@ -139,71 +112,34 @@ POSITIONS = {
|
||||
INPUT_REGIONS = (
|
||||
(("Store Named Attribute",), (-240, 0)),
|
||||
(("Switch",), (1100, -300)),
|
||||
(("Image Texture",), (-180, -190)),
|
||||
(("Image Texture",), (30, 520)),
|
||||
(("Math.002",), (-350, 1140)),
|
||||
(("Math.003",), (-530, 830)),
|
||||
(("Math.005",), (10, 1140)),
|
||||
(("Math.013",), (1100, 320)),
|
||||
(("Math.014",), (1680, 400)),
|
||||
(("Math.003",), (10, 1140)),
|
||||
(("Math.011",), (1100, 320)),
|
||||
(("Image Texture.001",), (1290, -270)),
|
||||
(("Math.015",), (1290, -940)),
|
||||
(("Math.012",), (1290, -940)),
|
||||
(("Vector Math.002",), (2340, 1200)),
|
||||
(("Math.018", "Math.019"), (2920, 680)),
|
||||
(("Math.015", "Math.016"), (2920, 680)),
|
||||
(("Mix",), (2920, 900)),
|
||||
(("Math.023",), (4150, -820)),
|
||||
(("Math.028",), (6900, -540)),
|
||||
(("Math.030",), (8080, 300)),
|
||||
(("Math.019",), (8080, 300)),
|
||||
)
|
||||
|
||||
|
||||
def _route(group, source_name, output, target_name, input_name, points):
|
||||
"""Place geometry references around the local branches they serve."""
|
||||
source = group.nodes[source_name].outputs[output]
|
||||
target = group.nodes[target_name].inputs[input_name]
|
||||
for link in list(group.links):
|
||||
if link.from_socket == source and link.to_socket == target:
|
||||
group.links.remove(link)
|
||||
for point in points:
|
||||
node = group.nodes.new("NodeReroute")
|
||||
node.location = point
|
||||
node.select = False
|
||||
group.links.new(source, node.inputs[0])
|
||||
source = node.outputs[0]
|
||||
group.links.new(source, target)
|
||||
def layout_geometry_references(group, stage):
|
||||
"""Separate the split bypass and long projection references from fields."""
|
||||
links = group.links
|
||||
entry = stage["Store Named Attribute"].inputs["Geometry"]
|
||||
source = entry.links[0].from_socket
|
||||
fork = route_geometry(group, source, [(-3250, -40), (-1450, -40), (-290, -40)])
|
||||
links.new(fork, entry)
|
||||
bypass = route_geometry(group, fork, [(-210, -280), (500, -280), (1100, -280)])
|
||||
links.new(bypass, stage["Switch"].inputs["False"])
|
||||
|
||||
|
||||
def layout_depth_surface(group):
|
||||
"""Keep the geometry path readable while staggering long and short branches."""
|
||||
arrange_nodes(group, POSITIONS, INPUT_REGIONS)
|
||||
_route(
|
||||
group,
|
||||
"Repeat Input",
|
||||
"Sides",
|
||||
"Join Geometry",
|
||||
"Geometry",
|
||||
((5810, -170), (6280, -170)),
|
||||
)
|
||||
_route(
|
||||
group,
|
||||
"Store Named Attribute.007",
|
||||
"Geometry",
|
||||
"Join Geometry.001",
|
||||
"Geometry",
|
||||
((5530, 150), (6950, 150)),
|
||||
)
|
||||
_route(
|
||||
group,
|
||||
"Store Named Attribute.007",
|
||||
"Geometry",
|
||||
"Set Position.002",
|
||||
"Geometry",
|
||||
((5530, -270), (6280, -270)),
|
||||
)
|
||||
_route(
|
||||
group,
|
||||
"Set Position",
|
||||
"Geometry",
|
||||
"Switch.002",
|
||||
"True",
|
||||
((4110, 240), (8290, 240)),
|
||||
)
|
||||
projection = next(n.outputs["Geometry"] for n in group.nodes if n.bl_idname == "GeometryNodeStoreNamedAttribute" and n.inputs["Name"].default_value == "o_balloon_surface_front_normal")
|
||||
shared = next(n.outputs["Geometry"] for n in group.nodes if n.bl_idname == "GeometryNodeStoreNamedAttribute" and n.inputs["Name"].default_value == "o_balloon_surface_inflation_normal")
|
||||
uniform = next(link.to_socket for link in shared.links if link.to_node.bl_idname == "GeometryNodeStoreNamedAttribute" and link.to_node.inputs["Name"].default_value == "o_balloon_surface_thickness")
|
||||
fork = route_geometry(group, projection, [(4360, -40), (4650, -1700), (8500, -1700), (11400, -1700)])
|
||||
uniform_route = route_geometry(group, shared, [(8250, -40), (8460, -1450), (11400, -1450), (11420, -370)])
|
||||
links.new(uniform_route, uniform)
|
||||
surface_route = route_geometry(group, fork, [(13500, -1700), (16800, -1700)])
|
||||
links.new(surface_route, stage["Switch.002"].inputs["True"])
|
||||
|
||||
142
tools/node_assets/cutout_inflation.py
Normal file
142
tools/node_assets/cutout_inflation.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Estimate existing front volume and add continuous normal-directed inflation."""
|
||||
from cutout_volume import node
|
||||
|
||||
|
||||
def _math(group, operation, a, b, location):
|
||||
result = node(group, "ShaderNodeMath", location)
|
||||
result.operation = operation
|
||||
for index, value in enumerate((a, b)):
|
||||
if hasattr(value, "node"):
|
||||
group.links.new(value, result.inputs[index])
|
||||
else:
|
||||
result.inputs[index].default_value = value
|
||||
return result.outputs[0]
|
||||
|
||||
|
||||
def _read(group, name, location, kind="FLOAT"):
|
||||
result = node(group, "GeometryNodeInputNamedAttribute", location)
|
||||
result.data_type = kind
|
||||
result.inputs["Name"].default_value = "o_balloon_surface_" + name
|
||||
return result.outputs["Attribute"]
|
||||
|
||||
|
||||
def _store(group, geometry, name, value, location, kind="FLOAT"):
|
||||
result = node(group, "GeometryNodeStoreNamedAttribute", location)
|
||||
result.data_type, result.domain = kind, "POINT"
|
||||
result.inputs["Name"].default_value = "o_balloon_surface_" + name
|
||||
group.links.new(geometry, result.inputs["Geometry"])
|
||||
group.links.new(value, result.inputs["Value"])
|
||||
return result.outputs["Geometry"]
|
||||
|
||||
|
||||
def build_front_fields(group, geometry):
|
||||
"""Fit structural amplitude over neighbouring points before creating the shell."""
|
||||
links = group.links
|
||||
|
||||
def math(operation, a, b, x, y):
|
||||
return _math(group, operation, a, b, (4800 + x, -2500 + y))
|
||||
|
||||
def blur(value, x, y, weight=None):
|
||||
result = node(group, "GeometryNodeBlurAttribute", (4800 + x, -2500 + y))
|
||||
result.data_type = "FLOAT"
|
||||
result.inputs["Iterations"].default_value = 256
|
||||
links.new(value, result.inputs["Value"])
|
||||
if weight is not None:
|
||||
links.new(weight, result.inputs["Weight"])
|
||||
return result.outputs[0]
|
||||
|
||||
profile_node = node(group, "GeometryNodeInputNamedAttribute", (4800, -2500))
|
||||
profile_node.data_type = "FLOAT"
|
||||
profile_node.inputs["Name"].default_value = "o_balloon"
|
||||
profile = profile_node.outputs["Attribute"]
|
||||
rim = _read(group, "rim", (4800, -3050))
|
||||
interior = math("SUBTRACT", 1, rim, 240, -550)
|
||||
position = node(group, "GeometryNodeInputPosition", (4800, -1900))
|
||||
axes = node(group, "ShaderNodeSeparateXYZ", (5040, -1900))
|
||||
links.new(position.outputs[0], axes.inputs[0])
|
||||
depth = axes.outputs["Z"]
|
||||
depth_slow = blur(depth, 480, 600, interior)
|
||||
profile_slow = blur(profile, 480, 0, interior)
|
||||
depth_bump = math("SUBTRACT", depth, depth_slow, 720, 600)
|
||||
profile_bump = math("SUBTRACT", profile, profile_slow, 720, 0)
|
||||
numerator = math("MULTIPLY", depth_bump, profile_bump, 960, 600)
|
||||
denominator = math("MULTIPLY", profile_bump, profile_bump, 960, 0)
|
||||
numerator = blur(numerator, 1200, 600)
|
||||
denominator = blur(denominator, 1200, 0)
|
||||
denominator = math("MAXIMUM", denominator, 1e-10, 1440, 0)
|
||||
structure = math("DIVIDE", numerator, denominator, 1680, 600)
|
||||
structure = math("MAXIMUM", structure, 0, 1920, 600)
|
||||
carrier = _store(group, geometry, "structure", structure, (7300, 0))
|
||||
|
||||
normal = _read(group, "front_normal", (7100, -600), "FLOAT_VECTOR")
|
||||
controls = node(group, "NodeGroupInput", (6860, -1100))
|
||||
# Keep the accepted broad front-direction filter at the default of 50;
|
||||
# zero disables both this filter and the initial front/back normal filters.
|
||||
spread = _math(group, "MULTIPLY", controls.outputs["Normal Smooth"], 256 / 50, (7100, -1100))
|
||||
smooth = node(group, "GeometryNodeBlurAttribute", (7340, -600))
|
||||
smooth.data_type = "FLOAT_VECTOR"
|
||||
links.new(normal, smooth.inputs["Value"])
|
||||
links.new(spread, smooth.inputs["Iterations"])
|
||||
normalize = node(group, "ShaderNodeVectorMath", (7580, -600))
|
||||
normalize.operation = "NORMALIZE"
|
||||
links.new(smooth.outputs[0], normalize.inputs[0])
|
||||
carrier = _store(group, carrier, "inflation_normal", normalize.outputs[0], (7770, 0), "FLOAT_VECTOR")
|
||||
return carrier
|
||||
|
||||
|
||||
def build_inflation_position(group, position, distance, uniform):
|
||||
"""Grow both modes continuously while leaving the rear cap in place."""
|
||||
previous = set(group.nodes)
|
||||
links = group.links
|
||||
|
||||
def math(operation, a, b, x, y):
|
||||
return _math(group, operation, a, b, (x, y))
|
||||
|
||||
structure = _read(group, "structure", (14000, -4300))
|
||||
control = node(group, "NodeGroupInput", (13760, -5000))
|
||||
a = math("MULTIPLY", control.outputs["Thickness"], control.outputs["Front Inflation"], 14240, -5000)
|
||||
# A shifted cubic blend preserves continuous growth and height order.
|
||||
shifted = math("ADD", a, 0.75, 14480, -5000)
|
||||
quadratic = math("MULTIPLY", a, shifted, 14720, -5000)
|
||||
quadratic = math("ADD", quadratic, 0.1875, 14960, -5000)
|
||||
q = math("MULTIPLY", a, quadratic, 15200, -5000)
|
||||
k = math("ADD", structure, 0.25, 14240, -4300)
|
||||
square = math("MULTIPLY", k, k, 14480, -4300)
|
||||
cube = math("MULTIPLY", square, k, 14720, -4300)
|
||||
total = math("ADD", cube, q, 14960, -4300)
|
||||
root = math("POWER", total, 1 / 3, 15200, -4300)
|
||||
root_square = math("MULTIPLY", root, root, 15440, -4000)
|
||||
product = math("MULTIPLY", root, k, 15440, -4300)
|
||||
denominator = math("ADD", root_square, product, 15680, -4300)
|
||||
denominator = math("ADD", denominator, square, 15920, -4300)
|
||||
response = math("DIVIDE", q, denominator, 15920, -4800)
|
||||
profile = node(group, "GeometryNodeInputNamedAttribute", (15920, -3700))
|
||||
profile.data_type = "FLOAT"
|
||||
profile.inputs["Name"].default_value = "o_balloon"
|
||||
balloon = math("MULTIPLY", profile.outputs["Attribute"], response, 16160, -4250)
|
||||
uniform_control = node(group, "NodeGroupInput", (15920, -5100))
|
||||
uniform_amount = math("MULTIPLY", uniform_control.outputs["Uniform Thickness"], uniform_control.outputs["Front Inflation"], 16160, -5100)
|
||||
selected = node(group, "GeometryNodeSwitch", (16400, -4550))
|
||||
selected.input_type = "FLOAT"
|
||||
links.new(uniform, selected.inputs["Switch"])
|
||||
links.new(balloon, selected.inputs["False"])
|
||||
links.new(uniform_amount, selected.inputs["True"])
|
||||
displacement = selected.outputs[0]
|
||||
height = _read(group, "thickness", (14000, -5500))
|
||||
layer = math("DIVIDE", distance, height, 14240, -5500)
|
||||
layer = math("ADD", 1, layer, 14480, -5500)
|
||||
layer = math("MAXIMUM", layer, 0, 14720, -5500)
|
||||
layer = math("MINIMUM", layer, 1, 14960, -5500)
|
||||
displacement = math("MULTIPLY", displacement, layer, 16640, -4550)
|
||||
normal = _read(group, "inflation_normal", (16640, -4000), "FLOAT_VECTOR")
|
||||
offset = node(group, "ShaderNodeVectorMath", (16880, -4550))
|
||||
offset.operation = "SCALE"
|
||||
links.new(normal, offset.inputs[0])
|
||||
links.new(displacement, offset.inputs[3])
|
||||
result = node(group, "ShaderNodeVectorMath", (17120, -4550))
|
||||
result.operation = "ADD"
|
||||
links.new(position, result.inputs[0])
|
||||
links.new(offset.outputs[0], result.inputs[1])
|
||||
for item in set(group.nodes) - previous:
|
||||
item.location.y = -3550 + (item.location.y + 3700) * 0.7
|
||||
return result.outputs[0]
|
||||
53
tools/node_assets/cutout_layout.py
Normal file
53
tools/node_assets/cutout_layout.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Place independent Cutout stages using authored local layouts."""
|
||||
from collections import Counter
|
||||
|
||||
|
||||
def route_geometry(group, source, positions):
|
||||
"""Guide a shared forward geometry reference through authored waypoints."""
|
||||
for position in positions:
|
||||
reroute = group.nodes.new("NodeReroute")
|
||||
reroute.location = position
|
||||
group.links.new(source, reroute.inputs[0])
|
||||
source = reroute.outputs[0]
|
||||
return source
|
||||
|
||||
|
||||
def layout_stage(group, previous, positions, input_regions, offset=(0, 0)):
|
||||
"""Map stage-local default names without renaming Blender nodes."""
|
||||
counts, stage = Counter(), {}
|
||||
for node in group.nodes:
|
||||
if node in previous or node.bl_idname == "NodeGroupInput":
|
||||
continue
|
||||
base, dot, suffix = node.name.rpartition(".")
|
||||
base = base if dot and suffix.isdigit() else node.name
|
||||
index = counts[base]
|
||||
counts[base] += 1
|
||||
stage[base if index == 0 else f"{base}.{index:03d}"] = node
|
||||
assert set(stage) == set(positions) - {"Set Shade Smooth", "Group Output"}, (group.name, set(stage) ^ set(positions))
|
||||
for name, node in stage.items():
|
||||
x, y = positions[name]
|
||||
node.location = (x + offset[0], y + offset[1])
|
||||
inputs = [(link.to_socket, link.from_socket.name) for link in group.links if link.to_node in stage.values() and link.from_node.bl_idname == "NodeGroupInput"]
|
||||
for targets, (x, y) in input_regions:
|
||||
sockets = [(socket, name) for socket, name in inputs if socket.node in [stage[key] for key in targets if key in stage]]
|
||||
if not sockets:
|
||||
continue
|
||||
control = group.nodes.new("NodeGroupInput")
|
||||
control.location = (x + offset[0], y + offset[1])
|
||||
for socket, name in sockets:
|
||||
group.links.new(control.outputs[name], socket)
|
||||
return stage
|
||||
|
||||
|
||||
def finish_layout(group):
|
||||
"""Expose linked fields and retain readable constants."""
|
||||
for node in group.nodes:
|
||||
node.select = False
|
||||
node.width = 200 if "Attribute" in node.bl_idname else 160
|
||||
if node.bl_idname in {"ShaderNodeMath", "ShaderNodeVectorMath"}:
|
||||
node.hide = all(socket.is_linked for socket in node.inputs if socket.enabled and not socket.hide)
|
||||
for socket in node.outputs:
|
||||
socket.hide = not socket.is_linked
|
||||
for node in list(group.nodes):
|
||||
if node.bl_idname == "NodeGroupInput" and not any(socket.is_linked for socket in node.outputs):
|
||||
group.nodes.remove(node)
|
||||
101
tools/node_assets/cutout_rounding.py
Normal file
101
tools/node_assets/cutout_rounding.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""Round depth volume around the smoothed center-surface normals."""
|
||||
from cutout_volume import node, shift_stage
|
||||
|
||||
|
||||
def build_volume_rounding(group, volume, offset):
|
||||
previous = set(group.nodes)
|
||||
links = group.links
|
||||
|
||||
def math(operation, a, b, location):
|
||||
result = node(group, "ShaderNodeMath", location)
|
||||
result.operation = operation
|
||||
for index, value in enumerate((a, b)):
|
||||
if isinstance(value, (int, float)):
|
||||
result.inputs[index].default_value = value
|
||||
else:
|
||||
links.new(value, result.inputs[index])
|
||||
return result.outputs[0]
|
||||
|
||||
def read(name, location, kind="FLOAT"):
|
||||
result = node(group, "GeometryNodeInputNamedAttribute", location)
|
||||
result.data_type = kind
|
||||
result.inputs["Name"].default_value = "o_balloon_surface_" + name
|
||||
return result.outputs["Attribute"]
|
||||
|
||||
def store(geometry, name, value, location, kind="FLOAT"):
|
||||
result = node(group, "GeometryNodeStoreNamedAttribute", location)
|
||||
result.data_type, result.domain = kind, "POINT"
|
||||
result.inputs["Name"].default_value = "o_balloon_surface_" + name
|
||||
links.new(geometry, result.inputs["Geometry"])
|
||||
links.new(value, result.inputs["Value"])
|
||||
return result.outputs["Geometry"]
|
||||
|
||||
control = node(group, "NodeGroupInput", (0, 1250))
|
||||
profile = node(group, "GeometryNodeInputNamedAttribute", (0, 850))
|
||||
profile.data_type = "FLOAT"
|
||||
profile.inputs["Name"].default_value = "o_balloon"
|
||||
balloon = profile.outputs["Attribute"]
|
||||
maximum = node(group, "GeometryNodeAttributeStatistic", (240, 850))
|
||||
maximum.data_type, maximum.domain = "FLOAT", "POINT"
|
||||
links.new(volume, maximum.inputs["Geometry"])
|
||||
links.new(balloon, maximum.inputs["Attribute"])
|
||||
limit = math("MAXIMUM", maximum.outputs["Max"], 1e-8, (480, 850))
|
||||
falloff = node(group, "ShaderNodeMapRange", (720, 850))
|
||||
falloff.interpolation_type = "SMOOTHERSTEP"
|
||||
falloff.inputs["To Min"].default_value = 1
|
||||
falloff.inputs["To Max"].default_value = 0
|
||||
links.new(balloon, falloff.inputs["Value"])
|
||||
links.new(limit, falloff.inputs["From Max"])
|
||||
weight = math("MULTIPLY", falloff.outputs[0], control.outputs["Edge Round"], (960, 850))
|
||||
center = read("center", (0, 1900))
|
||||
position = node(group, "GeometryNodeInputPosition", (0, 2250))
|
||||
axes = node(group, "ShaderNodeSeparateXYZ", (240, 2250))
|
||||
links.new(position.outputs[0], axes.inputs[0])
|
||||
target = math("ADD", center, balloon, (480, 1900))
|
||||
delta = math("SUBTRACT", target, axes.outputs["Z"], (720, 1900))
|
||||
delta = math("MULTIPLY", delta, weight, (960, 1900))
|
||||
enabled = math("MINIMUM", control.outputs["Thickness"], 1, (480, 1300))
|
||||
enabled = math("MAXIMUM", enabled, 0, (720, 1300))
|
||||
delta = math("MULTIPLY", delta, enabled, (1200, 1900))
|
||||
carrier = store(volume, "edge_weight", weight, (1200, 0))
|
||||
carrier = store(carrier, "front_delta", delta, (1440, 0))
|
||||
rear = math("MULTIPLY", balloon, weight, (1200, 850))
|
||||
rear = math("MULTIPLY", rear, control.outputs["Thickness"], (1440, 850))
|
||||
thickness = read("thickness", (1440, 1250))
|
||||
total = math("ADD", thickness, delta, (1680, 1250))
|
||||
total = math("ADD", total, rear, (1920, 1250))
|
||||
carrier = store(carrier, "thickness", total, (1920, 0))
|
||||
|
||||
# Evaluate normals on a separate center surface with identical point indices.
|
||||
center_position = node(group, "ShaderNodeCombineXYZ", (480, -550))
|
||||
for axis in ("X", "Y"):
|
||||
links.new(axes.outputs[axis], center_position.inputs[axis])
|
||||
links.new(center, center_position.inputs["Z"])
|
||||
surface = node(group, "GeometryNodeSetPosition", (720, -550))
|
||||
links.new(volume, surface.inputs["Geometry"])
|
||||
links.new(center_position.outputs[0], surface.inputs["Position"])
|
||||
normal = node(group, "GeometryNodeInputNormal", (720, -1000))
|
||||
blur = node(group, "GeometryNodeBlurAttribute", (960, -1000))
|
||||
blur.data_type = "FLOAT_VECTOR"
|
||||
links.new(normal.outputs[0], blur.inputs["Value"])
|
||||
local = node(group, "NodeGroupInput", (720, -1300))
|
||||
links.new(local.outputs["Normal Smooth"], blur.inputs["Iterations"])
|
||||
normalize = node(group, "ShaderNodeVectorMath", (1200, -1000))
|
||||
normalize.operation = "NORMALIZE"
|
||||
links.new(blur.outputs[0], normalize.inputs[0])
|
||||
index = node(group, "GeometryNodeInputIndex", (1200, -1350))
|
||||
sample = node(group, "GeometryNodeSampleIndex", (1440, -550))
|
||||
sample.data_type, sample.domain = "FLOAT_VECTOR", "POINT"
|
||||
links.new(surface.outputs[0], sample.inputs["Geometry"])
|
||||
links.new(normalize.outputs[0], sample.inputs["Value"])
|
||||
links.new(index.outputs[0], sample.inputs["Index"])
|
||||
carrier = store(carrier, "normal", sample.outputs[0], (2160, 0), "FLOAT_VECTOR")
|
||||
captured = read("front_delta", (2160, 850))
|
||||
displacement = node(group, "ShaderNodeCombineXYZ", (2400, 850))
|
||||
links.new(captured, displacement.inputs["Z"])
|
||||
front = node(group, "GeometryNodeSetPosition", (2640, 0))
|
||||
links.new(carrier, front.inputs["Geometry"])
|
||||
links.new(displacement.outputs[0], front.inputs["Offset"])
|
||||
shift_stage(group, previous, offset)
|
||||
return front.outputs[0]
|
||||
|
||||
141
tools/node_assets/cutout_shape_layouts.py
Normal file
141
tools/node_assets/cutout_shape_layouts.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Authored local positions for Cutout shape stages."""
|
||||
|
||||
LAYOUTS = {'BALLOON': ({'Named Attribute': (-950, 440),
|
||||
'Attribute Statistic': (-730, 1020),
|
||||
'Math': (-500, 1020),
|
||||
'Math.001': (-280, 1020),
|
||||
'Map Range': (-50, 1020),
|
||||
'Math.002': (-500, 440),
|
||||
'Math.003': (-500, 240),
|
||||
'Math.004': (-280, 240),
|
||||
'Extrude Mesh': (0, 0),
|
||||
'Switch': (220, 440),
|
||||
'Position': (20, 240),
|
||||
'Separate XYZ': (220, 240),
|
||||
'Combine XYZ': (420, 340),
|
||||
'Set Position': (690, 0),
|
||||
'Separate Geometry': (910, 0),
|
||||
'Flip Faces': (1140, 0),
|
||||
'Combine XYZ.001': (910, 530),
|
||||
'Set Position.001': (1140, 300),
|
||||
'Combine XYZ.002': (690, -550),
|
||||
'Set Position.002': (910, -300),
|
||||
'Flip Faces.001': (1140, -300),
|
||||
'Join Geometry': (1430, 0),
|
||||
'Merge by Distance': (1650, 0),
|
||||
'Math.005': (2100, 310),
|
||||
'Switch.001': (2100, 0),
|
||||
'Set Shade Smooth': (2320, 0),
|
||||
'Group Output': (2550, 0)},
|
||||
((('Extrude Mesh',), (-220, 0)),
|
||||
(('Attribute Statistic',), (-950, 1020)),
|
||||
(('Math.002', 'Math.003'), (-730, 240)),
|
||||
(('Set Position.001',), (910, 300)),
|
||||
(('Set Position.002',), (690, -300)),
|
||||
(('Math.005',), (1870, 340)),
|
||||
(('Switch.001',), (1870, -240)))),
|
||||
'UNIFORM': ({'Math': (-90, 680),
|
||||
'Math.001': (140, 680),
|
||||
'Edge Vertices': (-1630, -340),
|
||||
'Vector Math': (-1410, -340),
|
||||
'Edge Neighbors': (-1630, -560),
|
||||
'Math.002': (-1410, -560),
|
||||
'Attribute Statistic': (-1190, -340),
|
||||
'Math.003': (-960, -340),
|
||||
'Math.004': (-740, -340),
|
||||
'Float to Integer': (-520, -340),
|
||||
'Integer Math': (-290, -340),
|
||||
'Integer Math.001': (-70, -340),
|
||||
'Math.005': (190, -580),
|
||||
'Math.006': (410, -580),
|
||||
'Combine XYZ': (1630, 480),
|
||||
'Set Position': (1860, 260),
|
||||
'Repeat Input': (410, 0),
|
||||
'Extrude Mesh': (640, 0),
|
||||
'Separate Geometry': (860, 0),
|
||||
'Join Geometry': (1080, -180),
|
||||
'Repeat Output': (1310, 0),
|
||||
'Combine XYZ.001': (1410, 270),
|
||||
'Set Position.001': (1630, 0),
|
||||
'Flip Faces': (1860, 0),
|
||||
'Combine XYZ.002': (1410, -470),
|
||||
'Set Position.002': (1630, -260),
|
||||
'Flip Faces.001': (1860, -260),
|
||||
'Join Geometry.001': (2150, 0),
|
||||
'Merge by Distance': (2370, 0),
|
||||
'Math.007': (2820, 290),
|
||||
'Switch': (2820, 0),
|
||||
'Set Shade Smooth': (3040, 0),
|
||||
'Group Output': (3270, 0)},
|
||||
((('Math',), (-310, 680)),
|
||||
(('Attribute Statistic',), (-1410, -170)),
|
||||
(('Math.004',), (-960, -610)),
|
||||
(('Math.005',), (-30, -580)),
|
||||
(('Repeat Input',), (190, 0)),
|
||||
(('Set Position',), (1630, 260)),
|
||||
(('Set Position.002',), (1410, -260)),
|
||||
(('Math.007',), (2600, 310)),
|
||||
(('Switch',), (2600, -240)))),
|
||||
'DEPTH_BALLOON': ({'Named Attribute': (-1120, 650),
|
||||
'Attribute Statistic': (-890, 650),
|
||||
'Math': (-670, 650),
|
||||
'Math.001': (-450, 650),
|
||||
'Map Range': (-220, 650),
|
||||
'Named Attribute.001': (-1790, -440),
|
||||
'Image Texture': (-1570, -440),
|
||||
'Separate XYZ': (-1340, -440),
|
||||
'Math.002': (-1120, -440),
|
||||
'Vector Math': (-2240, -950),
|
||||
'Separate XYZ.001': (-2010, -950),
|
||||
'Position': (-2240, -1260),
|
||||
'Separate XYZ.002': (-2010, -1260),
|
||||
'Math.003': (-1790, -950),
|
||||
'Math.004': (-1790, -1160),
|
||||
'Math.005': (-1570, -950),
|
||||
'Math.006': (-1340, -950),
|
||||
'Math.007': (-1120, -950),
|
||||
'Math.008': (-890, -440),
|
||||
'Math.009': (-670, -440),
|
||||
'Math.010': (-450, -440),
|
||||
'Math.011': (-670, 310),
|
||||
'Math.012': (-670, 70),
|
||||
'Math.013': (-450, 70),
|
||||
'Mix': (20, 440),
|
||||
'Math.014': (240, 710),
|
||||
'Switch': (460, 710),
|
||||
'Extrude Mesh': (0, 0),
|
||||
'Switch.001': (460, 310),
|
||||
'Position.001': (280, 530),
|
||||
'Separate XYZ.003': (460, 530),
|
||||
'Combine XYZ': (660, 430),
|
||||
'Set Position': (930, 0),
|
||||
'Separate Geometry': (1150, 0),
|
||||
'Flip Faces': (1600, 0),
|
||||
'Combine XYZ.001': (1380, 570),
|
||||
'Set Position.001': (1600, 330),
|
||||
'Combine XYZ.002': (1150, -570),
|
||||
'Set Position.002': (1380, -320),
|
||||
'Flip Faces.001': (1600, -320),
|
||||
'Join Geometry': (1870, 0),
|
||||
'Merge by Distance': (2320, 0),
|
||||
'Position.002': (1600, 1120),
|
||||
'Separate XYZ.004': (1820, 1120),
|
||||
'Combine XYZ.003': (2050, 950),
|
||||
'Set Position.003': (2320, 680),
|
||||
'Math.015': (2560, -270),
|
||||
'Switch.002': (2560, 0),
|
||||
'Set Shade Smooth': (2790, 0),
|
||||
'Group Output': (3010, 0)},
|
||||
((('Extrude Mesh',), (-220, 0)),
|
||||
(('Attribute Statistic',), (-1120, 850)),
|
||||
(('Image Texture',), (-1790, -270)),
|
||||
(('Math.002',), (-1340, -750)),
|
||||
(('Vector Math',), (-2460, -950)),
|
||||
(('Math.007',), (-1340, -1160)),
|
||||
(('Math.010',), (-670, -650)),
|
||||
(('Math.011', 'Math.012'), (-890, 310)),
|
||||
(('Switch',), (240, 920)),
|
||||
(('Set Position.001',), (1380, 330)),
|
||||
(('Set Position.002',), (1150, -320)),
|
||||
(('Set Position.003',), (2100, 610)),
|
||||
(('Math.015',), (2340, -270))))}
|
||||
@@ -1,24 +1,6 @@
|
||||
"""Build the four Cutout Geometry Nodes groups stored in O_AnyImage.blend."""
|
||||
|
||||
|
||||
import bpy
|
||||
from node_graph import expand_smooth
|
||||
from cutout_depth_surface import (
|
||||
store_surface_camera,
|
||||
remove_surface_attributes,
|
||||
split_depth_surface,
|
||||
thicken_depth_surface,
|
||||
)
|
||||
from cutout_depth_surface_layout import layout_depth_surface
|
||||
from geometry_layouts import layout_geometry
|
||||
|
||||
from anyimage.operators.cutout_tool.shape import (
|
||||
BALLOON_ATTRIBUTE_NAME,
|
||||
CUTOUT_Z_TO_X,
|
||||
CUTOUT_NODE_GROUP_NAME,
|
||||
CUTOUT_NODE_GROUP_NAMES,
|
||||
CUTOUT_SHAPE_LABELS,
|
||||
)
|
||||
"""Construct the planar and depth-based Cutout shape stages."""
|
||||
from cutout_depth_surface import store_surface_camera, remove_surface_attributes, split_depth_surface, thicken_depth_surface
|
||||
from anyimage.operators.cutout_tool.shape import BALLOON_ATTRIBUTE_NAME
|
||||
|
||||
|
||||
def _socket(group, name, in_out, socket_type, parent=None):
|
||||
@@ -42,47 +24,6 @@ def _group_input(nodes, location, visible_names):
|
||||
return node
|
||||
|
||||
|
||||
def _localize_group_inputs(group, controls):
|
||||
"""Place short, socket-specific Group Inputs beside their consumers."""
|
||||
links = group.links
|
||||
outgoing = [link for link in links if link.from_node == controls]
|
||||
by_socket = {}
|
||||
for link in outgoing:
|
||||
if link.from_socket.name == "Geometry":
|
||||
continue
|
||||
by_socket.setdefault(link.from_socket.name, []).append(link)
|
||||
|
||||
for socket_name, socket_links in by_socket.items():
|
||||
ordered = sorted(socket_links, key=lambda link: link.to_node.location.x)
|
||||
clusters = []
|
||||
for link in ordered:
|
||||
if (
|
||||
not clusters
|
||||
or link.to_node.location.x - clusters[-1][-1].to_node.location.x > 900.0
|
||||
):
|
||||
clusters.append([])
|
||||
clusters[-1].append(link)
|
||||
for cluster in clusters:
|
||||
targets = [link.to_node for link in cluster]
|
||||
location = [
|
||||
min(node.location.x for node in targets) - 260.0,
|
||||
max(node.location.y for node in targets) + 320.0,
|
||||
]
|
||||
while any(
|
||||
abs(node.location.x - location[0]) < 190.0
|
||||
and abs(node.location.y - location[1]) < 190.0
|
||||
for node in group.nodes
|
||||
):
|
||||
location[1] += 220.0
|
||||
local = _group_input(group.nodes, location, {socket_name})
|
||||
for link in cluster:
|
||||
target = link.to_socket
|
||||
links.remove(link)
|
||||
links.new(local.outputs[socket_name], target)
|
||||
for output in controls.outputs:
|
||||
output.hide = output.name != "Geometry"
|
||||
|
||||
|
||||
def _float_input(
|
||||
group,
|
||||
name,
|
||||
@@ -610,14 +551,12 @@ def _build_depth_surface(
|
||||
uniform_scale,
|
||||
reference_depth,
|
||||
depth_image,
|
||||
cleanup,
|
||||
):
|
||||
nodes = group.nodes
|
||||
links = group.links
|
||||
geometry = split_depth_surface(
|
||||
group, geometry, depth_image, split, uniform_scale, depth_scale
|
||||
group, geometry, depth_image, split, uniform_scale
|
||||
)
|
||||
geometry = _island_cleanup(group, geometry, cleanup, (1800.0, 850.0))
|
||||
original_camera = _position_field(group, depth_image, (-200.0, -200.0))
|
||||
geometry, camera_position = store_surface_camera(
|
||||
group, geometry, original_camera, split
|
||||
@@ -672,366 +611,3 @@ def _build_depth_surface(
|
||||
group, project_geometry.outputs["Geometry"], shaped, thickness, (11800.0, 400.0)
|
||||
)
|
||||
return remove_surface_attributes(group, geometry)
|
||||
|
||||
|
||||
def build_node_group(shape):
|
||||
group_name = CUTOUT_NODE_GROUP_NAMES[shape]
|
||||
group = bpy.data.node_groups.get(group_name)
|
||||
if group is not None:
|
||||
return group
|
||||
group = bpy.data.node_groups.new(group_name, "GeometryNodeTree")
|
||||
group.is_modifier = False
|
||||
_socket(group, "Geometry", "INPUT", "NodeSocketGeometry")
|
||||
if shape in {"BALLOON", "DEPTH_BALLOON"}:
|
||||
thickness = _float_input(group, "Thickness", 1.0)
|
||||
thickness.description = (
|
||||
"Multiplier for the injected Poisson Balloon profile; zero keeps "
|
||||
"the source sheet"
|
||||
)
|
||||
else:
|
||||
thickness = _float_input(group, "Thickness", 0.0, 0.0, None, subtype="DISTANCE")
|
||||
thickness.description = "Final thickness in scene distance"
|
||||
|
||||
depth_image = None
|
||||
split = None
|
||||
if shape == "DEPTH_BALLOON":
|
||||
depth_scale = _float_input(group, "Depth Scale", 1.0)
|
||||
depth_scale.description = "Scale the fitted-plane-corrected metric depth"
|
||||
double_sided = _bool_input(group, "Double Sided", False)
|
||||
double_sided.description = (
|
||||
"Mirror the complete front surface across the local XY plane"
|
||||
)
|
||||
elif shape == "DEPTH_SURFACE":
|
||||
depth_scale = _float_input(group, "Depth Scale", 1.0)
|
||||
|
||||
if shape == "DEPTH_BALLOON":
|
||||
options = group.interface.new_panel(name="Options", default_closed=True)
|
||||
reference_depth = _float_input(
|
||||
group,
|
||||
"Reference Depth",
|
||||
1.0,
|
||||
0.0,
|
||||
None,
|
||||
subtype="DISTANCE",
|
||||
parent=options,
|
||||
)
|
||||
reference_depth.description = (
|
||||
"Shared upper-percentile metric depth for outward placement"
|
||||
)
|
||||
depth_direction = _vector_input(
|
||||
group,
|
||||
"Depth Direction",
|
||||
(0.0, 0.0, 1.0),
|
||||
subtype="DIRECTION",
|
||||
parent=options,
|
||||
)
|
||||
depth_direction.description = (
|
||||
"Normal direction of the fitted metric depth plane"
|
||||
)
|
||||
elif shape == "DEPTH_SURFACE":
|
||||
options = group.interface.new_panel(name="Options", default_closed=True)
|
||||
split = _float_input(
|
||||
group,
|
||||
"Split",
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
subtype="FACTOR",
|
||||
parent=options,
|
||||
)
|
||||
split.description = "Separate depth discontinuities; zero disables splitting"
|
||||
cleanup = _float_input(group, "Cleanup", 0.0, 0.0, None, parent=options)
|
||||
cleanup.description = "Remove split islands below this local-area threshold"
|
||||
reference_depth = _float_input(
|
||||
group,
|
||||
"Reference Depth",
|
||||
1.0,
|
||||
0.0,
|
||||
None,
|
||||
subtype="DISTANCE",
|
||||
parent=options,
|
||||
)
|
||||
reference_depth.description = (
|
||||
"Scaled camera depth placed on the original image sheet"
|
||||
)
|
||||
|
||||
if shape in {"DEPTH_BALLOON", "DEPTH_SURFACE"}:
|
||||
data = group.interface.new_panel(name="Data", default_closed=True)
|
||||
uniform_scale = _float_input(group, "Uniform Scale", 1.0, 0.0, parent=data)
|
||||
uniform_scale.description = (
|
||||
"Internal uniform conversion from MoGe meters to local distance"
|
||||
)
|
||||
uniform_scale.hide_in_modifier = True
|
||||
depth_image = _socket(group, "Depth Image", "INPUT", "NodeSocketImage", data)
|
||||
depth_image.description = (
|
||||
f"Internally generated {CUTOUT_SHAPE_LABELS[shape]} data"
|
||||
)
|
||||
depth_image.hide_in_modifier = True
|
||||
_socket(group, "Geometry", "OUTPUT", "NodeSocketGeometry")
|
||||
|
||||
controls = _group_input(
|
||||
group.nodes,
|
||||
(-1600.0, 500.0),
|
||||
{
|
||||
"Geometry",
|
||||
"Thickness",
|
||||
"Double Sided",
|
||||
"Depth Image",
|
||||
"Depth Scale",
|
||||
"Uniform Scale",
|
||||
"Reference Depth",
|
||||
"Depth Direction",
|
||||
"Split",
|
||||
"Cleanup",
|
||||
},
|
||||
)
|
||||
geometry = controls.outputs["Geometry"]
|
||||
if shape == "SURFACE":
|
||||
geometry = _build_cutout(group, geometry, controls.outputs["Thickness"])
|
||||
output_location = (4050.0, 300.0)
|
||||
elif shape == "BALLOON":
|
||||
geometry = _build_balloon(
|
||||
group,
|
||||
geometry,
|
||||
controls.outputs["Thickness"],
|
||||
)
|
||||
output_location = (4650.0, 650.0)
|
||||
elif shape == "DEPTH_BALLOON":
|
||||
geometry = _build_depth_balloon(
|
||||
group,
|
||||
geometry,
|
||||
controls.outputs["Thickness"],
|
||||
controls.outputs["Depth Scale"],
|
||||
controls.outputs["Double Sided"],
|
||||
controls.outputs["Uniform Scale"],
|
||||
controls.outputs["Depth Direction"],
|
||||
controls.outputs["Depth Image"],
|
||||
controls.outputs["Reference Depth"],
|
||||
)
|
||||
output_location = (5100.0, 600.0)
|
||||
else:
|
||||
geometry = _build_depth_surface(
|
||||
group,
|
||||
geometry,
|
||||
controls.outputs["Thickness"],
|
||||
controls.outputs["Depth Scale"],
|
||||
controls.outputs["Split"],
|
||||
controls.outputs["Uniform Scale"],
|
||||
controls.outputs["Reference Depth"],
|
||||
controls.outputs["Depth Image"],
|
||||
controls.outputs["Cleanup"],
|
||||
)
|
||||
output_location = (12100.0, 400.0)
|
||||
_localize_group_inputs(group, controls)
|
||||
_shade_output(group, geometry, output_location)
|
||||
if shape == "DEPTH_SURFACE":
|
||||
layout_depth_surface(group)
|
||||
else:
|
||||
layout_geometry(group)
|
||||
group.color_tag = "GEOMETRY"
|
||||
group.description = {
|
||||
"SURFACE": "Symmetrically thicken a Surface sheet.",
|
||||
"BALLOON": "Inflate a Surface sheet from its boundary profile.",
|
||||
"DEPTH_BALLOON": (
|
||||
"Mix Balloon profile and metric image depth around a fitted plane."
|
||||
),
|
||||
"DEPTH_SURFACE": (
|
||||
"Project and thicken a Surface sheet from hidden camera points."
|
||||
),
|
||||
}[shape]
|
||||
group.use_fake_user = True
|
||||
return group
|
||||
|
||||
|
||||
def build_cutout_modifier_group(shape_groups):
|
||||
group = bpy.data.node_groups.get(CUTOUT_NODE_GROUP_NAME)
|
||||
if group is not None:
|
||||
return group
|
||||
group = bpy.data.node_groups.new(CUTOUT_NODE_GROUP_NAME, "GeometryNodeTree")
|
||||
group.is_modifier = True
|
||||
_socket(group, "Geometry", "INPUT", "NodeSocketGeometry")
|
||||
_socket(group, "Shape", "INPUT", "NodeSocketMenu")
|
||||
inward_axis = _socket(group, "Inward Axis", "INPUT", "NodeSocketMenu")
|
||||
inward_axis.hide_in_modifier = True
|
||||
|
||||
thickness = _float_input(group, "Thickness", 0.0, 0.0)
|
||||
thickness.description = (
|
||||
"Scene thickness for Surface shapes or Balloon profile multiplier"
|
||||
)
|
||||
depth_scale = _float_input(group, "Depth Scale", 1.0, 0.0)
|
||||
depth_scale.description = "Scale metric image depth"
|
||||
double_sided = _bool_input(group, "Double Sided", False)
|
||||
double_sided.description = (
|
||||
"Mirror the complete Depth Balloon front surface across the local XY plane"
|
||||
)
|
||||
|
||||
iterations = _socket(group, "Smooth Iterations", "INPUT", "NodeSocketInt")
|
||||
iterations.default_value = 0
|
||||
iterations.min_value = 0
|
||||
iterations.max_value = 20
|
||||
iterations.description = "Number of smoothing passes"
|
||||
options = group.interface.new_panel(name="Options", default_closed=True)
|
||||
cleanup = _float_input(
|
||||
group,
|
||||
"Cleanup",
|
||||
0.0,
|
||||
0.0,
|
||||
None,
|
||||
parent=options,
|
||||
)
|
||||
cleanup.description = "Delete mesh islands below this absolute local-area threshold"
|
||||
smooth = _float_input(
|
||||
group,
|
||||
"Smooth",
|
||||
1.0,
|
||||
0.0,
|
||||
1.0,
|
||||
subtype="FACTOR",
|
||||
parent=options,
|
||||
)
|
||||
smooth.description = "Blend each smoothing pass into the selected shape"
|
||||
split = _float_input(
|
||||
group,
|
||||
"Split",
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
subtype="FACTOR",
|
||||
parent=options,
|
||||
)
|
||||
split.description = "Separate Depth Surface discontinuities; zero disables splitting"
|
||||
|
||||
reference_depth = _float_input(
|
||||
group,
|
||||
"Reference Depth",
|
||||
1.0,
|
||||
0.0,
|
||||
None,
|
||||
subtype="DISTANCE",
|
||||
parent=options,
|
||||
)
|
||||
reference_depth.description = "Depth of the flat base plane for both Depth shapes"
|
||||
depth_direction = _vector_input(
|
||||
group,
|
||||
"Depth Direction",
|
||||
(0.0, 0.0, 1.0),
|
||||
subtype="DIRECTION",
|
||||
parent=options,
|
||||
)
|
||||
depth_direction.description = "Normal direction of the fitted metric depth plane"
|
||||
|
||||
data = group.interface.new_panel(name="Data", default_closed=True)
|
||||
uniform_scale = _float_input(group, "Uniform Scale", 1.0, 0.0, parent=data)
|
||||
uniform_scale.description = (
|
||||
"Internal uniform conversion from MoGe meters to local distance"
|
||||
)
|
||||
uniform_scale.hide_in_modifier = True
|
||||
depth_image = _socket(group, "Depth Image", "INPUT", "NodeSocketImage", data)
|
||||
depth_image.description = "Internally generated Cutout depth data"
|
||||
depth_image.hide_in_modifier = True
|
||||
_socket(group, "Geometry", "OUTPUT", "NodeSocketGeometry")
|
||||
|
||||
base_controls = _group_input(
|
||||
group.nodes,
|
||||
(-2700.0, 500.0),
|
||||
{"Geometry", "Cleanup"},
|
||||
)
|
||||
cleanup_area = _math(group.nodes, "MULTIPLY", (-2500.0, 750.0))
|
||||
cleanup_area.inputs[1].default_value = 0.01
|
||||
group.links.new(base_controls.outputs["Cleanup"], cleanup_area.inputs[0])
|
||||
geometry = _island_cleanup(
|
||||
group,
|
||||
base_controls.outputs["Geometry"],
|
||||
cleanup_area.outputs[0],
|
||||
(-2350.0, 250.0),
|
||||
)
|
||||
|
||||
branch_y = {
|
||||
"SURFACE": 1150.0,
|
||||
"BALLOON": 550.0,
|
||||
"DEPTH_BALLOON": -50.0,
|
||||
"DEPTH_SURFACE": -650.0,
|
||||
}
|
||||
branch_nodes = {}
|
||||
for shape, y in branch_y.items():
|
||||
node = group.nodes.new("GeometryNodeGroup")
|
||||
node.node_tree = shape_groups[shape]
|
||||
node.location = (-850.0, y)
|
||||
node.width = 220.0
|
||||
group.links.new(
|
||||
base_controls.outputs["Geometry"] if shape == "DEPTH_SURFACE" else geometry,
|
||||
node.inputs["Geometry"],
|
||||
)
|
||||
visible = {
|
||||
socket.name
|
||||
for socket in node.inputs
|
||||
if socket.name and socket.name != "Geometry"
|
||||
}
|
||||
controls = _group_input(group.nodes, (-1200.0, y + 120.0), visible)
|
||||
for socket in node.inputs:
|
||||
if not socket.name or socket.name == "Geometry":
|
||||
continue
|
||||
group.links.new(
|
||||
cleanup_area.outputs[0] if socket.name == "Cleanup" else controls.outputs[socket.name],
|
||||
socket,
|
||||
)
|
||||
branch_nodes[shape] = node
|
||||
|
||||
menu_switch = group.nodes.new("GeometryNodeMenuSwitch")
|
||||
menu_switch.data_type = "GEOMETRY"
|
||||
shapes = list(CUTOUT_NODE_GROUP_NAMES)
|
||||
for item, shape in zip(menu_switch.enum_items, shapes[:2]):
|
||||
item.name = CUTOUT_SHAPE_LABELS[shape]
|
||||
for shape in shapes[2:]:
|
||||
menu_switch.enum_items.new(CUTOUT_SHAPE_LABELS[shape])
|
||||
menu_switch.location = (-350.0, 250.0)
|
||||
|
||||
shape_controls = _group_input(
|
||||
group.nodes,
|
||||
(-700.0, -1200.0),
|
||||
{"Shape"},
|
||||
)
|
||||
group.links.new(shape_controls.outputs["Shape"], menu_switch.inputs["Menu"])
|
||||
for shape, node in branch_nodes.items():
|
||||
group.links.new(
|
||||
node.outputs["Geometry"],
|
||||
menu_switch.inputs[CUTOUT_SHAPE_LABELS[shape]],
|
||||
)
|
||||
|
||||
geometry = expand_smooth(
|
||||
group,
|
||||
menu_switch.outputs["Output"],
|
||||
iterations_name="Smooth Iterations",
|
||||
)
|
||||
from mathutils import Matrix
|
||||
|
||||
orient = group.nodes.new("GeometryNodeTransform")
|
||||
orient.inputs["Rotation"].default_value = Matrix(CUTOUT_Z_TO_X).to_euler()
|
||||
orient.location = (3300.0, 350.0)
|
||||
group.links.new(geometry, orient.inputs["Geometry"])
|
||||
|
||||
axis_switch = group.nodes.new("GeometryNodeMenuSwitch")
|
||||
axis_switch.data_type = "GEOMETRY"
|
||||
axis_switch.enum_items[0].name = "-Z"
|
||||
axis_switch.enum_items[1].name = "+X"
|
||||
axis_switch.location = (3550.0, 550.0)
|
||||
axis_controls = _group_input(
|
||||
group.nodes,
|
||||
(3300.0, -650.0),
|
||||
{"Inward Axis"},
|
||||
)
|
||||
group.links.new(axis_controls.outputs["Inward Axis"], axis_switch.inputs["Menu"])
|
||||
group.links.new(geometry, axis_switch.inputs["-Z"])
|
||||
group.links.new(orient.outputs["Geometry"], axis_switch.inputs["+X"])
|
||||
_shade_output(group, axis_switch.outputs["Output"], (3850.0, 550.0))
|
||||
layout_geometry(group)
|
||||
group.color_tag = "GEOMETRY"
|
||||
group.description = (
|
||||
"Build Surface, Balloon, Depth Balloon, or Depth Surface from one "
|
||||
"menu-controlled Cutout modifier."
|
||||
)
|
||||
for node in group.nodes:
|
||||
for socket in node.outputs:
|
||||
socket.hide = not socket.is_linked
|
||||
group.use_fake_user = True
|
||||
return group
|
||||
122
tools/node_assets/cutout_shell.py
Normal file
122
tools/node_assets/cutout_shell.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Continue a front-normal thin shell into the rounded depth volume."""
|
||||
from cutout_inflation import build_inflation_position
|
||||
from cutout_volume import node, shift_stage
|
||||
|
||||
|
||||
def build_front_normals(group, geometry):
|
||||
links = group.links
|
||||
normal = node(group, "GeometryNodeInputNormal", (3400, -650))
|
||||
control = node(group, "NodeGroupInput", (3400, -950))
|
||||
blur = node(group, "GeometryNodeBlurAttribute", (3640, -650))
|
||||
blur.data_type = "FLOAT_VECTOR"
|
||||
links.new(normal.outputs[0], blur.inputs["Value"])
|
||||
links.new(control.outputs["Normal Smooth"], blur.inputs["Iterations"])
|
||||
normalize = node(group, "ShaderNodeVectorMath", (3880, -650))
|
||||
normalize.operation = "NORMALIZE"
|
||||
links.new(blur.outputs[0], normalize.inputs[0])
|
||||
store = node(group, "GeometryNodeStoreNamedAttribute", (4110, 0))
|
||||
store.data_type, store.domain = "FLOAT_VECTOR", "POINT"
|
||||
store.inputs["Name"].default_value = "o_balloon_surface_front_normal"
|
||||
links.new(geometry, store.inputs["Geometry"])
|
||||
links.new(normalize.outputs[0], store.inputs["Value"])
|
||||
return store.outputs[0]
|
||||
|
||||
|
||||
def build_shell_position(group, position, uniform, offset):
|
||||
previous = set(group.nodes)
|
||||
links = group.links
|
||||
|
||||
def connect(value, target):
|
||||
if hasattr(value, "node"):
|
||||
links.new(value, target)
|
||||
else:
|
||||
target.default_value = value
|
||||
|
||||
def math(operation, a, b, location):
|
||||
result = node(group, "ShaderNodeMath", location)
|
||||
result.operation = operation
|
||||
connect(a, result.inputs[0])
|
||||
connect(b, result.inputs[1])
|
||||
return result.outputs[0]
|
||||
|
||||
def vector(operation, a, b, location):
|
||||
result = node(group, "ShaderNodeVectorMath", location)
|
||||
result.operation = operation
|
||||
connect(a, result.inputs[0])
|
||||
connect(b, result.inputs[3 if operation == "SCALE" else 1])
|
||||
return result.outputs[0]
|
||||
|
||||
def read(name, location, kind="FLOAT"):
|
||||
result = node(group, "GeometryNodeInputNamedAttribute", location)
|
||||
result.data_type = kind
|
||||
result.inputs["Name"].default_value = name
|
||||
return result.outputs["Attribute"]
|
||||
|
||||
def z(value, location):
|
||||
result = node(group, "ShaderNodeSeparateXYZ", location)
|
||||
links.new(value, result.inputs[0])
|
||||
return result.outputs["Z"]
|
||||
|
||||
# Uniform and the thin end of Balloon share the actual front normal.
|
||||
front = read("o_depth_surface_position", (0, 0), "FLOAT_VECTOR")
|
||||
front_z = z(front, (240, 0))
|
||||
raw_z = z(position, (240, 250))
|
||||
distance = math("SUBTRACT", raw_z, front_z, (480, 250))
|
||||
normal = read("o_balloon_surface_front_normal", (480, 550), "FLOAT_VECTOR")
|
||||
thin_offset = vector("SCALE", normal, distance, (720, 550))
|
||||
uniform_position = vector("ADD", front, thin_offset, (3120, 550))
|
||||
|
||||
# R = t * (front_z - center) + (1 - t) * front_delta, with t clamped.
|
||||
# This avoids division by Thickness and removes the old zero-thickness drift.
|
||||
control = node(group, "NodeGroupInput", (0, -400))
|
||||
clamp = node(group, "ShaderNodeClamp", (240, -400))
|
||||
links.new(control.outputs["Thickness"], clamp.inputs["Value"])
|
||||
t = clamp.outputs[0]
|
||||
center = read("o_balloon_surface_center", (0, -750))
|
||||
delta = read("o_balloon_surface_front_delta", (480, -1050))
|
||||
radius = math("SUBTRACT", front_z, center, (480, -750))
|
||||
radius = math("MULTIPLY", radius, t, (720, -750))
|
||||
remaining = math("SUBTRACT", 1, t, (480, -400))
|
||||
remainder = math("MULTIPLY", remaining, delta, (720, -1050))
|
||||
radius = math("ADD", radius, remainder, (960, -750))
|
||||
|
||||
# Front and rear use the same edge field, evaluated on their own caps.
|
||||
edge = read("o_balloon_surface_edge_weight", (0, -1450))
|
||||
mask = read("o_normal_scale", (240, -1800))
|
||||
remaining = math("SUBTRACT", 1, edge, (240, -1450))
|
||||
remaining = math("MULTIPLY", remaining, mask, (480, -1450))
|
||||
weight = math("SUBTRACT", 1, remaining, (720, -1450))
|
||||
difference = math("SUBTRACT", weight, edge, (960, -1450))
|
||||
base = math("MULTIPLY", difference, radius, (1200, -1450))
|
||||
layer = math("MULTIPLY", weight, distance, (1200, -1800))
|
||||
rear_radius = math("ADD", base, layer, (1440, -1450))
|
||||
front_radius = math("MULTIPLY", edge, radius, (1440, -750))
|
||||
normal = read("o_balloon_surface_normal", (1200, -300), "FLOAT_VECTOR")
|
||||
direction = vector("SUBTRACT", normal, (0, 0, 1), (1440, -300))
|
||||
front_shift = vector("SCALE", direction, front_radius, (1680, -750))
|
||||
front_position = vector("ADD", front, front_shift, (1920, -750))
|
||||
rear_shift = vector("SCALE", direction, rear_radius, (1680, -1450))
|
||||
axis_offset = node(group, "ShaderNodeCombineXYZ", (1680, -1800))
|
||||
links.new(distance, axis_offset.inputs["Z"])
|
||||
full_offset = vector("ADD", axis_offset.outputs[0], rear_shift, (1920, -1450))
|
||||
|
||||
# Smoothly reach the existing full-volume shape at Thickness >= 1.
|
||||
transition = node(group, "ShaderNodeMapRange", (1920, 0))
|
||||
transition.interpolation_type = "SMOOTHERSTEP"
|
||||
links.new(t, transition.inputs["Value"])
|
||||
mix = node(group, "ShaderNodeMix", (2400, -1100))
|
||||
mix.data_type = "VECTOR"
|
||||
links.new(transition.outputs[0], mix.inputs[0])
|
||||
links.new(thin_offset, mix.inputs[4])
|
||||
links.new(full_offset, mix.inputs[5])
|
||||
balloon_position = vector("ADD", front_position, mix.outputs["Result"], (3120, -750))
|
||||
choose = node(group, "GeometryNodeSwitch", (3400, 0))
|
||||
choose.input_type = "VECTOR"
|
||||
links.new(uniform, choose.inputs["Switch"])
|
||||
links.new(balloon_position, choose.inputs["False"])
|
||||
links.new(uniform_position, choose.inputs["True"])
|
||||
for item in set(group.nodes) - previous:
|
||||
item.location.x *= 0.9
|
||||
item.location.y *= 0.65
|
||||
shift_stage(group, previous, offset)
|
||||
return build_inflation_position(group, choose.outputs[0], distance, uniform)
|
||||
88
tools/node_assets/cutout_volume.py
Normal file
88
tools/node_assets/cutout_volume.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""Build the smooth center field for depth volume."""
|
||||
from node_graph import edge_boundary_field
|
||||
|
||||
|
||||
def node(group, kind, location):
|
||||
result = group.nodes.new(kind)
|
||||
result.location = location
|
||||
return result
|
||||
|
||||
|
||||
def shift_stage(group, previous, offset):
|
||||
for item in group.nodes:
|
||||
if item not in previous:
|
||||
item.location.x += offset[0]
|
||||
item.location.y += offset[1]
|
||||
|
||||
|
||||
def build_volume_fields(group, geometry, offset=(0, 0)):
|
||||
previous = set(group.nodes)
|
||||
boundary = edge_boundary_field(group.nodes, group.links, (0, -400))
|
||||
store = node(group, "GeometryNodeStoreNamedAttribute", (860, 0))
|
||||
store.domain, store.data_type = "POINT", "FLOAT"
|
||||
store.inputs["Name"].default_value = "o_balloon_surface_rim"
|
||||
group.links.new(geometry, store.inputs["Geometry"])
|
||||
group.links.new(boundary, store.inputs["Value"])
|
||||
profile = node(group, "GeometryNodeInputNamedAttribute", (860, 700))
|
||||
profile.data_type = "FLOAT"
|
||||
profile.inputs["Name"].default_value = "o_balloon"
|
||||
links = group.links
|
||||
def math(operation, a, b, location):
|
||||
result = node(group, "ShaderNodeMath", location)
|
||||
result.operation = operation
|
||||
for index, value in enumerate((a, b)):
|
||||
if isinstance(value, (int, float)):
|
||||
result.inputs[index].default_value = value
|
||||
else:
|
||||
links.new(value, result.inputs[index])
|
||||
return result.outputs[0]
|
||||
position = node(group, "GeometryNodeInputPosition", (860, 1100))
|
||||
axes = node(group, "ShaderNodeSeparateXYZ", (1100, 1100))
|
||||
links.new(position.outputs[0], axes.inputs[0])
|
||||
seed = math("SUBTRACT", axes.outputs["Z"], profile.outputs["Attribute"], (1340, 900))
|
||||
center = node(group, "GeometryNodeStoreNamedAttribute", (1340, 0))
|
||||
center.domain, center.data_type = "POINT", "FLOAT"
|
||||
center.inputs["Name"].default_value = "o_balloon_surface_center"
|
||||
links.new(store.outputs["Geometry"], center.inputs["Geometry"])
|
||||
links.new(seed, center.inputs["Value"])
|
||||
current = node(group, "GeometryNodeInputNamedAttribute", (1660, -330))
|
||||
current.data_type = "FLOAT"
|
||||
current.inputs["Name"].default_value = "o_balloon_surface_center"
|
||||
rim = node(group, "GeometryNodeInputNamedAttribute", (1660, -660))
|
||||
rim.data_type = "FLOAT"
|
||||
rim.inputs["Name"].default_value = "o_balloon_surface_rim"
|
||||
interior = math("SUBTRACT", 1, rim.outputs["Attribute"], (1890, -660))
|
||||
blur = node(group, "GeometryNodeBlurAttribute", (2120, -330))
|
||||
blur.data_type = "FLOAT"
|
||||
blur.inputs["Iterations"].default_value = 256
|
||||
links.new(current.outputs["Attribute"], blur.inputs["Value"])
|
||||
links.new(interior, blur.inputs["Weight"])
|
||||
update = node(group, "GeometryNodeStoreNamedAttribute", (2370, 0))
|
||||
update.domain, update.data_type = "POINT", "FLOAT"
|
||||
update.inputs["Name"].default_value = "o_balloon_surface_center"
|
||||
links.new(center.outputs["Geometry"], update.inputs["Geometry"])
|
||||
links.new(blur.outputs[0], update.inputs["Value"])
|
||||
baseline = node(group, "GeometryNodeInputNamedAttribute", (2940, 1000))
|
||||
baseline.data_type = "FLOAT"
|
||||
baseline.inputs["Name"].default_value = "o_balloon_surface_center"
|
||||
profile_end = node(group, "GeometryNodeInputNamedAttribute", (2940, 700))
|
||||
profile_end.data_type = "FLOAT"
|
||||
profile_end.inputs["Name"].default_value = "o_balloon"
|
||||
position_end = node(group, "GeometryNodeInputPosition", (2940, 1360))
|
||||
axes_end = node(group, "ShaderNodeSeparateXYZ", (3180, 1360))
|
||||
links.new(position_end.outputs[0], axes_end.inputs[0])
|
||||
residual = math("SUBTRACT", axes_end.outputs["Z"], baseline.outputs["Attribute"], (3420, 1000))
|
||||
full = math("ADD", residual, profile_end.outputs["Attribute"], (3660, 1000))
|
||||
minimum = math("MULTIPLY", profile_end.outputs["Attribute"], 0.05, (3420, 700))
|
||||
positive = math("MAXIMUM", full, minimum, (3900, 1000))
|
||||
control = node(group, "NodeGroupInput", (3900, 700))
|
||||
scaled = math("MULTIPLY", positive, control.outputs["Thickness"], (4140, 1000))
|
||||
thickness = node(group, "GeometryNodeStoreNamedAttribute", (4140, 0))
|
||||
thickness.domain, thickness.data_type = "POINT", "FLOAT"
|
||||
thickness.inputs["Name"].default_value = "o_balloon_surface_thickness"
|
||||
group.links.new(update.outputs["Geometry"], thickness.inputs["Geometry"])
|
||||
group.links.new(scaled, thickness.inputs["Value"])
|
||||
shift_stage(group, previous, offset)
|
||||
return thickness.outputs["Geometry"]
|
||||
|
||||
|
||||
@@ -70,70 +70,6 @@ LAYOUTS = {
|
||||
(("Bounding Box.002",), (-550, 140)),
|
||||
),
|
||||
),
|
||||
"O Image Cutout": (
|
||||
{
|
||||
"Math": (-170, 580),
|
||||
"Mesh Island": (-620, 140),
|
||||
"Face Area": (-620, 340),
|
||||
"Accumulate Field": (-400, 340),
|
||||
"Math.001": (50, 310),
|
||||
"Delete Geometry": (430, 270),
|
||||
"Group": (1030, 520),
|
||||
"Group.001": (1030, 300),
|
||||
"Group.002": (1030, 80),
|
||||
"Group.003": (1030, -220),
|
||||
"Menu Switch": (1390, 240),
|
||||
"Repeat Input": (2170, 0),
|
||||
"Repeat Output": (5090, 0),
|
||||
"Vertex Neighbors": (2170, -780),
|
||||
"Compare": (2390, -780),
|
||||
"Edge Neighbors": (1940, -1020),
|
||||
"Compare.001": (2170, -1020),
|
||||
"Evaluate on Domain": (2390, -1020),
|
||||
"Boolean Math": (2610, -780),
|
||||
"Evaluate on Domain.001": (2840, -580),
|
||||
"Separate Geometry": (3110, -310),
|
||||
"Position": (3300, 540),
|
||||
"Blur Attribute": (3520, 540),
|
||||
"Position.001": (3110, -780),
|
||||
"Blur Attribute.001": (3340, -780),
|
||||
"Sample Nearest": (3340, -310),
|
||||
"Sample Index": (3590, -310),
|
||||
"Vertex Neighbors.001": (2390, 950),
|
||||
"Compare.002": (2610, 950),
|
||||
"Edge Neighbors.001": (2170, 1220),
|
||||
"Compare.003": (2390, 1220),
|
||||
"Evaluate on Domain.002": (2610, 1220),
|
||||
"Boolean Math.001": (2840, 950),
|
||||
"Switch": (3890, 340),
|
||||
"Mix": (4130, 340),
|
||||
"Normal": (3060, 1500),
|
||||
"Blur Attribute.002": (3280, 1500),
|
||||
"Vector Math": (3510, 1500),
|
||||
"Switch.001": (3730, 1500),
|
||||
"Math.002": (3950, 1360),
|
||||
"Switch.002": (4370, 410),
|
||||
"Position.002": (4370, 680),
|
||||
"Mix.001": (4660, 410),
|
||||
"Set Position": (4830, 0),
|
||||
"Transform Geometry": (5450, -340),
|
||||
"Menu Switch.001": (5740, 0),
|
||||
"Set Shade Smooth": (5970, 0),
|
||||
"Group Output": (6190, 0),
|
||||
},
|
||||
(
|
||||
(("Math",), (-400, 580)),
|
||||
(("Delete Geometry",), (430, 530)),
|
||||
(("Group",), (810, 520)),
|
||||
(("Group.001",), (810, 300)),
|
||||
(("Group.002",), (810, 80)),
|
||||
(("Group.003",), (810, -220)),
|
||||
(("Menu Switch",), (1390, 380)),
|
||||
(("Repeat Input",), (1940, 0)),
|
||||
(("Math.002",), (3730, 1220)),
|
||||
(("Menu Switch.001",), (5520, 340)),
|
||||
),
|
||||
),
|
||||
"O Image Depth Plane": (
|
||||
{
|
||||
"Group": (0, 0),
|
||||
@@ -173,163 +109,6 @@ LAYOUTS = {
|
||||
(("Math.007",), (1000, -980)),
|
||||
),
|
||||
),
|
||||
"O Image Balloon": (
|
||||
{
|
||||
"Named Attribute": (-950, 440),
|
||||
"Attribute Statistic": (-730, 1020),
|
||||
"Math": (-500, 1020),
|
||||
"Math.001": (-280, 1020),
|
||||
"Map Range": (-50, 1020),
|
||||
"Math.002": (-500, 440),
|
||||
"Math.003": (-500, 240),
|
||||
"Math.004": (-280, 240),
|
||||
"Extrude Mesh": (0, 0),
|
||||
"Switch": (220, 440),
|
||||
"Position": (20, 240),
|
||||
"Separate XYZ": (220, 240),
|
||||
"Combine XYZ": (420, 340),
|
||||
"Set Position": (690, 0),
|
||||
"Separate Geometry": (910, 0),
|
||||
"Flip Faces": (1140, 0),
|
||||
"Combine XYZ.001": (910, 530),
|
||||
"Set Position.001": (1140, 300),
|
||||
"Combine XYZ.002": (690, -550),
|
||||
"Set Position.002": (910, -300),
|
||||
"Flip Faces.001": (1140, -300),
|
||||
"Join Geometry": (1430, 0),
|
||||
"Merge by Distance": (1650, 0),
|
||||
"Math.005": (2100, 310),
|
||||
"Switch.001": (2100, 0),
|
||||
"Set Shade Smooth": (2320, 0),
|
||||
"Group Output": (2550, 0),
|
||||
},
|
||||
(
|
||||
(("Extrude Mesh",), (-220, 0)),
|
||||
(("Attribute Statistic",), (-950, 1020)),
|
||||
(("Math.002", "Math.003"), (-730, 240)),
|
||||
(("Set Position.001",), (910, 300)),
|
||||
(("Set Position.002",), (690, -300)),
|
||||
(("Math.005",), (1870, 340)),
|
||||
(("Switch.001",), (1870, -240)),
|
||||
),
|
||||
),
|
||||
"O Image Surface": (
|
||||
{
|
||||
"Math": (-90, 680),
|
||||
"Math.001": (140, 680),
|
||||
"Edge Vertices": (-1630, -340),
|
||||
"Vector Math": (-1410, -340),
|
||||
"Edge Neighbors": (-1630, -560),
|
||||
"Math.002": (-1410, -560),
|
||||
"Attribute Statistic": (-1190, -340),
|
||||
"Math.003": (-960, -340),
|
||||
"Math.004": (-740, -340),
|
||||
"Float to Integer": (-520, -340),
|
||||
"Integer Math": (-290, -340),
|
||||
"Integer Math.001": (-70, -340),
|
||||
"Math.005": (190, -580),
|
||||
"Math.006": (410, -580),
|
||||
"Combine XYZ": (1630, 480),
|
||||
"Set Position": (1860, 260),
|
||||
"Repeat Input": (410, 0),
|
||||
"Extrude Mesh": (640, 0),
|
||||
"Separate Geometry": (860, 0),
|
||||
"Join Geometry": (1080, -180),
|
||||
"Repeat Output": (1310, 0),
|
||||
"Combine XYZ.001": (1410, 270),
|
||||
"Set Position.001": (1630, 0),
|
||||
"Flip Faces": (1860, 0),
|
||||
"Combine XYZ.002": (1410, -470),
|
||||
"Set Position.002": (1630, -260),
|
||||
"Flip Faces.001": (1860, -260),
|
||||
"Join Geometry.001": (2150, 0),
|
||||
"Merge by Distance": (2370, 0),
|
||||
"Math.007": (2820, 290),
|
||||
"Switch": (2820, 0),
|
||||
"Set Shade Smooth": (3040, 0),
|
||||
"Group Output": (3270, 0),
|
||||
},
|
||||
(
|
||||
(("Math",), (-310, 680)),
|
||||
(("Attribute Statistic",), (-1410, -170)),
|
||||
(("Math.004",), (-960, -610)),
|
||||
(("Math.005",), (-30, -580)),
|
||||
(("Repeat Input",), (190, 0)),
|
||||
(("Set Position",), (1630, 260)),
|
||||
(("Set Position.002",), (1410, -260)),
|
||||
(("Math.007",), (2600, 310)),
|
||||
(("Switch",), (2600, -240)),
|
||||
),
|
||||
),
|
||||
"O Image Depth Balloon": (
|
||||
{
|
||||
"Named Attribute": (-1120, 650),
|
||||
"Attribute Statistic": (-890, 650),
|
||||
"Math": (-670, 650),
|
||||
"Math.001": (-450, 650),
|
||||
"Map Range": (-220, 650),
|
||||
"Named Attribute.001": (-1790, -440),
|
||||
"Image Texture": (-1570, -440),
|
||||
"Separate XYZ": (-1340, -440),
|
||||
"Math.002": (-1120, -440),
|
||||
"Vector Math": (-2240, -950),
|
||||
"Separate XYZ.001": (-2010, -950),
|
||||
"Position": (-2240, -1260),
|
||||
"Separate XYZ.002": (-2010, -1260),
|
||||
"Math.003": (-1790, -950),
|
||||
"Math.004": (-1790, -1160),
|
||||
"Math.005": (-1570, -950),
|
||||
"Math.006": (-1340, -950),
|
||||
"Math.007": (-1120, -950),
|
||||
"Math.008": (-890, -440),
|
||||
"Math.009": (-670, -440),
|
||||
"Math.010": (-450, -440),
|
||||
"Math.011": (-670, 310),
|
||||
"Math.012": (-670, 70),
|
||||
"Math.013": (-450, 70),
|
||||
"Mix": (20, 440),
|
||||
"Math.014": (240, 710),
|
||||
"Switch": (460, 710),
|
||||
"Extrude Mesh": (0, 0),
|
||||
"Switch.001": (460, 310),
|
||||
"Position.001": (280, 530),
|
||||
"Separate XYZ.003": (460, 530),
|
||||
"Combine XYZ": (660, 430),
|
||||
"Set Position": (930, 0),
|
||||
"Separate Geometry": (1150, 0),
|
||||
"Flip Faces": (1600, 0),
|
||||
"Combine XYZ.001": (1380, 570),
|
||||
"Set Position.001": (1600, 330),
|
||||
"Combine XYZ.002": (1150, -570),
|
||||
"Set Position.002": (1380, -320),
|
||||
"Flip Faces.001": (1600, -320),
|
||||
"Join Geometry": (1870, 0),
|
||||
"Merge by Distance": (2320, 0),
|
||||
"Position.002": (1600, 1120),
|
||||
"Separate XYZ.004": (1820, 1120),
|
||||
"Combine XYZ.003": (2050, 950),
|
||||
"Set Position.003": (2320, 680),
|
||||
"Math.015": (2560, -270),
|
||||
"Switch.002": (2560, 0),
|
||||
"Set Shade Smooth": (2790, 0),
|
||||
"Group Output": (3010, 0),
|
||||
},
|
||||
(
|
||||
(("Extrude Mesh",), (-220, 0)),
|
||||
(("Attribute Statistic",), (-1120, 850)),
|
||||
(("Image Texture",), (-1790, -270)),
|
||||
(("Math.002",), (-1340, -750)),
|
||||
(("Vector Math",), (-2460, -950)),
|
||||
(("Math.007",), (-1340, -1160)),
|
||||
(("Math.010",), (-670, -650)),
|
||||
(("Math.011", "Math.012"), (-890, 310)),
|
||||
(("Switch",), (240, 920)),
|
||||
(("Set Position.001",), (1380, 330)),
|
||||
(("Set Position.002",), (1150, -320)),
|
||||
(("Set Position.003",), (2100, 610)),
|
||||
(("Math.015",), (2340, -270)),
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -56,13 +56,13 @@ def edge_boundary_field(nodes, links, location):
|
||||
|
||||
|
||||
def expand_smooth(
|
||||
group, geometry, x_offset=0.0, iterations_name="Iterations"
|
||||
group, geometry, x_offset=0.0, iterations_name="Iterations", weight_name="Smooth"
|
||||
):
|
||||
nodes = group.nodes
|
||||
links = group.links
|
||||
existing_nodes = set(nodes)
|
||||
iteration_controls = group_input(nodes, (550.0, 1150.0), {iterations_name})
|
||||
weight_controls = group_input(nodes, (2300.0, 1450.0), {"Smooth"})
|
||||
weight_controls = group_input(nodes, (2300.0, 1450.0), {weight_name})
|
||||
repeat_output = nodes.new("GeometryNodeRepeatOutput")
|
||||
repeat_output.location = (3050.0, 550.0)
|
||||
repeat_input = nodes.new("GeometryNodeRepeatInput")
|
||||
@@ -153,7 +153,7 @@ def expand_smooth(
|
||||
smooth_weight = nodes.new("ShaderNodeMath")
|
||||
smooth_weight.operation = "MULTIPLY"
|
||||
smooth_weight.location = (2300.0, 1050.0)
|
||||
links.new(weight_controls.outputs["Smooth"], smooth_weight.inputs[0])
|
||||
links.new(weight_controls.outputs[weight_name], smooth_weight.inputs[0])
|
||||
links.new(sharp_switch.outputs["Output"], smooth_weight.inputs[1])
|
||||
|
||||
target_position = nodes.new("GeometryNodeSwitch")
|
||||
@@ -178,4 +178,3 @@ def expand_smooth(
|
||||
for node in set(nodes) - existing_nodes:
|
||||
node.location.x += x_offset
|
||||
return repeat_output.outputs["Geometry"]
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ from anyimage.common.material import (
|
||||
)
|
||||
from anyimage.common.node import load_node_group, node_asset_path
|
||||
from anyimage.operators.cutout_tool.shape import (
|
||||
CUTOUT_NODE_GROUP_NAME,
|
||||
CUTOUT_NODE_GROUP_NAMES,
|
||||
)
|
||||
|
||||
@@ -41,9 +40,8 @@ def main():
|
||||
image_layer = load_node_group(IMAGE_MATERIAL_NODE_GROUP_NAME)
|
||||
depth_layer = load_node_group(DEPTH_MATERIAL_NODE_GROUP_NAME)
|
||||
shadeless = load_node_group("O Shadeless")
|
||||
cutout = load_node_group(CUTOUT_NODE_GROUP_NAME)
|
||||
cutout_groups = {
|
||||
name: bpy.data.node_groups[name] for name in CUTOUT_NODE_GROUP_NAMES.values()
|
||||
name: load_node_group(name) for name in set(CUTOUT_NODE_GROUP_NAMES.values())
|
||||
}
|
||||
expected_names = {
|
||||
"O Mesh Plane",
|
||||
@@ -51,7 +49,6 @@ def main():
|
||||
IMAGE_MATERIAL_NODE_GROUP_NAME,
|
||||
DEPTH_MATERIAL_NODE_GROUP_NAME,
|
||||
"O Shadeless",
|
||||
CUTOUT_NODE_GROUP_NAME,
|
||||
*CUTOUT_NODE_GROUP_NAMES.values(),
|
||||
}
|
||||
with bpy.data.libraries.load(str(node_asset_path()), link=False) as (source, _):
|
||||
@@ -115,19 +112,10 @@ def main():
|
||||
assert shadeless.bl_idname == "ShaderNodeTree"
|
||||
assert input_names(shadeless) == ["Color"]
|
||||
|
||||
assert cutout.name == CUTOUT_NODE_GROUP_NAME
|
||||
assert cutout.bl_idname == "GeometryNodeTree"
|
||||
assert cutout.is_modifier
|
||||
assert input_names(cutout)[:4] == [
|
||||
"Geometry",
|
||||
"Shape",
|
||||
"Inward Axis",
|
||||
"Thickness",
|
||||
]
|
||||
assert set(cutout_groups) == set(CUTOUT_NODE_GROUP_NAMES.values())
|
||||
for group in cutout_groups.values():
|
||||
assert group.bl_idname == "GeometryNodeTree"
|
||||
assert not group.is_modifier
|
||||
assert group.is_modifier
|
||||
assert input_names(group)[0] == "Geometry"
|
||||
|
||||
public_groups = {
|
||||
@@ -136,7 +124,7 @@ def main():
|
||||
image_layer,
|
||||
depth_layer,
|
||||
shadeless,
|
||||
cutout,
|
||||
*cutout_groups.values(),
|
||||
}
|
||||
loaded = {*public_groups, *cutout_groups.values()}
|
||||
for group in loaded:
|
||||
|
||||
@@ -1,676 +1,92 @@
|
||||
"""Validate direct Cutout assets and their evaluated defaults."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from collections import Counter
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
PROJECT_ROOT = Path(__file__).parents[2]
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
sys.path.insert(0, str(PROJECT_ROOT / "src"))
|
||||
sys.path.insert(
|
||||
0,
|
||||
str(next((PROJECT_ROOT / "src" / "anyimage" / "wheels").glob("blendjob-*.whl"))),
|
||||
str(next((ROOT / "src" / "anyimage" / "wheels").glob("blendjob-*.whl"))),
|
||||
)
|
||||
|
||||
from anyimage.operators.cutout_tool.object import load_cutout_node_group
|
||||
from anyimage.common.object import modifier_input_identifier, set_modifier_input
|
||||
from node_layout import validate_node_layout
|
||||
|
||||
from anyimage.common.object import (
|
||||
modifier_input_identifier,
|
||||
set_modifier_input,
|
||||
)
|
||||
from anyimage.operators.cutout_tool import object as cutout_objects
|
||||
from anyimage.operators.cutout_tool import shape as shapes
|
||||
|
||||
|
||||
def evaluated_mesh(obj):
|
||||
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
|
||||
result = evaluated.to_mesh()
|
||||
return evaluated, result
|
||||
|
||||
|
||||
def validate_depth_surface_layout(group):
|
||||
"""Check the geometry path, stage spacing and drawn node bounds."""
|
||||
nodes = [node for node in group.nodes if node.bl_idname != "NodeReroute"]
|
||||
main = [
|
||||
group.nodes[name]
|
||||
for name in (
|
||||
"Store Named Attribute",
|
||||
"Store Named Attribute.001",
|
||||
"Store Named Attribute.002",
|
||||
"Store Named Attribute.003",
|
||||
"Split Edges",
|
||||
"Switch",
|
||||
"Delete Geometry",
|
||||
"Store Named Attribute.004",
|
||||
"Set Position",
|
||||
"Store Named Attribute.005",
|
||||
"Set Position.001",
|
||||
"Store Named Attribute.006",
|
||||
"Store Named Attribute.007",
|
||||
"Repeat Input",
|
||||
"Extrude Mesh",
|
||||
"Separate Geometry",
|
||||
"Repeat Output",
|
||||
"Flip Faces.001",
|
||||
"Join Geometry.001",
|
||||
"Set Position.003",
|
||||
"Merge by Distance",
|
||||
"Set Position.004",
|
||||
"Switch.002",
|
||||
"Remove Named Attribute",
|
||||
"Set Shade Smooth",
|
||||
"Group Output",
|
||||
)
|
||||
]
|
||||
assert len({node.location.y for node in main}) == 1
|
||||
assert all(right.location.x > left.location.x for left, right in pairwise(main))
|
||||
for left, right in (
|
||||
("Switch", "Delete Geometry"),
|
||||
("Delete Geometry", "Store Named Attribute.004"),
|
||||
("Set Position", "Store Named Attribute.005"),
|
||||
("Switch.002", "Remove Named Attribute"),
|
||||
):
|
||||
a, b = group.nodes[left], group.nodes[right]
|
||||
assert b.location.x - (a.location.x + a.width) >= 280
|
||||
assert not any(n.bl_idname == "FunctionNodeInputString" for n in nodes)
|
||||
assert min(n.location.x for n in nodes) < main[0].location.x
|
||||
|
||||
def height(node):
|
||||
if node.dimensions.y:
|
||||
return node.dimensions.y
|
||||
if node.hide or node.bl_idname == "NodeReroute":
|
||||
return 30.0
|
||||
if node.bl_idname == "GeometryNodeJoinGeometry":
|
||||
return 60.0
|
||||
return node.height
|
||||
|
||||
for index, node in enumerate(nodes):
|
||||
width = node.dimensions.x or node.width
|
||||
for other in nodes[index + 1 :]:
|
||||
other_width = other.dimensions.x or other.width
|
||||
overlap = (
|
||||
node.location.x < other.location.x + other_width
|
||||
and node.location.x + width > other.location.x
|
||||
and node.location.y - height(node) < other.location.y
|
||||
and node.location.y > other.location.y - height(other)
|
||||
)
|
||||
assert not overlap, (node.name, other.name)
|
||||
repeat_input = next(
|
||||
node for node in nodes if node.bl_idname == "GeometryNodeRepeatInput"
|
||||
)
|
||||
repeat_output = repeat_input.paired_output
|
||||
inside = {repeat_output}
|
||||
pending = [repeat_input]
|
||||
while pending:
|
||||
node = pending.pop()
|
||||
if node in inside:
|
||||
continue
|
||||
inside.add(node)
|
||||
pending.extend(link.to_node for link in group.links if link.from_node == node)
|
||||
zone_bottom = min(node.location.y - height(node) for node in inside) - 60.0
|
||||
zone_top = max(node.location.y for node in inside) + 60.0
|
||||
for node in nodes:
|
||||
if repeat_input.location.x <= node.location.x <= repeat_output.location.x:
|
||||
assert (
|
||||
node in inside
|
||||
or node.location.y <= zone_bottom
|
||||
or node.location.y - height(node) >= zone_top
|
||||
), node.name
|
||||
|
||||
|
||||
def validate_depth_surface_attributes(group):
|
||||
"""Check temporary fields are typed, locally read and removed at output."""
|
||||
expected = {
|
||||
"o_depth_face_center": ("FLOAT_VECTOR", "FACE"),
|
||||
"o_depth_face_camera": ("FLOAT_VECTOR", "FACE"),
|
||||
"o_depth_corner_camera": ("FLOAT_VECTOR", "CORNER"),
|
||||
"o_depth_cut_vertex": ("BOOLEAN", "CORNER"),
|
||||
"o_depth_camera": ("FLOAT_VECTOR", "POINT"),
|
||||
"o_depth_surface_position": ("FLOAT_VECTOR", "POINT"),
|
||||
"o_depth_source_vertex": ("INT", "POINT"),
|
||||
"o_depth_wall_layers": ("FLOAT", "POINT"),
|
||||
}
|
||||
stores = {
|
||||
n.inputs["Name"].default_value: (n.data_type, n.domain)
|
||||
for n in group.nodes
|
||||
if n.bl_idname == "GeometryNodeStoreNamedAttribute"
|
||||
}
|
||||
assert stores == expected
|
||||
assert not any(n.bl_idname == "GeometryNodeCaptureAttribute" for n in group.nodes)
|
||||
removes = [n for n in group.nodes if n.bl_idname == "GeometryNodeRemoveAttribute"]
|
||||
assert len(removes) == 1
|
||||
assert removes[0].pattern_mode == "WILDCARD"
|
||||
assert removes[0].inputs["Name"].default_value == "o_depth_*"
|
||||
for node in group.nodes:
|
||||
if node.bl_idname == "GeometryNodeInputNamedAttribute":
|
||||
name = node.inputs["Name"].default_value
|
||||
assert name == "UVMap" or node.data_type == expected[name][0]
|
||||
assert all(
|
||||
abs(link.to_node.location.x - node.location.x) <= 600
|
||||
for link in group.links
|
||||
if link.from_node == node
|
||||
)
|
||||
|
||||
|
||||
def input_names(group):
|
||||
return [
|
||||
item.name
|
||||
for item in group.interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.in_out == "INPUT"
|
||||
]
|
||||
|
||||
|
||||
def grid_object(name):
|
||||
vertices = [(float(x), float(y), 0.0) for y in range(3) for x in range(3)]
|
||||
faces = []
|
||||
for y in range(2):
|
||||
for x in range(2):
|
||||
a = y * 3 + x
|
||||
faces.extend(((a, a + 1, a + 4), (a, a + 4, a + 3)))
|
||||
data = bpy.data.meshes.new(name)
|
||||
data.from_pydata(vertices, (), faces)
|
||||
uv_layer = data.uv_layers.new(name="UVMap")
|
||||
for loop in data.loops:
|
||||
coordinate = data.vertices[loop.vertex_index].co
|
||||
uv_layer.data[loop.index].uv = (coordinate.x * 0.5, coordinate.y * 0.5)
|
||||
obj = bpy.data.objects.new(name, data)
|
||||
bpy.context.scene.collection.objects.link(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def add_modifier(obj, shape, thickness):
|
||||
group = cutout_objects.load_cutout_node_group()
|
||||
modifier = obj.modifiers.new(group.name, "NODES")
|
||||
modifier.node_group = group
|
||||
for name, value in (
|
||||
("Shape", shapes.CUTOUT_SHAPE_INDICES[shape]),
|
||||
("Inward Axis", 0),
|
||||
("Cleanup", 0.0),
|
||||
("Smooth", 0.0),
|
||||
("Smooth Iterations", 0),
|
||||
("Thickness", thickness),
|
||||
):
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(group, name),
|
||||
value,
|
||||
)
|
||||
return modifier
|
||||
|
||||
|
||||
def main():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
wrapper = cutout_objects.load_cutout_node_group()
|
||||
assert all(
|
||||
cutout_objects.load_cutout_node_group() == wrapper
|
||||
for shape in shapes.CUTOUT_SHAPES
|
||||
)
|
||||
assert wrapper.name == shapes.CUTOUT_NODE_GROUP_NAME
|
||||
assert wrapper.is_modifier
|
||||
groups = {
|
||||
shape: bpy.data.node_groups[name]
|
||||
for shape, name in shapes.CUTOUT_NODE_GROUP_NAMES.items()
|
||||
}
|
||||
validate_depth_surface_layout(groups["DEPTH_SURFACE"])
|
||||
assert all(not group.is_modifier for group in groups.values())
|
||||
|
||||
menu_switch = next(
|
||||
node for node in wrapper.nodes if node.bl_idname == "GeometryNodeMenuSwitch"
|
||||
)
|
||||
assert [item.name for item in menu_switch.enum_items] == list(
|
||||
shapes.CUTOUT_SHAPE_LABELS.values()
|
||||
)
|
||||
assert any(
|
||||
link.from_socket.name == "Shape"
|
||||
and link.to_node == menu_switch
|
||||
and link.to_socket.name == "Menu"
|
||||
for link in wrapper.links
|
||||
)
|
||||
axis_switch = next(
|
||||
node
|
||||
for node in wrapper.nodes
|
||||
if node.bl_idname == "GeometryNodeMenuSwitch"
|
||||
and [item.name for item in node.enum_items] == ["-Z", "+X"]
|
||||
)
|
||||
assert any(
|
||||
link.from_socket.name == "Inward Axis"
|
||||
and link.to_node == axis_switch
|
||||
and link.to_socket.name == "Menu"
|
||||
for link in wrapper.links
|
||||
)
|
||||
assert all(
|
||||
any(
|
||||
link.to_node == axis_switch and link.to_socket.name == axis
|
||||
for link in wrapper.links
|
||||
)
|
||||
for axis in ("-Z", "+X")
|
||||
)
|
||||
negative_z_link = next(
|
||||
link
|
||||
for link in wrapper.links
|
||||
if link.to_node == axis_switch and link.to_socket.name == "-Z"
|
||||
)
|
||||
positive_x_link = next(
|
||||
link
|
||||
for link in wrapper.links
|
||||
if link.to_node == axis_switch and link.to_socket.name == "+X"
|
||||
)
|
||||
assert positive_x_link.from_node.bl_idname == "GeometryNodeTransform"
|
||||
assert any(
|
||||
link.from_socket == negative_z_link.from_socket
|
||||
and link.to_node == positive_x_link.from_node
|
||||
and link.to_socket.name == "Geometry"
|
||||
for link in wrapper.links
|
||||
)
|
||||
child_nodes = {
|
||||
node.node_tree: node
|
||||
for node in wrapper.nodes
|
||||
if node.bl_idname == "GeometryNodeGroup"
|
||||
}
|
||||
assert set(child_nodes) == set(groups.values())
|
||||
for shape, group in groups.items():
|
||||
assert any(
|
||||
link.from_node == child_nodes[group]
|
||||
and link.to_node == menu_switch
|
||||
and link.to_socket.name == shapes.CUTOUT_SHAPE_LABELS[shape]
|
||||
for link in wrapper.links
|
||||
)
|
||||
|
||||
assert input_names(wrapper) == [
|
||||
"Geometry",
|
||||
"Shape",
|
||||
"Inward Axis",
|
||||
"Thickness",
|
||||
"Depth Scale",
|
||||
"Double Sided",
|
||||
"Smooth Iterations",
|
||||
"Cleanup",
|
||||
"Smooth",
|
||||
"Split",
|
||||
"Reference Depth",
|
||||
"Depth Direction",
|
||||
"Uniform Scale",
|
||||
"Depth Image",
|
||||
]
|
||||
expected_inputs = {
|
||||
"SURFACE": ["Geometry", "Thickness"],
|
||||
"BALLOON": ["Geometry", "Thickness"],
|
||||
"DEPTH_BALLOON": [
|
||||
"Geometry",
|
||||
"Thickness",
|
||||
"Depth Scale",
|
||||
"Double Sided",
|
||||
"Reference Depth",
|
||||
"Depth Direction",
|
||||
"Uniform Scale",
|
||||
"Depth Image",
|
||||
],
|
||||
"DEPTH_SURFACE": [
|
||||
"Geometry",
|
||||
"Thickness",
|
||||
"Depth Scale",
|
||||
"Split",
|
||||
"Cleanup",
|
||||
"Reference Depth",
|
||||
"Uniform Scale",
|
||||
"Depth Image",
|
||||
],
|
||||
}
|
||||
for shape, group in groups.items():
|
||||
assert input_names(group) == expected_inputs[shape]
|
||||
|
||||
dependencies = {}
|
||||
for link in wrapper.links:
|
||||
if link.from_node.bl_idname != "NodeGroupInput":
|
||||
continue
|
||||
if link.to_node.bl_idname != "GeometryNodeGroup":
|
||||
continue
|
||||
shape = next(
|
||||
shape for shape, group in groups.items() if group == link.to_node.node_tree
|
||||
)
|
||||
dependencies.setdefault(link.from_socket.name, set()).add(shape)
|
||||
assert dependencies == {
|
||||
"Geometry": {"DEPTH_SURFACE"},
|
||||
"Thickness": set(shapes.CUTOUT_SHAPES),
|
||||
"Depth Scale": {"DEPTH_BALLOON", "DEPTH_SURFACE"},
|
||||
"Split": {"DEPTH_SURFACE"},
|
||||
"Double Sided": {"DEPTH_BALLOON"},
|
||||
"Reference Depth": {"DEPTH_BALLOON", "DEPTH_SURFACE"},
|
||||
"Depth Direction": {"DEPTH_BALLOON"},
|
||||
"Uniform Scale": {"DEPTH_BALLOON", "DEPTH_SURFACE"},
|
||||
"Depth Image": {"DEPTH_BALLOON", "DEPTH_SURFACE"},
|
||||
}
|
||||
|
||||
repeat_counts = {
|
||||
shape: sum(node.bl_idname == "GeometryNodeRepeatInput" for node in group.nodes)
|
||||
for shape, group in groups.items()
|
||||
}
|
||||
assert repeat_counts == {
|
||||
"SURFACE": 1,
|
||||
"BALLOON": 0,
|
||||
"DEPTH_BALLOON": 0,
|
||||
"DEPTH_SURFACE": 1,
|
||||
}
|
||||
assert (
|
||||
sum(node.bl_idname == "GeometryNodeRepeatInput" for node in wrapper.nodes) == 1
|
||||
)
|
||||
assert (
|
||||
sum(node.bl_idname == "GeometryNodeInputMeshIsland" for node in wrapper.nodes)
|
||||
== 1
|
||||
)
|
||||
assert not any(
|
||||
node.bl_idname == "GeometryNodeAttributeStatistic" for node in wrapper.nodes
|
||||
)
|
||||
assert all(
|
||||
not any(node.bl_idname == "GeometryNodeInputMeshIsland" for node in group.nodes)
|
||||
for shape, group in groups.items()
|
||||
if shape != "DEPTH_SURFACE"
|
||||
)
|
||||
assert any(node.bl_idname == "GeometryNodeBlurAttribute" for node in wrapper.nodes)
|
||||
smooth = next(
|
||||
item
|
||||
for item in wrapper.interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.name == "Smooth"
|
||||
)
|
||||
iterations = next(
|
||||
item
|
||||
for item in wrapper.interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.name == "Smooth Iterations"
|
||||
)
|
||||
cleanup = next(
|
||||
item
|
||||
for item in wrapper.interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.name == "Cleanup"
|
||||
)
|
||||
assert cleanup.default_value == 0.0
|
||||
assert cleanup.subtype == "NONE"
|
||||
split_control = next(
|
||||
item
|
||||
for item in wrapper.interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.name == "Split"
|
||||
)
|
||||
child_split = next(
|
||||
item
|
||||
for item in groups["DEPTH_SURFACE"].interface.items_tree
|
||||
if item.item_type == "SOCKET" and item.name == "Split"
|
||||
)
|
||||
assert split_control.default_value == 0.0
|
||||
assert split_control.min_value == 0.0
|
||||
assert split_control.max_value == 1.0
|
||||
assert split_control.subtype == "FACTOR"
|
||||
assert getattr(split_control.parent, "name", "") == "Options"
|
||||
assert child_split.default_value == 0.0
|
||||
assert child_split.min_value == 0.0
|
||||
assert child_split.max_value == 1.0
|
||||
assert child_split.subtype == "FACTOR"
|
||||
assert getattr(child_split.parent, "name", "") == "Options"
|
||||
depth_surface_nodes = groups["DEPTH_SURFACE"].nodes
|
||||
assert any(
|
||||
node.bl_idname == "GeometryNodeSplitEdges" for node in depth_surface_nodes
|
||||
)
|
||||
validate_depth_surface_attributes(groups["DEPTH_SURFACE"])
|
||||
assert [
|
||||
node.domain
|
||||
for node in depth_surface_nodes
|
||||
if node.bl_idname == "GeometryNodeDeleteGeometry"
|
||||
] == ["FACE"]
|
||||
assert "Stretch Limit" not in [
|
||||
item.name for item in groups["DEPTH_SURFACE"].interface.items_tree
|
||||
]
|
||||
assert all(
|
||||
socket.is_linked or socket.hide
|
||||
for node in depth_surface_nodes
|
||||
for socket in node.outputs
|
||||
)
|
||||
for node in depth_surface_nodes:
|
||||
if node.bl_idname == "GeometryNodeRepeatInput":
|
||||
assert node.paired_output.location.x > node.location.x
|
||||
cleanup_scale = next(
|
||||
link.to_node
|
||||
for link in wrapper.links
|
||||
if link.from_socket.name == "Cleanup"
|
||||
and link.from_node.bl_idname == "NodeGroupInput"
|
||||
)
|
||||
assert cleanup_scale.bl_idname == "ShaderNodeMath"
|
||||
assert cleanup_scale.operation == "MULTIPLY"
|
||||
assert abs(cleanup_scale.inputs[1].default_value - 0.01) < 1e-7
|
||||
assert smooth.default_value == 1.0
|
||||
assert iterations.default_value == 0
|
||||
assert iterations.min_value == 0
|
||||
assert getattr(iterations.parent, "name", "") == ""
|
||||
assert all(
|
||||
not any(node.bl_idname == "GeometryNodeBlurAttribute" for node in group.nodes)
|
||||
for group in groups.values()
|
||||
)
|
||||
|
||||
for group in (wrapper, *groups.values()):
|
||||
groups = {shape: load_cutout_node_group(shape) for shape in ("FLAT", "SOLID", "DEPTH_SOLID", "DEPTH_BALLOON")}
|
||||
assert groups["FLAT"] == groups["SOLID"]
|
||||
assert len(set(groups.values())) == 3
|
||||
for group in set(groups.values()):
|
||||
validate_node_layout(group)
|
||||
for item in group.interface.items_tree:
|
||||
if item.item_type == "SOCKET" and item.in_out == "INPUT":
|
||||
assert item.structure_type == "SINGLE"
|
||||
surface = grid_object("Surface Validation")
|
||||
add_modifier(surface, "SURFACE", 2.4)
|
||||
evaluated, result = evaluated_mesh(surface)
|
||||
try:
|
||||
assert len(result.vertices) == 34
|
||||
assert len(result.polygons) == 40
|
||||
side_faces = [
|
||||
polygon for polygon in result.polygons if abs(polygon.normal.z) < 0.1
|
||||
]
|
||||
assert len(side_faces) == 24
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
balloon = grid_object("Balloon Validation")
|
||||
profile = balloon.data.attributes.new(
|
||||
shapes.BALLOON_ATTRIBUTE_NAME, "FLOAT", "POINT"
|
||||
)
|
||||
profile.data.foreach_set(
|
||||
"value",
|
||||
(0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0),
|
||||
)
|
||||
modifier = add_modifier(balloon, "BALLOON", 1.0)
|
||||
evaluated, result = evaluated_mesh(balloon)
|
||||
try:
|
||||
initial_faces = len(result.polygons)
|
||||
initial_extent = max(abs(vertex.co.z) for vertex in result.vertices)
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(modifier.node_group, "Thickness"),
|
||||
2.0,
|
||||
)
|
||||
balloon.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(balloon)
|
||||
try:
|
||||
assert len(result.polygons) == initial_faces
|
||||
extent = max(abs(vertex.co.z) for vertex in result.vertices)
|
||||
assert abs(extent - initial_extent * 2.0) < 1e-5
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
depth_balloon = grid_object("Depth Balloon Metric Validation")
|
||||
profile = depth_balloon.data.attributes.new(
|
||||
shapes.BALLOON_ATTRIBUTE_NAME, "FLOAT", "POINT"
|
||||
)
|
||||
profile.data.foreach_set("value", (1.0,) * 9)
|
||||
modifier = add_modifier(depth_balloon, "DEPTH_BALLOON", 0.0)
|
||||
point_image = bpy.data.images.new(
|
||||
"Depth Balloon Points",
|
||||
width=3,
|
||||
height=3,
|
||||
alpha=True,
|
||||
float_buffer=True,
|
||||
)
|
||||
point_image.colorspace_settings.name = "Non-Color"
|
||||
point_image.alpha_mode = "CHANNEL_PACKED"
|
||||
pixels = []
|
||||
for z in range(3):
|
||||
for y in range(3):
|
||||
if (y, z) == (1, 1):
|
||||
depth = 1.5
|
||||
elif (y, z) == (0, 0):
|
||||
depth = 2.5
|
||||
assert group.is_modifier and group.get("anyimage_asset_revision") == 11
|
||||
assert not any(node.bl_idname == "GeometryNodeGroup" for node in group.nodes)
|
||||
inputs = {item.name: item for item in group.interface.items_tree if item.item_type == "SOCKET" and item.in_out == "INPUT"}
|
||||
assert "Shape" not in inputs and "Rim Thickness" not in inputs
|
||||
assert next(s for s in group.interface.items_tree if s.name == "Thickness").default_value == 1
|
||||
assert all(item.structure_type == "SINGLE" for item in inputs.values())
|
||||
if "Mode" in inputs:
|
||||
assert inputs["Thickness"].subtype == "DISTANCE"
|
||||
assert inputs["Mode"].default_value == "Balloon"
|
||||
if "Double Sided" in inputs:
|
||||
assert inputs["Double Sided"].default_value
|
||||
if group == groups["DEPTH_SOLID"]:
|
||||
assert np.isclose(inputs["Edge Round"].default_value, 0.2)
|
||||
assert inputs["Edge Round"].parent.name == "Options"
|
||||
assert list(inputs)[list(inputs).index("Front Inflation") - 1] == "Edge Round"
|
||||
assert inputs["Normal Smooth"].default_value == 50
|
||||
assert inputs["Front Inflation"].default_value == 1
|
||||
assert inputs["Front Inflation"].parent.name == "Options"
|
||||
assert not set(inputs) & {"Edge Round Range", "Back Rim Range", "Normal Influence", "Edge Round Amount", "Back Rim Fullness"}
|
||||
options = [s.name for s in inputs.values() if s.parent and s.parent.name == "Options"]
|
||||
expected = ["Cleanup Threshold"]
|
||||
if group == groups["DEPTH_SOLID"]:
|
||||
expected += ["Split Threshold", "Reference Depth", "Edge Round", "Front Inflation", "Normal Smooth"]
|
||||
elif group == groups["DEPTH_BALLOON"]:
|
||||
expected += ["Reference Depth"]
|
||||
expected += ["Smooth Weight"]
|
||||
if group == groups["DEPTH_BALLOON"]:
|
||||
expected += ["Depth Direction"]
|
||||
assert options == expected, (group.name, options)
|
||||
assert inputs["Smooth"].socket_type == "NodeSocketInt" and inputs["Smooth"].default_value == 0
|
||||
assert inputs["Smooth Weight"].default_value == 1
|
||||
incoming = [link for link in group.links if link.from_node.bl_idname == "NodeGroupInput" and link.from_socket.name == "Geometry"]
|
||||
assert len(incoming) == 1 and incoming[0].to_node.bl_idname == "GeometryNodeDeleteGeometry"
|
||||
mesh = bpy.data.meshes.new("Profile")
|
||||
mesh.from_pydata([(-1,-1,0), (1,-1,0), (1,1,0), (-1,1,0), (0,0,0)], [], [(0,1,4), (1,2,4), (2,3,4), (3,0,4)])
|
||||
profile = mesh.attributes.new("o_balloon", "FLOAT", "POINT")
|
||||
profile.data.foreach_set("value", [0,0,0,0,0.6])
|
||||
obj = bpy.data.objects.new("Profile", mesh)
|
||||
bpy.context.collection.objects.link(obj)
|
||||
modifier = obj.modifiers.new("Cutout", "NODES")
|
||||
modifier.node_group = groups["SOLID"]
|
||||
for mode, thickness in ((0, 0), (0, 1), (1, 0), (1, 0.4)):
|
||||
for name, value in (("Mode", mode), ("Thickness", thickness)):
|
||||
subtype = ("DISTANCE" if mode else "NONE") if name == "Thickness" else None
|
||||
set_modifier_input(modifier, modifier_input_identifier(modifier.node_group, name, subtype=subtype), value)
|
||||
obj.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
|
||||
result = evaluated.to_mesh()
|
||||
try:
|
||||
z = np.array([vertex.co.z for vertex in result.vertices])
|
||||
assert np.isfinite(z).all() and len(z)
|
||||
if thickness == 0:
|
||||
assert len(result.polygons) == 4 and np.max(abs(z)) < 1e-7
|
||||
assert all(abs(item.value - 1) < 1e-7 for item in result.attributes["o_normal_scale"].data)
|
||||
else:
|
||||
depth = 2.0
|
||||
pixels.extend((0.0, 0.0, depth, 0.0))
|
||||
point_image.pixels.foreach_set(pixels)
|
||||
for name, value in (
|
||||
("Depth Image", point_image),
|
||||
("Depth Scale", 1.0),
|
||||
("Uniform Scale", 1.0),
|
||||
("Reference Depth", 2.0),
|
||||
("Depth Direction", (0.0, 0.0, 1.0)),
|
||||
):
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(modifier.node_group, name),
|
||||
value,
|
||||
)
|
||||
depth_balloon.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_balloon)
|
||||
try:
|
||||
z_values = [vertex.co.z for vertex in result.vertices]
|
||||
assert abs(min(z_values)) < 1e-5
|
||||
assert abs(max(z_values) - 0.5) < 1e-5
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
pixels[(1 * 3 + 1) * 4 + 3] = -1.0
|
||||
point_image.pixels.foreach_set(pixels)
|
||||
point_image.update()
|
||||
depth_balloon.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_balloon)
|
||||
try:
|
||||
z_values = [vertex.co.z for vertex in result.vertices]
|
||||
assert abs(min(z_values)) < 1e-5
|
||||
assert abs(max(z_values) - 0.5) < 1e-5
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
depth_surface = grid_object("Depth Surface Projection Validation")
|
||||
modifier = add_modifier(depth_surface, "DEPTH_SURFACE", 0.0)
|
||||
point_image = bpy.data.images.new(
|
||||
"Depth Surface Points",
|
||||
width=3,
|
||||
height=3,
|
||||
alpha=True,
|
||||
float_buffer=True,
|
||||
)
|
||||
point_image.colorspace_settings.name = "Non-Color"
|
||||
point_image.alpha_mode = "CHANNEL_PACKED"
|
||||
pixels = []
|
||||
for y in range(3):
|
||||
for x in range(3):
|
||||
depth = 7.0 if (x, y) == (0, 0) else 2.0 + x * 0.25
|
||||
pixels.extend((x * 0.5, -y * 0.5, depth, 0.0))
|
||||
point_image.pixels.foreach_set(pixels)
|
||||
for name, value in (
|
||||
("Depth Image", point_image),
|
||||
("Depth Scale", 1.0),
|
||||
("Uniform Scale", 1.0),
|
||||
("Reference Depth", 2.0),
|
||||
("Smooth Iterations", 0),
|
||||
):
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(modifier.node_group, name),
|
||||
value,
|
||||
)
|
||||
depth_surface.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_surface)
|
||||
try:
|
||||
coordinates = [tuple(vertex.co) for vertex in result.vertices]
|
||||
assert all(
|
||||
all(
|
||||
abs(actual - expected) < 1e-5 for actual, expected in zip(point, target)
|
||||
)
|
||||
for point, target in zip(
|
||||
coordinates,
|
||||
(
|
||||
(
|
||||
x * 0.5,
|
||||
y * 0.5,
|
||||
-5.0 if (x, y) == (0, 0) else -x * 0.25,
|
||||
)
|
||||
for y in range(3)
|
||||
for x in range(3)
|
||||
),
|
||||
)
|
||||
)
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(modifier.node_group, "Split"),
|
||||
0.6,
|
||||
)
|
||||
depth_surface.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_surface)
|
||||
try:
|
||||
assert len(result.polygons) == 8
|
||||
face_edges = {
|
||||
tuple(sorted((start, end)))
|
||||
for polygon in result.polygons
|
||||
for start, end in zip(
|
||||
polygon.vertices,
|
||||
(*polygon.vertices[1:], polygon.vertices[0]),
|
||||
)
|
||||
}
|
||||
assert all(tuple(sorted(edge.vertices)) in face_edges for edge in result.edges)
|
||||
face_vertices = {
|
||||
vertex for polygon in result.polygons for vertex in polygon.vertices
|
||||
}
|
||||
assert face_vertices == set(range(len(result.vertices)))
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
set_modifier_input(
|
||||
modifier,
|
||||
modifier_input_identifier(modifier.node_group, "Depth Scale"),
|
||||
0.0,
|
||||
)
|
||||
depth_surface.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_surface)
|
||||
try:
|
||||
assert len(result.vertices) == 9
|
||||
assert len(result.polygons) == 8
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
set_modifier_input(
|
||||
modifier, modifier_input_identifier(modifier.node_group, "Depth Scale"), 1.0
|
||||
)
|
||||
set_modifier_input(
|
||||
modifier, modifier_input_identifier(modifier.node_group, "Thickness"), 0.2
|
||||
)
|
||||
depth_surface.update_tag(refresh={"DATA"})
|
||||
bpy.context.view_layer.update()
|
||||
evaluated, result = evaluated_mesh(depth_surface)
|
||||
try:
|
||||
edge_uses = Counter(
|
||||
tuple(sorted((a, b)))
|
||||
for face in result.polygons
|
||||
for a, b in zip(face.vertices, (*face.vertices[1:], face.vertices[0]))
|
||||
)
|
||||
assert edge_uses and set(edge_uses.values()) == {2}
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
|
||||
print(
|
||||
f"Validated Blender {bpy.app.version_string}: "
|
||||
f"{wrapper.name} wrapping "
|
||||
f"{', '.join(group.name for group in groups.values())}"
|
||||
)
|
||||
radius = 0.6 if mode == 0 else 0.2
|
||||
assert np.isclose(z.min(), -radius) and np.isclose(z.max(), radius)
|
||||
uses = Counter(tuple(sorted((a,b))) for face in result.polygons for a,b in zip(face.vertices, (*face.vertices[1:],face.vertices[0])))
|
||||
assert set(uses.values()) == {2}
|
||||
finally:
|
||||
evaluated.to_mesh_clear()
|
||||
print("Validated three Cutout assets, four presets, both thickness modes and closed defaults")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
198
tools/pisa_sr_export.py
Normal file
198
tools/pisa_sr_export.py
Normal file
@@ -0,0 +1,198 @@
|
||||
# /// script
|
||||
# requires-python = "==3.11.*"
|
||||
# dependencies = [
|
||||
# "torch==2.7.1", "torchvision==0.22.1", "diffusers==0.25.0",
|
||||
# "transformers==4.28.1", "peft==0.9.0", "accelerate==0.27.2",
|
||||
# "huggingface-hub==0.25.2", "numpy==1.26.4", "onnx==1.19.0",
|
||||
# ]
|
||||
# [tool.uv.sources]
|
||||
# torch = { index = "pytorch" }
|
||||
# torchvision = { index = "pytorch" }
|
||||
# [[tool.uv.index]]
|
||||
# name = "pytorch"
|
||||
# url = "https://download.pytorch.org/whl/cu128"
|
||||
# explicit = true
|
||||
# ///
|
||||
"""Export PiSA-SR components from pinned upstream weights on CUDA."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE_COMMIT = "9c76e12e261d1980148738a0cff41e5e27d18c9f"
|
||||
BASE_REPOSITORY = "sd2-community/stable-diffusion-2-1-base"
|
||||
BASE_REVISION = "4e63672c03103b6c636b8fb4119ba982469b2955"
|
||||
CHECKPOINT_SHA256 = "13502f7bde5e4e585f84f24c3d904d9c848e068bf89f984046fe87da81a391f6"
|
||||
CHECKPOINT_URL = "https://drive.google.com/uc?export=download&id=1PWFM5zUd6lNMOyKX64anvUXhKEOCrf8L"
|
||||
|
||||
|
||||
def finalize_assets(destination):
|
||||
import shutil
|
||||
import onnx
|
||||
|
||||
for path in destination.glob("*.onnx"):
|
||||
model = onnx.load(path)
|
||||
onnx.helper.set_model_props(model, {
|
||||
"license": "Apache-2.0; CreativeML Open RAIL++-M (LICENSE-MODEL.txt)",
|
||||
"modifications": "AnyImage: merged PiSA-SR LoRA; FP16; fixed empty prompt and timestep; split VAE. See NOTICE.txt.",
|
||||
"source_commit": SOURCE_COMMIT,
|
||||
})
|
||||
onnx.save(model, path)
|
||||
for path in (Path(__file__).parent / "model_licenses/pisa-sr").glob("*.txt"):
|
||||
shutil.copyfile(path, destination / path.name)
|
||||
|
||||
|
||||
def prepare_sources(cache):
|
||||
import io
|
||||
import zipfile
|
||||
from urllib.request import urlopen
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
source = cache / f"PiSA-SR-{SOURCE_COMMIT}"
|
||||
if not source.exists():
|
||||
url = f"https://codeload.github.com/csslc/PiSA-SR/zip/{SOURCE_COMMIT}"
|
||||
with urlopen(url, timeout=60) as response:
|
||||
archive = zipfile.ZipFile(io.BytesIO(response.read()))
|
||||
for member in archive.infolist():
|
||||
destination = (cache / member.filename).resolve()
|
||||
if not destination.is_relative_to(cache.resolve()):
|
||||
raise ValueError("Invalid upstream archive path")
|
||||
archive.extractall(cache)
|
||||
checkpoint = cache / "pisa_sr.pkl"
|
||||
if not checkpoint.exists():
|
||||
with urlopen(CHECKPOINT_URL, timeout=60) as response:
|
||||
checkpoint.write_bytes(response.read())
|
||||
if hashlib.sha256(checkpoint.read_bytes()).hexdigest() != CHECKPOINT_SHA256:
|
||||
raise ValueError("PiSA-SR checkpoint checksum mismatch")
|
||||
base = snapshot_download(
|
||||
BASE_REPOSITORY, revision=BASE_REVISION, local_dir=cache / "base-model",
|
||||
allow_patterns=["*/*.json", "tokenizer/*", "*/*.fp16.safetensors"],
|
||||
)
|
||||
return source, Path(base), checkpoint
|
||||
|
||||
|
||||
def export_components(source, base, checkpoint, destination):
|
||||
import gc
|
||||
import numpy as np
|
||||
import torch
|
||||
from peft import LoraConfig
|
||||
from diffusers.utils import set_weights_and_activate_adapters
|
||||
from transformers import AutoTokenizer, CLIPTextModel
|
||||
|
||||
if hashlib.sha256(checkpoint.read_bytes()).hexdigest() != CHECKPOINT_SHA256:
|
||||
raise ValueError("PiSA-SR checkpoint checksum mismatch")
|
||||
sys.path.insert(0, str(source))
|
||||
from src.models.autoencoder_kl import AutoencoderKL
|
||||
from src.models.unet_2d_condition import UNet2DConditionModel
|
||||
|
||||
class Residual(torch.nn.Module):
|
||||
def __init__(self, model, prompt):
|
||||
super().__init__()
|
||||
self.model = model
|
||||
self.register_buffer("prompt", prompt)
|
||||
self.register_buffer("timestep", torch.tensor([1], dtype=torch.long))
|
||||
|
||||
def forward(self, latent):
|
||||
return self.model(latent, self.timestep, encoder_hidden_states=self.prompt).sample
|
||||
|
||||
class Encoder(torch.nn.Module):
|
||||
def __init__(self, model):
|
||||
super().__init__()
|
||||
self.encoder = model.encoder
|
||||
self.quant_conv = model.quant_conv
|
||||
|
||||
def forward(self, image):
|
||||
return self.quant_conv(self.encoder(image))
|
||||
|
||||
class Decoder(torch.nn.Module):
|
||||
def __init__(self, model):
|
||||
super().__init__()
|
||||
self.decoder = model.decoder
|
||||
self.post_quant_conv = model.post_quant_conv
|
||||
|
||||
def forward(self, latent):
|
||||
return self.decoder(self.post_quant_conv(latent / 0.18215)).clamp(-1, 1)
|
||||
|
||||
def export(wrapper, component, tensor):
|
||||
wrapper.eval().cuda()
|
||||
with torch.inference_mode():
|
||||
torch.onnx.export(
|
||||
wrapper, (tensor.cuda(),), str(destination / f"{component}.onnx"),
|
||||
opset_version=17, input_names=["input"], output_names=["output"],
|
||||
do_constant_folding=True, dynamo=False,
|
||||
)
|
||||
wrapper.cpu()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
torch.set_num_threads(8)
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
tokenizer = AutoTokenizer.from_pretrained(base, subfolder="tokenizer")
|
||||
text = CLIPTextModel.from_pretrained(
|
||||
base, subfolder="text_encoder", variant="fp16", torch_dtype=torch.float16,
|
||||
).eval().cuda()
|
||||
with torch.inference_mode():
|
||||
tokens = tokenizer("", max_length=tokenizer.model_max_length,
|
||||
padding="max_length", truncation=True, return_tensors="pt")
|
||||
prompt = text(tokens.input_ids.cuda())[0].cpu()
|
||||
del text
|
||||
torch.cuda.empty_cache()
|
||||
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
||||
latent = torch.zeros((1, 4, 64, 64), dtype=torch.float16)
|
||||
unet = UNet2DConditionModel.from_pretrained(base, subfolder="unet", variant="fp16")
|
||||
for strength, component in (("pix", "unet-pixel"), ("sem", "unet-full")):
|
||||
adapters = []
|
||||
for part in ("encoder", "decoder", "others"):
|
||||
key = f"{part}_modules"
|
||||
config = LoraConfig(
|
||||
r=state[f"lora_rank_unet_{strength}"], init_lora_weights="gaussian",
|
||||
target_modules=state[f"unet_lora_{key}_{strength}"],
|
||||
)
|
||||
name = f"default_{part}_{strength}"
|
||||
unet.add_adapter(config, adapter_name=name)
|
||||
adapters.append(name)
|
||||
for name, parameter in unet.named_parameters():
|
||||
if "lora" in name:
|
||||
parameter.data.copy_(state["state_dict_unet"][name])
|
||||
set_weights_and_activate_adapters(unet, adapters, [1.0]*3)
|
||||
unet.merge_and_unload()
|
||||
# Export a half-precision copy; retain FP32 weights for the semantic merge.
|
||||
import copy
|
||||
wrapper = Residual(copy.deepcopy(unet).half(), prompt)
|
||||
export(wrapper, component, latent)
|
||||
del wrapper
|
||||
gc.collect()
|
||||
del unet, state
|
||||
gc.collect()
|
||||
vae = AutoencoderKL.from_pretrained(base, subfolder="vae", variant="fp16", torch_dtype=torch.float16)
|
||||
export(Encoder(vae), "encoder", torch.zeros((1,3,512,512), dtype=torch.float16))
|
||||
export(Decoder(vae), "decoder", latent)
|
||||
torch.manual_seed(42)
|
||||
np.save(destination / "noise.npy", torch.randn((1,4,64,64), device="cuda", dtype=torch.float16).cpu().numpy())
|
||||
finalize_assets(destination)
|
||||
files = []
|
||||
for path in sorted(destination.iterdir()):
|
||||
if path.suffix in (".onnx", ".npy", ".txt"):
|
||||
with path.open("rb") as stream:
|
||||
checksum = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
files.append((path.name, path.stat().st_size, checksum))
|
||||
(destination / "provenance.json").write_text(json.dumps({
|
||||
"source_commit": SOURCE_COMMIT, "base_repository": BASE_REPOSITORY,
|
||||
"base_revision": BASE_REVISION, "checkpoint_sha256": CHECKPOINT_SHA256,
|
||||
"licenses": ["Apache-2.0", "CreativeML Open RAIL++-M"], "files": files,
|
||||
}, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--cache", type=Path, default=Path(".model-cache/pisa-sr"))
|
||||
parser.add_argument("--destination", type=Path, default=Path("models/pisa-sr"))
|
||||
args = parser.parse_args()
|
||||
args.cache.mkdir(parents=True, exist_ok=True)
|
||||
export_components(*prepare_sources(args.cache), args.destination)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -193,6 +193,14 @@ def prepare_model(model):
|
||||
if model.build:
|
||||
build_model(model)
|
||||
return
|
||||
if model.key == "PISA_SR":
|
||||
subprocess.run(
|
||||
["uv", "run", "--script", str(PROJECT_ROOT / "tools/pisa_sr_export.py")],
|
||||
cwd=PROJECT_ROOT, check=True,
|
||||
)
|
||||
if not verify_file(model.destination, model.size, model.sha256):
|
||||
raise RuntimeError("PiSA-SR export differs from the published catalog")
|
||||
return
|
||||
if not model.source_url:
|
||||
raise RuntimeError(f"No upstream source or builder for {model.key}")
|
||||
download_file(
|
||||
|
||||
Reference in New Issue
Block a user