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.

Generate 3D: Hunyuan3D 2.1 default, TRELLIS.2 no-token fallback, Quad Remesh for generated models

islandmed50b6ab1a0542
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5607791..a1dfb621 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,13 +6,27 @@ All notable changes to SculptForge are listed here. The format follows
## [Unreleased]
+### Changed
+- Image and text to 3D work out of the box with no token: the free Hugging Face default is now **Hunyuan3D 2.1**,
+ for new installs and for everyone who never picked a model (an explicit choice is kept; a saved TRELLIS.2 is
+ kept when a token is saved too). TRELLIS.2 shows as "Best detail (needs token)".
+- TRELLIS.2 without a Hugging Face token no longer fails: Hunyuan3D 2.1 runs instead and the status line says
+ "TRELLIS.2 needs a free Hugging Face token (Preferences > AI); used Hunyuan3D 2.1 instead." The token can now be
+ set in the new **Preferences > AI** too.
+- Generated models get **Quad Remesh** by default instead of voxel remesh: clean quads (about resolution² / 2, 32768
+ at the default 256) with one subdivision level projected onto the model, ready to sculpt and subdivide. A voxel
+ pass cleans up holes and overlapping pieces first. It runs in the background with the progress bar (about 20 s
+ for a typical Hunyuan3D model). **Remesh** in Generate 3D also offers Voxel remesh and Off; the CLI takes
+ `remesh=quad|voxel|false` (`true` means quad) and `levels=0-2`. The status line says "remeshed to N quads".
+- The Hunyuan3D licence notice (the Tencent Hunyuan Community License doesn't cover use in the EU, UK or South
+ Korea) is shown once, the first time a Hunyuan3D model runs, and stays in the Model picker's tooltip.
+
## [0.10.8] - 2026-11-02
### Fixed
- Tablet Mouse mode (Preferences > Tablet): on some Windows tablets the brush stopped following the pen in 0.10.7,
because the system cursor reading stayed put while the pen moved. A reading that doesn't move with the pen is now
ignored and the pen moves the brush relatively, from where it was, with no jump (#72).
-
## [0.10.7] - 2026-11-01
### Changed
diff --git a/CMakeLists.txt b/CMakeLists.txt
index dd947ce2..d550ffae 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -99,6 +99,7 @@ add_library(sculptforge_core STATIC
src/core/TextureTransfer.cpp
src/core/SurfaceQuery.cpp
src/core/QRemesh.cpp
+ src/core/GeneratedRemesh.cpp
src/core/QRemeshGuides.cpp
src/core/QRemesh2.cpp
src/core/QRemesh2Proxy.cpp
diff --git a/REPORT.md b/REPORT.md
new file mode 100644
index 00000000..3fafe7e7
--- /dev/null
+++ b/REPORT.md
@@ -0,0 +1,4 @@
+# fix/gen3d-default: PAUSED (usage stop), committed locally, NOT pushed
+Done: default Hunyuan3D 2.1 (hfModelChosen migration), TRELLIS.2 no-token fallback + note, Preferences > AI token, one-time Hunyuan licence notice + tooltip; Quad Remesh default for generated models (core/GeneratedRemesh, worker thread, remesh=quad|voxel|false, levels); text_to_3d offline-service fix; docs/CHANGELOG/What's New 0.10.8; targeted tests (free_huggingface_models, generated_remesh*) pass. Lion head Quad Remesh 21.6 s (nice 19, load 3-5) vs voxel 0.8 s.
+Left: full ctest never finished (stopped). AI visibility switch NOT started (two conflicting pasted notes; awaiting Tony's choice).
+Resume: nice -n 19 ionice -c3 cmake --build build -j3; if `pgrep -x ctest` is empty: SDL_APP_ID=sculptforge-agent nice -n 19 ionice -c3 ctest --test-dir build -j3; green -> git push -u origin fix/gen3d-default, add SHA here, message coordinator.
diff --git a/docs/guide/generate-3d.md b/docs/guide/generate-3d.md
index 77aefb98..5df4f2b4 100644
--- a/docs/guide/generate-3d.md
+++ b/docs/guide/generate-3d.md
@@ -11,8 +11,8 @@ tools: relief, inflate and stamp.
1. You give SculptForge an image (a sketch, concept art, a photo of a figurine) or a short description.
2. The service you picked reconstructs a complete mesh: front, back, limbs and all.
-3. SculptForge opens the result as a new scene and, unless you turn it off, **voxel-remeshes** it into one
- even, watertight surface, so the brushes behave the same as on any other sculpt.
+3. SculptForge opens the result as a new scene and, unless you choose otherwise, **Quad Remeshes** it into
+ clean quads with one subdivision level that holds the detail, ready to sculpt and subdivide.
Nothing leaves your computer until you choose a hosted service and press **Generate 3D model**. For exactly
what is sent where, see [AI services and privacy](#privacy-and-model-licences) below.
@@ -41,13 +41,20 @@ The window has two tabs, **From image** and **From text**.
2. Pick a service in the drop-down under **Full 3D model (AI reconstruction)**. The default is **Hugging Face
- free models**.
3. Set the service's options (model, token or key, see below).
-4. Leave **Remesh for sculpting** on and set its **Resolution** (96 to 400, default 256). Higher keeps more
- detail and makes more triangles.
+4. Choose **Remesh** and its **Resolution** (96 to 400, default 256; higher keeps more detail):
+ - **Quad Remesh** (the default): clean, all-quad topology of about resolution² / 2 quads (32768 at 256), then
+ one subdivision level projected onto the model so the detail survives. Generated meshes often have holes
+ and overlapping pieces, so a voxel pass cleans the mesh up first. Step down to the quad cage with
+ <kbd>Shift</kbd>+<kbd>D</kbd>.
+ - **Voxel remesh**: one even, watertight triangle surface. Faster (about a second).
+ - **Off (raw mesh)**: the model exactly as the service made it.
5. Click **Generate 3D model**. A progress bar shows the queue position and progress; **Cancel** stops the
job.
-When it finishes, the status line reports the triangle count before and after remeshing, for example
-"Generated model imported (412000 tris, remeshed to 180000) - ready to sculpt".
+When it finishes, the status line reports the size before and after remeshing, for example
+"Generated model imported (47214 tris, remeshed to 133540 quads (2 subdivision levels)) - ready to sculpt".
+Quad Remesh takes about 10 to 25 seconds after the model arrives (a 47,000-triangle Hunyuan3D head took 22 s
+on a busy 10-core computer); the progress bar shows it and the window stays usable.
### Pictures that work well
@@ -91,25 +98,30 @@ This runs each model author's own public demo on Hugging Face's shared ZeroGPU h
| Model | Notes |
|---|---|
-| TRELLIS.2 (Microsoft) | The default. The most detail, MIT licence. Needs a free Hugging Face token |
-| Hunyuan3D 2.1 (Tencent) | Detailed shapes, about 20 seconds, no token needed |
+| Hunyuan3D 2.1 (Tencent) | The default. Detailed shapes, about 20 seconds, no token needed |
+| TRELLIS.2 (Microsoft) | Best detail, MIT licence. Needs a free Hugging Face token |
| Hunyuan3D 2 mini Turbo (Tencent) | The fastest, about 6 seconds |
| Hunyuan3D 2 (Tencent) | |
-
-The Hunyuan3D models' licence doesn't cover use in the European Union, the United Kingdom or South Korea; the
-panel says so when one is picked. See [AI services](https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md)
-for each model's licence.
| Stable Fast 3D (Stability AI) | Quick and simple, removes the background itself |
+If you never picked a model, SculptForge uses the default, so updates that change it reach you; a model you pick
+(and save) is kept. If you pick TRELLIS.2 without a token, Hunyuan3D 2.1 runs instead and the status line says
+"TRELLIS.2 needs a free Hugging Face token (Preferences > AI); used Hunyuan3D 2.1 instead."
+
+The Hunyuan3D models' licence doesn't cover use in the European Union, the United Kingdom or South Korea. The
+first time a Hunyuan3D model runs, a notice says so, and it stays in the **Model** picker's tooltip. See
+[AI services](https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md) for each model's licence.
+
GPU time is rationed per person per day, there can be a queue at busy times, and a demo can be paused or
changed by its owner. To raise the allowance, create a free token with read access at
-huggingface.co/settings/tokens and paste it into **HF token** (or set the `HF_TOKEN` environment variable).
+huggingface.co/settings/tokens and paste it into **HF token** or **Preferences > AI** (or set the `HF_TOKEN`
+environment variable).
When the allowance runs out you see "Hugging Face's free GPU time is used up for now"; add a token, wait for
it to refill, or pick another model.
> **Warning:** The Hunyuan3D models are under the Tencent Hunyuan Community License, which does not cover use
-> in the European Union, the United Kingdom or South Korea. If you work there, choose TRELLIS.2, Stable Fast
-> 3D or a paid service. Each model has its own licence; read it before using results commercially.
+> in the European Union, the United Kingdom or South Korea. If you work there, choose TRELLIS.2 (free token),
+> Stable Fast 3D or a paid service. Each model has its own licence; read it before using results commercially.
### fal.ai and Meshy (paid)
@@ -211,9 +223,9 @@ run instantly. The same tools are in the **Generate** palette as **Relief**, **I
Generated meshes are a starting point. A typical next pass:
-1. Check the size of the remeshed result in the title strip (Verts, Tris). If the detail is too soft, generate
- again with a higher **Resolution**, or run **Tool > Remesh > Voxel Remesh** at a higher value on the
- result.
+1. Check the size of the remeshed result in the title strip (Verts, Tris). If the detail is too soft, divide once more
+ (<kbd>Ctrl</kbd>+<kbd>D</kbd>), or generate again with a higher **Resolution**. **Tool > Remesh** has Quad Remesh
+ (first) and Voxel Remesh for another pass.
2. Turn on **X** symmetry if the subject is symmetrical, and sculpt the forms with Clay Block, Move and Sharp Crease ([Sculpting and brushes](sculpting.md)).
3. Save a project (<kbd>Ctrl</kbd>+<kbd>S</kbd>): generated scenes start untitled.
@@ -222,12 +234,15 @@ Generated meshes are a starting point. A typical next pass:
The same services are available as commands, in the console, `sculptforge-cli`, Python and MCP agents:
```sh
-# free (Hunyuan3D 2.1 on Hugging Face)
+# free, no token (Hunyuan3D 2.1 on Hugging Face, the default)
sculptforge-cli -c 'image_to_3d path=hero.png; export_glb path=hero.glb'
-# TRELLIS.2 with a Hugging Face token
+# TRELLIS.2, best detail, with a free Hugging Face token (without one, Hunyuan3D 2.1 runs and says so)
HF_TOKEN=hf_... sculptforge-cli -c 'image_to_3d path=hero.png model=trellis-2; export_glb path=hero.glb'
+# voxel remesh instead of the default Quad Remesh
+sculptforge-cli -c 'image_to_3d path=hero.png remesh=voxel; export_glb path=hero.glb'
+
# fal.ai, keeping the raw (not remeshed) result
FAL_KEY=... sculptforge-cli -c 'image_to_3d path=hero.png service=fal model=fal-ai/trellis-2 remesh=false; export_glb path=hero.glb'
@@ -244,8 +259,8 @@ sculptforge-cli -c 'image_inflate path=sketch.png thickness=0.7; save_project pa
| Command | Key parameters |
|---|---|
-| `image_to_3d` | `path` (required), `service` (`huggingface`, `fal`, `meshy`, `comfyui`, `command`, `inflate`), `model`, `workflow`, `url`, `seed`, `remesh` (default true), `resolution` (64 to 512, default 256) |
-| `text_to_3d` | `prompt` (required), `service` (`huggingface`, `fal`, `meshy`, `comfyui`), `model`, `workflow`, `url`, `seed`, `remesh`, `resolution` |
+| `image_to_3d` | `path` (required), `service` (`huggingface`, `fal`, `meshy`, `comfyui`, `command`, `inflate`), `model`, `workflow`, `url`, `seed`, `remesh` (`quad`, the default; `voxel`; `false`), `resolution` (64 to 512, default 256), `levels` (quad: 0 to 2 subdivision levels, default 1) |
+| `text_to_3d` | `prompt` (required), `service` (`huggingface`, `fal`, `meshy`, `comfyui`), `model`, `workflow`, `url`, `seed`, `remesh`, `resolution`, `levels` |
| `image_relief` | `path` (required), `depth` (default 0.12), `resolution` (default 384), `invert` |
| `image_inflate` | `path` (required), `thickness` (default 1), `resolution` (default 160), `subdivisions` (default 1) |
| `image_project` | `path` (required), `depth` (default 0.03), `invert`. Projects from the front (+Z) |
@@ -270,7 +285,7 @@ The full table of what is sent where is in `docs/ai-services.md` in the SculptFo
## See also
- [Sculpting and brushes](sculpting.md): refine the generated model
-- [Subdivide, Remesh, Decimate and LODs](geometry.md): voxel remesh in detail
+- [Subdivide, Remesh, Decimate and LODs](geometry.md): Quad Remesh and voxel remesh in detail
- [Gaussian splats](splats.md): start from a phone capture instead of a picture
- [Scripting and automation](scripting.md): batch generation from the command line
- [Troubleshooting](troubleshooting.md#ai-services): quota and connection messages
diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.md
index d8920df6..e82b7222 100644
--- a/docs/guide/whats-new.md
+++ b/docs/guide/whats-new.md
@@ -5,6 +5,14 @@ chapter opens by itself the first time you start a new version; you can always f
**Help > What's New**. Every detail is in the
[changelog](https://github.com/islandmed/SculptForge/blob/main/CHANGELOG.md).
+## Version 0.10.9
+
+- **Image to 3D with no setup**: the free default is now Hunyuan3D 2.1, which needs no token. TRELLIS.2 ("Best
+ detail") still needs a free Hugging Face token (**Preferences > AI**); without one, Hunyuan3D 2.1 runs instead
+ and the status line tells you. Your own model choice is kept. See [Image and text to 3D](generate-3d.md).
+- **Generated models arrive as clean quads**: Quad Remesh is now the default, with one subdivision level holding
+ the detail, so you can sculpt and subdivide straight away. Voxel remesh and Off are still in **Remesh**.
+
## Version 0.10.8
- **Tablets in mouse mode work again**: on some Windows tablets with **Mouse mode** on (Preferences > Tablet) the
diff --git a/src/ai/AiCommands.cpp b/src/ai/AiCommands.cpp
index c79dd551..7d4adede 100644
--- a/src/ai/AiCommands.cpp
+++ b/src/ai/AiCommands.cpp
@@ -6,6 +6,7 @@
#include "ai/ComfyUI.h"
#include "ai/ImageTo3DService.h"
#include "core/EnginePresets.h"
+#include "core/GeneratedRemesh.h"
#include "core/Texture.h"
#include "core/Voxel.h"
#include "link/UnrealLink.h"
@@ -24,6 +25,45 @@ std::optional<uint64_t> comfySeed(const Args& a) {
return uint64_t(std::max(0.0, argNumber(a, "seed", 0.0)));
}
+// remesh=quad (default) | voxel | false. true means quad, the default since 0.10.9.
+bool remeshArg(const Args& a, GeneratedRemesh& mode, std::string& error) {
+ mode = GeneratedRemesh::Quad;
+ const auto it = a.find("remesh");
+ if (it == a.end()) return true;
+ if (const auto* s = std::get_if<std::string>(&it->second)) {
+ if (generatedRemeshFromName(*s, mode)) return true;
+ error = "remesh must be quad, voxel or false";
+ return false;
+ }
+ mode = argBool(a, "remesh", true) ? GeneratedRemesh::Quad : GeneratedRemesh::Off;
+ return true;
+}
+
+// Opens the generated file into the document and makes it sculptable; the message ends "- ready to sculpt".
+CommandResult importGenerated(Document& doc, const Args& a, const GeneratorResult& r, GeneratedRemesh mode,
+ const std::string& what) {
+ CommandResult opened = CommandRegistry().execute(doc, "open", {{"path", r.outputPath}});
+ std::error_code ec;
+ std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
+ if (!opened.ok) return opened;
+ doc.path.clear();
+ GeneratedRemeshStats st;
+ if (mode != GeneratedRemesh::Off) {
+ std::string err;
+ Mesh m;
+ if (!remeshGenerated(doc.mesh, mode, std::clamp(int(argNumber(a, "resolution", 256)), 64, 512),
+ int(argNumber(a, "levels", 1)), m, err, &st))
+ return {false, "Generated, but remeshing failed: " + err};
+ doc.setMesh(std::move(m));
+ } else {
+ st.rawTriangles = doc.mesh.triangleCount();
+ }
+ const std::string note = generatedRemeshNote(st, mode);
+ return {true, "Generated a 3D model" + what + " (" + std::to_string(st.rawTriangles) + " triangles" +
+ (note.empty() ? std::string() : ", " + note) + ") - ready to sculpt" +
+ (r.note.empty() ? std::string() : " " + r.note)};
+}
+
} // namespace
void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> settings) {
@@ -57,12 +97,17 @@ void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> s
"ComfyUI (service=comfyui workflow=FILE). Replaces the scene. A transparent background works best.",
{{"path", T::String, "Image file (png, jpg...).", true},
{"service", T::String, "'huggingface' (free, default), 'fal', 'meshy', 'comfyui' (your ComfyUI server), 'command' (your generator) or 'inflate' (offline blockout).", false},
- {"model", T::String, "huggingface: hunyuan3d-2.1, trellis-2, hunyuan3d-2-turbo, hunyuan3d-2, stable-fast-3d; fal: a model id such as fal-ai/trellis-2.", false},
+ {"model", T::String, "huggingface: hunyuan3d-2.1 (default, no token), trellis-2 (needs HF_TOKEN, else hunyuan3d-2.1 runs), hunyuan3d-2-turbo, hunyuan3d-2, stable-fast-3d; fal: a model id such as fal-ai/trellis-2.", false},
{"workflow", T::String, "comfyui: API-format workflow file (default: your saved one, else the bundled one).", false},
{"url", T::String, "comfyui: server address. Default http://127.0.0.1:8188 or your saved one.", false},
{"seed", T::Number, "comfyui: seed for the workflow's sf_seed / seed inputs (default: random).", false},
- {"remesh", T::Bool, "Voxel-remesh the result into a clean watertight sculpting surface. Default true.", false},
- {"resolution", T::Number, "Remesh voxels across the model (64-512). Default 256.", false}},
+ {"remesh", T::String, "'quad' (default): clean quads for sculpting and subdividing (a voxel cleanup "
+ "pass, Quad Remesh, then Divide with the detail projected back); 'voxel': an even "
+ "watertight triangle surface; 'false': the raw mesh.", false},
+ {"resolution", T::Number, "Remesh detail (64-512): voxels across the model; quad picks about "
+ "resolution^2/2 quads (256: 32768). Default 256.", false},
+ {"levels", T::Number, "quad: subdivision levels above the quad cage (0-2), projected onto the "
+ "model. Default 1.", false}},
[settings](Document& doc, const Args& a) -> CommandResult {
AiSettings s = settings();
if (a.contains("service")) s.generatorService = argString(a, "service");
@@ -77,27 +122,14 @@ void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> s
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
const auto stemU8 = stem.u8string();
const std::string out(stemU8.begin(), stemU8.end());
+ GeneratedRemesh mode;
+ std::string err;
+ if (!remeshArg(a, mode, err)) return {false, err};
GeneratorResult r = s.generatorService == "comfyui"
? comfy::run(s, argString(a, "workflow"), argString(a, "path"), {}, out, nullptr, comfySeed(a))
: generate3D(s, argString(a, "path"), out);
- if (!r.ok) return {false, r.error};
- CommandResult opened = CommandRegistry().execute(doc, "open", {{"path", r.outputPath}});
- std::error_code ec;
- std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
- if (!opened.ok) return opened;
- doc.path.clear();
- const size_t raw = doc.mesh.triangleCount();
- if (argBool(a, "remesh", true)) {
- std::string err;
- Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 256)), 64, 512), &err);
- if (m.triangleCount() == 0) return {false, "Generated, but remeshing failed: " + err};
- doc.setMesh(std::move(m));
- }
- return {true, "Generated a 3D model (" + std::to_string(raw) + " triangles" +
- (raw != doc.mesh.triangleCount()
- ? ", remeshed to " + std::to_string(doc.mesh.triangleCount())
- : std::string()) +
- ") - ready to sculpt"};
+ if (!r.ok) return {false, r.error + (r.note.empty() ? std::string() : " " + r.note)};
+ return importGenerated(doc, a, r, mode, "");
}});
registry.add({"text_to_3d",
@@ -110,13 +142,20 @@ void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> s
{"workflow", T::String, "comfyui: API-format workflow file (default: your saved one, else the bundled one).", false},
{"url", T::String, "comfyui: server address. Default http://127.0.0.1:8188 or your saved one.", false},
{"seed", T::Number, "comfyui: seed for the workflow's sf_seed / seed inputs (default: random).", false},
- {"remesh", T::Bool, "Voxel-remesh the result into a clean watertight sculpting surface. Default true.", false},
- {"resolution", T::Number, "Remesh voxels across the model (64-512). Default 256.", false}},
+ {"remesh", T::String, "'quad' (default): clean quads for sculpting and subdividing (a voxel cleanup "
+ "pass, Quad Remesh, then Divide with the detail projected back); 'voxel': an even "
+ "watertight triangle surface; 'false': the raw mesh.", false},
+ {"resolution", T::Number, "Remesh detail (64-512): voxels across the model; quad picks about "
+ "resolution^2/2 quads (256: 32768). Default 256.", false},
+ {"levels", T::Number, "quad: subdivision levels above the quad cage (0-2), projected onto the "
+ "model. Default 1.", false}},
[settings](Document& doc, const Args& a) -> CommandResult {
AiSettings s = settings();
if (a.contains("service")) s.generatorService = argString(a, "service");
if (a.contains("url")) s.comfyUrl = argString(a, "url");
- if (s.generatorService == "command" || s.generatorService == "inflate") s.generatorService = "huggingface";
+ if (s.generatorService == "command" || s.generatorService == "inflate")
+ return {false, "Text to 3D can't use '" + s.generatorService + "' (it works from an image); pass "
+ "service=huggingface, fal, meshy or comfyui"};
if (a.contains("model")) {
if (s.generatorService == "meshy") s.meshyModel = argString(a, "model");
else if (s.generatorService != "fal") s.hfModel = argString(a, "model");
@@ -126,6 +165,9 @@ void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> s
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
const auto stemU8 = stem.u8string();
const std::string out(stemU8.begin(), stemU8.end());
+ GeneratedRemesh mode;
+ std::string err;
+ if (!remeshArg(a, mode, err)) return {false, err};
GeneratorResult r;
if (s.generatorService == "comfyui") {
if (argString(a, "prompt").find_first_not_of(" \t\r\n") == std::string::npos) return {false, "Describe the model you want"};
@@ -133,20 +175,8 @@ void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> s
} else {
r = generate3DFromText(s, argString(a, "prompt"), out);
}
- if (!r.ok) return {false, r.error};
- CommandResult opened = CommandRegistry().execute(doc, "open", {{"path", r.outputPath}});
- std::error_code ec;
- std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
- if (!opened.ok) return opened;
- doc.path.clear();
- if (argBool(a, "remesh", true)) {
- std::string err;
- Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 256)), 64, 512), &err);
- if (m.triangleCount() == 0) return {false, "Generated, but remeshing failed: " + err};
- doc.setMesh(std::move(m));
- }
- return {true, "Generated a 3D model from text (" + std::to_string(doc.mesh.triangleCount()) +
- " triangles) - ready to sculpt"};
+ if (!r.ok) return {false, r.error + (r.note.empty() ? std::string() : " " + r.note)};
+ return importGenerated(doc, a, r, mode, " from text");
}});
registry.add({"comfyui_check",
diff --git a/src/ai/BrushAssistant.cpp b/src/ai/BrushAssistant.cpp
index 4fdf8e7c..fc0409d5 100644
--- a/src/ai/BrushAssistant.cpp
+++ b/src/ai/BrushAssistant.cpp
@@ -133,6 +133,8 @@ Json AiSettings::toJson() const {
j.set("generatorCommand", generatorCommand);
j.set("hfToken", hfToken);
j.set("hfModel", hfModel);
+ j.set("hfModelChosen", hfModelChosen);
+ j.set("hunyuanNoticeShown", hunyuanNoticeShown);
j.set("falKey", falKey);
j.set("falModel", falModel);
j.set("falEndpoint", falEndpoint);
@@ -164,7 +166,13 @@ AiSettings AiSettings::fromJson(const Json& j) {
};
text("generatorService", s.generatorService);
text("hfToken", s.hfToken);
- text("hfModel", s.hfModel);
+ // A model the user never chose follows the default. Files from before hfModelChosen: TRELLIS.2 was the
+ // default then, so it counts as chosen only with a saved token (it needs one); any other model was picked.
+ const std::string savedModel = j["hfModel"].asString();
+ s.hfModelChosen = j["hfModelChosen"].isBool() ? j["hfModelChosen"].asBool()
+ : !savedModel.empty() && (savedModel != "trellis-2" || !s.hfToken.empty());
+ if (s.hfModelChosen && !savedModel.empty()) s.hfModel = savedModel;
+ s.hunyuanNoticeShown = j["hunyuanNoticeShown"].asBool();
text("falKey", s.falKey);
text("falModel", s.falModel);
text("falEndpoint", s.falEndpoint);
diff --git a/src/ai/BrushAssistant.h b/src/ai/BrushAssistant.h
index 01c2aa2c..118678df 100644
--- a/src/ai/BrushAssistant.h
+++ b/src/ai/BrushAssistant.h
@@ -29,7 +29,9 @@ struct AiSettings {
// {input}/{output}) or "inflate" (offline).
std::string generatorService = "huggingface";
std::string hfToken; // empty = HF_TOKEN from the environment (optional; raises the free quota)
- std::string hfModel = "trellis-2"; // MIT; the default (hfPresets()[0])
+ std::string hfModel = "hunyuan3d-2.1"; // the default (hfPresets()[0]): free, no token
+ bool hfModelChosen = false; // the user picked hfModel; otherwise loading resets it to the current default
+ bool hunyuanNoticeShown = false; // the one-time Hunyuan3D licence notice
std::string generatorCommand;
std::string falKey; // empty = FAL_KEY from the environment
std::string falModel = "fal-ai/trellis-2";
diff --git a/src/ai/Generator3D.h b/src/ai/Generator3D.h
index edaca2ea..2dfba62f 100644
--- a/src/ai/Generator3D.h
+++ b/src/ai/Generator3D.h
@@ -17,6 +17,7 @@ struct GeneratorResult {
bool ok = false;
std::string outputPath;
std::string error;
+ std::string note; // shown with the result, e.g. which model ran instead of the chosen one
};
std::string defaultGeneratorCommand(const std::string& cliPath);
diff --git a/src/ai/ImageTo3DService.cpp b/src/ai/ImageTo3DService.cpp
index d8eb1254..69537cf4 100644
--- a/src/ai/ImageTo3DService.cpp
+++ b/src/ai/ImageTo3DService.cpp
@@ -269,12 +269,8 @@ GeneratorResult runHuggingFace(const AiSettings& s, const std::string& imagePath
const std::string& outputStem, GenerationProgress* p) {
GeneratorResult result;
const bool text = !prompt.empty();
- const auto& presets = text ? hfTextPresets() : hfPresets();
- const HfPreset* preset = nullptr;
- for (const auto& h : presets)
- if (s.hfModel == h.id) preset = &h;
- if (!preset) preset = &presets[0];
-
+ const HfPreset* preset = &resolveHfPreset(s, text, &result.note);
+ if (!result.note.empty()) status(p, result.note);
status(p, "Connecting to " + std::string(preset->label) + "...");
GradioClient client;
if (!client.connect(preset->space, s.resolvedHfToken(), result.error)) return result;
@@ -374,8 +370,26 @@ bool hunyuanModel(std::string_view id) {
}
const char* kHunyuanLicenceNote =
- "Hunyuan3D's licence (Tencent Hunyuan Community License) doesn't cover use in the European Union, the United "
- "Kingdom or South Korea. There, pick TRELLIS.2 or another model.";
+ "Hunyuan3D models are under the Tencent Hunyuan Community License, which doesn't cover use in the EU, UK or "
+ "South Korea. There, choose TRELLIS.2 (free token) or another model.";
+
+const char* kTrellisNoTokenNote =
+ "TRELLIS.2 needs a free Hugging Face token (Preferences > AI); used Hunyuan3D 2.1 instead.";
+
+const HfPreset& resolveHfPreset(const AiSettings& s, bool text, std::string* note) {
+ const auto& presets = text ? hfTextPresets() : hfPresets();
+ auto find = [&](std::string_view id) -> const HfPreset* {
+ for (const auto& h : presets)
+ if (id == h.id) return &h;
+ return nullptr;
+ };
+ if (!text && s.hfModel == "trellis-2" && s.resolvedHfToken().empty()) {
+ if (note) *note = kTrellisNoTokenNote;
+ return *find("hunyuan3d-2.1");
+ }
+ const HfPreset* preset = find(s.hfModel);
+ return preset ? *preset : presets[0];
+}
std::string base64Encode(const uint8_t* data, size_t size) {
static const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -428,11 +442,11 @@ const std::vector<HfPreset>& hfTextPresets() {
const std::vector<HfPreset>& hfPresets() {
static const std::vector<HfPreset> presets = {
- // TRELLIS.2 first: the default, under the MIT licence.
- {"trellis-2", "TRELLIS.2 (Microsoft, MIT) - free, best detail, needs an HF token", "https://microsoft-trellis-2.hf.space",
- {{"start_session", {}}, {"preprocess_image", {"$IMG"}}, {"image_to_3d", {"$OUT1"}}, {"extract_glb", {}}}},
- {"hunyuan3d-2.1", "Hunyuan3D 2.1 (Tencent) - free, detailed shape", "https://tencent-hunyuan3d-2-1.hf.space",
+ // Hunyuan3D 2.1 first: the default, works with no token. resolveHfPreset() falls back to it.
+ {"hunyuan3d-2.1", "Hunyuan3D 2.1 (Tencent) - free, no token", "https://tencent-hunyuan3d-2-1.hf.space",
{{"shape_generation", {"$IMG"}}}},
+ {"trellis-2", "TRELLIS.2 (Microsoft, MIT) - Best detail (needs token)", "https://microsoft-trellis-2.hf.space",
+ {{"start_session", {}}, {"preprocess_image", {"$IMG"}}, {"image_to_3d", {"$OUT1"}}, {"extract_glb", {}}}},
{"hunyuan3d-2-turbo", "Hunyuan3D 2 mini Turbo (Tencent) - free, fastest", "https://tencent-hunyuan3d-2mini-turbo.hf.space",
{{"shape_generation", {"\"\"", "$IMG"}}}},
{"hunyuan3d-2", "Hunyuan3D 2 (Tencent) - free", "https://tencent-hunyuan3d-2.hf.space",
diff --git a/src/ai/ImageTo3DService.h b/src/ai/ImageTo3DService.h
index fa1f46c0..f1d6b6a1 100644
--- a/src/ai/ImageTo3DService.h
+++ b/src/ai/ImageTo3DService.h
@@ -68,6 +68,11 @@ const std::vector<HfPreset>& hfPresets();
// A Hunyuan3D model (Hugging Face preset or fal.ai id): its licence's territory note is shown where it's chosen.
bool hunyuanModel(std::string_view id);
extern const char* kHunyuanLicenceNote;
+// TRELLIS.2's Space needs a Hugging Face token; without one Hunyuan3D 2.1 runs instead, with this note.
+extern const char* kTrellisNoTokenNote;
+// The preset that runs for these settings (image presets, or text presets when `text`). An unknown id gets the
+// first preset; TRELLIS.2 without a token falls back to Hunyuan3D 2.1 and sets `note` to kTrellisNoTokenNote.
+const HfPreset& resolveHfPreset(const AiSettings& settings, bool text, std::string* note = nullptr);
// Free text-to-3D models ("$PROMPT" in step args is the description).
const std::vector<HfPreset>& hfTextPresets();
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 08c6194c..7fcd5879 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -2894,41 +2894,98 @@ void App::startGenerator() {
aiSettings_.comfyUrl = comfyUrl_;
// With no workflow chosen, ComfyUI runs the bundled one the panel shows (not saved, so updates reach it).
ai::AiSettings settings = aiSettings_;
+ const bool hunyuan = settings.generatorService == "huggingface"
+ ? ai::hunyuanModel(ai::resolveHfPreset(settings, textMode_).id)
+ : settings.generatorService == "fal" && ai::hunyuanModel(settings.falModel);
+ if (hunyuan) showHunyuanNoticeOnce();
if (settings.comfyImageWorkflow.empty()) settings.comfyImageWorkflow = comfyDefaultWorkflow(false);
if (settings.comfyTextWorkflow.empty()) settings.comfyTextWorkflow = comfyDefaultWorkflow(true);
auto stem = (std::filesystem::temp_directory_path() / ("sculptforge_generated_" + std::to_string(SDL_GetTicksNS()))).u8string();
generatorTime_ = 0.0f;
generatorProgress_ = std::make_shared<ai::GenerationProgress>();
generatorProgress_->setStatus("Starting...");
- auto promise = std::make_shared<std::promise<ai::GeneratorResult>>();
+ auto promise = std::make_shared<std::promise<GeneratedModel>>();
pendingGenerator_ = promise->get_future();
std::thread([promise, settings, in = refImagePath_, text = textMode_ ? std::string(textPrompt_) : std::string(),
- out = std::string(stem.begin(), stem.end()), progress = generatorProgress_] {
- promise->set_value(text.empty() ? ai::generate3D(settings, in, out, progress.get())
- : ai::generate3DFromText(settings, text, out, progress.get()));
+ out = std::string(stem.begin(), stem.end()), progress = generatorProgress_,
+ mode = GeneratedRemesh(generatedRemesh_), resolution = remeshResolution_] {
+ GeneratedModel g;
+ g.result = text.empty() ? ai::generate3D(settings, in, out, progress.get())
+ : ai::generate3DFromText(settings, text, out, progress.get());
+ if (g.result.ok && mode != GeneratedRemesh::Off) {
+ // Made sculptable here, so the window stays responsive; the main thread opens the file and swaps this in.
+ Document scratch;
+ const CommandResult opened = CommandRegistry().execute(scratch, "open", {{"path", g.result.outputPath}});
+ progress->percent = 0;
+ progress->setStatus(mode == GeneratedRemesh::Quad ? "Making it sculptable: Quad Remesh..." : "Making it sculptable: Voxel Remesh...");
+ Mesh m;
+ if (!opened.ok) {
+ g.remeshError = opened.message;
+ } else if (remeshGenerated(scratch.mesh, mode, resolution, 1, m, g.remeshError, &g.stats, [progress](float f) {
+ progress->percent = int(f * 100.0f);
+ return !progress->cancel.load();
+ })) {
+ g.remeshed = std::make_shared<Mesh>(std::move(m));
+ }
+ }
+ promise->set_value(std::move(g));
}).detach();
}
void App::pollGenerator() {
if (!pendingGenerator_.valid() || pendingGenerator_.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
return;
- ai::GeneratorResult r = pendingGenerator_.get();
+ GeneratedModel g = pendingGenerator_.get();
+ const ai::GeneratorResult& r = g.result;
+ const std::string note = r.note.empty() ? std::string() : " - " + r.note;
if (!r.ok) {
- status_ = "Image to 3D failed: " + r.error;
+ status_ = "Image to 3D failed: " + r.error + note;
return;
}
runCommand("open", {{"path", r.outputPath}});
std::error_code ec;
std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
const size_t raw = doc_.mesh.triangleCount();
- if (remeshGenerated_) runCommand("remesh", {{"resolution", double(remeshResolution_)}});
+ const auto mode = GeneratedRemesh(generatedRemesh_);
+ if (g.remeshed) doc_.replaceMeshUndoable(std::move(*g.remeshed), mode == GeneratedRemesh::Quad ? "Quad Remesh" : "Remesh");
doc_.path.clear();
- status_ = "Generated model imported (" + std::to_string(raw) + " tris" +
- (remeshGenerated_ ? ", remeshed to " + std::to_string(doc_.mesh.triangleCount()) : std::string()) +
- ") - ready to sculpt";
+ const std::string remeshNote = g.remeshed ? ", " + generatedRemeshNote(g.stats, mode) : std::string();
+ status_ = !g.remeshError.empty()
+ ? "Generated model imported (" + std::to_string(raw) + " tris, not remeshed: " + g.remeshError + ")" + note
+ : "Generated model imported (" + std::to_string(raw) + " tris" + remeshNote + ") - ready to sculpt" + note;
updateTitle();
}
+void App::showHunyuanNoticeOnce() {
+ if (aiSettings_.hunyuanNoticeShown) return;
+ aiSettings_.hunyuanNoticeShown = true;
+ openHunyuanNotice_ = true;
+ if (aiSettingsPath_.empty()) return;
+ // Only the flag: keys typed into the panel are saved when the user presses Save settings.
+ ai::AiSettings saved = ai::AiSettings::load(aiSettingsPath_);
+ saved.hunyuanNoticeShown = true;
+ std::string err;
+ saved.save(aiSettingsPath_, err);
+}
+
+void App::drawAiPrefsSection() {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##hftoken", "Hugging Face token (hf_...)", hfToken_, sizeof hfToken_, ImGuiInputTextFlags_Password);
+ ui::HelpText("Hugging Face token", nullptr,
+ "Free at huggingface.co/settings/tokens (read access). Raises the free daily allowance in "
+ "Generate 3D, and TRELLIS.2 needs it. Empty = the HF_TOKEN environment variable.",
+ "Preferences > AI");
+ if (ImGui::Button("Save", ImVec2(-1, 0))) {
+ // Saves the token into the settings as they are on disk, so other unsaved panel edits stay unsaved.
+ aiSettings_.hfToken = hfToken_;
+ ai::AiSettings saved = aiSettingsPath_.empty() ? aiSettings_ : ai::AiSettings::load(aiSettingsPath_);
+ saved.hfToken = hfToken_;
+ std::string err;
+ status_ = !aiSettingsPath_.empty() && saved.save(aiSettingsPath_, err) ? "Hugging Face token saved"
+ : "Save failed " + err;
+ }
+}
+
std::string App::comfyDefaultWorkflow(bool text) {
if (!comfyWorkflowsScanned_) {
comfyWorkflows_ = ai::comfy::bundledWorkflows();
@@ -3094,12 +3151,19 @@ void App::drawImageTo3D() {
if (aiSettings_.hfModel == p.id) preview = p.label;
if (ImGui::BeginCombo("Model", preview)) {
for (const auto& p : presets)
- if (ImGui::Selectable(p.label, aiSettings_.hfModel == p.id)) aiSettings_.hfModel = p.id;
+ if (ImGui::Selectable(p.label, aiSettings_.hfModel == p.id)) {
+ aiSettings_.hfModel = p.id;
+ aiSettings_.hfModelChosen = true;
+ }
ImGui::EndCombo();
}
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", ai::kHunyuanLicenceNote);
+ const bool hasToken = hfToken_[0] || !ai::AiSettings{}.resolvedHfToken().empty(); // field, else HF_TOKEN
if (ai::hunyuanModel(aiSettings_.hfModel)) hint(ai::kHunyuanLicenceNote);
+ if (aiSettings_.hfModel == "trellis-2" && !hasToken)
+ hint("TRELLIS.2 needs a free Hugging Face token; without one, Hunyuan3D 2.1 runs instead.");
ImGui::InputText("HF token", hfToken_, sizeof hfToken_, ImGuiInputTextFlags_Password);
- hint(hfToken_[0] || std::getenv("HF_TOKEN")
+ hint(hasToken
? "Runs on Hugging Face's shared GPUs with your account's free daily allowance."
: "Runs free on Hugging Face's shared GPUs with a small daily allowance. A free token "
"(huggingface.co/settings/tokens, read access) raises it; TRELLIS.2 needs one.");
@@ -3114,6 +3178,7 @@ void App::drawImageTo3D() {
std::snprintf(falModel_, sizeof falModel_, "%s", m.id);
ImGui::EndCombo();
}
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", ai::kHunyuanLicenceNote);
ImGui::InputText("Model id", falModel_, sizeof falModel_);
if (ai::hunyuanModel(falModel_)) hint(ai::kHunyuanLicenceNote);
ImGui::InputText("API key", falKey_, sizeof falKey_, ImGuiInputTextFlags_Password);
@@ -3133,8 +3198,15 @@ void App::drawImageTo3D() {
hint("Offline and instant, but only a puffy blockout of the outline - not a real reconstruction.");
}
if (serviceId != "inflate") {
- ImGui::Checkbox("Remesh for sculpting", &remeshGenerated_);
- if (remeshGenerated_) ImGui::SliderInt("Resolution", &remeshResolution_, 96, 400);
+ static const char* remeshModes[] = {"Quad Remesh", "Voxel remesh", "Off (raw mesh)"};
+ ImGui::Combo("Remesh", &generatedRemesh_, remeshModes, 3);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))
+ ImGui::SetTooltip("Quad Remesh (default): clean quads ready for sculpting and subdividing, with one subdivision "
+ "level holding the detail. Voxel remesh: an even, watertight triangle surface. Off: the "
+ "model as the service made it.");
+ if (generatedRemesh_ != int(GeneratedRemesh::Off)) ImGui::SliderInt("Resolution", &remeshResolution_, 96, 400);
+ if (generatedRemesh_ == int(GeneratedRemesh::Quad))
+ ImGui::TextDisabled("About %d quads, then 1 subdivision level", generatedQuadTarget(remeshResolution_));
}
ImGui::PopItemWidth();
if (pendingGenerator_.valid()) {
@@ -3146,6 +3218,17 @@ void App::drawImageTo3D() {
} else if (ImGui::Button("Generate 3D model", ImVec2(-1, 0))) {
startGenerator();
}
+ if (openHunyuanNotice_) {
+ ImGui::OpenPopup("Hunyuan3D licence");
+ openHunyuanNotice_ = false;
+ }
+ ImGui::SetNextWindowSize(ImVec2(320 * scale, 0));
+ if (ImGui::BeginPopupModal("Hunyuan3D licence", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::TextWrapped("%s", ai::kHunyuanLicenceNote);
+ ImGui::TextDisabled("This stays in the Model tooltip.");
+ if (ImGui::Button("OK", ImVec2(-1, 0))) ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
if (ImGui::SmallButton("Save settings")) {
aiSettings_.generatorCommand = generatorCommand_;
aiSettings_.falKey = falKey_;
diff --git a/src/app/App.h b/src/app/App.h
index 34fbdfa2..2ef02d85 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -25,6 +25,7 @@
#include "core/Pack.h"
#include "core/Document.h"
#include "core/Face.h"
+#include "core/GeneratedRemesh.h"
#include "core/MeshTransform.h"
#include "core/PenPredictor.h"
#include "core/AutoUv.h"
@@ -192,6 +193,8 @@ private:
bool loadReferenceImage(const std::string& path);
void projectImageFromView();
void startGenerator();
+ void showHunyuanNoticeOnce(); // the licence notice, once ever (saved in ai.json)
+ void drawAiPrefsSection(); // Preferences > AI: the Hugging Face token
void pollGenerator();
int renderHeadless();
void openPath(const std::string& path);
@@ -467,7 +470,7 @@ private:
bool comfyWorkflowsScanned_ = false;
bool comfyPickingText_ = false;
std::string comfyWorkflowError_;
- bool remeshGenerated_ = true;
+ int generatedRemesh_ = int(GeneratedRemesh::Quad); // Generate 3D's Remesh: Quad (default), Voxel, Off
int voxelResolution_ = 200;
bool voxelKeepMasked_ = false; // Voxel Remesh's Keep Masked (#43)
static constexpr const char* kKeepMaskedHelp =
@@ -476,7 +479,15 @@ private:
"If the mask's edge is too ragged to join up, the status line says so and nothing changes.";
bool keepTexture_ = true; // Keep Texture: remeshes carry a painted texture over (core/TextureTransfer.h)
int remeshResolution_ = 256;
- std::future<ai::GeneratorResult> pendingGenerator_;
+ // A generated model, made sculptable on the worker thread (Quad Remesh takes seconds).
+ struct GeneratedModel {
+ ai::GeneratorResult result;
+ std::shared_ptr<Mesh> remeshed; // null: Remesh off, or it failed (remeshError)
+ GeneratedRemeshStats stats;
+ std::string remeshError;
+ };
+ std::future<GeneratedModel> pendingGenerator_;
+ bool openHunyuanNotice_ = false;
std::shared_ptr<ai::GenerationProgress> generatorProgress_;
float generatorTime_ = 0.0f;
diff --git a/src/app/Demo.cpp b/src/app/Demo.cpp
index f86c6464..06bfef10 100644
--- a/src/app/Demo.cpp
+++ b/src/app/Demo.cpp
@@ -696,7 +696,7 @@ void Demo::buildImageTo3D() {
app_.showBrushLab_ = false;
app_.aiSettings_.generatorService = "huggingface";
app_.aiSettings_.hfModel = "hunyuan3d-2.1";
- app_.remeshGenerated_ = true;
+ app_.generatedRemesh_ = int(GeneratedRemesh::Quad);
app_.remeshResolution_ = 256;
app_.openPath(app_.options_.demoAsset); // opens the Generate 3D panel with the drawing
fadeFrom_ = fadeTo_ = 1.0f;
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 36025693..64141d63 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -580,6 +580,10 @@ void App::drawPalette_Preferences() {
tray::Section section;
drawPerformanceSection();
}
+ if (subpalette("preferences.ai", "AI")) {
+ tray::Section section;
+ drawAiPrefsSection();
+ }
if (subpalette("preferences.updates", "Updates")) {
tray::Section section;
drawUpdatesSection();
diff --git a/src/core/GeneratedRemesh.cpp b/src/core/GeneratedRemesh.cpp
new file mode 100644
index 00000000..e9946984
--- /dev/null
+++ b/src/core/GeneratedRemesh.cpp
@@ -0,0 +1,91 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/GeneratedRemesh.h"
+
+#include "core/Multires.h"
+#include "core/Projection.h"
+#include "core/QRemesh.h"
+#include "core/Voxel.h"
+
+#include <algorithm>
+#include <chrono>
+#include <vector>
+
+namespace sf {
+
+bool generatedRemeshFromName(std::string_view name, GeneratedRemesh& mode) {
+ if (name == "quad" || name == "true" || name == "1") mode = GeneratedRemesh::Quad;
+ else if (name == "voxel") mode = GeneratedRemesh::Voxel;
+ else if (name == "false" || name == "off" || name == "none" || name == "0") mode = GeneratedRemesh::Off;
+ else return false;
+ return true;
+}
+
+const char* generatedRemeshName(GeneratedRemesh mode) {
+ return mode == GeneratedRemesh::Quad ? "quad" : mode == GeneratedRemesh::Voxel ? "voxel" : "false";
+}
+
+int generatedQuadTarget(int resolution) {
+ const int r = std::clamp(resolution, 64, 512);
+ return std::clamp(r * r / 2, 2000, 40000);
+}
+
+int generatedCleanupResolution(int resolution) {
+ return std::clamp(int(float(std::clamp(resolution, 64, 512)) * 0.7f + 0.5f), 64, 200);
+}
+
+bool remeshGenerated(const Mesh& raw, GeneratedRemesh mode, int resolution, int levels, Mesh& out, std::string& error,
+ GeneratedRemeshStats* stats, const std::function<bool(float)>& progress) {
+ const auto start = std::chrono::steady_clock::now();
+ GeneratedRemeshStats st;
+ st.rawTriangles = raw.triangleCount();
+ if (mode == GeneratedRemesh::Off) {
+ out = raw;
+ } else {
+ // The cleanup pass: one watertight, manifold surface whatever the model came as.
+ Mesh voxel = voxelRemesh(raw, std::clamp(resolution, 32, 512), &error);
+ if (voxel.triangleCount() == 0) return false;
+ if (mode == GeneratedRemesh::Voxel) {
+ out = std::move(voxel);
+ } else {
+ QRemeshOptions o;
+ o.targetQuads = generatedQuadTarget(resolution);
+ o.measureQuality = false; // the report is for Tool > Remesh; here it only costs time
+ const int cleanupRes = generatedCleanupResolution(resolution);
+ Mesh cleanup = cleanupRes < std::clamp(resolution, 32, 512) ? voxelRemesh(raw, cleanupRes, &error) : voxel;
+ if (cleanup.triangleCount() == 0) return false;
+ Mesh quads;
+ if (!qremesh(cleanup, o, quads, error, progress)) return false;
+ for (int i = 0; i < std::clamp(levels, 0, 2); ++i) {
+ if (!subdivDivide(quads, true, error)) return false;
+ ++st.levels;
+ }
+ if (st.levels > 0) { // Divide smooths: put the top level back on the surface
+ std::vector<glm::vec3> positions;
+ ProjectStats ps;
+ ProjectOptions po;
+ po.polypaint = false;
+ if (!computeProjection(quads, {&voxel}, po, positions, nullptr, ps, error)) return false;
+ quads.layerTarget(-1) = positions;
+ quads.recomputeAllNormals();
+ subdivCommit(quads);
+ }
+ out = std::move(quads);
+ st.quads = out.quadCount() + (out.triangleCount() - 2 * out.quadCount());
+ }
+ }
+ st.triangles = out.triangleCount();
+ st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
+ if (stats) *stats = st;
+ return true;
+}
+
+std::string generatedRemeshNote(const GeneratedRemeshStats& st, GeneratedRemesh mode) {
+ if (mode == GeneratedRemesh::Quad)
+ return "remeshed to " + std::to_string(st.quads) + " quads" +
+ (st.levels ? " (" + std::to_string(st.levels + 1) + " subdivision levels)" : std::string());
+ if (mode == GeneratedRemesh::Voxel) return "remeshed to " + std::to_string(st.triangles) + " triangles";
+ return {};
+}
+
+} // namespace sf
diff --git a/src/core/GeneratedRemesh.h b/src/core/GeneratedRemesh.h
new file mode 100644
index 00000000..d9ba48fc
--- /dev/null
+++ b/src/core/GeneratedRemesh.h
@@ -0,0 +1,49 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Makes a generated (image or text to 3D) model sculptable. AI meshes are often non-manifold, holey and uneven,
+// so the default runs a voxel pass first as cleanup, then Quad Remesh on the watertight result, then divides it
+// (Catmull-Clark, the levels kept) and projects the top level onto a full-resolution voxel surface so the detail
+// survives. Quad Remesh's time grows with its input, so the cleanup pass it reads is coarser (0.7x, at most 200).
+// Voxel: the voxel pass alone (triangles). Off: the raw mesh.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <functional>
+
+#include <string>
+#include <string_view>
+
+namespace sf {
+
+enum class GeneratedRemesh { Quad, Voxel, Off };
+
+// "quad" (also "true"), "voxel", "false" / "off" / "none". False for anything else.
+bool generatedRemeshFromName(std::string_view name, GeneratedRemesh& mode);
+const char* generatedRemeshName(GeneratedRemesh mode);
+
+// Quad Remesh's target quads for a Resolution (the voxel resolution, 64-512): about res^2 / 2, so the default 256
+// gives 32768 quads (131072 after one Divide).
+int generatedQuadTarget(int resolution);
+
+struct GeneratedRemeshStats {
+ size_t rawTriangles = 0;
+ size_t quads = 0; // Quad: faces at the top level
+ size_t triangles = 0; // the result's triangles
+ int levels = 0; // Quad: subdivision levels above the base cage
+ double seconds = 0;
+};
+
+// The voxel resolution of the cleanup pass Quad Remesh reads.
+int generatedCleanupResolution(int resolution);
+
+// `levels` (Quad only, 0-2): Divide steps after Quad Remesh. `progress` (0..1; false cancels) follows Quad Remesh.
+// Runs on any thread. False with `error` on failure or cancel.
+bool remeshGenerated(const Mesh& raw, GeneratedRemesh mode, int resolution, int levels, Mesh& out, std::string& error,
+ GeneratedRemeshStats* stats = nullptr, const std::function<bool(float)>& progress = {});
+
+// "remeshed to 131072 quads" / "remeshed to 180000 triangles" / "" (Off), for the status line.
+std::string generatedRemeshNote(const GeneratedRemeshStats& stats, GeneratedRemesh mode);
+
+} // namespace sf
diff --git a/tests/test_core.cpp b/tests/test_core.cpp
index d315e2e5..5a58e933 100644
--- a/tests/test_core.cpp
+++ b/tests/test_core.cpp
@@ -29,6 +29,7 @@
#include <cmath>
#include <algorithm>
+#include <cstdlib>
#include <cstring>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
@@ -1348,12 +1349,69 @@ TEST(free_huggingface_models) {
CHECK(wellFormed && usesImage);
ai::AiSettings defaults;
CHECK(defaults.generatorService == "huggingface" && defaults.hfModel == presets[0].id);
- CHECK(defaults.hfModel == "trellis-2"); // MIT, the default; Hunyuan3D carries its licence note
- CHECK(!ai::hunyuanModel(defaults.hfModel) && ai::hunyuanModel("hunyuan3d-2.1") && ai::hunyuanModel("fal-ai/hunyuan-3d/v3.1/pro/image-to-3d"));
- defaults.hfModel = "hunyuan3d-2.1";
- defaults.hfToken = "hf_test";
- ai::AiSettings loaded = ai::AiSettings::fromJson(defaults.toJson());
- CHECK(loaded.hfModel == "hunyuan3d-2.1" && loaded.resolvedHfToken() == "hf_test");
+ CHECK(defaults.hfModel == "hunyuan3d-2.1" && !defaults.hfModelChosen); // free, works with no token
+ CHECK(ai::hunyuanModel(defaults.hfModel) && !ai::hunyuanModel("trellis-2") && ai::hunyuanModel("fal-ai/hunyuan-3d/v3.1/pro/image-to-3d"));
+ {
+ // Default selection: an explicit choice is kept; a model the user never chose follows the default.
+ ai::AiSettings chosen;
+ chosen.hfModel = "hunyuan3d-2-turbo";
+ chosen.hfModelChosen = true;
+ chosen.hfToken = "hf_test";
+ ai::AiSettings loaded = ai::AiSettings::fromJson(chosen.toJson());
+ CHECK(loaded.hfModel == "hunyuan3d-2-turbo" && loaded.hfModelChosen && loaded.resolvedHfToken() == "hf_test");
+ ai::AiSettings unchosen;
+ unchosen.hfModel = "trellis-2"; // saved by "Save settings" without picking a model
+ CHECK(ai::AiSettings::fromJson(unchosen.toJson()).hfModel == "hunyuan3d-2.1");
+ CHECK(ai::AiSettings::fromJson(Json::object()).hfModel == "hunyuan3d-2.1"); // new install
+ // ai.json from 0.10.8 and earlier (no hfModelChosen): TRELLIS.2 was the default, kept only with a token.
+ Json old = Json::object();
+ old.set("hfModel", "trellis-2");
+ CHECK(ai::AiSettings::fromJson(old).hfModel == "hunyuan3d-2.1" && !ai::AiSettings::fromJson(old).hfModelChosen);
+ old.set("hfToken", "hf_x");
+ CHECK(ai::AiSettings::fromJson(old).hfModel == "trellis-2");
+ Json picked = Json::object();
+ picked.set("hfModel", "stable-fast-3d");
+ CHECK(ai::AiSettings::fromJson(picked).hfModel == "stable-fast-3d");
+ // The licence notice is shown once, ever.
+ CHECK(!ai::AiSettings::fromJson(old).hunyuanNoticeShown);
+ ai::AiSettings noticed;
+ noticed.hunyuanNoticeShown = true;
+ CHECK(ai::AiSettings::fromJson(noticed.toJson()).hunyuanNoticeShown);
+ }
+ {
+ // TRELLIS.2 without a token falls back to Hunyuan3D 2.1 with a note; with one it runs. No token from the
+ // environment either, for the length of this block.
+ std::vector<std::pair<std::string, std::string>> savedEnv;
+ for (const char* name : {"HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"}) {
+ if (const char* v = std::getenv(name)) savedEnv.emplace_back(name, v);
+#ifdef _WIN32
+ _putenv_s(name, "");
+#else
+ unsetenv(name);
+#endif
+ }
+ ai::AiSettings s;
+ std::string note;
+ CHECK(std::string(ai::resolveHfPreset(s, false, &note).id) == "hunyuan3d-2.1" && note.empty());
+ s.hfModel = "trellis-2";
+ CHECK(std::string(ai::resolveHfPreset(s, false, &note).id) == "hunyuan3d-2.1");
+ CHECK(note == ai::kTrellisNoTokenNote && note.find("Preferences > AI") != std::string::npos);
+ note.clear();
+ s.hfToken = "hf_test";
+ CHECK(std::string(ai::resolveHfPreset(s, false, &note).id) == "trellis-2" && note.empty());
+ s.hfModel = "no-such-model";
+ CHECK(std::string(ai::resolveHfPreset(s, false).id) == ai::hfPresets()[0].id);
+ s.hfModel = "hunyuan3d-2.1"; // not a text model: text uses the first text preset
+ CHECK(std::string(ai::resolveHfPreset(s, true).id) == ai::hfTextPresets()[0].id);
+ for (const auto& [name, value] : savedEnv) {
+#ifdef _WIN32
+ _putenv_s(name.c_str(), value.c_str());
+#else
+ setenv(name.c_str(), value.c_str(), 1);
+#endif
+ }
+ }
+ CHECK(std::string(ai::kHunyuanLicenceNote).find("EU, UK or South Korea") != std::string::npos);
CHECK(ai::friendlyGradioError("You have exceeded your ZeroGPU quota (120s requested vs. 0s left).").find("free GPU time") !=
std::string::npos);
CHECK(ai::friendlyGradioError("some other failure") == "some other failure");
diff --git a/tests/test_generated_remesh.cpp b/tests/test_generated_remesh.cpp
new file mode 100644
index 00000000..75c3d1a1
--- /dev/null
+++ b/tests/test_generated_remesh.cpp
@@ -0,0 +1,95 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Generate 3D makes its result sculptable with Quad Remesh by default (core/GeneratedRemesh.h): a voxel cleanup
+// pass (AI meshes have holes and overlapping, non-manifold pieces Quad Remesh can't take), Quad Remesh, one Divide
+// projected back onto the surface. Voxel and Off stay as options; the CLI takes remesh=quad|voxel|false.
+#include "TestHarness.h"
+
+#include "ai/AiCommands.h"
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/GeneratedRemesh.h"
+#include "core/Multires.h"
+#include "core/Primitives.h"
+#include "core/QRemesh.h"
+#include "core/SubTools.h"
+
+#include <glm/glm.hpp>
+
+using namespace sf;
+
+namespace {
+
+// What image-to-3D services hand back: overlapping pieces, a hole, and a non-manifold fin.
+Mesh aiLikeMesh() {
+ Mesh a = makeIcosphere(4, 1.0f);
+ Mesh b = makeIcosphere(3, 0.6f);
+ for (auto& p : b.positions) p += glm::vec3(0.0f, 0.9f, 0.0f);
+ Mesh m = mergeMeshes({&a, &b});
+ m.triangles.erase(m.triangles.begin(), m.triangles.begin() + 12); // a hole
+ const uint32_t base = uint32_t(m.positions.size());
+ m.positions.push_back(m.positions[m.triangles[0].x]); // a fin hanging off an edge: three faces share it
+ m.triangles.push_back({m.triangles[0].x, m.triangles[0].y, base});
+ m.positions.back() += glm::vec3(0.3f, 0.3f, 0.3f);
+ m.sanitizeAttributes();
+ m.recomputeAllNormals();
+ return m;
+}
+
+} // namespace
+
+TEST(generated_remesh_modes_and_target) {
+ GeneratedRemesh mode;
+ CHECK(generatedRemeshFromName("quad", mode) && mode == GeneratedRemesh::Quad);
+ CHECK(generatedRemeshFromName("true", mode) && mode == GeneratedRemesh::Quad);
+ CHECK(generatedRemeshFromName("voxel", mode) && mode == GeneratedRemesh::Voxel);
+ CHECK(generatedRemeshFromName("false", mode) && mode == GeneratedRemesh::Off);
+ CHECK(!generatedRemeshFromName("dyna", mode));
+ // The default Resolution (256) asks for 20-40k quads; the cleanup pass Quad Remesh reads is coarser.
+ CHECK(generatedQuadTarget(256) == 32768);
+ CHECK(generatedQuadTarget(96) >= 2000 && generatedQuadTarget(400) <= 40000);
+ CHECK(generatedCleanupResolution(256) == 179 && generatedCleanupResolution(400) == 200);
+}
+
+TEST(generated_remesh_quad_cleans_an_ai_mesh) {
+ const Mesh raw = aiLikeMesh();
+ CHECK(!topologyReport(raw).manifold() || topologyReport(raw).boundaryEdges > 0);
+
+ Mesh out;
+ std::string err;
+ GeneratedRemeshStats st;
+ CHECK(remeshGenerated(raw, GeneratedRemesh::Quad, 96, 1, out, err, &st));
+ const TopologyReport topo = topologyReport(out);
+ CHECK(topo.manifold() && topo.boundaryEdges == 0);
+ CHECK(topo.quadFraction() > 0.95f);
+ CHECK(st.levels == 1 && subdivLevelCount(out) == 2 && subdivCurrentLevel(out) == 1); // the quad cage below
+ CHECK(st.quads == topo.faces && st.quads > 3 * size_t(generatedQuadTarget(96)));
+ CHECK(generatedRemeshNote(st, GeneratedRemesh::Quad).find("remeshed to " + std::to_string(st.quads) + " quads") == 0);
+ // Projected back: the top level sits on the big sphere where nothing else is (its equator, radius 1).
+ float maxDev = 0.0f;
+ for (const auto& p : out.positions)
+ if (std::abs(p.y) < 0.2f && p.x > 0.0f) maxDev = std::max(maxDev, std::abs(glm::length(p) - 1.0f));
+ CHECK(maxDev < 0.04f);
+
+ CHECK(remeshGenerated(raw, GeneratedRemesh::Voxel, 96, 1, out, err, &st));
+ CHECK(!out.multires && st.levels == 0 && topologyReport(out).boundaryEdges == 0); // watertight
+ CHECK(generatedRemeshNote(st, GeneratedRemesh::Voxel) == "remeshed to " + std::to_string(out.triangleCount()) + " triangles");
+ CHECK(remeshGenerated(raw, GeneratedRemesh::Off, 96, 1, out, err, &st));
+ CHECK(out.triangleCount() == raw.triangleCount() && generatedRemeshNote(st, GeneratedRemesh::Off).empty());
+
+ // Cancel from the progress callback.
+ CHECK(!remeshGenerated(raw, GeneratedRemesh::Quad, 96, 1, out, err, nullptr, [](float) { return false; }));
+}
+
+TEST(generated_remesh_cli_argument) {
+ // remesh= is checked before anything is sent: a bad value fails at once, with no network.
+ CommandRegistry reg;
+ ai::registerAiCommands(reg, [] { return ai::AiSettings{}; });
+ Document doc;
+ const CommandResult r = reg.execute(doc, "image_to_3d", {{"path", std::string("missing.png")}, {"remesh", std::string("dyna")}});
+ CHECK(!r.ok && r.message.find("quad, voxel or false") != std::string::npos);
+ // An offline service isn't swapped for a hosted one behind the user's back.
+ const CommandResult t = reg.execute(doc, "text_to_3d", {{"prompt", std::string("an owl")}, {"service", std::string("inflate")}});
+ CHECK(!t.ok && t.message.find("service=huggingface") != std::string::npos);
+}
diff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfui
index 0e5cf4b3..7270488d 100644
--- a/tests/ui/whats_new.sfui
+++ b/tests/ui/whats_new.sfui
@@ -5,6 +5,8 @@ click "Help##palette.help"
click "What's New##help.whats_new"
expect_value guide_open == 1
expect_guide whats-new.md
+expect_text "Version 0.10.9"
+expect_text "Image to 3D with no setup"
expect_text "Version 0.10.8"
expect_text "Tablets in mouse mode work again"
expect_text "Version 0.10.7"