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.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Generate 3D: Hyper3D Rodin direct (service hyper3d), with your own key, safe by construction
islandmed18a1d3245d06
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ffe7a2e6..40b850e0 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -264,7 +264,7 @@ set_source_files_properties(third_party/xatlas/xatlas.cpp third_party/tinyexr/ti# --- Bring-your-own-AI (brush assistant). HTTPS via WinHTTP or libcurl. ---add_library(sculptforge_ai STATIC src/ai/Http.cpp src/ai/AiPolicy.cpp src/ai/Providers.cpp src/ai/Secrets.cpp src/ai/Oidc.cpp src/ai/BrushAssistant.cpp src/ai/Generator3D.cpp- src/ai/ImageTo3DService.cpp src/ai/GradioClient.cpp src/ai/ComfyUI.cpp src/ai/AiCommands.cpp src/ai/BrushGalleryClient.cpp src/link/Socket.cpp+ src/ai/ImageTo3DService.cpp src/ai/Hyper3D.cpp src/ai/GradioClient.cpp src/ai/ComfyUI.cpp src/ai/AiCommands.cpp src/ai/BrushGalleryClient.cpp src/link/Socket.cppsrc/link/UnrealLink.cpp src/ai/Process.cpp src/ai/SplatTrainer.cpp)# Lets a build run from its tree find the bundled ComfyUI workflows (integrations/comfyui/workflows).target_compile_definitions(sculptforge_ai PRIVATE SF_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")diff --git a/changes/feat-rodin-direct.md b/changes/feat-rodin-direct.mdnew file mode 100644index 00000000..9eb58737--- /dev/null+++ b/changes/feat-rodin-direct.md@@ -0,0 +1,16 @@+---+whats_new: **Hyper3D Rodin, direct**: **Generate 3D > Hyper3D Rodin (direct)** runs Rodin Gen-2.5 on Hyper3D's own service with your own Hyper3D key, from an image or a description, in five tiers from Extreme Low to Extreme High. It stays off until you add your key, which is kept in the system keychain; your image or description goes to Hyper3D only, and generations are billed to your Hyper3D account. Rodin through fal.ai stays as it was.+added: **Hyper3D Rodin (direct)** in Generate 3D and the `image_to_3d` / `text_to_3d` commands (`service=hyper3d`,+ `model=` a Gen-2.5 tier): Hyper3D's own API with your key (system keychain only; no environment variable, no+ shared or trial key). One pinned https host for the API, the key sent nowhere else; the GLB only from Hyper3D's+ domains, capped at 200 MB and checked before import, kept in a private temporary folder deleted after import;+ polling backs off to 30 s. Studios: provider id `hyper3d` in the policy, one audit log line per generation.+ Thanks to ElgoogUdiab for suggesting it (#123); re-implemented in house from Hyper3D's public API documentation.+testers:+ - Any OS, with your own Hyper3D key: Generate 3D > Hyper3D Rodin (direct), tier Gen-2.5 Low, paste the key, Save+ settings, generate from an image and from text; the model opens and remeshes. Restart: the key field is empty but+ "Using your key from the system keychain" shows, and generating still works.+ - Without a key: Generate says to add your Hyper3D key and nothing is sent.+ - Preferences > AI > Enable AI features off: Generate 3D can't send anything.+---+Re-implemented from the PR #123 description and docs.hyper3d.ai only; the PR's code was not read or run.diff --git a/docs/ai-services.md b/docs/ai-services.mdindex 54f5b89e..faef6620 100644--- a/docs/ai-services.md+++ b/docs/ai-services.md@@ -75,6 +75,25 @@ See [Generate 3D with your own ComfyUI](comfyui.md).## Paid services-fal.ai and Meshy are paid services with their own terms of service and pricing; generations are-billed to your account with them. Hyper3D Rodin 2.5 runs through fal.ai with your fal.ai key: the-image or description goes to fal.ai, which runs Rodin; SculptForge never contacts Hyper3D directly. Model availability and names can change on their side.+fal.ai, Meshy and Hyper3D are paid services with their own terms of service and pricing; generations are+billed to your account with them. Model availability and names can change on their side.++Hyper3D Rodin 2.5 can run two ways:++- **fal.ai > Rodin 2.5**: with your fal.ai key. The image or description goes to fal.ai, which runs Rodin.+- **Hyper3D Rodin (direct)**: with your own Hyper3D key, from the API dashboard at hyper3d.ai (a Creator+ plan or higher; Basic API access covers the Extreme Low and Low tiers, the others need Full access). The+ image or description goes to Hyper3D (`api.hyper3d.com`) and nowhere else; each generation is billed to+ your Hyper3D account, and Hyper3D keeps results as its data retention policy says.++ What SculptForge does to keep this narrow:+ - It is off until you enter your own key. The key is kept in the system keychain, never in `ai.json`,+ never in a log, and there is no environment variable, shared or trial key.+ - The API address is fixed in the app: https only, certificates checked, no redirects followed. The+ key is sent only there. The model file is accepted only over https from Hyper3D's own domains+ (`hyper3d.com`, `hyper3d.ai`, `deemos.com`), up to 200 MB, and only when it is a well-formed GLB; it is+ saved in a private temporary folder, read by the usual glTF importer and deleted after import.+ - It waits politely: the first status check after 5 s, then slower, up to every 30 s, for 20 minutes at most.+ - With **Enable AI features** off nothing is sent. Studios: the provider id is `hyper3d` in+ `ai.providers` (and `https://api.hyper3d.com/` in `ai.endpoints` when that list is used); each+ generation writes one audit log line (tier, image or text, prompt length; never the key or the image).diff --git a/docs/generators.md b/docs/generators.mdindex 8952fe20..040bc13a 100644--- a/docs/generators.md+++ b/docs/generators.md@@ -1,12 +1,13 @@# Image-to-3D generators-**Image to 3D → Full 3D model** offers six sources:+**Image to 3D → Full 3D model** offers seven sources:| Service | What it is | Setup ||---|---|---|| **Hugging Face** (default, free) | The official public demos of Hunyuan3D 2.1 / 2 / 2 mini Turbo (Tencent), TRELLIS.2 (Microsoft) and Stable Fast 3D (Stability AI), on Hugging Face's shared ZeroGPU hardware | Nothing. A free token from huggingface.co/settings/tokens (read access), or `HF_TOKEN`, raises the daily GPU allowance; TRELLIS.2 needs one || **fal.ai** | Hosted reconstruction models, billed per generation: TRELLIS.2 (Microsoft), Hunyuan3D 3.1 Pro/Rapid (Tencent), Meshy 6, Hyper3D Rodin 2.5 (image or text) - or any other fal model id | Key from fal.ai/dashboard/keys, or `FAL_KEY` || **Meshy** | Meshy's own API (`meshy-7.1` by default) | Key from meshy.ai, or `MESHY_API_KEY` |+| **Hyper3D Rodin (direct)** | Hyper3D's own API: Rodin Gen-2.5, image or text, in five tiers (Extreme Low to Extreme High), billed to your Hyper3D account | Your key from hyper3d.ai (API dashboard), saved in the system keychain; no environment variable. See [ai-services.md](ai-services.md#paid-services) || **ComfyUI** | Any workflow on your own ComfyUI, on this computer or a studio GPU server: Hunyuan3D, TRELLIS, your own graph. See [comfyui.md](comfyui.md) | The server address and an API-format workflow (bundled ones included) || **My generator command** | Anything you run locally (see below) | A command line || **Offline blockout** | Inflates the outline into a rounded blob. Fine for simple shapes, not characters | Nothing |diff --git a/docs/guide/generate-3d.md b/docs/guide/generate-3d.mdindex f8ca308a..4861de9b 100644--- a/docs/guide/generate-3d.md+++ b/docs/guide/generate-3d.md@@ -76,6 +76,7 @@ Which model runs depends on the service:| Hugging Face | Hunyuan3D 2 mini Turbo (Tencent), or Hunyuan3D 2 if you chose it in **Model**. Any other choice uses Turbo || fal.ai | Rodin 2.5 (Hyper3D) when it is the chosen **Model** (Rodin 2.5 or Rodin 2.5 Fast), otherwise Hunyuan3D 3.1 Rapid (Tencent) || Meshy | Meshy's own text-to-3D model |+| Hyper3D Rodin (direct) | Rodin Gen-2.5 at the chosen **Tier** || ComfyUI | The text workflow you choose (the bundled `text-to-3d` uses FLUX.1 schnell and Hunyuan3D 2.1) |## Services@@ -120,7 +121,7 @@ it to refill, or pick another model.> 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)+### fal.ai, Meshy and Hyper3D (paid)- **fal.ai**: choose a **Model** (TRELLIS.2, Hunyuan3D 3.1 Pro, Hunyuan3D 3.1 Rapid, Meshy 6, Rodin 2.5 orRodin 2.5 Fast) or type any fal model id into **Model id**. Rodin 2.5 (Hyper3D) works from an image or a@@ -128,6 +129,12 @@ it to refill, or pick another model.low poly (up to about 20K triangles), fine as a blockout before remeshing. Paste your key from fal.ai/dashboard/keys into **API key**, or set`FAL_KEY`.- **Meshy**: paste your key from meshy.ai (API settings) into **API key**, or set `MESHY_API_KEY`.+- **Hyper3D Rodin (direct)**: Rodin Gen-2.5 on Hyper3D's own service, from an image or a description. Choose+ a **Tier** (Extreme Low is the fastest; Extreme High costs more credits) and paste your key from the API+ dashboard at hyper3d.ai into **API key**, then **Save settings**: the key goes into the system keychain. It+ stays off until you add a key. Your image or description goes to Hyper3D (api.hyper3d.com) and nowhere else,+ and SculptForge asks for the shape only (GLB, no materials). Basic API access (Creator plans) covers Extreme+ Low and Low; the other tiers need Full access.Generations are billed to your account with that service. Errors such as "The API key was rejected", "Out ofcredits on this account" or "Rate limited" come from the service.diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 30533010..d1978f8a 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -125,6 +125,16 @@ If no pen is detected or pressure doesn't change:| *Model or endpoint not found* | Check the fal model id || *Rate limited* | Wait a moment and try again |+### Hyper3D Rodin (direct)++| Message | What to do |+|---|---|+| *Add your Hyper3D API key* | It stays off until you add your own key (hyper3d.ai > API dashboard) in the Generate 3D window |+| *Hyper3D rejected the API key* | Check the key, or create a new one in the API dashboard |+| *Your Hyper3D plan doesn't include this tier* | Basic API access covers Extreme Low and Low; choose one of those, or upgrade on hyper3d.ai |+| *Out of credits on your Hyper3D account* | Top up on hyper3d.ai |+| *Refused the model file* | The result came from somewhere other than Hyper3D's servers, so SculptForge didn't download it. Try again; if it keeps happening, [report it](https://github.com/islandmed/SculptForge/issues) |+### Brush LabThe default **Free** provider uses a hosted open model with no account. If it is unreachable and Ollama runs@@ -135,7 +145,7 @@ requests in a short time: wait a few seconds. For setup of local models, see### No connection at allAI features need internet access (except a local Ollama, LM Studio or ComfyUI). Behind a company proxy or-firewall, ask IT to allow the service you use: huggingface.co (and `*.hf.space`), fal.ai, meshy.ai, or the+firewall, ask IT to allow the service you use: huggingface.co (and `*.hf.space`), fal.ai, meshy.ai, api.hyper3d.com (and Hyper3D's file servers), or thePollinations.ai text endpoint for the free Brush Lab model.## ComfyUI errorsdiff --git a/src/ai/AiCommands.cpp b/src/ai/AiCommands.cppindex 371946e0..bdfffb9a 100644--- a/src/ai/AiCommands.cpp+++ b/src/ai/AiCommands.cpp@@ -47,6 +47,7 @@ CommandResult importGenerated(Document& doc, const Args& a, const GeneratorResulCommandResult 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 (!r.privateDir.empty()) std::filesystem::remove_all(std::filesystem::path(std::u8string(r.privateDir.begin(), r.privateDir.end())), ec);if (!opened.ok) return opened;doc.path.clear();GeneratedRemeshStats st;@@ -115,11 +116,11 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>add({"image_to_3d","Reconstruct a full 3D model from one picture (character, creature, prop) and make it sculptable. ""Free by default via Hugging Face Spaces (Hunyuan3D, TRELLIS.2, Stable Fast 3D; HF_TOKEN raises the "- "daily quota), paid via fal.ai (FAL_KEY) / Meshy (MESHY_API_KEY), or any workflow on your own "+ "daily quota), paid via fal.ai (FAL_KEY) / Meshy (MESHY_API_KEY) / Hyper3D Rodin direct (service=hyper3d, your key saved in Generate 3D), or any workflow on your own ""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 (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 or fal-ai/hyper3d/rodin/v2.5.", false},+ {"service", T::String, "'huggingface' (free, default), 'fal', 'meshy', 'hyper3d' (Rodin direct, your Hyper3D key), 'comfyui' (your ComfyUI server), 'command' (your generator) or 'inflate' (offline blockout).", 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 or fal-ai/hyper3d/rodin/v2.5; hyper3d: a tier, Gen-2.5-Extreme-Low, Gen-2.5-Low (default), Gen-2.5-Medium, Gen-2.5-High or Gen-2.5-Extreme-High.", 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},@@ -136,6 +137,7 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>if (a.contains("url")) s.comfyUrl = argString(a, "url");if (a.contains("model")) {if (s.generatorService == "meshy") s.meshyModel = argString(a, "model");+ else if (s.generatorService == "hyper3d") s.hyper3dTier = argString(a, "model");else if (s.generatorService == "fal") s.falModel = argString(a, "model");else s.hfModel = argString(a, "model");}@@ -157,11 +159,11 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>add({"text_to_3d","Create a 3D model from a description and make it sculptable. Free by default via Hugging Face ""(Hunyuan3D 2 / 2 mini Turbo; HF_TOKEN raises the daily quota), or paid via fal.ai (FAL_KEY) / "- "Meshy (MESHY_API_KEY), or a workflow on your own ComfyUI (service=comfyui workflow=FILE). Replaces the scene.",+ "Meshy (MESHY_API_KEY) / Hyper3D Rodin direct (service=hyper3d, your key saved in Generate 3D), or a workflow on your own ComfyUI (service=comfyui workflow=FILE). Replaces the scene.",{{"prompt", T::String, "One object, e.g. 'a stylised dragon head with curled horns'.", true},- {"service", T::String, "'huggingface' (free, default), 'fal', 'meshy' or 'comfyui' (your ComfyUI server).", false},+ {"service", T::String, "'huggingface' (free, default), 'fal', 'meshy', 'hyper3d' (Rodin direct, your Hyper3D key) or 'comfyui' (your ComfyUI server).", false},{"model", T::String, "huggingface: hunyuan3d-2-turbo or hunyuan3d-2; fal: fal-ai/hyper3d/rodin/v2.5 (or /fast), "- "else Hunyuan3D 3.1 Rapid.", false},+ "else Hunyuan3D 3.1 Rapid; hyper3d: a Gen-2.5 tier (default Gen-2.5-Low).", 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},@@ -178,9 +180,10 @@ void addAiFeatureCommands(CommandRegistry& registry, std::function<AiSettings()>if (a.contains("url")) s.comfyUrl = argString(a, "url");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"};+ "service=huggingface, fal, meshy, hyper3d or comfyui"};if (a.contains("model")) {if (s.generatorService == "meshy") s.meshyModel = argString(a, "model");+ else if (s.generatorService == "hyper3d") s.hyper3dTier = argString(a, "model");else if (s.generatorService == "fal") s.falModel = argString(a, "model");else s.hfModel = argString(a, "model");}diff --git a/src/ai/BrushAssistant.cpp b/src/ai/BrushAssistant.cppindex 9bf1d252..1bb02959 100644--- a/src/ai/BrushAssistant.cpp+++ b/src/ai/BrushAssistant.cpp@@ -134,6 +134,11 @@ std::string AiSettings::resolvedMeshyKey() const {return env ? env : "";}+std::string AiSettings::resolvedHyper3dKey() const {+ if (!hyper3dKey.empty()) return hyper3dKey;+ return secrets::cached(secrets::kHyper3d);+}+Json AiSettings::toJson() const {Json j = Json::object();// (no keys: they are in the keychain, ai/Secrets.h)@@ -151,6 +156,7 @@ Json AiSettings::toJson() const {j.set("falEndpoint", falEndpoint);j.set("meshyModel", meshyModel);j.set("meshyEndpoint", meshyEndpoint);+ j.set("hyper3dTier", hyper3dTier);j.set("comfyUrl", comfyUrl);j.set("comfyImageWorkflow", comfyImageWorkflow);j.set("comfyTextWorkflow", comfyTextWorkflow);@@ -193,6 +199,7 @@ AiSettings AiSettings::fromJson(const Json& j) {text("meshyKey", s.meshyKey);text("meshyModel", s.meshyModel);text("meshyEndpoint", s.meshyEndpoint);+ text("hyper3dTier", s.hyper3dTier); // (never a key: the keychain only)text("comfyUrl", s.comfyUrl);s.comfyImageWorkflow = j["comfyImageWorkflow"].asString();s.comfyTextWorkflow = j["comfyTextWorkflow"].asString();diff --git a/src/ai/BrushAssistant.h b/src/ai/BrushAssistant.hindex 1945b97a..1539683a 100644--- a/src/ai/BrushAssistant.h+++ b/src/ai/BrushAssistant.h@@ -27,11 +27,11 @@ struct AiSettings {std::string preset; // the provider preset (ai/Providers.h: "ollama", "litellm", ...); "" = from provider/endpointstd::string endpoint;std::string model;- // Keys (apiKey, hfToken, falKey, meshyKey) are kept in the OS keychain (ai/Secrets.h), never in ai.json: these+ // Keys (apiKey, hfToken, falKey, meshyKey, hyper3dKey) are kept in the OS keychain (ai/Secrets.h), never in ai.json: these// fields hold one typed in this session, or read from an older ai.json (moved to the keychain at start-up).std::string apiKey; // Free: unused; empty = the keychain, then ANTHROPIC_API_KEY / OPENAI_API_KEY / the preset'sstd::string effort = "low";- // Image to 3D. service: "huggingface" (free Spaces), "fal", "meshy",+ // Image to 3D. service: "huggingface" (free Spaces), "fal", "meshy", "hyper3d" (Rodin direct),// "comfyui" (your ComfyUI server), "command" (generatorCommand with// {input}/{output}) or "inflate" (offline).std::string generatorService = "huggingface";@@ -46,12 +46,15 @@ struct AiSettings {std::string meshyKey; // empty = MESHY_API_KEY from the environmentstd::string meshyModel = "latest";std::string meshyEndpoint = "https://api.meshy.ai";+ std::string hyper3dKey; // Hyper3D Rodin direct (ai/Hyper3D.h): the keychain only - no environment variable+ std::string hyper3dTier = "Gen-2.5-Low";std::string comfyUrl = "http://127.0.0.1:8188";std::string comfyImageWorkflow; // API-format workflow files; empty = the bundled defaultstd::string comfyTextWorkflow;std::string resolvedFalKey() const;std::string resolvedHfToken() const;std::string resolvedMeshyKey() const;+ std::string resolvedHyper3dKey() const; // typed in this session, else the keychain; never the environmentstatic AiSettings defaults(Provider provider);static Provider providerFromName(const std::string& name); // "free", "anthropic", "openai-compatible"diff --git a/src/ai/Generator3D.h b/src/ai/Generator3D.hindex 2dfba62f..eb14a1ee 100644--- a/src/ai/Generator3D.h+++ b/src/ai/Generator3D.h@@ -18,6 +18,7 @@ struct GeneratorResult {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 privateDir; // set: outputPath is inside it; the caller deletes the folder after import (ai/Hyper3D.h)};std::string defaultGeneratorCommand(const std::string& cliPath);diff --git a/src/ai/Hyper3D.cpp b/src/ai/Hyper3D.cppnew file mode 100644index 00000000..180b31e2--- /dev/null+++ b/src/ai/Hyper3D.cpp@@ -0,0 +1,395 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "ai/Hyper3D.h"++#include "ai/AiPolicy.h"+#include "ai/Http.h"+#include "ai/ImageTo3DService.h"+#include "core/AuditLog.h"+#include "core/Json.h"+#include "core/NetworkPolicy.h"++#include <algorithm>+#include <chrono>+#include <cstdint>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <random>+#include <thread>++#if !defined(_WIN32)+#include <unistd.h>+#endif++namespace sf::ai::hyper3d {++namespace {++constexpr int kMaxMinutes = 20;+constexpr int kTimeoutSeconds = 60;++Transport gTransport; // (tests)+std::vector<int>* gWaits = nullptr;+size_t gMaxBytes = kMaxDownloadBytes;++void status(GenerationProgress* p, const std::string& text, int percent = -1) {+ if (!p) return;+ p->setStatus(text);+ p->percent = percent;+}++bool wait(GenerationProgress* p, int seconds) {+ if (gTransport) {+ if (gWaits) gWaits->push_back(seconds);+ return !(p && p->cancel);+ }+ for (int i = 0; i < seconds * 10; ++i) {+ if (p && p->cancel) return false;+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }+ return !(p && p->cancel);+}++bool hostUnder(const std::string& host, const char* domain) {+ const std::string d = domain;+ return host == d || (host.size() > d.size() && host.compare(host.size() - d.size(), d.size(), d) == 0 &&+ host[host.size() - d.size() - 1] == '.');+}++// Hyper3D answers application errors with HTTP 201 and {"error": CODE, "message": ...}.+std::string bodyError(const Json& j) {+ const std::string code = j["error"].isString() ? j["error"].asString() : std::string();+ if (code.empty()) return {};+ const std::string msg = j["message"].isString() ? j["message"].asString().substr(0, 200) : std::string();+ if (code == "API_INSUFFICIENT_FUNDS") return "Out of credits on your Hyper3D account";+ if (code == "API_NO_ACTIVE_SUBSCRIPTION") return "Your Hyper3D account has no active API subscription";+ if (code == "API_SUBSCRIPTION_PLAN_TOO_LOW")+ return "Your Hyper3D plan doesn't include this tier (Basic API access covers Extreme-Low and Low)";+ if (code == "API_PARALLELISM_LIMIT_REACHED") return "Hyper3D is already running your other generations - try again shortly";+ if (code == "API_OBJECT_NOT_FOUND_ON_IMAGE") return "Hyper3D found no object in the image";+ if (code == "IMAGE_CONTENT_VIOLATION") return "Hyper3D refused the content";+ return "Hyper3D: " + code.substr(0, 60) + (msg.empty() ? std::string() : " (" + msg + ")");+}++std::string httpError(const HttpResponse& r) {+ if (!r.error.empty()) return "Could not reach Hyper3D: " + r.error;+ switch (r.status) {+ case 401:+ case 403: return "Hyper3D rejected the API key";+ case 429: return "Hyper3D is rate limiting - wait a moment and try again";+ default: return "Hyper3D answered HTTP " + std::to_string(r.status);+ }+}++// One API call: a POST to exactly kApiBase + path, the key only here.+HttpResponse post(const std::string& key, const std::string& path, const std::string& contentType, const std::string& body) {+ const std::string url = std::string(kApiBase) + path;+ if (!apiUrl(url)) {+ HttpResponse r;+ r.error = "refused";+ return r;+ }+ const std::vector<std::string> headers = {"Authorization: Bearer " + key, contentType, "Accept: application/json"};+ if (gTransport) return gTransport("POST", url, headers, body);+ return httpPostNoRedirect(url, headers, body, kTimeoutSeconds);+}++uint32_t le32(const std::string& b, size_t at) {+ return uint32_t(uint8_t(b[at])) | uint32_t(uint8_t(b[at + 1])) << 8 | uint32_t(uint8_t(b[at + 2])) << 16 |+ uint32_t(uint8_t(b[at + 3])) << 24;+}++} // namespace++const std::vector<Tier>& tiers() {+ static const std::vector<Tier> t = {+ {"Gen-2.5-Extreme-Low", "Gen-2.5 Extreme Low (fastest)"},+ {"Gen-2.5-Low", "Gen-2.5 Low"},+ {"Gen-2.5-Medium", "Gen-2.5 Medium"},+ {"Gen-2.5-High", "Gen-2.5 High"},+ {"Gen-2.5-Extreme-High", "Gen-2.5 Extreme High (more credits)"},+ };+ return t;+}++std::string resolvedTier(const std::string& tier) {+ for (const Tier& t : tiers())+ if (tier == t.id) return tier;+ return kDefaultTier;+}++bool apiUrl(const std::string& url) {+ net::UrlParts u;+ if (!net::parseUrl(url, u) || u.scheme != "https" || u.host != kApiHost || u.port != 443) return false;+ return u.path.rfind("/api/v2/", 0) == 0 && u.path.find("..") == std::string::npos;+}++bool downloadUrlAllowed(const std::string& url) {+ net::UrlParts u;+ if (!net::parseUrl(url, u) || u.scheme != "https" || u.port != 443) return false;+ return hostUnder(u.host, "hyper3d.com") || hostUnder(u.host, "hyper3d.ai") || hostUnder(u.host, "deemos.com");+}++std::string submitBody(const std::string& tier, const std::string& png, const std::string& prompt,+ std::string& contentTypeHeader) {+ std::vector<MultipartField> fields;+ if (!png.empty()) fields.push_back({"images", png, "input.png", "image/png"});+ else fields.push_back({"prompt", prompt.substr(0, 800)});+ fields.push_back({"tier", resolvedTier(tier)});+ fields.push_back({"geometry_file_format", "glb"});+ fields.push_back({"material", "None"}); // the shape is what we sculpt+ fields.push_back({"mesh_mode", "Raw"});+ return multipartBody(fields, contentTypeHeader);+}++bool parseSubmit(const std::string& body, std::string& taskUuid, std::string& subscriptionKey, std::string& error) {+ Json j;+ std::string err;+ if (!Json::parse(body, j, err) || !j.isObject()) return (error = "Unexpected reply from Hyper3D", false);+ if (std::string e = bodyError(j); !e.empty()) return (error = e, false);+ taskUuid = j["uuid"].asString();+ subscriptionKey = j["jobs"]["subscription_key"].asString();+ if (taskUuid.empty() || subscriptionKey.empty()) return (error = "Unexpected reply from Hyper3D", false);+ return true;+}++bool parseStatus(const std::string& body, JobState& state, int& queue, std::string& error) {+ Json j;+ std::string err;+ queue = -1;+ if (!Json::parse(body, j, err) || !j.isObject()) return (error = "Unexpected reply from Hyper3D", false);+ if (std::string e = bodyError(j); !e.empty()) return (error = e, false);+ if (!j["jobs"].isArray() || j["jobs"].size() == 0) return (error = "Unexpected reply from Hyper3D", false);+ bool allDone = true, anyGenerating = false;+ for (const Json& job : j["jobs"].items()) {+ const std::string s = job["status"].asString();+ if (s == "Failed") return (state = JobState::Failed, true);+ if (s != "Done") allDone = false;+ if (s == "Generating") anyGenerating = true;+ if (job["queue_length"].isNumber()) queue = int(job["queue_length"].asNumber());+ }+ if (j["queue_length"].isNumber()) queue = int(j["queue_length"].asNumber());+ state = allDone ? JobState::Done : anyGenerating ? JobState::Generating : JobState::Waiting;+ return true;+}++bool parseDownload(const std::string& body, std::string& url, std::string& error) {+ Json j;+ std::string err;+ if (!Json::parse(body, j, err) || !j.isObject()) return (error = "Unexpected reply from Hyper3D", false);+ if (std::string e = bodyError(j); !e.empty()) return (error = e, false);+ for (const Json& f : j["list"].items()) {+ std::string name = f["name"].asString();+ std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ if (name.size() > 4 && name.compare(name.size() - 4, 4, ".glb") == 0 && f["url"].isString()) {+ url = f["url"].asString();+ return true;+ }+ }+ return (error = "Hyper3D finished but returned no GLB", false);+}++int pollDelaySeconds(int attempt) {+ static const int steps[] = {5, 5, 7, 10, 15, 20, 30};+ return attempt < int(std::size(steps)) ? steps[std::max(attempt, 0)] : 30;+}++bool checkGlb(const std::string& b, std::string& error) {+ error = "The downloaded file is not a valid GLB model";+ if (b.size() < 20 || b.size() > gMaxBytes) return false;+ if (b.compare(0, 4, "glTF") != 0 || le32(b, 4) != 2 || le32(b, 8) != b.size()) return false;+ size_t at = 12;+ bool first = true;+ while (at < b.size()) {+ if (b.size() - at < 8) return false;+ const uint64_t len = le32(b, at);+ const uint32_t type = le32(b, at + 4);+ if (len % 4 != 0 || len > b.size() - at - 8) return false;+ if (first) {+ if (type != 0x4E4F534Au || len == 0) return false; // "JSON"+ Json j;+ std::string err;+ if (!Json::parse(b.substr(at + 8, size_t(len)), j, err) || !j.isObject() || !j["asset"].isObject()) return false;+ first = false;+ }+ at += 8 + size_t(len);+ }+ if (first) return false;+ error.clear();+ return true;+}++std::string makePrivateDir(std::string& error) {+ std::error_code ec;+ const std::filesystem::path base = std::filesystem::temp_directory_path(ec);+ if (ec) return (error = "No temporary folder: " + ec.message(), std::string());+#if defined(_WIN32)+ // (the temp folder is the user's own, under %LOCALAPPDATA%)+ std::random_device rd;+ for (int i = 0; i < 16; ++i) {+ const std::filesystem::path dir = base / ("sculptforge-hyper3d-" + std::to_string(rd()) + std::to_string(rd()));+ if (std::filesystem::create_directory(dir, ec)) {+ const auto u8 = dir.u8string();+ return std::string(u8.begin(), u8.end());+ }+ }+ error = "Could not make a temporary folder";+ return {};+#else+ std::string templ = (base / "sculptforge-hyper3d-XXXXXX").string();+ if (!mkdtemp(templ.data())) return (error = "Could not make a temporary folder", std::string()); // (mode 0700)+ return templ;+#endif+}++GeneratorResult run(const AiSettings& s, const std::string& imagePath, const std::string& prompt, GenerationProgress* p) {+ GeneratorResult result;+ const bool text = imagePath.empty();+ const std::string tier = resolvedTier(s.hyper3dTier);+ const auto start = std::chrono::steady_clock::now();++ // Gates before anything is sent: the AI switch, the studio policy, the audit log when it is required.+ if (!aiRequestAllowed("hyper3d", std::string(kApiBase) + "/rodin", result.error)) return result;+ const std::string key = s.resolvedHyper3dKey();+ if (key.empty()) {+ result.error = "Add your Hyper3D API key (hyper3d.ai > API dashboard) in Generate 3D";+ return result;+ }+ if (std::string why; audit::required() && !audit::writable(&why)) {+ result.error = why;+ return result;+ }+ auto record = [&](const GeneratorResult& r) {+ audit::Entry e;+ e.tool = "ai";+ e.command = text ? "text_to_3d" : "image_to_3d";+ e.args.set("service", "hyper3d");+ e.args.set("tier", tier);+ if (text) e.args.set("promptChars", double(prompt.size())); // (the length, not the words)+ e.ok = r.ok;+ e.message = r.ok ? "Model downloaded" : r.error;+ e.endpoint = kApiHost;+ e.ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();+ audit::record(e);+ };+ auto fail = [&](std::string error) {+ result = {};+ result.error = std::move(error);+ record(result);+ return result;+ };++ std::string png;+ if (!text) {+ std::string err;+ if (!prepareImagePng(imagePath, png, err)) {+ result.error = err;+ return result;+ }+ } else if (prompt.find_first_not_of(" \t\r\n") == std::string::npos) {+ result.error = "Describe the model you want";+ return result;+ }++ status(p, "Sending to Hyper3D Rodin...");+ std::string contentType;+ const std::string body = submitBody(tier, png, prompt, contentType);+ const HttpResponse submitted = post(key, "/rodin", contentType, body);+ if (!submitted.error.empty() || submitted.status < 200 || submitted.status >= 300) return fail(httpError(submitted));+ std::string taskUuid, subscriptionKey, err;+ if (!parseSubmit(submitted.body, taskUuid, subscriptionKey, err)) return fail(err);++ Json statusBody = Json::object();+ statusBody.set("subscription_key", subscriptionKey);+ for (int attempt = 0;; ++attempt) {+ if (!wait(p, pollDelaySeconds(attempt)))+ return fail("Cancelled (the Hyper3D task keeps running on your account)");+ if (std::chrono::steady_clock::now() - start > std::chrono::minutes(kMaxMinutes))+ return fail("Timed out waiting for Hyper3D");+ const HttpResponse st = post(key, "/status", "Content-Type: application/json", statusBody.dump());+ if (!st.error.empty() || st.status == 429 || st.status >= 500) continue; // transient: back off and ask again+ if (st.status < 200 || st.status >= 300) return fail(httpError(st));+ JobState state;+ int queue = -1;+ if (!parseStatus(st.body, state, queue, err)) return fail(err);+ const int secs = int(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start).count());+ if (state == JobState::Failed) return fail("Hyper3D could not make this model");+ if (state == JobState::Done) break;+ status(p, state == JobState::Waiting+ ? "Waiting in queue" + (queue >= 0 ? " (" + std::to_string(queue) + " ahead)" : std::string()) + "... " ++ std::to_string(secs) + "s"+ : "Generating 3D model... " + std::to_string(secs) + "s");+ }++ Json downloadBody = Json::object();+ downloadBody.set("task_uuid", taskUuid);+ const HttpResponse listed = post(key, "/download", "Content-Type: application/json", downloadBody.dump());+ if (!listed.error.empty() || listed.status < 200 || listed.status >= 300) return fail(httpError(listed));+ std::string fileUrl;+ if (!parseDownload(listed.body, fileUrl, err)) return fail(err);+ if (!downloadUrlAllowed(fileUrl)) {+ net::UrlParts u;+ return fail("Refused the model file: it isn't on Hyper3D's servers (" ++ (net::parseUrl(fileUrl, u) ? u.host : std::string("not an https address")) + ")");+ }+ if (!aiRequestAllowed("hyper3d", fileUrl, err)) return fail(err);++ // The file: no key sent, Hyper3D's hosts only (each redirect too), capped, then checked before anyone parses it.+ status(p, "Downloading model...");+ std::string bytes;+ bool tooBig = false;+ auto get = [&](const std::string& url, const std::function<bool(const std::string&)>& allowed, int stall,+ const std::function<bool(const char*, size_t)>& onData,+ const std::function<bool(uint64_t, uint64_t)>& onProgress) {+ if (!gTransport) return httpGetRestricted(url, allowed, stall, onData, onProgress);+ HttpResponse r = gTransport("GET", url, {}, {});+ if (!r.body.empty() && !onData(r.body.data(), r.body.size())) r.error = "stopped";+ r.body.clear();+ return r;+ };+ const HttpResponse got = get(+ fileUrl, [](const std::string& u) { return downloadUrlAllowed(u); }, kTimeoutSeconds,+ [&](const char* d, size_t n) {+ if (bytes.size() + n > gMaxBytes) return (tooBig = true, false);+ bytes.append(d, n);+ return true;+ },+ [&](uint64_t received, uint64_t total) {+ if (total > gMaxBytes) return (tooBig = true, false);+ if (p && total > 0) p->percent = int(received * 100 / total);+ return !(p && p->cancel);+ });+ if (tooBig) return fail("The model file is larger than 200 MB - refused");+ if (p && p->cancel) return fail("Cancelled");+ if (!got.error.empty() || got.status != 200) return fail("Download failed: " + (got.error.empty() ? "HTTP " + std::to_string(got.status) : got.error));+ if (!checkGlb(bytes, err)) return fail(err);++ const std::string dir = makePrivateDir(err);+ if (dir.empty()) return fail(err);+ const std::string path = dir + "/model.glb";+ {+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ if (!f || !f.write(bytes.data(), std::streamsize(bytes.size()))) {+ f.close();+ std::error_code ec;+ std::filesystem::remove_all(std::filesystem::path(std::u8string(dir.begin(), dir.end())), ec);+ return fail("Cannot write the model file");+ }+ }+ result = {};+ result.ok = true;+ result.outputPath = path;+ result.privateDir = dir;+ record(result);+ return result;+}++void setMaxDownloadBytesForTests(size_t bytes) { gMaxBytes = bytes ? bytes : kMaxDownloadBytes; }++void setTransportForTests(Transport transport, std::vector<int>* waits) {+ gTransport = std::move(transport);+ gWaits = waits;+}++} // namespace sf::ai::hyper3ddiff --git a/src/ai/Hyper3D.h b/src/ai/Hyper3D.hnew file mode 100644index 00000000..e6072289--- /dev/null+++ b/src/ai/Hyper3D.h@@ -0,0 +1,86 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Hyper3D Rodin, direct: Generate 3D's "hyper3d" service (image or text to 3D on Hyper3D's own API, billed to the+// user's Hyper3D account). Written in house from Hyper3D's public API documentation (docs.hyper3d.ai); the idea came+// from a contributor (ElgoogUdiab, PR #123).+//+// Kept narrow on purpose:+// - Only with the user's own key, from the OS keychain (ai/Secrets.h "ai/hyper3d") or typed in this session. No+// environment variable, no shared or trial key: no key, no request.+// - One host for the API, pinned here (kApiHost); every API call is a POST to exactly that URL, https, certificates+// checked, no redirects followed. The key goes only there, never to the file host.+// - The model file: https only, from Hyper3D's own domains (downloadUrlAllowed, every redirect hop too), at most+// kMaxDownloadBytes, checked to be a well-formed GLB (checkGlb) before the existing glTF importer reads it. It is+// written into a private temporary folder (GeneratorResult::privateDir) that the caller deletes after import.+// - Polling backs off from 5 s to 30 s (pollDelaySeconds); 20 minutes at most.+// - The studio policy decides (provider id "hyper3d", the endpoint allow-list, sign-in); one audit log line per+// generation (tier, input kind, prompt length; never the key or the image).+#pragma once++#include "ai/BrushAssistant.h"+#include "ai/Generator3D.h"+#include "ai/Http.h"++#include <cstddef>+#include <functional>+#include <string>+#include <string_view>+#include <vector>++namespace sf::ai {+struct GenerationProgress;+}++namespace sf::ai::hyper3d {++inline constexpr const char* kApiHost = "api.hyper3d.com";+inline constexpr const char* kApiBase = "https://api.hyper3d.com/api/v2";+inline constexpr size_t kMaxDownloadBytes = size_t(200) << 20;+inline constexpr const char* kDefaultTier = "Gen-2.5-Low"; // (Basic API access covers Extreme-Low and Low)++struct Tier {+ const char* id;+ const char* label;+};+// The Gen-2.5 tiers the API offers.+const std::vector<Tier>& tiers();+// A known tier id; anything else runs kDefaultTier.+std::string resolvedTier(const std::string& tier);++// Pieces exposed for tests.+// True for exactly https://api.hyper3d.com/api/v2/<path> (default port, no user info).+bool apiUrl(const std::string& url);+// True for an https URL (default port, no user info) on hyper3d.com, hyper3d.ai or deemos.com or a subdomain.+bool downloadUrlAllowed(const std::string& url);+// The multipart submit body: tier, GLB, raw mesh, no material; the PNG as `images` (image to 3D) or `prompt` (text).+std::string submitBody(const std::string& tier, const std::string& png, const std::string& prompt,+ std::string& contentTypeHeader);+// Reads a /rodin answer: the task uuid (for /download) and the subscription key (for /status).+bool parseSubmit(const std::string& body, std::string& taskUuid, std::string& subscriptionKey, std::string& error);+enum class JobState { Waiting, Generating, Done, Failed };+// Reads a /status answer: Done only when every job is, Failed when any is. `queue` gets queue_length (-1 if none).+bool parseStatus(const std::string& body, JobState& state, int& queue, std::string& error);+// Reads a /download answer: the URL of the first .glb file.+bool parseDownload(const std::string& body, std::string& url, std::string& error);+// The wait before status check `attempt` (0 = the first): 5 s, growing to 30 s.+int pollDelaySeconds(int attempt);+// A well-formed binary glTF 2.0: header, length, a JSON chunk holding an object with "asset", an optional BIN chunk.+bool checkGlb(const std::string& bytes, std::string& error);+// A folder only this user can read, under the system temp folder ("" and ERROR when it can't be made).+std::string makePrivateDir(std::string& error);++// Blocking (a worker thread). Exactly one of `imagePath` / `prompt` is used. The checks of generate3D (the AI switch,+// the studio policy) come first there; this repeats the gate before it sends anything.+GeneratorResult run(const AiSettings& settings, const std::string& imagePath, const std::string& prompt,+ GenerationProgress* progress);++// Tests: answer the requests run() makes ("POST" API calls, the "GET" of the file) instead of the network, after the+// same URL checks; waits are recorded in `waits` instead of slept. {} = the network again.+using Transport = std::function<HttpResponse(const std::string& method, const std::string& url,+ const std::vector<std::string>& headers, const std::string& body)>;+void setTransportForTests(Transport transport, std::vector<int>* waits = nullptr);+// Tests: a smaller size cap (0 = kMaxDownloadBytes).+void setMaxDownloadBytesForTests(size_t bytes);++} // namespace sf::ai::hyper3ddiff --git a/src/ai/ImageTo3DService.cpp b/src/ai/ImageTo3DService.cppindex 1887ae31..13253feb 100644--- a/src/ai/ImageTo3DService.cpp+++ b/src/ai/ImageTo3DService.cpp@@ -6,6 +6,7 @@#include "ai/ComfyUI.h"#include "ai/GradioClient.h"+#include "ai/Hyper3D.h"#include "ai/Http.h"#include "core/Image.h"#include "core/ImageTo3D.h"@@ -556,6 +557,7 @@ namespace {bool serviceAllowed(const AiSettings& s, std::string& error) {const std::string& svc = s.generatorService;if (svc == "inflate") return true;+ if (svc == "hyper3d") return aiRequestAllowed(svc, std::string(hyper3d::kApiBase) + "/rodin", error); // (pinned)const std::string url = svc == "fal" ? s.falEndpoint : svc == "meshy" ? s.meshyEndpoint : svc == "comfyui" ? s.comfyUrl: svc == "command" ? std::string() : std::string("https://huggingface.co/");if (url.empty()) return policy::aiProviderAllowed(svc, &error);@@ -568,6 +570,7 @@ GeneratorResult generate3D(const AiSettings& s, const std::string& imagePath, coif (!aiEnabled()) return {false, {}, aiOffError()};if (std::string why; !serviceAllowed(s, why)) return {false, {}, why};if (s.generatorService == "meshy") return runMeshy(s, imagePath, outputStem, progress);+ if (s.generatorService == "hyper3d") return hyper3d::run(s, imagePath, {}, progress);if (s.generatorService == "command") {status(progress, "Running your generator...");return runGenerator(s.generatorCommand, imagePath, outputStem + ".glb");@@ -607,12 +610,13 @@ GeneratorResult generate3DFromText(const AiSettings& s, const std::string& prompresult.error = "Describe the model you want";return result;}+ if (s.generatorService == "hyper3d") return hyper3d::run(s, {}, prompt, progress);if (s.generatorService == "meshy") return runMeshyRequest(s, "/openapi/v2/text-to-3d", meshyTextBody(s.meshyModel, prompt), outputStem, progress);if (s.generatorService == "fal")return runFalRequest(s, falTextModel(s.falModel), falTextBody(prompt, s.falModel), outputStem, progress);if (s.generatorService == "comfyui") return comfy::run(s, {}, {}, prompt, outputStem, progress);if (s.generatorService == "command" || s.generatorService == "inflate") {- result.error = "Text to 3D needs Hugging Face (free), fal.ai, Meshy or ComfyUI - pick one of those services";+ result.error = "Text to 3D needs Hugging Face (free), fal.ai, Meshy, Hyper3D or ComfyUI - pick one of those services";return result;}return runHuggingFace(s, {}, prompt, outputStem, progress);diff --git a/src/ai/Secrets.cpp b/src/ai/Secrets.cppindex a2bc718f..4b550a24 100644--- a/src/ai/Secrets.cpp+++ b/src/ai/Secrets.cpp@@ -39,6 +39,7 @@ std::vector<std::string> allAccounts() {out.push_back(kHuggingFace);out.push_back(kFal);out.push_back(kMeshy);+ out.push_back(kHyper3d);return out;}@@ -91,6 +92,7 @@ bool storeKeys(const AiSettings& s) {if (!s.hfToken.empty()) ok = put(kHuggingFace, s.hfToken) && ok;if (!s.falKey.empty()) ok = put(kFal, s.falKey) && ok;if (!s.meshyKey.empty()) ok = put(kMeshy, s.meshyKey) && ok;+ if (!s.hyper3dKey.empty()) ok = put(kHyper3d, s.hyper3dKey) && ok;return ok;}diff --git a/src/ai/Secrets.h b/src/ai/Secrets.hindex 7c0213b2..387e1c18 100644--- a/src/ai/Secrets.h+++ b/src/ai/Secrets.h@@ -3,7 +3,7 @@//// AI keys live in the OS keychain (core/Keychain.h), never in ai.json. One keychain account per key:// ai/<preset id> a Brush Lab provider's API key (ai/Providers.h: "ai/anthropic", "ai/openrouter", ...)-// ai/huggingface the Hugging Face token; ai/fal, ai/meshy the Generate 3D services' keys+// ai/huggingface the Hugging Face token; ai/fal, ai/meshy, ai/hyper3d the Generate 3D services' keys// The app reads the keychain once (preload, on a worker thread at start-up) into a process cache, so drawing a panel// never waits on it; the CLI and Python read an account the first time a command needs it (setLazy). Keys found in// an older ai.json move into the keychain and out of the file (migrateLegacyKeys). With no keychain (SF_KEYCHAIN=none, a Linux without the Secret Service), a key typed in lasts@@ -22,6 +22,7 @@ namespace sf::ai::secrets {constexpr const char* kHuggingFace = "ai/huggingface";constexpr const char* kFal = "ai/fal";constexpr const char* kMeshy = "ai/meshy";+constexpr const char* kHyper3d = "ai/hyper3d";// The account of a Brush Lab preset's key.std::string presetAccount(const std::string& presetId);// Every account SculptForge may keep AI keys under.diff --git a/src/app/App.cpp b/src/app/App.cppindex 01873c77..0d1c3b76 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -22,6 +22,7 @@#include "core/AuditLog.h"#include "core/Keychain.h"#include "core/ManagedPolicy.h"+#include "ai/Hyper3D.h"#include "ai/Providers.h"#include "app/Demo.h"#include "app/Shell.h"@@ -3571,6 +3572,7 @@ void App::startGenerator() {aiSettings_.falKey = falKey_;aiSettings_.falModel = falModel_;aiSettings_.meshyKey = meshyKey_;+ aiSettings_.hyper3dKey = hyper3dKey_;aiSettings_.hfToken = hfToken_;aiSettings_.comfyUrl = comfyUrl_;// With no workflow chosen, ComfyUI runs the bundled one the panel shows (not saved, so updates reach it).@@ -3620,6 +3622,13 @@ void App::pollGenerator() {GeneratedModel g = pendingGenerator_.get();const ai::GeneratorResult& r = g.result;const std::string note = r.note.empty() ? std::string() : " - " + r.note;+ struct PrivateDir { // (Hyper3D: the downloaded file's own folder, gone once the model is in)+ std::string path;+ ~PrivateDir() {+ std::error_code ec;+ if (!path.empty()) std::filesystem::remove_all(std::filesystem::path(std::u8string(path.begin(), path.end())), ec);+ }+ } privateDir{r.privateDir};if (!r.ok) {status_ = "Image to 3D failed: " + r.error + note;return;@@ -3825,8 +3834,9 @@ void App::drawImageTo3D() {: "Builds the whole model - limbs, face, back - from one picture with a reconstruction model, then ""makes it sculptable. Characters on a transparent background work best.");static const char* services[] = {"Hugging Face - free models", "fal.ai - paid, your key", "Meshy - paid, your key",- "ComfyUI - your server", "My generator command", "Offline blockout (inflate silhouette)"};- static const char* serviceIds[] = {"huggingface", "fal", "meshy", "comfyui", "command", "inflate"};+ "Hyper3D Rodin (direct) - paid, your key", "ComfyUI - your server", "My generator command",+ "Offline blockout (inflate silhouette)"};+ static const char* serviceIds[] = {"huggingface", "fal", "meshy", "hyper3d", "comfyui", "command", "inflate"};constexpr int kServices = int(std::size(serviceIds));int service = 0;for (int i = 0; i < kServices; ++i)@@ -3834,6 +3844,10 @@ void App::drawImageTo3D() {ImGui::SetNextItemWidth(-1);if (ImGui::Combo("##service", &service, services, kServices)) aiSettings_.generatorService = serviceIds[service];const std::string serviceId = serviceIds[service];+ if (std::string why; serviceId != "inflate" && !policy::aiProviderAllowed(serviceId, &why)) { // (studio policy)+ ui::ManagedBadge();+ hint(why.c_str());+ }ImGui::PushItemWidth(-labelW);if (serviceId == "huggingface") {const auto& presets = ai::hfPresets();@@ -3880,6 +3894,24 @@ void App::drawImageTo3D() {ImGui::InputText("API key", meshyKey_, sizeof meshyKey_, ImGuiInputTextFlags_Password);if (!meshyKey_[0])hint(std::getenv("MESHY_API_KEY") ? "Using MESHY_API_KEY from the environment." : "Get a key at meshy.ai (API settings)");+ } else if (serviceId == "hyper3d") {+ const auto& tiers = ai::hyper3d::tiers();+ const std::string tier = ai::hyper3d::resolvedTier(aiSettings_.hyper3dTier);+ const char* preview = tiers[0].label;+ for (const auto& t : tiers)+ if (tier == t.id) preview = t.label;+ if (ImGui::BeginCombo(tr("Tier"), preview)) {+ for (const auto& t : tiers)+ if (ImGui::Selectable(t.label, tier == t.id)) aiSettings_.hyper3dTier = t.id;+ ImGui::EndCombo();+ }+ ImGui::InputText(tr("API key##hyper3d"), hyper3dKey_, sizeof hyper3dKey_, ImGuiInputTextFlags_Password);+ if (!hyper3dKey_[0])+ hint(aiSettings_.resolvedHyper3dKey().empty()+ ? tr("Off until you add your own key: hyper3d.ai > API dashboard (a Creator plan or higher).")+ : tr("Using your key from the system keychain."));+ hint(tr("Sends your image or description to Hyper3D (api.hyper3d.com), which builds the model. Each generation "+ "is billed to your Hyper3D account. Basic API access covers Extreme Low and Low."));} else if (serviceId == "comfyui") {drawComfyUi();} else if (serviceId == "command") {@@ -3927,6 +3959,7 @@ void App::drawImageTo3D() {aiSettings_.falKey = falKey_;aiSettings_.falModel = falModel_;aiSettings_.meshyKey = meshyKey_;+ aiSettings_.hyper3dKey = hyper3dKey_;aiSettings_.hfToken = hfToken_;aiSettings_.comfyUrl = comfyUrl_;std::string err;diff --git a/src/app/App.h b/src/app/App.hindex 0dcea562..7b87f51d 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -638,7 +638,7 @@ private:float projectDepth_ = 0.02f;bool projectInvert_ = false;char generatorCommand_[1024] = "";- char falKey_[256] = "", falModel_[256] = "", meshyKey_[256] = "", hfToken_[256] = "";+ char falKey_[256] = "", falModel_[256] = "", meshyKey_[256] = "", hfToken_[256] = "", hyper3dKey_[256] = "";// ComfyUI: "Test connection" result, bundled workflows, the chosen file's problem (UI format...)char comfyUrl_[256] = "";struct ComfyCheck {diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex fdc0fcc1..5a368f84 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -3283,6 +3283,10 @@ constexpr Entry kSimplifiedChinese[] = {{"AI tools may use only the kinds of command your studio allows.", "AI 工具只能使用你的工作室允许的命令类型。"},{"AI tools work on their own scene; your studio doesn't let them control this window.", "AI 工具在自己的场景中工作;你的工作室不允许它们控制这个窗口。"},{"API key", "API 密钥"},+ {"Tier", "等级"},+ {"Off until you add your own key: hyper3d.ai > API dashboard (a Creator plan or higher).", "在你添加自己的密钥前保持关闭:hyper3d.ai > API dashboard(需 Creator 或更高方案)。"},+ {"Using your key from the system keychain.", "正在使用系统钥匙串中的密钥。"},+ {"Sends your image or description to Hyper3D (api.hyper3d.com), which builds the model. Each generation is billed to your Hyper3D account. Basic API access covers Extreme Low and Low.", "将你的图片或描述发送到 Hyper3D(api.hyper3d.com)生成模型。每次生成均由你的 Hyper3D 账户计费。基础 API 访问涵盖 Extreme Low 和 Low。"},{"Audit log", "审计日志"},{"Connecting...", "正在连接..."},{"Copy code", "复制代码"},diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex cbca1f9f..376d930f 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -3664,6 +3664,10 @@ constexpr Entry kSpanish[] = {{"AI tools may use only the kinds of command your studio allows.", "Las herramientas de IA solo pueden usar los tipos de comando que permite tu estudio."},{"AI tools work on their own scene; your studio doesn't let them control this window.", "Las herramientas de IA trabajan en su propia escena; tu estudio no les permite controlar esta ventana."},{"API key", "Clave de API"},+ {"Tier", "Nivel"},+ {"Off until you add your own key: hyper3d.ai > API dashboard (a Creator plan or higher).", "Desactivado hasta que añadas tu propia clave: hyper3d.ai > API dashboard (plan Creator o superior)."},+ {"Using your key from the system keychain.", "Usando tu clave del llavero del sistema."},+ {"Sends your image or description to Hyper3D (api.hyper3d.com), which builds the model. Each generation is billed to your Hyper3D account. Basic API access covers Extreme Low and Low.", "Envía tu imagen o descripción a Hyper3D (api.hyper3d.com), que crea el modelo. Cada generación se cobra en tu cuenta de Hyper3D. El acceso básico a la API incluye Extreme Low y Low."},{"Audit log", "Registro de auditoría"},{"Connecting...", "Conectando..."},{"Copy code", "Copiar código"},diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex cf787c0e..58f1781e 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -3189,6 +3189,10 @@ constexpr Entry kTraditionalChinese[] = {{"AI tools may use only the kinds of command your studio allows.", "AI 工具只能使用你的工作室允許的指令類型。"},{"AI tools work on their own scene; your studio doesn't let them control this window.", "AI 工具在自己的場景中運作;你的工作室不允許它們控制這個視窗。"},{"API key", "API 金鑰"},+ {"Tier", "等級"},+ {"Off until you add your own key: hyper3d.ai > API dashboard (a Creator plan or higher).", "在你加入自己的金鑰前保持關閉:hyper3d.ai > API dashboard(需 Creator 或更高方案)。"},+ {"Using your key from the system keychain.", "正在使用系統鑰匙圈中的金鑰。"},+ {"Sends your image or description to Hyper3D (api.hyper3d.com), which builds the model. Each generation is billed to your Hyper3D account. Basic API access covers Extreme Low and Low.", "將你的圖片或描述傳送到 Hyper3D(api.hyper3d.com)建立模型。每次生成都由你的 Hyper3D 帳戶計費。基本 API 存取涵蓋 Extreme Low 與 Low。"},{"Audit log", "稽核記錄"},{"Connecting...", "連線中..."},{"Copy code", "複製代碼"},diff --git a/src/core/ManagedPolicy.cpp b/src/core/ManagedPolicy.cppindex 52c7778d..c7a3ab77 100644--- a/src/core/ManagedPolicy.cpp+++ b/src/core/ManagedPolicy.cpp@@ -134,7 +134,7 @@ const std::vector<std::string>& aiProviderIds() {// Brush Lab (ai/Providers.h)"free", "anthropic", "openai", "ollama", "lmstudio", "vllm", "llamacpp", "litellm", "openrouter", "openai-compatible",// Generate 3D (ai/ImageTo3DService.h)- "huggingface", "fal", "meshy", "comfyui", "command"};+ "huggingface", "fal", "meshy", "hyper3d", "comfyui", "command"};return ids;}diff --git a/tests/test_hyper3d.cpp b/tests/test_hyper3d.cppnew file mode 100644index 00000000..abaaa01b--- /dev/null+++ b/tests/test_hyper3d.cpp@@ -0,0 +1,442 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Hyper3D Rodin direct (ai/Hyper3D.h): off without the user's own key (keychain only, no environment variable), one+// pinned API host, the key sent nowhere else, polling backs off, the file is capped and checked before the importer+// sees it and lives in a private folder, the studio policy and the AI switch stop it before anything is sent, one+// audit line per generation with neither the key nor the image. No test talks to Hyper3D: the transport is faked.+#include "TestHarness.h"++#include "ai/AiPolicy.h"+#include "ai/Http.h"+#include "ai/Hyper3D.h"+#include "ai/ImageTo3DService.h"+#include "ai/Secrets.h"+#include "core/AuditLog.h"+#include "core/Commands.h"+#include "core/Image.h"+#include "core/Keychain.h"+#include "core/ManagedPolicy.h"++#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <sstream>++using namespace sf;+using namespace sf::ai;+namespace fs = std::filesystem;++namespace {++constexpr const char* kKey = "h3d-test-key-123";++void setEnv(const char* name, const char* value) {+#if defined(_WIN32)+ _putenv_s(name, value ? value : "");+#else+ if (value) setenv(name, value, 1);+ else unsetenv(name);+#endif+}++std::string readFile(const std::string& path) {+ std::ifstream f(fs::path(path), std::ios::binary);+ std::stringstream ss;+ ss << f.rdbuf();+ return ss.str();+}++// A minimal well-formed GLB around JSON (padded to 4 bytes) and an optional BIN chunk.+std::string glb(std::string json, const std::string& bin = {}) {+ while (json.size() % 4) json += ' ';+ auto u32 = [](std::string& s, uint32_t v) {+ for (int i = 0; i < 4; ++i) s += char((v >> (8 * i)) & 0xff);+ };+ std::string out = "glTF";+ u32(out, 2);+ const size_t total = 12 + 8 + json.size() + (bin.empty() ? 0 : 8 + bin.size());+ u32(out, uint32_t(total));+ u32(out, uint32_t(json.size()));+ u32(out, 0x4E4F534Au);+ out += json;+ if (!bin.empty()) {+ u32(out, uint32_t(bin.size()));+ u32(out, 0x004E4942u);+ out += bin;+ }+ return out;+}++// Everything a test touches, back as it was.+struct State {+ std::string auditDir;+ std::vector<int> waits;+ State() {+ auditDir = (fs::temp_directory_path() / "sf_hyper3d_audit").string();+ std::error_code ec;+ fs::remove_all(auditDir, ec);+ fs::create_directories(auditDir, ec);+ policy::resetPolicyForTests();+ audit::setPathForTests(auditDir + "/audit.jsonl");+ keychain::useMemoryForTests(true);+ secrets::clearCacheForTests();+ setAiEnabled(true);+ }+ ~State() {+ hyper3d::setTransportForTests({});+ hyper3d::setMaxDownloadBytesForTests(0);+ policy::resetPolicyForTests();+ audit::setPathForTests({});+ secrets::put(secrets::kHyper3d, "");+ secrets::clearCacheForTests();+ setAiEnabled(true);+ setEnv("HYPER3D_API_KEY", nullptr);+ }+ std::string audit() const { return readFile(auditDir + "/audit.jsonl"); }+};++AiSettings hyper3dSettings() {+ AiSettings s = AiSettings::defaults(AiSettings::Provider::Free);+ s.generatorService = "hyper3d";+ return s;+}++// A Hyper3D that answers like the documented API; records what it was sent.+struct FakeHyper3d {+ struct Call {+ std::string method, url, body;+ std::vector<std::string> headers;+ };+ std::vector<Call> calls;+ int pendingPolls = 2;+ std::string fileUrl = "https://file.hyper3d.com/task/model.glb";+ std::string file;+ long fileStatus = 200;++ HttpResponse operator()(const std::string& method, const std::string& url, const std::vector<std::string>& headers,+ const std::string& body) {+ calls.push_back({method, url, body, headers});+ HttpResponse r;+ r.status = 201;+ if (method == "GET") {+ r.status = fileStatus;+ r.body = file;+ } else if (url.ends_with("/rodin")) {+ r.body = R"({"message":"Submitted.","uuid":"task-1","jobs":{"uuids":["job-1"],"subscription_key":"sub-1"},"consumed":0.5})";+ } else if (url.ends_with("/status")) {+ r.body = pendingPolls-- > 0 ? R"({"jobs":[{"uuid":"job-1","status":"Generating"}]})"+ : R"({"jobs":[{"uuid":"job-1","status":"Done"}]})";+ } else if (url.ends_with("/download")) {+ r.body = R"({"list":[{"name":"preview.webp","url":"https://file.hyper3d.com/p.webp"},{"name":"base_basic_pbr.glb","url":")" ++ fileUrl + R"("}]})";+ }+ return r;+ }+};++void useFake(FakeHyper3d& fake, State& st) {+ hyper3d::setTransportForTests([&fake](const std::string& m, const std::string& u, const std::vector<std::string>& h,+ const std::string& b) { return fake(m, u, h, b); },+ &st.waits);+}++bool hasKeyHeader(const std::vector<std::string>& headers) {+ for (const auto& h : headers)+ if (h.find(kKey) != std::string::npos) return true;+ return false;+}++} // namespace++TEST(hyper3d_key_only_from_user_keychain_never_env_or_file) {+ State st;+ setEnv("HYPER3D_API_KEY", "from-env");+ AiSettings s = hyper3dSettings();+ CHECK(s.resolvedHyper3dKey().empty()); // no environment variable, no built-in or trial key+ s.hyper3dKey = kKey;+ CHECK(s.resolvedHyper3dKey() == kKey);+ // ai.json never holds it, even when an old or hand-edited file has one+ CHECK(s.toJson().dump().find(kKey) == std::string::npos);+ Json j = s.toJson();+ j.set("hyper3dKey", "planted");+ CHECK(AiSettings::fromJson(j).resolvedHyper3dKey().empty());+ // saved: the keychain account "ai/hyper3d"+ CHECK(secrets::storeKeys(s));+ std::string v;+ CHECK(keychain::load(secrets::kHyper3d, v) && v == kKey);+ secrets::clearCacheForTests();+ CHECK(hyper3dSettings().resolvedHyper3dKey() == kKey);+ bool listed = false;+ for (const auto& a : secrets::allAccounts()) listed = listed || a == secrets::kHyper3d;+ CHECK(listed);+}++TEST(hyper3d_without_key_sends_nothing) {+ State st;+ FakeHyper3d fake;+ useFake(fake, st);+ const uint64_t before = httpRequestCount();+ GeneratorResult r = generate3DFromText(hyper3dSettings(), "a dragon head", tempPath("sf_h3d_nokey"));+ CHECK(!r.ok && r.error.find("Hyper3D API key") != std::string::npos);+ CHECK(fake.calls.empty() && httpRequestCount() == before);+}++TEST(hyper3d_ai_switch_off_sends_nothing) {+ State st;+ FakeHyper3d fake;+ useFake(fake, st);+ AiSettings s = hyper3dSettings();+ s.hyper3dKey = kKey;+ setAiEnabled(false);+ const uint64_t before = httpRequestCount();+ CHECK(!generate3DFromText(s, "a dragon head", tempPath("sf_h3d_off")).ok);+ CHECK(!hyper3d::run(s, {}, "a dragon head", nullptr).ok); // the module's own gate too+ CHECK(fake.calls.empty() && httpRequestCount() == before);+}++TEST(hyper3d_studio_policy_controls_it) {+ State st;+ FakeHyper3d fake;+ useFake(fake, st);+ AiSettings s = hyper3dSettings();+ s.hyper3dKey = kKey;+ bool known = false;+ for (const auto& id : policy::aiProviderIds()) known = known || id == "hyper3d";+ CHECK(known); // a provider id the policy's allow-list names+ policy::Policy p;+ p.present = true;+ p.aiProviders = {"fal"};+ policy::setPolicyForTests(p);+ GeneratorResult r = generate3DFromText(s, "a dragon head", tempPath("sf_h3d_policy"));+ CHECK(!r.ok && fake.calls.empty());+ CHECK(!hyper3d::run(s, {}, "a dragon head", nullptr).ok && fake.calls.empty());+ // the endpoint allow-list applies too (the host is pinned, the studio can still refuse it)+ p.aiProviders = {"hyper3d"};+ p.aiEndpoints = {"https://llm.studio.internal/"};+ policy::setPolicyForTests(p);+ CHECK(!generate3DFromText(s, "a dragon head", tempPath("sf_h3d_policy")).ok && fake.calls.empty());+ // audit.required with a log that can't be written: refused before anything is sent+ p.aiEndpoints.clear();+ p.auditRequired = true;+ policy::setPolicyForTests(p);+ { std::ofstream(st.auditDir + "/file") << "x"; }+ audit::setPathForTests(st.auditDir + "/file/audit.jsonl");+ CHECK(!hyper3d::run(s, {}, "a dragon head", nullptr).ok && fake.calls.empty());+}++TEST(hyper3d_api_host_is_pinned) {+ CHECK(hyper3d::apiUrl("https://api.hyper3d.com/api/v2/rodin"));+ CHECK(hyper3d::apiUrl("https://api.hyper3d.com/api/v2/status"));+ CHECK(!hyper3d::apiUrl("http://api.hyper3d.com/api/v2/rodin"));+ CHECK(!hyper3d::apiUrl("https://api.hyper3d.com:8443/api/v2/rodin"));+ CHECK(!hyper3d::apiUrl("https://api.hyper3d.com.evil.example/api/v2/rodin"));+ CHECK(!hyper3d::apiUrl("https://[email protected]/api/v2/rodin"));+ CHECK(!hyper3d::apiUrl("https://evil.example/api/v2/rodin"));+ CHECK(!hyper3d::apiUrl("https://api.hyper3d.com/api/v2/../../x"));+ // the file: https on Hyper3D's own domains only+ CHECK(hyper3d::downloadUrlAllowed("https://file.hyper3d.com/a/model.glb"));+ CHECK(hyper3d::downloadUrlAllowed("https://cdn.hyper3d.ai/model.glb"));+ CHECK(hyper3d::downloadUrlAllowed("https://files.deemos.com/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("http://file.hyper3d.com/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("https://hyper3d.com.evil.example/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("https://evilhyper3d.com/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("https://[email protected]/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("https://127.0.0.1/model.glb"));+ CHECK(!hyper3d::downloadUrlAllowed("file:///etc/passwd"));+}++TEST(hyper3d_request_pieces) {+ std::string ct;+ const std::string body = hyper3d::submitBody("Gen-2.5-High", "PNGDATA", {}, ct);+ CHECK(ct.rfind("Content-Type: multipart/form-data; boundary=", 0) == 0);+ CHECK(body.find("name=\"images\"; filename=\"input.png\"") != std::string::npos && body.find("PNGDATA") != std::string::npos);+ CHECK(body.find("Gen-2.5-High") != std::string::npos && body.find("name=\"prompt\"") == std::string::npos);+ CHECK(body.find("geometry_file_format\"\r\n\r\nglb") != std::string::npos);+ const std::string text = hyper3d::submitBody("bogus", {}, "a vase", ct);+ CHECK(text.find("name=\"prompt\"\r\n\r\na vase") != std::string::npos && text.find("name=\"images\"") == std::string::npos);+ CHECK(text.find(hyper3d::kDefaultTier) != std::string::npos); // an unknown tier runs the default+ CHECK(hyper3d::tiers().size() == 5 && hyper3d::resolvedTier("Gen-2.5-Extreme-High") == "Gen-2.5-Extreme-High");++ std::string uuid, sub, err;+ CHECK(hyper3d::parseSubmit(R"({"uuid":"u","jobs":{"uuids":["j"],"subscription_key":"k"}})", uuid, sub, err) && uuid == "u" && sub == "k");+ CHECK(!hyper3d::parseSubmit(R"({"error":"API_INSUFFICIENT_FUNDS","message":"no"})", uuid, sub, err) &&+ err.find("credits") != std::string::npos);+ CHECK(!hyper3d::parseSubmit("<html>", uuid, sub, err));+ hyper3d::JobState state;+ int queue = 0;+ CHECK(hyper3d::parseStatus(R"({"jobs":[{"status":"Done"},{"status":"Generating"}]})", state, queue, err) &&+ state == hyper3d::JobState::Generating);+ CHECK(hyper3d::parseStatus(R"({"jobs":[{"status":"Done"},{"status":"Failed"}]})", state, queue, err) &&+ state == hyper3d::JobState::Failed);+ CHECK(hyper3d::parseStatus(R"({"jobs":[{"status":"Waiting","queue_length":3}]})", state, queue, err) &&+ state == hyper3d::JobState::Waiting && queue == 3);+ CHECK(!hyper3d::parseStatus(R"({"jobs":[]})", state, queue, err));+ std::string url;+ CHECK(hyper3d::parseDownload(R"({"list":[{"name":"a.webp","url":"x"},{"name":"B.GLB","url":"https://f/b.glb"}]})", url, err) &&+ url == "https://f/b.glb");+ CHECK(!hyper3d::parseDownload(R"({"list":[{"name":"a.fbx","url":"x"}]})", url, err));+ // back-off: at least 5 s first, growing, capped at 30 s+ CHECK(hyper3d::pollDelaySeconds(0) == 5);+ for (int i = 1; i < 100; ++i) CHECK(hyper3d::pollDelaySeconds(i) >= hyper3d::pollDelaySeconds(i - 1) && hyper3d::pollDelaySeconds(i) <= 30);+ CHECK(hyper3d::pollDelaySeconds(99) == 30);+}++TEST(hyper3d_glb_checked_before_parse) {+ std::string err;+ CHECK(hyper3d::checkGlb(glb(R"({"asset":{"version":"2.0"}})"), err));+ CHECK(hyper3d::checkGlb(glb(R"({"asset":{"version":"2.0"}})", std::string(8, '\0')), err));+ CHECK(hyper3d::checkGlb(readFile(SF_TEST_DATA_DIR "/marble-bust.glb"), err)); // a real file+ std::string g = glb(R"({"asset":{"version":"2.0"}})");+ CHECK(!hyper3d::checkGlb("", err));+ CHECK(!hyper3d::checkGlb("<html>not a model</html> padding padding", err));+ std::string bad = g;+ bad[4] = 1; // version 1+ CHECK(!hyper3d::checkGlb(bad, err));+ CHECK(!hyper3d::checkGlb(g + "xxxx", err)); // length field disagrees+ CHECK(!hyper3d::checkGlb(g.substr(0, g.size() - 4), err)); // truncated+ CHECK(!hyper3d::checkGlb(glb(R"([1,2,3])"), err)); // JSON chunk without an asset+ CHECK(!hyper3d::checkGlb(glb(R"({"asset":)"), err)); // broken JSON+ std::string lying = g;+ lying[12] = char(0xff), lying[13] = char(0xff); // chunk longer than the file+ CHECK(!hyper3d::checkGlb(lying, err));+}++TEST(hyper3d_private_dir) {+ std::string err;+ const std::string dir = hyper3d::makePrivateDir(err);+ CHECK(!dir.empty() && fs::is_directory(dir));+#if !defined(_WIN32)+ const auto perms = fs::status(dir).permissions();+ CHECK((perms & (fs::perms::group_all | fs::perms::others_all)) == fs::perms::none);+#endif+ const std::string other = hyper3d::makePrivateDir(err);+ CHECK(other != dir);+ std::error_code ec;+ fs::remove_all(dir, ec);+ fs::remove_all(other, ec);+}++TEST(hyper3d_full_flow_with_fake_service) {+ State st;+ FakeHyper3d fake;+ fake.file = readFile(SF_TEST_DATA_DIR "/marble-bust.glb");+ useFake(fake, st);+ AiSettings s = hyper3dSettings();+ s.hyper3dKey = kKey;+ s.hyper3dTier = "Gen-2.5-Medium";+ GenerationProgress progress;+ const uint64_t before = httpRequestCount();+ GeneratorResult r = generate3DFromText(s, "a stylised dragon head", tempPath("sf_h3d_flow"), &progress);+ CHECK(r.ok);+ CHECK(httpRequestCount() == before); // (all through the fake)+ // submit, two pending polls, done, download list, file+ CHECK(fake.calls.size() == 6);+ for (size_t i = 0; i + 1 < fake.calls.size(); ++i) {+ CHECK(fake.calls[i].method == "POST" && hyper3d::apiUrl(fake.calls[i].url));+ CHECK(hasKeyHeader(fake.calls[i].headers));+ }+ CHECK(fake.calls[0].body.find("Gen-2.5-Medium") != std::string::npos);+ CHECK(fake.calls[1].body.find("sub-1") != std::string::npos); // status: the subscription key+ CHECK(fake.calls[4].body.find("task-1") != std::string::npos); // download: the task uuid+ CHECK(fake.calls[5].method == "GET" && fake.calls[5].url == fake.fileUrl);+ CHECK(!hasKeyHeader(fake.calls[5].headers)); // the key never goes to the file host+ CHECK(st.waits.size() == 3 && st.waits[0] >= 5);+ // the file sits in a private folder, readable by the existing glTF importer+ CHECK(!r.privateDir.empty() && fs::path(r.outputPath).parent_path() == fs::path(r.privateDir));+ Document doc;+ CHECK(CommandRegistry().execute(doc, "open", {{"path", r.outputPath}}).ok && doc.mesh.vertexCount() > 0);+ std::error_code ec;+ fs::remove_all(r.privateDir, ec);+ // one audit line: service, tier, endpoint; never the key or the words+ const std::string log = st.audit();+ CHECK(log.find("hyper3d") != std::string::npos && log.find("api.hyper3d.com") != std::string::npos);+ CHECK(log.find("Gen-2.5-Medium") != std::string::npos);+ CHECK(log.find(kKey) == std::string::npos && log.find("dragon") == std::string::npos);+}++TEST(hyper3d_image_is_sent_as_png_and_never_logged) {+ State st;+ FakeHyper3d fake;+ fake.file = glb(R"({"asset":{"version":"2.0"}})");+ useFake(fake, st);+ Image img;+ img.width = img.height = 32;+ img.rgba.assign(32 * 32 * 4, 255);+ const std::string path = tempPath("sf_h3d_input.png");+ std::string err;+ CHECK(img.savePng(path, err));+ AiSettings s = hyper3dSettings();+ s.hyper3dKey = kKey;+ GeneratorResult r = generate3D(s, path, tempPath("sf_h3d_img"));+ CHECK(r.ok && !fake.calls.empty());+ CHECK(fake.calls[0].body.find("name=\"images\"; filename=\"input.png\"") != std::string::npos);+ CHECK(fake.calls[0].body.find("\x89PNG") != std::string::npos);+ CHECK(st.audit().find("image_to_3d") != std::string::npos && st.audit().find("PNG") == std::string::npos);+ std::error_code ec;+ fs::remove_all(r.privateDir, ec);+ fs::remove(path, ec);+}++TEST(hyper3d_bad_downloads_refused) {+ State st;+ AiSettings s = hyper3dSettings();+ s.hyper3dKey = kKey;+ auto attempt = [&](FakeHyper3d& fake) {+ fake.calls.clear();+ useFake(fake, st);+ return hyper3d::run(s, {}, "a vase", nullptr);+ };+ {+ FakeHyper3d fake; // a file host outside Hyper3D's domains: not fetched at all+ fake.fileUrl = "https://evil.example/model.glb";+ fake.file = glb(R"({"asset":{"version":"2.0"}})");+ GeneratorResult r = attempt(fake);+ CHECK(!r.ok && r.error.find("evil.example") != std::string::npos && fake.calls.back().method == "POST");+ }+ {+ FakeHyper3d fake; // plain http+ fake.fileUrl = "http://file.hyper3d.com/model.glb";+ CHECK(!attempt(fake).ok && fake.calls.back().method == "POST");+ }+ {+ FakeHyper3d fake; // not a GLB+ fake.file = "<html>hello</html>";+ GeneratorResult r = attempt(fake);+ CHECK(!r.ok && r.error.find("not a valid GLB") != std::string::npos && r.privateDir.empty());+ }+ {+ FakeHyper3d fake; // over the size cap (200 MB; 1 KB here)+ CHECK(hyper3d::kMaxDownloadBytes == size_t(200) << 20);+ hyper3d::setMaxDownloadBytesForTests(1024);+ fake.file = glb(R"({"asset":{"version":"2.0"}})", std::string(2048, '\0'));+ GeneratorResult r = attempt(fake);+ hyper3d::setMaxDownloadBytesForTests(0);+ CHECK(!r.ok && r.error.find("200 MB") != std::string::npos);+ }+ {+ FakeHyper3d fake; // a failed job+ fake.pendingPolls = 0;+ hyper3d::setTransportForTests([&fake](const std::string& m, const std::string& u, const std::vector<std::string>& h,+ const std::string& b) {+ HttpResponse r = fake(m, u, h, b);+ if (u.ends_with("/status")) r.body = R"({"jobs":[{"uuid":"job-1","status":"Failed"}]})";+ return r;+ });+ CHECK(!hyper3d::run(s, {}, "a vase", nullptr).ok && fake.calls.size() == 2);+ }+ {+ FakeHyper3d fake; // a rejected key: stops at the submit+ hyper3d::setTransportForTests([&fake](const std::string& m, const std::string& u, const std::vector<std::string>& h,+ const std::string& b) {+ fake.calls.push_back({m, u, b, h});+ HttpResponse r;+ r.status = 401;+ return r;+ });+ GeneratorResult r = hyper3d::run(s, {}, "a vase", nullptr);+ CHECK(!r.ok && r.error.find("rejected") != std::string::npos && fake.calls.size() == 1);+ CHECK(r.error.find(kKey) == std::string::npos);+ }+ CHECK(st.audit().find(kKey) == std::string::npos);+}diff --git a/tests/ui/generate_hyper3d.sfui b/tests/ui/generate_hyper3d.sfuinew file mode 100644index 00000000..38ee96d7--- /dev/null+++ b/tests/ui/generate_hyper3d.sfui@@ -0,0 +1,37 @@+# Generate 3D > Hyper3D Rodin (direct) (ai/Hyper3D.h, #123): the tier picker, the key field and what is sent to whom;+# without a key Generate refuses before anything is sent; a studio policy that doesn't list "hyper3d" shows the+# Managed badge and refuses too. Nothing is generated (no key, no network).+run ui_look look=classic layout=classic # written for the Classic look+drop ../../assets/demo/teddy-sketch.png+wait_for "Generate 3D" 5+click "Generate 3D/##service"+expect_text Hyper3D Rodin (direct) - paid, your key+click "Hyper3D Rodin (direct) - paid, your key"+wait 0.2+expect_text Off until you add your own key+expect_text Sends your image or description to Hyper3D (api.hyper3d.com)+expect_text billed to your Hyper3D account+shot generate-hyper3d-image++click "Generate 3D/Tier"+expect_text Gen-2.5 Extreme Low (fastest)+expect_text Gen-2.5 Extreme High (more credits)+shot generate-hyper3d-tiers+click "Gen-2.5 Medium"+wait 0.2+expect_text Gen-2.5 Medium++click "Generate 3D/Generate 3D model"+wait 0.5+expect_text Add your Hyper3D API key++click "Generate 3D/From text"+wait 0.2+expect_text Sends your image or description to Hyper3D+shot generate-hyper3d-text++run ui_policy json="{\"format\":\"sculptforge-policy\",\"version\":1,\"organization\":\"Acme Animation\",\"ai\":{\"enabled\":true,\"providers\":[\"fal\",\"huggingface\"]}}"+wait 0.2+expect_text doesn't allow this AI provider (hyper3d)+shot generate-hyper3d-managed+run ui_policy json=""