Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

ComfyUI-SculptForge: custom node pack for ComfyUI

islandmedd27179d5d65a
diff --git a/integrations/comfyui/ComfyUI-SculptForge/.gitignore b/integrations/comfyui/ComfyUI-SculptForge/.gitignore
new file mode 100644
index 00000000..7a60b85e
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/.gitignore
@@ -0,0 +1,2 @@
+__pycache__/
+*.pyc
diff --git a/integrations/comfyui/ComfyUI-SculptForge/LICENSE b/integrations/comfyui/ComfyUI-SculptForge/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/integrations/comfyui/ComfyUI-SculptForge/README.md b/integrations/comfyui/ComfyUI-SculptForge/README.md
new file mode 100644
index 00000000..397ea4c8
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/README.md
@@ -0,0 +1,120 @@
+# ComfyUI-SculptForge
+
+[SculptForge](https://github.com/islandmed/SculptForge) nodes for [ComfyUI](https://github.com/comfyanonymous/ComfyUI):
+turn the meshes your graphs generate (Hunyuan3D, TRELLIS, or a quick sketch inflate) into **sculpt-ready**,
+**game-ready** and **VFX-ready** assets without leaving ComfyUI.
+
+- **Voxel Remesh** (like DynaMesh) rebuilds noisy, broken or self-intersecting AI meshes as one clean, watertight
+ sculpting surface.
+- **Decimate**, **Subdivide** and **LOD Chain** for game budgets.
+- **Export** to GLB, FBX (Unreal, Unity, Maya), USDA/USDZ (VFX pipelines, Apple AR), OBJ, STL (3D printing) or PLY.
+- **Inflate Image** turns a sketch or silhouette into a 3D base mesh in a second on the CPU, no GPU or model download.
+- Works with ComfyUI's own 3D nodes: every SculptForge mesh input also takes the core `MESH` type, and
+ *SculptForge to MESH* goes the other way.
+- **Open in SculptForge** sends the result to the desktop app to keep sculpting.
+
+The nodes run the free `sculptforge-cli` command-line tool, so they add no Python dependencies to ComfyUI.
+
+## Install
+
+### 1. Install SculptForge
+
+Download it from the [SculptForge releases](https://github.com/islandmed/SculptForge/releases/latest) (Windows,
+macOS, Linux) or build it from source. The nodes look for `sculptforge-cli` in this order:
+
+1. the `SCULPTFORGE_CLI` environment variable (the full path of the executable, or the folder it is in),
+2. your `PATH`,
+3. the usual install folders: `C:\Program Files\SculptForge`, `%LOCALAPPDATA%\Programs\SculptForge`,
+ `/Applications/SculptForge.app/Contents/MacOS`, `/usr/bin`, `/usr/local/bin`, `~/.local/bin`, `/opt/sculptforge/bin`.
+
+If it lives anywhere else, set the variable before starting ComfyUI:
+
+```sh
+# Linux / macOS
+export SCULPTFORGE_CLI=/path/to/sculptforge-cli
+python main.py
+```
+
+```bat
+:: Windows
+set SCULPTFORGE_CLI=D:\Tools\SculptForge\sculptforge-cli.exe
+python main.py
+```
+
+*Open in SculptForge* finds the desktop app next to the CLI, or set `SCULPTFORGE_APP`.
+
+### 2. Install the nodes
+
+**ComfyUI-Manager:** search for **SculptForge** in *Custom Nodes Manager* and click *Install*, or with comfy-cli:
+
+```sh
+comfy node install comfyui-sculptforge
+```
+
+**Manually:** the pack lives in the SculptForge repository, in `integrations/comfyui/ComfyUI-SculptForge`. Clone the
+repository and link (or copy) that folder into `ComfyUI/custom_nodes`:
+
+```sh
+git clone --depth 1 https://github.com/islandmed/SculptForge.git
+ln -s "$PWD/SculptForge/integrations/comfyui/ComfyUI-SculptForge" ComfyUI/custom_nodes/ComfyUI-SculptForge
+```
+
+On Windows, copy the folder, or use `mklink /D` from an administrator prompt. Restart ComfyUI; the nodes appear under
+**SculptForge** in the node library.
+
+## Nodes
+
+| Node | Inputs | Outputs | What it does |
+|---|---|---|---|
+| **SculptForge Load Mesh** | `path` | `mesh` | Loads OBJ, FBX, GLB/glTF, PLY, STL, USD/USDA/USDZ, ZBrush GoZ or a SculptForge `.sfproj`. Relative paths are looked up in ComfyUI's `input` folder (e.g. `3d/rock.glb`). |
+| **SculptForge Inflate Image** | `image`, optional `mask`, `thickness`, `resolution`, `subdivisions` | `mesh` | Inflates a sketch or silhouette into a rounded, closed base mesh. Connect *Load Image*'s `MASK` so the transparent background is left out; a plain backdrop works too. Uses the first image of a batch. |
+| **SculptForge Image Relief** | `image`, `depth`, `resolution`, `invert` | `mesh` | Turns an image into a relief: light areas rise (logos, coins, emblems, height maps). |
+| **SculptForge Voxel Remesh** | `mesh`, `resolution` (32-512) | `mesh` | Rebuilds the mesh as an even, watertight surface (like DynaMesh); fixes broken scans and generated models. |
+| **SculptForge Decimate** | `mesh`, `ratio`, `triangles` | `mesh` | Reduces the triangle count, keeping the shape. `triangles` > 0 sets an exact target instead of the ratio. |
+| **SculptForge Subdivide** | `mesh`, `levels` (1-4) | `mesh` | Loop subdivision; each level multiplies the triangles by 4. |
+| **SculptForge LOD Chain** | `mesh`, `levels`, `ratio`, `filename_prefix` | `file_paths` | Saves `<prefix>_00001_LOD0.glb`, `_LOD1.glb`... to the output folder. |
+| **SculptForge Export** | `mesh`, `format`, `filename_prefix` | `file_path` | Saves GLB, FBX, USDA, USDZ, OBJ, STL or PLY to the output folder, numbered like ComfyUI's save nodes. |
+| **SculptForge Mesh Info** | `mesh` | `info` | Vertex and triangle counts, bounds and SubTools, shown on the node. |
+| **SculptForge to MESH** | `mesh` | `MESH` | Converts to ComfyUI's core `MESH` (with normals and vertex colours) for *Save 3D Model*, *Preview 3D* and the other core 3D nodes. |
+| **Open in SculptForge** | `enabled`, optional `mesh` or `file_path` | | Opens the mesh, or an exported file, in the SculptForge desktop app. Only useful when ComfyUI runs on your own computer. |
+
+Every `mesh` input accepts both SculptForge meshes (`SF_MESH`) and ComfyUI's core `MESH`, so you can wire
+*VAE Decode Hunyuan3D → Voxel to Mesh* straight into *SculptForge Voxel Remesh*. Between SculptForge nodes the mesh
+stays a SculptForge project in ComfyUI's temp folder, so polygroups, polypaint and sculpt layers survive every step.
+
+Exported files are listed in the node's UI output under `3d` (`filename`, `subfolder`, `type: "output"`), the same
+way ComfyUI's *Save 3D Model* reports them, so API clients (including SculptForge's own ComfyUI generator) can
+download them from `/view`.
+
+## Examples
+
+The [`examples`](examples) folder has workflows in ComfyUI's API format (load them with *Workflow → Open*, or
+queue them with `POST /prompt`):
+
+- [`inflate-remesh-export.json`](examples/inflate-remesh-export.json): *Load Image* → *Inflate Image* → *Voxel
+ Remesh* → *Export* GLB. Runs in a few seconds on a CPU. Put [`teddy.png`](examples/teddy.png) in ComfyUI's `input`
+ folder to try it.
+- [`hunyuan3d-remesh-lods.json`](examples/hunyuan3d-remesh-lods.json): ComfyUI's core Hunyuan3D 2.1 image-to-3D graph
+ feeding *Voxel Remesh*, then a sculpt-ready GLB, a 4-level game LOD chain and a USDZ. Needs the Hunyuan3D 2.1
+ checkpoint in `models/checkpoints` and a GPU.
+- [`core-mesh-roundtrip.json`](examples/core-mesh-roundtrip.json): SculptForge → core `MESH` (*Get Mesh Info*, *Save
+ 3D Model*) → back into SculptForge for *Voxel Remesh*, *Decimate*, an LOD chain and an FBX.
+
+The `LoadImage` nodes are titled `sf_image`, so SculptForge's ComfyUI generator can run these workflows too.
+
+## Development
+
+The tests need numpy, torch and Pillow (use ComfyUI's Python environment) plus pytest:
+
+```sh
+python -m pytest # unit tests with a fake sculptforge-cli, plus real-CLI tests if it is installed
+COMFYUI_DIR=/path/to/ComfyUI SCULPTFORGE_CLI=/path/to/sculptforge-cli python -m pytest tests/test_comfyui_e2e.py
+```
+
+The end-to-end test starts its own ComfyUI on port 8189 (`SF_COMFYUI_PORT`) with this pack linked into a throwaway
+`custom_nodes`, checks the nodes register in `/object_info`, queues the example workflows through the HTTP API and
+opens the exported files with `sculptforge-cli`. Set `COMFYUI_PYTHON` if ComfyUI uses another interpreter.
+
+## License
+
+GPL-3.0-or-later, like SculptForge. See [LICENSE](LICENSE).
diff --git a/integrations/comfyui/ComfyUI-SculptForge/__init__.py b/integrations/comfyui/ComfyUI-SculptForge/__init__.py
new file mode 100644
index 00000000..d70f7b79
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/__init__.py
@@ -0,0 +1,6 @@
+# ComfyUI-SculptForge: SculptForge nodes for ComfyUI (remesh, decimate, LODs, export to GLB/FBX/USD).
+# SPDX-License-Identifier: GPL-3.0-or-later
+if __package__: # loaded by ComfyUI as a package (pytest imports this file on its own)
+ from .sculptforge_comfy import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
+
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
diff --git a/integrations/comfyui/ComfyUI-SculptForge/examples/core-mesh-roundtrip.json b/integrations/comfyui/ComfyUI-SculptForge/examples/core-mesh-roundtrip.json
new file mode 100644
index 00000000..85ba5842
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/examples/core-mesh-roundtrip.json
@@ -0,0 +1,52 @@
+{
+ "1": {
+ "class_type": "LoadImage",
+ "inputs": {"image": "teddy.png"},
+ "_meta": {"title": "sf_image"}
+ },
+ "2": {
+ "class_type": "SculptForgeInflateImage",
+ "inputs": {"image": ["1", 0], "mask": ["1", 1], "thickness": 0.8, "resolution": 128, "subdivisions": 1},
+ "_meta": {"title": "SculptForge Inflate Image"}
+ },
+ "3": {
+ "class_type": "SculptForgeToMesh",
+ "inputs": {"mesh": ["2", 0]},
+ "_meta": {"title": "SculptForge to MESH"}
+ },
+ "4": {
+ "class_type": "GetMeshInfo",
+ "inputs": {"mesh": ["3", 0]},
+ "_meta": {"title": "Get Mesh Info (core)"}
+ },
+ "5": {
+ "class_type": "SaveGLB",
+ "inputs": {"mesh": ["4", 0], "filename_prefix": "3d/core_save"},
+ "_meta": {"title": "Save 3D Model (core)"}
+ },
+ "6": {
+ "class_type": "SculptForgeVoxelRemesh",
+ "inputs": {"mesh": ["4", 0], "resolution": 160},
+ "_meta": {"title": "SculptForge Voxel Remesh (core MESH in)"}
+ },
+ "7": {
+ "class_type": "SculptForgeDecimate",
+ "inputs": {"mesh": ["6", 0], "ratio": 0.5, "triangles": 0},
+ "_meta": {"title": "SculptForge Decimate"}
+ },
+ "8": {
+ "class_type": "SculptForgeMeshInfo",
+ "inputs": {"mesh": ["7", 0]},
+ "_meta": {"title": "SculptForge Mesh Info"}
+ },
+ "9": {
+ "class_type": "SculptForgeLODChain",
+ "inputs": {"mesh": ["7", 0], "levels": 3, "ratio": 0.5, "filename_prefix": "3d/SculptForge_roundtrip_lods"},
+ "_meta": {"title": "SculptForge LOD Chain"}
+ },
+ "10": {
+ "class_type": "SculptForgeExport",
+ "inputs": {"mesh": ["7", 0], "format": "fbx", "filename_prefix": "3d/SculptForge_roundtrip"},
+ "_meta": {"title": "SculptForge Export"}
+ }
+}
diff --git a/integrations/comfyui/ComfyUI-SculptForge/examples/hunyuan3d-remesh-lods.json b/integrations/comfyui/ComfyUI-SculptForge/examples/hunyuan3d-remesh-lods.json
new file mode 100644
index 00000000..195c7c62
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/examples/hunyuan3d-remesh-lods.json
@@ -0,0 +1,70 @@
+{
+ "1": {
+ "class_type": "ImageOnlyCheckpointLoader",
+ "inputs": {"ckpt_name": "hunyuan_3d_v2.1.safetensors"},
+ "_meta": {"title": "Load Hunyuan3D 2.1 (models/checkpoints)"}
+ },
+ "2": {
+ "class_type": "LoadImage",
+ "inputs": {"image": "teddy.png"},
+ "_meta": {"title": "sf_image"}
+ },
+ "3": {
+ "class_type": "ModelSamplingAuraFlow",
+ "inputs": {"model": ["1", 0], "shift": 1.0},
+ "_meta": {"title": "ModelSamplingAuraFlow"}
+ },
+ "4": {
+ "class_type": "CLIPVisionEncode",
+ "inputs": {"clip_vision": ["1", 1], "image": ["2", 0], "crop": "center"},
+ "_meta": {"title": "CLIP Vision Encode"}
+ },
+ "5": {
+ "class_type": "Hunyuan3Dv2Conditioning",
+ "inputs": {"clip_vision_output": ["4", 0]},
+ "_meta": {"title": "Hunyuan3Dv2 Conditioning"}
+ },
+ "6": {
+ "class_type": "EmptyLatentHunyuan3Dv2",
+ "inputs": {"resolution": 4096, "batch_size": 1},
+ "_meta": {"title": "Empty Latent Hunyuan3Dv2"}
+ },
+ "7": {
+ "class_type": "KSampler",
+ "inputs": {
+ "model": ["3", 0], "positive": ["5", 0], "negative": ["5", 1], "latent_image": ["6", 0],
+ "seed": 1234, "steps": 30, "cfg": 5.0, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0
+ },
+ "_meta": {"title": "sf_seed"}
+ },
+ "8": {
+ "class_type": "VAEDecodeHunyuan3D",
+ "inputs": {"samples": ["7", 0], "vae": ["1", 2], "num_chunks": 8000, "octree_resolution": 256},
+ "_meta": {"title": "VAE Decode Hunyuan3D"}
+ },
+ "9": {
+ "class_type": "VoxelToMesh",
+ "inputs": {"voxel": ["8", 0], "algorithm": "surface net", "threshold": 0.6},
+ "_meta": {"title": "Voxel to Mesh"}
+ },
+ "10": {
+ "class_type": "SculptForgeVoxelRemesh",
+ "inputs": {"mesh": ["9", 0], "resolution": 256},
+ "_meta": {"title": "SculptForge Voxel Remesh"}
+ },
+ "11": {
+ "class_type": "SculptForgeExport",
+ "inputs": {"mesh": ["10", 0], "format": "glb", "filename_prefix": "3d/SculptForge_hunyuan3d"},
+ "_meta": {"title": "SculptForge Export (sculpt-ready GLB)"}
+ },
+ "12": {
+ "class_type": "SculptForgeLODChain",
+ "inputs": {"mesh": ["10", 0], "levels": 4, "ratio": 0.5, "filename_prefix": "3d/SculptForge_hunyuan3d_lods"},
+ "_meta": {"title": "SculptForge LOD Chain (game LODs)"}
+ },
+ "13": {
+ "class_type": "SculptForgeExport",
+ "inputs": {"mesh": ["10", 0], "format": "usdz", "filename_prefix": "3d/SculptForge_hunyuan3d"},
+ "_meta": {"title": "SculptForge Export (USDZ for VFX / AR)"}
+ }
+}
diff --git a/integrations/comfyui/ComfyUI-SculptForge/examples/inflate-remesh-export.json b/integrations/comfyui/ComfyUI-SculptForge/examples/inflate-remesh-export.json
new file mode 100644
index 00000000..d3590d9b
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/examples/inflate-remesh-export.json
@@ -0,0 +1,22 @@
+{
+ "1": {
+ "class_type": "LoadImage",
+ "inputs": {"image": "teddy.png"},
+ "_meta": {"title": "sf_image"}
+ },
+ "2": {
+ "class_type": "SculptForgeInflateImage",
+ "inputs": {"image": ["1", 0], "mask": ["1", 1], "thickness": 1.0, "resolution": 160, "subdivisions": 1},
+ "_meta": {"title": "SculptForge Inflate Image"}
+ },
+ "3": {
+ "class_type": "SculptForgeVoxelRemesh",
+ "inputs": {"mesh": ["2", 0], "resolution": 200},
+ "_meta": {"title": "SculptForge Voxel Remesh"}
+ },
+ "4": {
+ "class_type": "SculptForgeExport",
+ "inputs": {"mesh": ["3", 0], "format": "glb", "filename_prefix": "3d/SculptForge_teddy"},
+ "_meta": {"title": "SculptForge Export"}
+ }
+}
diff --git a/integrations/comfyui/ComfyUI-SculptForge/examples/teddy.png b/integrations/comfyui/ComfyUI-SculptForge/examples/teddy.png
new file mode 100644
index 00000000..be22e3a3
Binary files /dev/null and b/integrations/comfyui/ComfyUI-SculptForge/examples/teddy.png differ
diff --git a/integrations/comfyui/ComfyUI-SculptForge/pyproject.toml b/integrations/comfyui/ComfyUI-SculptForge/pyproject.toml
new file mode 100644
index 00000000..107ed407
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/pyproject.toml
@@ -0,0 +1,29 @@
+[project]
+name = "comfyui-sculptforge"
+description = "SculptForge for ComfyUI: turn generated 3D (Hunyuan3D, TRELLIS, image inflate) into sculpt-ready, game-ready and VFX-ready assets - voxel remesh, decimate, subdivide, LOD chains, export to GLB, FBX, USD/USDZ, OBJ, STL. Needs the free SculptForge CLI."
+version = "0.1.0"
+license = { text = "GPL-3.0-or-later" }
+readme = "README.md"
+requires-python = ">=3.10"
+# numpy, torch and Pillow come with ComfyUI; the work is done by the sculptforge-cli executable.
+dependencies = []
+classifiers = [
+ "Operating System :: OS Independent",
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
+]
+keywords = ["3d", "mesh", "remesh", "sculpting", "lod", "glb", "fbx", "usd", "hunyuan3d", "trellis"]
+
+[project.urls]
+Repository = "https://github.com/islandmed/SculptForge"
+Documentation = "https://github.com/islandmed/SculptForge/tree/main/integrations/comfyui/ComfyUI-SculptForge"
+"Bug Tracker" = "https://github.com/islandmed/SculptForge/issues"
+
+[tool.comfy]
+PublisherId = "islandmed"
+DisplayName = "SculptForge"
+Icon = "https://raw.githubusercontent.com/islandmed/SculptForge/main/assets/branding/sculptforge-256.png"
+includes = []
+
+[tool.pytest.ini_options]
+addopts = "--import-mode=importlib -p no:cacheprovider"
+testpaths = ["tests"]
diff --git a/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/__init__.py b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/__init__.py
new file mode 100644
index 00000000..8f3b364a
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/__init__.py
@@ -0,0 +1,5 @@
+# SculptForge - ComfyUI nodes.
+# SPDX-License-Identifier: GPL-3.0-or-later
+from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
+
+__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
diff --git a/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/cli.py b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/cli.py
new file mode 100644
index 00000000..dd9c9d19
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/cli.py
@@ -0,0 +1,140 @@
+# SculptForge - ComfyUI nodes: locating and running sculptforge-cli.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Every node is a short sculptforge-cli script. File paths never go through the script
+# text: they are passed as --set variables ($IN, $OUT...), so spaces, quotes and
+# backslashes in paths need no escaping. The CLI runs without a shell.
+import os
+import shutil
+import subprocess
+import sys
+
+CLI_ENV = "SCULPTFORGE_CLI"
+APP_ENV = "SCULPTFORGE_APP"
+TIMEOUT_ENV = "SCULPTFORGE_TIMEOUT"
+DEFAULT_TIMEOUT = 600
+
+_EXE = ".exe" if sys.platform == "win32" else ""
+
+
+class SculptForgeError(RuntimeError):
+ """A SculptForge command failed (or the CLI could not be found)."""
+
+
+def _install_dirs():
+ """Folders the official packages install SculptForge into, most likely first."""
+ home = os.path.expanduser("~")
+ if sys.platform == "win32":
+ dirs = []
+ for var in ("ProgramFiles", "ProgramW6432", "LOCALAPPDATA"):
+ base = os.environ.get(var)
+ if base:
+ dirs.append(os.path.join(base, "SculptForge"))
+ dirs.append(os.path.join(base, "SculptForge", "bin"))
+ dirs.append(os.path.join(base, "Programs", "SculptForge"))
+ return dirs
+ if sys.platform == "darwin":
+ return [
+ "/Applications/SculptForge.app/Contents/MacOS",
+ os.path.join(home, "Applications/SculptForge.app/Contents/MacOS"),
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ ]
+ return [
+ "/usr/bin",
+ "/usr/local/bin",
+ os.path.join(home, ".local/bin"),
+ "/opt/sculptforge/bin",
+ "/opt/SculptForge/bin",
+ "/app/bin", # Flatpak
+ ]
+
+
+def _find(name, env_var):
+ override = os.environ.get(env_var, "").strip().strip('"')
+ if override:
+ if os.path.isdir(override):
+ override = os.path.join(override, name + _EXE)
+ if os.path.isfile(override):
+ return override
+ raise SculptForgeError(f"{env_var} is set to '{override}', but no such file exists.")
+ found = shutil.which(name)
+ if found:
+ return found
+ for folder in _install_dirs():
+ candidate = os.path.join(folder, name + _EXE)
+ if os.path.isfile(candidate):
+ return candidate
+ return None
+
+
+def find_cli():
+ """Path of sculptforge-cli: $SCULPTFORGE_CLI, then PATH, then the usual install folders."""
+ path = _find("sculptforge-cli", CLI_ENV)
+ if not path:
+ raise SculptForgeError(
+ "sculptforge-cli was not found. Install SculptForge (https://github.com/islandmed/SculptForge) "
+ f"and put sculptforge-cli on PATH, or set the {CLI_ENV} environment variable to its full path "
+ "before starting ComfyUI."
+ )
+ return path
+
+
+def find_app():
+ """Path of the SculptForge desktop app: $SCULPTFORGE_APP, next to the CLI, PATH, install folders."""
+ try:
+ cli = find_cli()
+ except SculptForgeError:
+ cli = None
+ if not os.environ.get(APP_ENV) and cli:
+ sibling = os.path.join(os.path.dirname(cli), "sculptforge" + _EXE)
+ if os.path.isfile(sibling):
+ return sibling
+ path = _find("sculptforge", APP_ENV)
+ if not path:
+ raise SculptForgeError(
+ f"The SculptForge app was not found. Put sculptforge on PATH or set {APP_ENV} to its full path."
+ )
+ return path
+
+
+def _timeout():
+ try:
+ return float(os.environ.get(TIMEOUT_ENV, DEFAULT_TIMEOUT))
+ except ValueError:
+ return DEFAULT_TIMEOUT
+
+
+def run(script, variables=None):
+ """Run a command script (statements separated by ';'), returning the CLI's stdout.
+
+ variables maps names to values substituted for $NAME in the script (use them for paths).
+ Raises SculptForgeError with the CLI's own message when a command fails.
+ """
+ cmd = [find_cli()]
+ for name, value in (variables or {}).items():
+ cmd += ["--set", f"{name}={value}"]
+ cmd += ["-c", script]
+ try:
+ proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=_timeout(), stdin=subprocess.DEVNULL)
+ except subprocess.TimeoutExpired:
+ raise SculptForgeError(f"sculptforge-cli timed out after {_timeout():g} s running: {script}") from None
+ except OSError as e:
+ raise SculptForgeError(f"Could not run {cmd[0]}: {e}") from None
+ if proc.returncode != 0:
+ message = (proc.stderr.strip() or proc.stdout.strip() or f"exit code {proc.returncode}")
+ raise SculptForgeError(f"SculptForge: {message}")
+ return proc.stdout
+
+
+def launch_app(path):
+ """Open a file in the SculptForge desktop app without waiting for it."""
+ app = find_app()
+ kwargs = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
+ if sys.platform == "win32":
+ kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
+ else:
+ kwargs["start_new_session"] = True
+ subprocess.Popen([app, path], **kwargs)
+ return app
diff --git a/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/meshio.py b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/meshio.py
new file mode 100644
index 00000000..4c6ef9ba
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/meshio.py
@@ -0,0 +1,203 @@
+# SculptForge - ComfyUI nodes: converting ComfyUI MESH values to and from mesh files.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# ComfyUI's core 3D nodes (Hunyuan3D VAE decode -> VoxelToMesh, TRELLIS, Get 3D Components,
+# SaveGLB...) pass comfy_api.latest.Types.MESH: vertices (B, N, 3) float, faces (B, M, 3) int,
+# optional vertex_colors (B, N, 3|4) in 0-1 and normals (B, N, 3), with vertex_counts /
+# face_counts (B,) when a batch is zero-padded. Coordinates are glTF-style (Y up), the same
+# convention SculptForge uses, so no axis swap is needed. Meshes cross the process boundary as
+# binary PLY, which SculptForge reads and writes with vertex colours (polypaint).
+import struct
+
+import numpy as np
+
+_PLY_TYPES = {
+ "char": "i1", "int8": "i1", "uchar": "u1", "uint8": "u1",
+ "short": "i2", "int16": "i2", "ushort": "u2", "uint16": "u2",
+ "int": "i4", "int32": "i4", "uint": "u4", "uint32": "u4",
+ "float": "f4", "float32": "f4", "double": "f8", "float64": "f8",
+}
+
+
+def write_ply(path, vertices, faces, colors=None):
+ """Write a binary little-endian PLY. colors: (N, 3|4) floats in 0-1, or None."""
+ vertices = np.ascontiguousarray(vertices, dtype="<f4").reshape(-1, 3)
+ faces = np.ascontiguousarray(faces, dtype="<i4").reshape(-1, 3)
+ if len(faces) and (faces.min() < 0 or faces.max() >= len(vertices)):
+ raise ValueError(f"face index out of range for {len(vertices)} vertices")
+ fields = [("x", "<f4"), ("y", "<f4"), ("z", "<f4")]
+ header = ["ply", "format binary_little_endian 1.0", "comment Written by ComfyUI-SculptForge",
+ f"element vertex {len(vertices)}", "property float x", "property float y", "property float z"]
+ if colors is not None:
+ fields += [("red", "u1"), ("green", "u1"), ("blue", "u1")]
+ header += ["property uchar red", "property uchar green", "property uchar blue"]
+ header += [f"element face {len(faces)}", "property list uchar int vertex_indices", "end_header"]
+
+ vert_data = np.empty(len(vertices), dtype=fields)
+ vert_data["x"], vert_data["y"], vert_data["z"] = vertices[:, 0], vertices[:, 1], vertices[:, 2]
+ if colors is not None:
+ rgb = np.clip(np.asarray(colors, dtype=np.float32)[:, :3] * 255.0 + 0.5, 0, 255).astype("u1")
+ vert_data["red"], vert_data["green"], vert_data["blue"] = rgb[:, 0], rgb[:, 1], rgb[:, 2]
+ face_data = np.empty(len(faces), dtype=[("n", "u1"), ("i", "<i4", (3,))])
+ face_data["n"] = 3
+ face_data["i"] = faces
+
+ with open(path, "wb") as f:
+ f.write(("\n".join(header) + "\n").encode("ascii"))
+ f.write(vert_data.tobytes())
+ f.write(face_data.tobytes())
+
+
+def read_ply(path):
+ """Read a binary little-endian PLY mesh as dict(vertices, faces, normals, colors)."""
+ with open(path, "rb") as f:
+ data = f.read()
+ end = data.find(b"end_header")
+ if not data.startswith(b"ply") or end < 0:
+ raise ValueError(f"{path} is not a PLY file")
+ body = data.index(b"\n", end) + 1
+ elements = [] # (name, count, [(prop, dtype)] or ("list", count_dtype, index_dtype))
+ for line in data[:end].decode("ascii", "replace").splitlines():
+ parts = line.split()
+ if not parts:
+ continue
+ if parts[0] == "format" and parts[1] != "binary_little_endian":
+ raise ValueError(f"{path}: only binary little-endian PLY is supported, not {parts[1]}")
+ if parts[0] == "element":
+ elements.append((parts[1], int(parts[2]), []))
+ elif parts[0] == "property":
+ if parts[1] == "list":
+ elements[-1][2].append((parts[4], ("list", _PLY_TYPES[parts[2]], _PLY_TYPES[parts[3]])))
+ else:
+ elements[-1][2].append((parts[2], _PLY_TYPES[parts[1]]))
+
+ offset = body
+ vertex = faces = None
+ for name, count, props in elements:
+ lists = [p for p in props if isinstance(p[1], tuple)]
+ if not lists:
+ dtype = np.dtype([(p, "<" + t) for p, t in props])
+ arr = np.frombuffer(data, dtype=dtype, count=count, offset=offset)
+ offset += dtype.itemsize * count
+ if name == "vertex":
+ vertex = arr
+ continue
+ if name != "face" or len(props) != 1:
+ raise ValueError(f"{path}: unsupported PLY element '{name}'")
+ count_t, index_t = lists[0][1][1], lists[0][1][2]
+ faces, offset = _read_faces(data, offset, count, "<" + count_t, "<" + index_t)
+
+ if vertex is None or faces is None:
+ raise ValueError(f"{path}: PLY has no vertex/face elements")
+ names = vertex.dtype.names
+ out = {
+ "vertices": np.stack([vertex["x"], vertex["y"], vertex["z"]], axis=1).astype(np.float32),
+ "faces": faces,
+ "normals": None,
+ "colors": None,
+ }
+ if all(n in names for n in ("nx", "ny", "nz")):
+ out["normals"] = np.stack([vertex["nx"], vertex["ny"], vertex["nz"]], axis=1).astype(np.float32)
+ if all(n in names for n in ("red", "green", "blue")):
+ rgb = np.stack([vertex["red"], vertex["green"], vertex["blue"]], axis=1).astype(np.float32)
+ if vertex.dtype["red"].kind in "ui":
+ rgb /= float(np.iinfo(vertex.dtype["red"]).max)
+ out["colors"] = rgb
+ return out
+
+
+def _read_faces(data, offset, count, count_t, index_t):
+ """Faces of a PLY list property, triangulated as fans. Fast path when all are triangles."""
+ tri = np.dtype([("n", count_t), ("i", index_t, (3,))])
+ if count == 0:
+ return np.zeros((0, 3), np.int64), offset
+ if offset + tri.itemsize * count <= len(data):
+ arr = np.frombuffer(data, dtype=tri, count=count, offset=offset)
+ if np.all(arr["n"] == 3):
+ return arr["i"].astype(np.int64), offset + tri.itemsize * count
+ cs, isz = np.dtype(count_t), np.dtype(index_t)
+ out = []
+ for _ in range(count):
+ n = int(np.frombuffer(data, dtype=cs, count=1, offset=offset)[0])
+ offset += cs.itemsize
+ idx = np.frombuffer(data, dtype=isz, count=n, offset=offset)
+ offset += isz.itemsize * n
+ for k in range(1, n - 1):
+ out.append((idx[0], idx[k], idx[k + 1]))
+ return np.asarray(out, dtype=np.int64).reshape(-1, 3), offset
+
+
+# ---------------------------------------------------------------- ComfyUI MESH
+
+
+def is_comfy_mesh(value):
+ return hasattr(value, "vertices") and hasattr(value, "faces") and not isinstance(value, (str, bytes))
+
+
+def _np(t):
+ if t is None:
+ return None
+ if hasattr(t, "detach"):
+ t = t.detach().float().cpu() if t.is_floating_point() else t.detach().cpu()
+ return t.numpy()
+ return np.asarray(t)
+
+
+def comfy_mesh_item(mesh, index=0):
+ """(vertices, faces, colors) numpy arrays of one item of a ComfyUI MESH batch."""
+ vertices, faces, colors = mesh.vertices[index], mesh.faces[index], getattr(mesh, "vertex_colors", None)
+ colors = colors[index] if colors is not None else None
+ counts = getattr(mesh, "vertex_counts", None)
+ if counts is not None:
+ nv, nf = int(mesh.vertex_counts[index]), int(mesh.face_counts[index])
+ vertices, faces = vertices[:nv], faces[:nf]
+ colors = colors[:nv] if colors is not None else None
+ return _np(vertices), _np(faces), _np(colors)
+
+
+def comfy_mesh_to_ply(mesh, path, index=0):
+ vertices, faces, colors = comfy_mesh_item(mesh, index)
+ if vertices is None or len(vertices) == 0 or len(faces) == 0:
+ raise ValueError("the MESH is empty (no vertices or faces)")
+ write_ply(path, vertices, faces, colors)
+
+
+class _FallbackMesh:
+ """Stand-in with Types.MESH's attributes, for ComfyUI versions without comfy_api.latest."""
+
+ def __init__(self, vertices, faces, vertex_colors=None, normals=None):
+ self.vertices, self.faces = vertices, faces
+ self.vertex_colors, self.normals = vertex_colors, normals
+ self.uvs = self.texture = self.metallic_roughness = None
+ self.vertex_counts = self.face_counts = None
+ self.tangents = self.normal_map = self.material = self.emissive = None
+ self.unlit = self.occlusion_in_mr = False
+
+
+def mesh_class():
+ try:
+ from comfy_api.latest import Types
+ return Types.MESH
+ except Exception:
+ return _FallbackMesh
+
+
+def ply_to_comfy_mesh(path):
+ """Read a PLY written by SculptForge into a ComfyUI MESH (batch of one)."""
+ import torch
+
+ m = read_ply(path)
+ batch = lambda a: None if a is None else torch.from_numpy(np.ascontiguousarray(a))[None]
+ cls = mesh_class()
+ vertices, faces = batch(m["vertices"]), batch(m["faces"])
+ try:
+ return cls(vertices=vertices, faces=faces, vertex_colors=batch(m["colors"]), normals=batch(m["normals"]))
+ except TypeError: # older ComfyUI: MESH(vertices, faces) only
+ return cls(vertices, faces)
+
+
+def glb_bytes_magic(path):
+ """True if the file starts like a binary glTF (sanity check for exported GLBs)."""
+ with open(path, "rb") as f:
+ head = f.read(12)
+ return len(head) == 12 and head[:4] == b"glTF" and struct.unpack("<I", head[4:8])[0] == 2
diff --git a/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/nodes.py b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/nodes.py
new file mode 100644
index 00000000..5ee5d41a
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/nodes.py
@@ -0,0 +1,424 @@
+# SculptForge - ComfyUI nodes: the node classes.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Meshes flow between SculptForge nodes as SF_MESH: a small object holding the path of a
+# working file (a .sfproj project, so polygroups, polypaint and sculpt layers survive every
+# step). Every mesh input also accepts ComfyUI's core MESH type (Hunyuan3D, TRELLIS, Get 3D
+# Components...), and "SculptForge to MESH" goes the other way, so core and SculptForge
+# nodes chain freely.
+import logging
+import os
+import re
+import uuid
+
+import numpy as np
+
+from . import cli, meshio, paths
+
+log = logging.getLogger("SculptForge")
+
+CATEGORY = "SculptForge"
+SF_MESH = "SF_MESH"
+MESH_IN = "SF_MESH,MESH" # union type: SculptForge meshes or ComfyUI core MESH
+
+EXPORT_COMMANDS = {
+ "glb": "export_glb",
+ "fbx": "export_fbx",
+ "usda": "export_usd",
+ "usdz": "export_usd",
+ "obj": "save_obj",
+ "stl": "export_stl",
+ "ply": "export_ply",
+}
+
+
+class SFMesh:
+ """A mesh on disk that sculptforge-cli can open (normally a .sfproj in ComfyUI's temp folder)."""
+
+ def __init__(self, path, info=""):
+ self.path = path
+ self.info = info
+
+ def __repr__(self):
+ return f"SFMesh({self.path!r})"
+
+
+def _temp(ext, stem=None):
+ """A new working file. Give a stem when SculptForge names the SubTool after the file."""
+ if not stem:
+ return os.path.join(paths.work_dir(), f"{uuid.uuid4().hex}{ext}")
+ folder = os.path.join(paths.work_dir(), uuid.uuid4().hex)
+ os.makedirs(folder)
+ return os.path.join(folder, stem + ext)
+
+
+def _source(mesh):
+ """Path of a file sculptforge-cli can open for an SF_MESH or core MESH input."""
+ if isinstance(mesh, SFMesh):
+ if not os.path.isfile(mesh.path):
+ raise cli.SculptForgeError(
+ f"The working file {mesh.path} is gone (ComfyUI clears its temp folder on restart); "
+ "re-run the nodes before this one.")
+ return mesh.path
+ if meshio.is_comfy_mesh(mesh):
+ if mesh.vertices.shape[0] > 1:
+ log.warning("SculptForge: the MESH batch has %d items; using the first", mesh.vertices.shape[0])
+ ply = _temp(".ply", "ComfyUI_mesh")
+ meshio.comfy_mesh_to_ply(mesh, ply)
+ return ply
+ raise TypeError(f"Expected a SculptForge mesh or a ComfyUI MESH, got {type(mesh).__name__}")
+
+
+def _process(mesh, script):
+ """Open the mesh, run the script, save the result as a new working project."""
+ out = _temp(".sfproj")
+ stdout = cli.run(f"open path=$IN; {script}; save_project path=$OUT", {"IN": _source(mesh), "OUT": out})
+ lines = [l for l in stdout.strip().splitlines() if l.strip()]
+ info = lines[-2].split(": ", 1)[-1] if len(lines) >= 2 else ""
+ log.info("SculptForge: %s", info)
+ return SFMesh(out, info)
+
+
+def _create(script, variables):
+ """Run a script that creates a scene (image_inflate...) and save it as a working project."""
+ out = _temp(".sfproj")
+ stdout = cli.run(f"{script}; save_project path=$OUT", dict(variables, OUT=out))
+ info = [l for l in stdout.strip().splitlines() if l.strip()][0].split(": ", 1)[-1]
+ log.info("SculptForge: %s", info)
+ return SFMesh(out, info)
+
+
+def _image_to_png(image, mask=None):
+ """Save the first image of a ComfyUI IMAGE batch (B, H, W, C floats) as PNG; a MASK becomes alpha."""
+ from PIL import Image
+
+ arr = image[0] if getattr(image, "ndim", 3) == 4 else image
+ arr = arr.detach().cpu().numpy() if hasattr(arr, "detach") else np.asarray(arr)
+ rgba = np.clip(arr * 255.0 + 0.5, 0, 255).astype(np.uint8)
+ if rgba.shape[-1] == 3 and mask is not None:
+ m = mask[0] if getattr(mask, "ndim", 2) == 3 else mask
+ m = m.detach().cpu().numpy() if hasattr(m, "detach") else np.asarray(m)
+ # LoadImage's MASK is 1 where the picture is transparent; an all-zero mask means "no alpha".
+ if m.shape == rgba.shape[:2] and m.max() > 0:
+ alpha = np.clip((1.0 - m) * 255.0 + 0.5, 0, 255).astype(np.uint8)
+ rgba = np.concatenate([rgba, alpha[..., None]], axis=-1)
+ if rgba.shape[-1] == 1:
+ rgba = rgba[..., 0]
+ path = _temp(".png")
+ Image.fromarray(rgba).save(path)
+ return path
+
+
+def _output_ui(saved):
+ """UI payload listing saved files the way ComfyUI's own 3D save node does ("3d" key)."""
+ return {"3d": [{"filename": f, "subfolder": s, "type": "output"} for f, s in saved]}
+
+
+# ---------------------------------------------------------------- source nodes
+
+
+class SculptForgeLoadMesh:
+ DESCRIPTION = ("Load a model file (OBJ, FBX, GLB/glTF, PLY, STL, USD/USDZ, ZBrush GoZ or a SculptForge "
+ ".sfproj) for the SculptForge nodes. Relative paths are looked up in ComfyUI's input folder.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "load"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {"path": ("STRING", {"default": "", "tooltip": "Model file path (absolute, or "
+ "relative to the ComfyUI input folder, e.g. 3d/rock.glb)."})}}
+
+ @classmethod
+ def IS_CHANGED(cls, path):
+ try:
+ return os.path.getmtime(paths.resolve_input(path))
+ except (OSError, ValueError):
+ return float("nan")
+
+ def load(self, path):
+ full = paths.resolve_input(path)
+ if not os.path.isfile(full):
+ raise cli.SculptForgeError(f"Model file not found: {full}")
+ return (_create("open path=$IN", {"IN": full}),)
+
+
+class SculptForgeInflateImage:
+ DESCRIPTION = ("Inflate a sketch or silhouette into a rounded, closed 3D base mesh (no GPU, a second or two). "
+ "Works best with a transparent background (connect LoadImage's MASK) or a plain backdrop.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "inflate"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "thickness": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.05,
+ "tooltip": "1 = round, lower = flatter."}),
+ "resolution": ("INT", {"default": 160, "min": 32, "max": 512, "step": 8,
+ "tooltip": "Detail along the long side."}),
+ "subdivisions": ("INT", {"default": 1, "min": 0, "max": 3, "tooltip": "Smoothing passes."}),
+ },
+ "optional": {
+ "mask": ("MASK", {"tooltip": "LoadImage's MASK output: the transparent area is background."}),
+ },
+ }
+
+ def inflate(self, image, thickness, resolution, subdivisions, mask=None):
+ png = _image_to_png(image, mask)
+ script = (f"image_inflate path=$IMG thickness={thickness:g} resolution={int(resolution)} "
+ f"subdivisions={int(subdivisions)}")
+ return (_create(script, {"IMG": png}),)
+
+
+class SculptForgeImageRelief:
+ DESCRIPTION = ("Turn an image into a sculpted relief: light areas rise, dark areas stay low "
+ "(logos, coins, emblems, height maps).")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "relief"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "image": ("IMAGE",),
+ "depth": ("FLOAT", {"default": 0.12, "min": 0.01, "max": 1.0, "step": 0.01,
+ "tooltip": "Relief height as a fraction of the width."}),
+ "resolution": ("INT", {"default": 384, "min": 32, "max": 2048, "step": 16}),
+ "invert": ("BOOLEAN", {"default": False, "tooltip": "Make dark areas high instead."}),
+ }}
+
+ def relief(self, image, depth, resolution, invert):
+ png = _image_to_png(image)
+ script = (f"image_relief path=$IMG depth={depth:g} resolution={int(resolution)} "
+ f"invert={'true' if invert else 'false'}")
+ return (_create(script, {"IMG": png}),)
+
+
+# ---------------------------------------------------------------- processing nodes
+
+
+class SculptForgeVoxelRemesh:
+ DESCRIPTION = ("Voxel remesh (like DynaMesh): rebuild the mesh as an even, watertight sculpting surface, "
+ "merging overlapping parts and fixing broken scans or AI-generated models.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "remesh"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "mesh": (MESH_IN,),
+ "resolution": ("INT", {"default": 200, "min": 32, "max": 512, "step": 8,
+ "tooltip": "Voxels across the longest side; higher keeps more detail."}),
+ }}
+
+ def remesh(self, mesh, resolution):
+ return (_process(mesh, f"remesh resolution={int(resolution)}"),)
+
+
+class SculptForgeDecimate:
+ DESCRIPTION = "Reduce the triangle count while preserving shape (quadric edge collapse)."
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "decimate"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "mesh": (MESH_IN,),
+ "ratio": ("FLOAT", {"default": 0.5, "min": 0.01, "max": 1.0, "step": 0.01,
+ "tooltip": "Fraction of triangles to keep."}),
+ "triangles": ("INT", {"default": 0, "min": 0, "max": 100_000_000,
+ "tooltip": "Exact target triangle count; 0 uses the ratio."}),
+ }}
+
+ def decimate(self, mesh, ratio, triangles):
+ args = f"triangles={int(triangles)}" if triangles > 0 else f"ratio={ratio:g}"
+ return (_process(mesh, f"decimate {args}"),)
+
+
+class SculptForgeSubdivide:
+ DESCRIPTION = "Smoothly subdivide the mesh (Loop subdivision). Each level multiplies the triangle count by 4."
+ CATEGORY = CATEGORY
+ RETURN_TYPES = (SF_MESH,)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "subdivide"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {"mesh": (MESH_IN,), "levels": ("INT", {"default": 1, "min": 1, "max": 4})}}
+
+ def subdivide(self, mesh, levels):
+ return (_process(mesh, f"subdivide levels={int(levels)}"),)
+
+
+class SculptForgeToMesh:
+ DESCRIPTION = ("Convert a SculptForge mesh to ComfyUI's core MESH type (with vertex colours and normals), "
+ "for Save 3D Model, Preview 3D and the other core 3D nodes.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = ("MESH",)
+ RETURN_NAMES = ("mesh",)
+ FUNCTION = "convert"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {"mesh": (SF_MESH,)}}
+
+ def convert(self, mesh):
+ ply = _temp(".ply")
+ cli.run("open path=$IN; export_ply path=$OUT", {"IN": _source(mesh), "OUT": ply})
+ return (meshio.ply_to_comfy_mesh(ply),)
+
+
+# ---------------------------------------------------------------- output nodes
+
+
+class SculptForgeExport:
+ DESCRIPTION = ("Export to the ComfyUI output folder: GLB (game engines, web), FBX (Unreal, Unity, Maya), "
+ "USDA/USDZ (VFX pipelines, Apple AR), OBJ, STL (3D printing) or PLY (vertex colours).")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("file_path",)
+ OUTPUT_NODE = True
+ FUNCTION = "export"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "mesh": (MESH_IN,),
+ "format": (list(EXPORT_COMMANDS), {"default": "glb"}),
+ "filename_prefix": ("STRING", {"default": "3d/SculptForge"}),
+ }}
+
+ def export(self, mesh, format, filename_prefix):
+ command = EXPORT_COMMANDS[format]
+ folder, filename, counter, subfolder = paths.save_path(filename_prefix)
+ name = f"{filename}_{counter:05}_.{format}"
+ full = os.path.join(folder, name)
+ cli.run(f"open path=$IN; {command} path=$OUT", {"IN": _source(mesh), "OUT": full})
+ if not os.path.isfile(full):
+ raise cli.SculptForgeError(f"SculptForge reported success but {full} was not written")
+ log.info("SculptForge: exported %s", full)
+ return {"ui": _output_ui([(name, subfolder)]), "result": (full,)}
+
+
+class SculptForgeLODChain:
+ DESCRIPTION = ("Generate a game LOD chain and save each level as a GLB (<name>_LOD0.glb, _LOD1.glb...) "
+ "in the ComfyUI output folder.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("file_paths",)
+ OUTPUT_NODE = True
+ FUNCTION = "export"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "mesh": (MESH_IN,),
+ "levels": ("INT", {"default": 4, "min": 1, "max": 8, "tooltip": "LODs including LOD0."}),
+ "ratio": ("FLOAT", {"default": 0.5, "min": 0.1, "max": 0.9, "step": 0.05,
+ "tooltip": "Triangle ratio between consecutive LODs."}),
+ "filename_prefix": ("STRING", {"default": "3d/SculptForge_lods"}),
+ }}
+
+ def export(self, mesh, levels, ratio, filename_prefix):
+ folder, filename, counter, subfolder = paths.save_path(filename_prefix)
+ base = f"{filename}_{counter:05}"
+ cli.run(f"open path=$IN; export_lods path=$OUT levels={int(levels)} ratio={ratio:g}",
+ {"IN": _source(mesh), "OUT": os.path.join(folder, base + ".glb")})
+ names = [f"{base}_LOD{i}.glb" for i in range(int(levels))]
+ missing = [n for n in names if not os.path.isfile(os.path.join(folder, n))]
+ if missing:
+ raise cli.SculptForgeError(f"LOD files were not written: {', '.join(missing)}")
+ full = [os.path.join(folder, n) for n in names]
+ return {"ui": _output_ui([(n, subfolder) for n in names]), "result": ("\n".join(full),)}
+
+
+class SculptForgeMeshInfo:
+ DESCRIPTION = "Report vertex and triangle counts, bounds and SubTools of a mesh."
+ CATEGORY = CATEGORY
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("info",)
+ OUTPUT_NODE = True
+ FUNCTION = "info"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {"mesh": (MESH_IN,)}, "hidden": {"unique_id": "UNIQUE_ID"}}
+
+ def info(self, mesh, unique_id=None):
+ stdout = cli.run("open path=$IN; mesh_info; subtool_list", {"IN": _source(mesh)})
+ lines = [l.split(": ", 1)[-1] if re.match(r"^\w+: ", l) else l for l in stdout.strip().splitlines()[1:]]
+ text = "\n".join(lines)
+ paths.show_text(text, unique_id)
+ return {"ui": {"text": (text,)}, "result": (text,)}
+
+
+class SculptForgeOpenInApp:
+ DESCRIPTION = ("Open the mesh (or an exported file) in the SculptForge desktop app to keep sculpting. "
+ "Only useful when ComfyUI runs on your own computer.")
+ CATEGORY = CATEGORY
+ RETURN_TYPES = ()
+ OUTPUT_NODE = True
+ FUNCTION = "open"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {"enabled": ("BOOLEAN", {"default": True})},
+ "optional": {
+ "mesh": (MESH_IN,),
+ "file_path": ("STRING", {"forceInput": True, "tooltip": "e.g. the file_path of SculptForge Export."}),
+ },
+ }
+
+ def open(self, enabled, mesh=None, file_path=None):
+ if not enabled:
+ return {}
+ target = file_path.splitlines()[0].strip() if file_path else None
+ if not target and mesh is not None:
+ # Copy the working file so the app's Save doesn't write into ComfyUI's temp folder.
+ target = os.path.join(paths.work_dir(), "SculptForge from ComfyUI.sfproj")
+ cli.run("open path=$IN; save_project path=$OUT", {"IN": _source(mesh), "OUT": target})
+ if not target:
+ raise cli.SculptForgeError("Open in SculptForge needs a mesh or a file_path input.")
+ app = cli.launch_app(target)
+ log.info("SculptForge: opened %s in %s", target, app)
+ return {"ui": {"text": (f"Opened {os.path.basename(target)} in SculptForge",)}}
+
+
+NODE_CLASS_MAPPINGS = {
+ "SculptForgeLoadMesh": SculptForgeLoadMesh,
+ "SculptForgeInflateImage": SculptForgeInflateImage,
+ "SculptForgeImageRelief": SculptForgeImageRelief,
+ "SculptForgeVoxelRemesh": SculptForgeVoxelRemesh,
+ "SculptForgeDecimate": SculptForgeDecimate,
+ "SculptForgeSubdivide": SculptForgeSubdivide,
+ "SculptForgeLODChain": SculptForgeLODChain,
+ "SculptForgeExport": SculptForgeExport,
+ "SculptForgeMeshInfo": SculptForgeMeshInfo,
+ "SculptForgeToMesh": SculptForgeToMesh,
+ "SculptForgeOpenInApp": SculptForgeOpenInApp,
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "SculptForgeLoadMesh": "SculptForge Load Mesh",
+ "SculptForgeInflateImage": "SculptForge Inflate Image",
+ "SculptForgeImageRelief": "SculptForge Image Relief",
+ "SculptForgeVoxelRemesh": "SculptForge Voxel Remesh",
+ "SculptForgeDecimate": "SculptForge Decimate",
+ "SculptForgeSubdivide": "SculptForge Subdivide",
+ "SculptForgeLODChain": "SculptForge LOD Chain",
+ "SculptForgeExport": "SculptForge Export",
+ "SculptForgeMeshInfo": "SculptForge Mesh Info",
+ "SculptForgeToMesh": "SculptForge to MESH",
+ "SculptForgeOpenInApp": "Open in SculptForge",
+}
diff --git a/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/paths.py b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/paths.py
new file mode 100644
index 00000000..9845d0a8
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/sculptforge_comfy/paths.py
@@ -0,0 +1,71 @@
+# SculptForge - ComfyUI nodes: ComfyUI folders (input, output, temp) and UI helpers.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Inside ComfyUI these use folder_paths and PromptServer; without them (unit tests, scripts)
+# they fall back to folders under the system temp directory.
+import os
+import tempfile
+
+try:
+ import folder_paths
+except ImportError: # not running inside ComfyUI
+ folder_paths = None
+
+
+def _fallback(name):
+ path = os.path.join(tempfile.gettempdir(), "comfyui-sculptforge", name)
+ os.makedirs(path, exist_ok=True)
+ return path
+
+
+def input_dir():
+ return folder_paths.get_input_directory() if folder_paths else _fallback("input")
+
+
+def output_dir():
+ return folder_paths.get_output_directory() if folder_paths else _fallback("output")
+
+
+def work_dir():
+ """Where intermediate meshes live: ComfyUI's temp folder (cleared when ComfyUI starts)."""
+ base = folder_paths.get_temp_directory() if folder_paths else _fallback("temp")
+ path = os.path.join(base, "sculptforge")
+ os.makedirs(path, exist_ok=True)
+ return path
+
+
+def resolve_input(path):
+ path = os.path.expanduser(path.strip().strip('"'))
+ if not path:
+ raise ValueError("No file path given")
+ return path if os.path.isabs(path) else os.path.join(input_dir(), path)
+
+
+def save_path(filename_prefix):
+ """(folder, filename, counter, subfolder) for a new output file, numbered like ComfyUI's save nodes."""
+ if folder_paths:
+ folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir())
+ os.makedirs(folder, exist_ok=True)
+ return folder, filename, counter, subfolder
+ root = output_dir()
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
+ filename = os.path.basename(os.path.normpath(filename_prefix))
+ folder = os.path.abspath(os.path.join(root, subfolder))
+ if os.path.commonpath([folder, os.path.abspath(root)]) != os.path.abspath(root):
+ raise ValueError("Saving outside the output folder is not allowed")
+ os.makedirs(folder, exist_ok=True)
+ taken = [f[len(filename) + 1:].split("_")[0].split(".")[0] for f in os.listdir(folder)
+ if f.startswith(filename + "_")]
+ counter = max([int(t) for t in taken if t.isdigit()], default=0) + 1
+ return folder, filename, counter, subfolder
+
+
+def show_text(text, unique_id):
+ """Show text on the node in the ComfyUI frontend (like the core Get Mesh Info node)."""
+ if unique_id is None:
+ return
+ try:
+ from server import PromptServer
+ PromptServer.instance.send_progress_text(text, unique_id)
+ except Exception:
+ pass
diff --git a/integrations/comfyui/ComfyUI-SculptForge/tests/conftest.py b/integrations/comfyui/ComfyUI-SculptForge/tests/conftest.py
new file mode 100644
index 00000000..ac21e05f
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/tests/conftest.py
@@ -0,0 +1,51 @@
+# SculptForge - ComfyUI node tests: shared fixtures.
+# SPDX-License-Identifier: GPL-3.0-or-later
+import json
+import os
+import stat
+import sys
+
+import pytest
+
+PACK_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, PACK_DIR)
+
+from sculptforge_comfy import cli, paths # noqa: E402
+
+
[email protected](autouse=True)
+def comfy_dirs(tmp_path, monkeypatch):
+ """Point the input/output/temp folders at a fresh directory for every test."""
+ def fallback(name):
+ path = tmp_path / "comfy" / name
+ path.mkdir(parents=True, exist_ok=True)
+ return str(path)
+
+ monkeypatch.setattr(paths, "folder_paths", None)
+ monkeypatch.setattr(paths, "_fallback", fallback)
+ return tmp_path / "comfy"
+
+
+def fake_cli(tmp_path, monkeypatch):
+ """Install tests/fake_cli.py as $SCULPTFORGE_CLI; returns a helper to read its call log."""
+ if sys.platform == "win32":
+ pytest.skip("the fake CLI is a shebang script")
+ exe = tmp_path / "bin" / "sculptforge-cli"
+ exe.parent.mkdir()
+ with open(os.path.join(os.path.dirname(__file__), "fake_cli.py"), encoding="utf-8") as f:
+ exe.write_text(f"#!{sys.executable}\n" + f.read())
+ exe.chmod(exe.stat().st_mode | stat.S_IEXEC)
+ log = tmp_path / "calls.jsonl"
+ monkeypatch.setenv(cli.CLI_ENV, str(exe))
+ monkeypatch.setenv("FAKE_SF_LOG", str(log))
+
+ class Calls:
+ path = str(exe)
+
+ def __call__(self):
+ if not log.exists():
+ return []
+ return [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines()]
+
+ return Calls()
diff --git a/integrations/comfyui/ComfyUI-SculptForge/tests/fake_cli.py b/integrations/comfyui/ComfyUI-SculptForge/tests/fake_cli.py
new file mode 100644
index 00000000..1dd27384
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/tests/fake_cli.py
@@ -0,0 +1,130 @@
+# SculptForge - a stand-in for sculptforge-cli used by the unit tests.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Understands the subset of commands the nodes use, keeps a toy "mesh" (triangle count) in
+# JSON files, and appends every invocation to $FAKE_SF_LOG so tests can check the scripts.
+# Standard library only, so it runs with any Python.
+import json
+import os
+import struct
+import sys
+
+
+def fail(line, cmd, message):
+ sys.stderr.write(f"error (line {line}, {cmd}): {message}\n")
+ sys.exit(2)
+
+
+def write_state(path, state, magic=b""):
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ with open(path, "wb") as f:
+ f.write(magic + json.dumps(state).encode())
+
+
+def read_state(path):
+ with open(path, "rb") as f:
+ data = f.read()
+ if data.startswith(b"ply"):
+ header = data[:data.index(b"end_header")].decode()
+ counts = {l.split()[1]: int(l.split()[2]) for l in header.splitlines() if l.startswith("element")}
+ return {"name": os.path.splitext(os.path.basename(path))[0], "triangles": counts.get("face", 0)}
+ if data.startswith(b"glTF"):
+ data = data[12:]
+ try:
+ return json.loads(data)
+ except ValueError:
+ return {"name": os.path.splitext(os.path.basename(path))[0], "triangles": 100}
+
+
+def write_ply(path):
+ v = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
+ f = [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]
+ header = ("ply\nformat binary_little_endian 1.0\nelement vertex 4\nproperty float x\nproperty float y\n"
+ "property float z\nproperty float nx\nproperty float ny\nproperty float nz\nproperty uchar red\n"
+ "property uchar green\nproperty uchar blue\nelement face 4\n"
+ "property list uchar int vertex_indices\nend_header\n")
+ with open(path, "wb") as out:
+ out.write(header.encode())
+ for p in v:
+ out.write(struct.pack("<ffffffBBB", *p, 0, 0, 1, 255, 128, 0))
+ for t in f:
+ out.write(struct.pack("<Biii", 3, *t))
+
+
+def main(argv):
+ variables, script = {}, None
+ i = 0
+ while i < len(argv):
+ if argv[i] == "--set":
+ name, _, value = argv[i + 1].partition("=")
+ variables[name] = value
+ i += 2
+ elif argv[i] == "-c":
+ script = argv[i + 1]
+ i += 2
+ else:
+ i += 1
+ log = os.environ.get("FAKE_SF_LOG")
+ if log:
+ with open(log, "a", encoding="utf-8") as f:
+ f.write(json.dumps({"vars": variables, "script": script}) + "\n")
+ if os.environ.get("FAKE_SF_FAIL"):
+ fail(1, "remesh", os.environ["FAKE_SF_FAIL"])
+
+ state = None
+ for line, statement in enumerate((s.strip() for s in script.split(";")), 1):
+ if not statement:
+ continue
+ cmd, *tokens = statement.split()
+ args = {}
+ for tok in tokens:
+ key, _, value = tok.partition("=")
+ args[key] = variables[value[1:]] if value.startswith("$") else value
+ path = args.get("path")
+ if cmd == "open":
+ if not os.path.isfile(path):
+ fail(line, cmd, f"Cannot open {path}")
+ state = read_state(path)
+ print(f"open: Opened {path} ({state['triangles']} triangles)")
+ elif cmd in ("image_inflate", "image_relief"):
+ if not os.path.isfile(path):
+ fail(line, cmd, f"Cannot read image {path}")
+ state = {"name": os.path.splitext(os.path.basename(path))[0], "triangles": 1000}
+ print(f"{cmd}: Inflated sketch into 1000 triangles")
+ elif cmd == "remesh":
+ state["triangles"] = int(args.get("resolution", 200)) * 10
+ print(f"remesh: Remeshed to {state['triangles']} triangles")
+ elif cmd == "decimate":
+ state["triangles"] = int(args["triangles"]) if "triangles" in args else \
+ int(state["triangles"] * float(args.get("ratio", 0.5)))
+ print(f"decimate: Decimated to {state['triangles']} triangles")
+ elif cmd == "subdivide":
+ state["triangles"] *= 4 ** int(args.get("levels", 1))
+ print(f"subdivide: Subdivided to {state['triangles']} triangles")
+ elif cmd in ("save_project", "export_fbx", "export_usd", "save_obj", "export_stl"):
+ write_state(path, state)
+ print(f"{cmd}: Saved {path}")
+ elif cmd == "export_glb":
+ write_state(path, state, b"glTF" + struct.pack("<II", 2, 0))
+ print(f"{cmd}: Exported {path}")
+ elif cmd == "export_ply":
+ write_ply(path)
+ print(f"{cmd}: Exported {path}")
+ elif cmd == "export_lods":
+ base, ext = os.path.splitext(path)
+ if not os.path.isdir(os.path.dirname(base)):
+ fail(line, cmd, f"Cannot write {base}_LOD0{ext}")
+ for level in range(int(args.get("levels", 4))):
+ write_state(f"{base}_LOD{level}{ext}", state, b"glTF" + struct.pack("<II", 2, 0))
+ print(f"{cmd}: Exported {args.get('levels', 4)} LODs")
+ elif cmd == "mesh_info":
+ print(f"mesh_info: {state['triangles'] // 2} vertices, {state['triangles']} triangles, "
+ "bounds (-1, -1, -1) - (1, 1, 1)")
+ elif cmd == "subtool_list":
+ print(f"subtool_list: 1 SubTool:\n0. {state['name']} ({state['triangles']} triangles, active)")
+ else:
+ fail(line, cmd, f"Unknown command '{cmd}'")
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/integrations/comfyui/ComfyUI-SculptForge/tests/test_comfyui_e2e.py b/integrations/comfyui/ComfyUI-SculptForge/tests/test_comfyui_e2e.py
new file mode 100644
index 00000000..41680835
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/tests/test_comfyui_e2e.py
@@ -0,0 +1,172 @@
+# SculptForge - end-to-end test: a real ComfyUI server with this pack and the real sculptforge-cli.
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Starts its own ComfyUI (CPU, port $SF_COMFYUI_PORT or 8189) with a throwaway base directory
+# whose custom_nodes/ holds a symlink to this pack, checks the nodes register, then queues the
+# example workflows through the HTTP API and opens the exported files with sculptforge-cli.
+#
+# COMFYUI_DIR=/path/to/ComfyUI [COMFYUI_PYTHON=/path/to/venv/bin/python] \
+# SCULPTFORGE_CLI=/path/to/sculptforge-cli pytest tests/test_comfyui_e2e.py
+import json
+import os
+import shutil
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+
+import pytest
+
+from sculptforge_comfy import cli, meshio, nodes
+
+PACK_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+EXAMPLES = os.path.join(PACK_DIR, "examples")
+COMFYUI_DIR = os.environ.get("COMFYUI_DIR")
+PORT = int(os.environ.get("SF_COMFYUI_PORT", "8189"))
+BASE = f"http://127.0.0.1:{PORT}"
+
+pytestmark = pytest.mark.skipif(not COMFYUI_DIR, reason="set COMFYUI_DIR to a ComfyUI checkout to run")
+
+
+def get(path):
+ with urllib.request.urlopen(BASE + path, timeout=30) as r:
+ return r.read()
+
+
+def get_json(path):
+ return json.loads(get(path))
+
+
+def post_json(path, payload):
+ req = urllib.request.Request(BASE + path, json.dumps(payload).encode(), {"Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return json.loads(r.read())
+ except urllib.error.HTTPError as e:
+ raise AssertionError(f"POST {path} failed: {e.code} {e.read().decode(errors='replace')}") from None
+
+
+def upload_image(path):
+ boundary = uuid.uuid4().hex
+ with open(path, "rb") as f:
+ data = f.read()
+ body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n"
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{os.path.basename(path)}\"\r\n"
+ "Content-Type: image/png\r\n\r\n").encode() + data + f"\r\n--{boundary}--\r\n".encode()
+ req = urllib.request.Request(BASE + "/upload/image", body,
+ {"Content-Type": f"multipart/form-data; boundary={boundary}"})
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return json.loads(r.read())["name"]
+
+
+def run_workflow(name, image):
+ with open(os.path.join(EXAMPLES, name), encoding="utf-8") as f:
+ prompt = json.load(f)
+ for node in prompt.values():
+ if node["class_type"] == "LoadImage":
+ node["inputs"]["image"] = image
+ prompt_id = post_json("/prompt", {"prompt": prompt, "client_id": "sculptforge-e2e"})["prompt_id"]
+ deadline = time.time() + 300
+ while time.time() < deadline:
+ history = get_json(f"/history/{prompt_id}")
+ if prompt_id in history:
+ entry = history[prompt_id]
+ status = entry.get("status", {})
+ if status.get("status_str") == "error" or not status.get("completed", True):
+ messages = [m for m in status.get("messages", []) if m[0] == "execution_error"]
+ raise AssertionError(f"{name} failed: {json.dumps(messages, indent=1)[:4000]}")
+ return entry["outputs"]
+ time.sleep(0.5)
+ raise AssertionError(f"{name} did not finish in time")
+
+
+def download(entry, folder):
+ query = urllib.parse.urlencode({k: entry[k] for k in ("filename", "subfolder", "type")})
+ path = os.path.join(folder, entry["filename"])
+ with open(path, "wb") as f:
+ f.write(get(f"/view?{query}"))
+ return path
+
+
+def triangles(path):
+ out = cli.run("open path=$IN; mesh_info", {"IN": path})
+ info = out.strip().splitlines()[-1]
+ return int(info.split(" triangles")[0].split()[-1])
+
+
[email protected](scope="module")
+def server(tmp_path_factory):
+ try:
+ cli.find_cli()
+ except cli.SculptForgeError as e:
+ pytest.skip(str(e))
+ base = tmp_path_factory.mktemp("comfy-base")
+ (base / "custom_nodes").mkdir()
+ os.symlink(PACK_DIR, base / "custom_nodes" / "ComfyUI-SculptForge")
+ python = os.environ.get("COMFYUI_PYTHON") or sys.executable
+ log = open(base / "server.log", "w")
+ proc = subprocess.Popen(
+ [python, "main.py", "--cpu", "--listen", "127.0.0.1", "--port", str(PORT),
+ "--base-directory", str(base), "--disable-auto-launch"],
+ cwd=COMFYUI_DIR, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, SCULPTFORGE_CLI=cli.find_cli()))
+ try:
+ deadline = time.time() + 180
+ while True:
+ try:
+ get("/system_stats")
+ break
+ except (urllib.error.URLError, ConnectionError, TimeoutError):
+ if proc.poll() is not None or time.time() > deadline:
+ raise AssertionError("ComfyUI did not start:\n" + (base / "server.log").read_text()[-4000:])
+ time.sleep(1)
+ yield base
+ finally:
+ proc.terminate()
+ try:
+ proc.wait(20)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ log.close()
+
+
+def test_nodes_register(server):
+ info = get_json("/object_info")
+ for name, display in nodes.NODE_DISPLAY_NAME_MAPPINGS.items():
+ assert name in info, f"{name} missing; see {server / 'server.log'}"
+ assert info[name]["display_name"] == display
+ assert info[name]["category"] == "SculptForge"
+ assert info["SculptForgeVoxelRemesh"]["input"]["required"]["mesh"][0] == "SF_MESH,MESH"
+ assert info["SculptForgeToMesh"]["output"] == ["MESH"]
+ assert info["SculptForgeExport"]["output_node"] is True
+ log = (server / "server.log").read_text()
+ assert "IMPORT FAILED" not in log or "ComfyUI-SculptForge" not in log
+
+
+def test_inflate_remesh_export_glb(server, tmp_path):
+ image = upload_image(os.path.join(EXAMPLES, "teddy.png"))
+ outputs = run_workflow("inflate-remesh-export.json", image)
+ entries = outputs["4"]["3d"]
+ assert len(entries) == 1 and entries[0]["type"] == "output" and entries[0]["filename"].endswith(".glb")
+ glb = download(entries[0], tmp_path)
+ assert meshio.glb_bytes_magic(glb)
+ assert triangles(glb) > 10_000
+ shutil.copy(glb, server / "teddy-e2e.glb") # kept with the server log for inspection
+
+
+def test_core_mesh_roundtrip(server, tmp_path):
+ image = upload_image(os.path.join(EXAMPLES, "teddy.png"))
+ outputs = run_workflow("core-mesh-roundtrip.json", image)
+ # SculptForge -> core MESH -> core SaveGLB
+ core_glb = download(outputs["5"]["3d"][0], tmp_path)
+ assert meshio.glb_bytes_magic(core_glb) and triangles(core_glb) > 10_000
+ # core MESH -> SculptForge remesh/decimate -> LODs and FBX
+ lods = [download(e, tmp_path) for e in outputs["9"]["3d"]]
+ counts = [triangles(p) for p in lods]
+ assert len(counts) == 3 and counts[0] > counts[1] > counts[2] > 0
+ fbx = download(outputs["10"]["3d"][0], tmp_path)
+ assert fbx.endswith(".fbx") and triangles(fbx) == counts[0]
+ info = outputs["8"]["text"][0]
+ assert f"{counts[0]} triangles" in info
diff --git a/integrations/comfyui/ComfyUI-SculptForge/tests/test_nodes.py b/integrations/comfyui/ComfyUI-SculptForge/tests/test_nodes.py
new file mode 100644
index 00000000..b95ee6da
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/tests/test_nodes.py
@@ -0,0 +1,293 @@
+# SculptForge - ComfyUI node tests against the fake CLI (no SculptForge install needed).
+# SPDX-License-Identifier: GPL-3.0-or-later
+import os
+import struct
+
+import numpy as np
+import pytest
+import torch
+from PIL import Image
+
+from sculptforge_comfy import cli, meshio, nodes, paths
+
+
+class CoreMesh:
+ """Shaped like comfy_api.latest.Types.MESH."""
+
+ def __init__(self, vertices, faces, vertex_colors=None, vertex_counts=None, face_counts=None):
+ self.vertices, self.faces, self.vertex_colors = vertices, faces, vertex_colors
+ self.vertex_counts, self.face_counts = vertex_counts, face_counts
+
+
+def tetra_mesh():
+ v = torch.tensor([[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]], dtype=torch.float32)
+ f = torch.tensor([[[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]]], dtype=torch.int64)
+ return CoreMesh(v, f)
+
+
+def disc_image(size=64):
+ """An orange disc on a transparent background, as LoadImage returns it (IMAGE + MASK)."""
+ yy, xx = torch.meshgrid(torch.arange(size), torch.arange(size), indexing="ij")
+ inside = ((yy - size / 2) ** 2 + (xx - size / 2) ** 2) < (size / 3) ** 2
+ image = torch.zeros(1, size, size, 3)
+ image[0][inside] = torch.tensor([1.0, 0.5, 0.0])
+ mask = (~inside).float()[None]
+ return image, mask
+
+
+# ---------------------------------------------------------------- finding and running the CLI
+
+
+def test_cli_env_var_pointing_nowhere_is_an_error(monkeypatch, tmp_path):
+ monkeypatch.setenv(cli.CLI_ENV, str(tmp_path / "missing"))
+ with pytest.raises(cli.SculptForgeError, match="SCULPTFORGE_CLI is set"):
+ cli.find_cli()
+
+
+def test_cli_missing_explains_how_to_fix(monkeypatch):
+ monkeypatch.delenv(cli.CLI_ENV, raising=False)
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr(cli, "_install_dirs", lambda: [])
+ with pytest.raises(cli.SculptForgeError, match="SCULPTFORGE_CLI"):
+ cli.find_cli()
+
+
+def test_cli_found_in_install_dir_or_env_folder(monkeypatch, fake_cli):
+ folder = os.path.dirname(fake_cli.path)
+ monkeypatch.setenv(cli.CLI_ENV, folder) # a folder works too
+ assert cli.find_cli() == fake_cli.path
+ monkeypatch.delenv(cli.CLI_ENV)
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr(cli, "_install_dirs", lambda: ["/nonexistent", folder])
+ assert cli.find_cli() == fake_cli.path
+
+
+def test_paths_go_through_variables_not_script_text(fake_cli, tmp_path):
+ odd = tmp_path / 'a folder; with "quotes" and $dollar'
+ odd.mkdir()
+ src = odd / "in put.obj"
+ src.write_text('{"name": "rock", "triangles": 100}')
+ out = odd / "out.sfproj"
+ cli.run("open path=$IN; save_project path=$OUT", {"IN": str(src), "OUT": str(out)})
+ call = fake_cli()[-1]
+ assert call["script"] == "open path=$IN; save_project path=$OUT"
+ assert call["vars"] == {"IN": str(src), "OUT": str(out)}
+ assert out.exists()
+
+
+def test_cli_errors_carry_the_cli_message(fake_cli, monkeypatch):
+ monkeypatch.setenv("FAKE_SF_FAIL", "Resolution too high")
+ with pytest.raises(cli.SculptForgeError, match="Resolution too high"):
+ cli.run("new_sphere")
+
+
+# ---------------------------------------------------------------- nodes
+
+
+def test_every_node_is_well_formed():
+ assert set(nodes.NODE_CLASS_MAPPINGS) == set(nodes.NODE_DISPLAY_NAME_MAPPINGS)
+ for name, cls in nodes.NODE_CLASS_MAPPINGS.items():
+ assert cls.CATEGORY == "SculptForge", name
+ assert callable(getattr(cls, cls.FUNCTION)), name
+ spec = cls.INPUT_TYPES()
+ assert "required" in spec, name
+ assert len(getattr(cls, "RETURN_NAMES", cls.RETURN_TYPES)) == len(cls.RETURN_TYPES), name
+ assert cls.DESCRIPTION, name
+ # Mesh inputs accept SculptForge meshes and ComfyUI's core MESH.
+ assert nodes.SculptForgeVoxelRemesh.INPUT_TYPES()["required"]["mesh"][0] == "SF_MESH,MESH"
+
+
+def test_inflate_writes_png_with_mask_as_alpha(fake_cli):
+ image, mask = disc_image()
+ (mesh,) = nodes.SculptForgeInflateImage().inflate(image, 0.8, 96, 2, mask)
+ assert isinstance(mesh, nodes.SFMesh) and os.path.isfile(mesh.path)
+ call = fake_cli()[-1]
+ assert call["script"].startswith("image_inflate path=$IMG thickness=0.8 resolution=96 subdivisions=2;")
+ png = Image.open(call["vars"]["IMG"])
+ assert png.mode == "RGBA"
+ alpha = np.asarray(png)[..., 3]
+ assert alpha[32, 32] == 255 and alpha[0, 0] == 0
+
+
+def test_inflate_ignores_empty_mask(fake_cli):
+ image, _ = disc_image()
+ nodes.SculptForgeInflateImage().inflate(image, 1.0, 160, 1, torch.zeros(1, 64, 64))
+ assert Image.open(fake_cli()[-1]["vars"]["IMG"]).mode == "RGB"
+
+
+def test_processing_chain(fake_cli):
+ image, mask = disc_image()
+ (mesh,) = nodes.SculptForgeInflateImage().inflate(image, 1.0, 160, 1, mask)
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(mesh, 128)
+ assert mesh.info == "Remeshed to 1280 triangles"
+ (mesh,) = nodes.SculptForgeDecimate().decimate(mesh, 0.25, 0)
+ assert mesh.info == "Decimated to 320 triangles"
+ (mesh,) = nodes.SculptForgeDecimate().decimate(mesh, 0.25, 100)
+ assert mesh.info == "Decimated to 100 triangles"
+ (mesh,) = nodes.SculptForgeSubdivide().subdivide(mesh, 2)
+ assert mesh.info == "Subdivided to 1600 triangles"
+ scripts = [c["script"] for c in fake_cli()]
+ assert scripts[1] == "open path=$IN; remesh resolution=128; save_project path=$OUT"
+ assert "decimate ratio=0.25;" in scripts[2] and "decimate triangles=100;" in scripts[3]
+ # Each step reads the previous step's output.
+ calls = fake_cli()
+ assert all(calls[i + 1]["vars"]["IN"] == calls[i]["vars"]["OUT"] for i in range(len(calls) - 1))
+
+
+def test_core_mesh_input_is_converted_to_ply(fake_cli):
+ # A zero-padded batch of two: only the first item's real vertices/faces may be used.
+ v = torch.zeros(2, 6, 3)
+ v[0, :4] = tetra_mesh().vertices[0]
+ f = torch.zeros(2, 5, 3, dtype=torch.int64)
+ f[0, :4] = tetra_mesh().faces[0]
+ colors = torch.ones(2, 6, 3) * torch.tensor([1.0, 0.0, 0.0])
+ mesh = CoreMesh(v, f, colors, torch.tensor([4, 6]), torch.tensor([4, 5]))
+ (out,) = nodes.SculptForgeVoxelRemesh().remesh(mesh, 64)
+ ply = fake_cli()[-1]["vars"]["IN"]
+ assert os.path.basename(ply) == "ComfyUI_mesh.ply"
+ m = meshio.read_ply(ply)
+ assert m["vertices"].shape == (4, 3) and m["faces"].shape == (4, 3)
+ np.testing.assert_allclose(m["colors"][0], [1, 0, 0])
+ assert out.info == "Remeshed to 640 triangles"
+
+
+def test_to_mesh_produces_core_mesh(fake_cli):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ (core,) = nodes.SculptForgeToMesh().convert(mesh)
+ assert tuple(core.vertices.shape) == (1, 4, 3) and core.vertices.dtype == torch.float32
+ assert tuple(core.faces.shape) == (1, 4, 3) and core.faces.dtype == torch.int64
+ assert tuple(core.normals.shape) == (1, 4, 3)
+ np.testing.assert_allclose(core.vertex_colors[0, 0].numpy(), [1.0, 128 / 255, 0.0], atol=1e-6)
+
+
[email protected]("fmt,command", sorted(nodes.EXPORT_COMMANDS.items()))
+def test_export_formats(fake_cli, comfy_dirs, fmt, command):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ result = nodes.SculptForgeExport().export(mesh, fmt, "3d/Rock")
+ entry = result["ui"]["3d"][0]
+ assert entry == {"filename": f"Rock_00001_.{fmt}", "subfolder": "3d", "type": "output"}
+ path = result["result"][0]
+ assert path == str(comfy_dirs / "output" / "3d" / entry["filename"]) and os.path.isfile(path)
+ assert fake_cli()[-1]["script"] == f"open path=$IN; {command} path=$OUT"
+
+
+def test_export_numbers_files_like_comfyui(fake_cli):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ names = [nodes.SculptForgeExport().export(mesh, "glb", "Rock")["ui"]["3d"][0]["filename"] for _ in range(3)]
+ assert names == ["Rock_00001_.glb", "Rock_00002_.glb", "Rock_00003_.glb"]
+
+
+def test_export_refuses_paths_outside_output(fake_cli):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ with pytest.raises(ValueError):
+ nodes.SculptForgeExport().export(mesh, "glb", "../../escape")
+
+
+def test_lod_chain(fake_cli, comfy_dirs):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ result = nodes.SculptForgeLODChain().export(mesh, 3, 0.4, "lods/Rock")
+ names = [e["filename"] for e in result["ui"]["3d"]]
+ assert names == ["Rock_00001_LOD0.glb", "Rock_00001_LOD1.glb", "Rock_00001_LOD2.glb"]
+ assert all(meshio.glb_bytes_magic(p) for p in result["result"][0].splitlines())
+ assert "export_lods path=$OUT levels=3 ratio=0.4" in fake_cli()[-1]["script"]
+ # The next chain gets the next number.
+ again = nodes.SculptForgeLODChain().export(mesh, 1, 0.5, "lods/Rock")
+ assert again["ui"]["3d"][0]["filename"] == "Rock_00002_LOD0.glb"
+
+
+def test_mesh_info(fake_cli):
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ result = nodes.SculptForgeMeshInfo().info(mesh)
+ text = result["result"][0]
+ assert text.startswith("320 vertices, 640 triangles")
+ assert "ComfyUI_mesh (640 triangles, active)" in text
+ assert result["ui"]["text"] == (text,)
+
+
+def test_load_mesh_relative_to_input(fake_cli, comfy_dirs):
+ (comfy_dirs / "input" / "3d").mkdir(parents=True)
+ (comfy_dirs / "input" / "3d" / "rock.obj").write_text('{"name": "rock", "triangles": 100}')
+ (mesh,) = nodes.SculptForgeLoadMesh().load("3d/rock.obj")
+ assert fake_cli()[-1]["vars"]["IN"] == str(comfy_dirs / "input" / "3d" / "rock.obj")
+ assert os.path.isfile(mesh.path)
+ assert nodes.SculptForgeLoadMesh.IS_CHANGED("3d/rock.obj") > 0
+ with pytest.raises(cli.SculptForgeError, match="not found"):
+ nodes.SculptForgeLoadMesh().load("3d/missing.obj")
+
+
+def test_missing_working_file_is_explained(fake_cli):
+ with pytest.raises(cli.SculptForgeError, match="temp folder"):
+ nodes.SculptForgeDecimate().decimate(nodes.SFMesh("/nonexistent/x.sfproj"), 0.5, 0)
+
+
+def test_open_in_app(fake_cli, monkeypatch):
+ launched = []
+ monkeypatch.setattr(cli, "launch_app", lambda path: launched.append(path) or "sculptforge")
+ node = nodes.SculptForgeOpenInApp()
+ assert node.open(False, file_path="/x.glb") == {}
+ node.open(True, file_path="/out/a.glb\n/out/b.glb")
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(tetra_mesh(), 64)
+ node.open(True, mesh=mesh)
+ assert launched[0] == "/out/a.glb"
+ assert launched[1].endswith("SculptForge from ComfyUI.sfproj") and os.path.isfile(launched[1])
+ with pytest.raises(cli.SculptForgeError):
+ node.open(True)
+
+
+def test_launch_app_finds_app_next_to_cli(fake_cli, monkeypatch, tmp_path):
+ app = os.path.join(os.path.dirname(fake_cli.path), "sculptforge")
+ with open(app, "w") as f:
+ f.write("")
+ monkeypatch.delenv(cli.APP_ENV, raising=False)
+ assert cli.find_app() == app
+ started = []
+ monkeypatch.setattr(cli.subprocess, "Popen", lambda args, **kw: started.append((args, kw)))
+ cli.launch_app("/tmp/a.glb")
+ assert started[0][0] == [app, "/tmp/a.glb"] and "shell" not in started[0][1]
+
+
+# ---------------------------------------------------------------- PLY reading/writing
+
+
+def test_ply_roundtrip(tmp_path):
+ rng = np.random.default_rng(1)
+ v = rng.random((50, 3), dtype=np.float32)
+ f = rng.integers(0, 50, (80, 3))
+ c = rng.random((50, 3))
+ path = tmp_path / "m.ply"
+ meshio.write_ply(path, v, f, c)
+ m = meshio.read_ply(path)
+ np.testing.assert_array_equal(m["vertices"], v)
+ np.testing.assert_array_equal(m["faces"], f)
+ np.testing.assert_allclose(m["colors"], c, atol=0.5 / 255 + 1e-6)
+ assert m["normals"] is None
+
+
+def test_ply_polygons_are_fan_triangulated(tmp_path):
+ header = (b"ply\nformat binary_little_endian 1.0\nelement vertex 5\nproperty float x\nproperty float y\n"
+ b"property float z\nelement face 2\nproperty list uchar uint vertex_indices\nend_header\n")
+ body = b"".join(struct.pack("<fff", *p) for p in [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (2, 0, 0)])
+ body += struct.pack("<BIIII", 4, 0, 1, 2, 3) + struct.pack("<BIII", 3, 1, 4, 2)
+ path = tmp_path / "quad.ply"
+ path.write_bytes(header + body)
+ np.testing.assert_array_equal(meshio.read_ply(path)["faces"], [[0, 1, 2], [0, 2, 3], [1, 4, 2]])
+
+
+def test_ply_rejects_out_of_range_faces(tmp_path):
+ with pytest.raises(ValueError):
+ meshio.write_ply(tmp_path / "bad.ply", np.zeros((3, 3)), [[0, 1, 3]])
+
+
+def test_save_path_uses_comfyui_when_available(monkeypatch, tmp_path):
+ class FolderPaths:
+ @staticmethod
+ def get_output_directory():
+ return str(tmp_path)
+
+ @staticmethod
+ def get_save_image_path(prefix, output_dir):
+ return str(tmp_path / "sub"), "name", 7, "sub", prefix
+
+ monkeypatch.setattr(paths, "folder_paths", FolderPaths)
+ assert paths.save_path("sub/name") == (str(tmp_path / "sub"), "name", 7, "sub")
+ assert os.path.isdir(tmp_path / "sub")
diff --git a/integrations/comfyui/ComfyUI-SculptForge/tests/test_real_cli.py b/integrations/comfyui/ComfyUI-SculptForge/tests/test_real_cli.py
new file mode 100644
index 00000000..840ad35b
--- /dev/null
+++ b/integrations/comfyui/ComfyUI-SculptForge/tests/test_real_cli.py
@@ -0,0 +1,62 @@
+# SculptForge - node tests against the real sculptforge-cli (skipped when it isn't installed).
+# SPDX-License-Identifier: GPL-3.0-or-later
+import os
+
+import numpy as np
+import pytest
+import torch
+from PIL import Image
+
+from sculptforge_comfy import cli, meshio, nodes
+
+EXAMPLES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "examples")
+
+
[email protected](autouse=True)
+def real_cli():
+ try:
+ cli.find_cli()
+ except cli.SculptForgeError as e:
+ pytest.skip(str(e))
+
+
+def load_teddy():
+ """examples/teddy.png the way ComfyUI's LoadImage returns it."""
+ rgba = np.asarray(Image.open(os.path.join(EXAMPLES, "teddy.png")).convert("RGBA"), dtype=np.float32) / 255
+ return torch.from_numpy(rgba[..., :3])[None], torch.from_numpy(1.0 - rgba[..., 3])[None]
+
+
+def triangles(mesh):
+ text = nodes.SculptForgeMeshInfo().info(mesh)["result"][0]
+ return int(text.split(" triangles")[0].split()[-1])
+
+
+def test_teddy_to_game_ready_assets(tmp_path):
+ image, mask = load_teddy()
+ (mesh,) = nodes.SculptForgeInflateImage().inflate(image, 1.0, 128, 1, mask)
+ inflated = triangles(mesh)
+ assert inflated > 10_000
+ (mesh,) = nodes.SculptForgeVoxelRemesh().remesh(mesh, 96)
+ (mesh,) = nodes.SculptForgeDecimate().decimate(mesh, 0.5, 0)
+ decimated = triangles(mesh)
+ (sub,) = nodes.SculptForgeSubdivide().subdivide(mesh, 1)
+ assert triangles(sub) == decimated * 4
+
+ glb = nodes.SculptForgeExport().export(mesh, "glb", "test/teddy")["result"][0]
+ assert meshio.glb_bytes_magic(glb)
+ for fmt in ("fbx", "usdz", "obj", "stl"):
+ path = nodes.SculptForgeExport().export(mesh, fmt, "test/teddy")["result"][0]
+ assert os.path.getsize(path) > 1000, fmt
+ lods = nodes.SculptForgeLODChain().export(mesh, 3, 0.5, "test/teddy_lods")["result"][0].splitlines()
+ assert len(lods) == 3 and all(meshio.glb_bytes_magic(p) for p in lods)
+
+
+def test_core_mesh_roundtrip_keeps_geometry_and_colour():
+ v = torch.tensor([[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]], dtype=torch.float32)
+ f = torch.tensor([[[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]]], dtype=torch.int64)
+ core = meshio.mesh_class()(vertices=v, faces=f, vertex_colors=torch.full((1, 4, 3), 0.5))
+ (sf,) = nodes.SculptForgeSubdivide().subdivide(core, 1)
+ (back,) = nodes.SculptForgeToMesh().convert(sf)
+ assert tuple(back.faces.shape) == (1, 16, 3) and back.vertices.shape[1] == 10
+ np.testing.assert_allclose(back.vertex_colors[0].numpy(), 0.5, atol=1 / 255)
+ assert back.vertices.min() >= -1e-6 and back.vertices.max() <= 1 + 1e-6