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
ComfyUI workflows for SculptForge, plus a validator and smoke test
islandmed5e9e72156ea1
diff --git a/integrations/comfyui/workflows/README.md b/integrations/comfyui/workflows/README.mdnew file mode 100644index 00000000..f5fa1e22--- /dev/null+++ b/integrations/comfyui/workflows/README.md@@ -0,0 +1,83 @@+# ComfyUI workflows for SculptForge++Ready-made [ComfyUI](https://github.com/comfyanonymous/ComfyUI) workflows that SculptForge's **Generate 3D** window can+run on your own ComfyUI server (image or text in, mesh out). They are saved in ComfyUI's **API format**, so you can also+queue them yourself with `POST /prompt`, or drag one onto the ComfyUI canvas to look at and change it.++| Workflow | Input | What it does | Needs | Runs on |+|---|---|---|---|---|+| [`sculptforge-inflate.json`](sculptforge-inflate.json) | image | Inflates a sketch or silhouette into a rounded, closed base mesh with SculptForge, then exports a GLB. | The [ComfyUI-SculptForge](../ComfyUI-SculptForge/) node pack and SculptForge installed. No models. | Any CPU, 1 to 2 seconds |+| [`hunyuan3d-image-to-3d.json`](hunyuan3d-image-to-3d.json) | image | Hunyuan3D 2.1 image-to-3D with ComfyUI's built-in nodes: a detailed, untextured mesh saved as GLB. | `hunyuan_3d_v2.1.safetensors` (7.4 GB). | A GPU (Tencent quotes about 10 GB of VRAM for shape generation) |+| [`text-to-3d.json`](text-to-3d.json) | text | FLUX.1 [schnell] draws the object on a plain backdrop, BiRefNet cuts it out onto white, Hunyuan3D 2.1 turns it into a mesh. Also saves the concept image. | `flux1-schnell-fp8.safetensors` (17.2 GB), `birefnet.safetensors` (444 MB), `hunyuan_3d_v2.1.safetensors` (7.4 GB). | A GPU; ComfyUI moves each model in and out of VRAM as it is needed |++Apart from the SculptForge nodes in the first one, all three use only nodes that ship with ComfyUI. They were+checked against ComfyUI 0.42.0; older versions may lack *Remove Background* or *Trim Text*, so update ComfyUI if a+node is reported missing.++## Model files++Download each file into the folder shown, inside your ComfyUI install, then restart ComfyUI or press **R** in the+editor to refresh the lists.++| File | Folder | Used by | Download |+|---|---|---|---|+| `hunyuan_3d_v2.1.safetensors` | `models/checkpoints/` | hunyuan3d-image-to-3d, text-to-3d | [Comfy-Org/hunyuan3D_2.1_repackaged](https://huggingface.co/Comfy-Org/hunyuan3D_2.1_repackaged/resolve/main/hunyuan_3d_v2.1.safetensors) |+| `flux1-schnell-fp8.safetensors` | `models/checkpoints/` | text-to-3d | [Comfy-Org/flux1-schnell](https://huggingface.co/Comfy-Org/flux1-schnell/resolve/main/flux1-schnell-fp8.safetensors) |+| `birefnet.safetensors` | `models/background_removal/` | text-to-3d | [Comfy-Org/BiRefNet](https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors) |++```+ComfyUI/+└── models/+ ├── checkpoints/+ │ ├── hunyuan_3d_v2.1.safetensors+ │ └── flux1-schnell-fp8.safetensors+ └── background_removal/+ └── birefnet.safetensors+```++The Hunyuan3D 2.1 checkpoint holds the shape model, its image encoder and its VAE, so it is the only file the+image-to-3D workflow needs. To use **Hunyuan3D 2.0** instead (smaller, 4.9 GB), download+[`hunyuan3d-dit-v2_fp16.safetensors`](https://huggingface.co/Comfy-Org/hunyuan3D_2.0_repackaged/resolve/main/split_files/hunyuan3d-dit-v2_fp16.safetensors)+into `models/checkpoints/`, pick it in the loader, and set the latent `resolution` to 3072, `steps` to 20 and `cfg`+to 8. FLUX.1 [schnell] and BiRefNet are released under licences that allow commercial use; check the+[Hunyuan3D 2.1 licence](https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1/blob/main/LICENSE) for where it applies.++The image-to-3D workflow works best with one object, whole and centred, on a plain light background (a white sketch+page is ideal). For photos with busy backgrounds, copy the BiRefNet nodes (9 to 12) from `text-to-3d.json` in front+of the Hunyuan3D part.++## How SculptForge fills in a workflow++Any API-format workflow works with SculptForge if it follows these rules. The workflows here already do.++- **Image:** every `LoadImage` node titled `sf_image` gets the picture SculptForge uploads. If no node has that title,+ the first `LoadImage` node does.+- **Text:** the node titled `sf_prompt` gets the prompt in its `text`, `prompt` or `string` input, whichever it has.+ In `text-to-3d.json` that is a *Trim Text* node, so the prompt then gets the 3D-friendly framing ("a single+ object, centered, plain white background, ...") appended before it reaches FLUX.+- **Seed:** a node titled `sf_seed`, and every input named `seed` or `noise_seed`, may get a fresh random seed.+- **Result:** SculptForge downloads the first mesh file (`.glb`, `.gltf`, `.obj`, `.ply`, `.stl`, `.fbx`, `.usdz`) in+ the finished job's outputs. Other outputs, such as the concept image, are ignored.++To make your own: build the graph in ComfyUI, set node titles with *right click > Title*, end it with a mesh saver+(*Save 3D Model*, or *SculptForge Export*), then save it with *Workflow > Export (API)*.++## Checking a workflow++Two scripts in [`tools/`](../../../tools/) check workflows against a running ComfyUI. Both use only Python's standard+library (and curl).++```sh+# Every node exists on the server, every required input is set, every link points at a real output of the+# right type, values are in range, an output node exists, plus which nodes SculptForge will fill in.+tools/comfyui-validate-workflow.py integrations/comfyui/workflows/*.json+tools/comfyui-validate-workflow.py --server http://192.168.1.20:8188 --strict my-workflow.json++# Run one for real like SculptForge does: upload assets/demo/teddy-sketch.png, fill in the inputs, queue it,+# wait, download the mesh and check it.+tools/comfyui-smoke.sh integrations/comfyui/workflows/sculptforge-inflate.json+tools/comfyui-smoke.sh --prompt "a carved stone owl" --out /tmp/meshes integrations/comfyui/workflows/text-to-3d.json+```++Missing model files and an unloaded SculptForge pack are warnings in the validator (errors with `--strict`), since+they are about the server rather than the workflow.diff --git a/integrations/comfyui/workflows/hunyuan3d-image-to-3d.json b/integrations/comfyui/workflows/hunyuan3d-image-to-3d.jsonnew file mode 100644index 00000000..574411c7--- /dev/null+++ b/integrations/comfyui/workflows/hunyuan3d-image-to-3d.json@@ -0,0 +1,63 @@+{+ "1": {+ "class_type": "ImageOnlyCheckpointLoader",+ "inputs": {"ckpt_name": "hunyuan_3d_v2.1.safetensors"},+ "_meta": {"title": "Load Hunyuan3D 2.1 (models/checkpoints)"}+ },+ "2": {+ "class_type": "LoadImage",+ "inputs": {"image": "teddy-sketch.png"},+ "_meta": {"title": "sf_image"}+ },+ "3": {+ "class_type": "ModelSamplingAuraFlow",+ "inputs": {"model": ["1", 0], "shift": 1.0, "sampling": "flow"},+ "_meta": {"title": "ModelSamplingAuraFlow"}+ },+ "4": {+ "class_type": "CLIPVisionEncode",+ "inputs": {"clip_vision": ["1", 1], "image": ["2", 0], "crop": "center"},+ "_meta": {"title": "CLIP Vision Encode"}+ },+ "5": {+ "class_type": "Hunyuan3Dv2Conditioning",+ "inputs": {"clip_vision_output": ["4", 0]},+ "_meta": {"title": "Hunyuan3Dv2 Conditioning"}+ },+ "6": {+ "class_type": "EmptyLatentHunyuan3Dv2",+ "inputs": {"resolution": 4096, "batch_size": 1},+ "_meta": {"title": "Empty Latent Hunyuan3Dv2"}+ },+ "7": {+ "class_type": "KSampler",+ "inputs": {+ "model": ["3", 0],+ "positive": ["5", 0],+ "negative": ["5", 1],+ "latent_image": ["6", 0],+ "seed": 1234,+ "steps": 30,+ "cfg": 5.0,+ "sampler_name": "euler",+ "scheduler": "normal",+ "denoise": 1.0+ },+ "_meta": {"title": "KSampler"}+ },+ "8": {+ "class_type": "VAEDecodeHunyuan3D",+ "inputs": {"samples": ["7", 0], "vae": ["1", 2], "num_chunks": 8000, "octree_resolution": 256},+ "_meta": {"title": "VAE Decode Hunyuan3D"}+ },+ "9": {+ "class_type": "VoxelToMesh",+ "inputs": {"voxel": ["8", 0], "algorithm": "surface net", "threshold": 0.6},+ "_meta": {"title": "Voxel to Mesh"}+ },+ "10": {+ "class_type": "SaveGLB",+ "inputs": {"mesh": ["9", 0], "filename_prefix": "3d/sculptforge_hunyuan3d"},+ "_meta": {"title": "Save GLB"}+ }+}diff --git a/integrations/comfyui/workflows/sculptforge-inflate.json b/integrations/comfyui/workflows/sculptforge-inflate.jsonnew file mode 100644index 00000000..084453fa--- /dev/null+++ b/integrations/comfyui/workflows/sculptforge-inflate.json@@ -0,0 +1,17 @@+{+ "1": {+ "class_type": "LoadImage",+ "inputs": {"image": "teddy-sketch.png"},+ "_meta": {"title": "sf_image"}+ },+ "2": {+ "class_type": "SculptForgeInflateImage",+ "inputs": {"image": ["1", 0], "mask": ["1", 1], "thickness": 1.0, "resolution": 160, "subdivisions": 1},+ "_meta": {"title": "SculptForge Inflate Image"}+ },+ "3": {+ "class_type": "SculptForgeExport",+ "inputs": {"mesh": ["2", 0], "format": "glb", "filename_prefix": "3d/sculptforge_inflate"},+ "_meta": {"title": "SculptForge Export"}+ }+}diff --git a/integrations/comfyui/workflows/text-to-3d.json b/integrations/comfyui/workflows/text-to-3d.jsonnew file mode 100644index 00000000..4d6c5e2d--- /dev/null+++ b/integrations/comfyui/workflows/text-to-3d.json@@ -0,0 +1,138 @@+{+ "1": {+ "class_type": "StringTrim",+ "inputs": {"string": "a friendly cartoon teddy bear sitting", "mode": "Both"},+ "_meta": {"title": "sf_prompt"}+ },+ "2": {+ "class_type": "StringConcatenate",+ "inputs": {+ "string_a": ["1", 0],+ "string_b": "a single object, centered, whole object in view, plain white background, soft even studio lighting, clean 3D clay render, no text",+ "delimiter": ", "+ },+ "_meta": {"title": "Add 3D-friendly framing"}+ },+ "3": {+ "class_type": "CheckpointLoaderSimple",+ "inputs": {"ckpt_name": "flux1-schnell-fp8.safetensors"},+ "_meta": {"title": "Load FLUX.1 schnell (models/checkpoints)"}+ },+ "4": {+ "class_type": "CLIPTextEncode",+ "inputs": {"text": ["2", 0], "clip": ["3", 1]},+ "_meta": {"title": "Prompt"}+ },+ "5": {+ "class_type": "CLIPTextEncode",+ "inputs": {"text": "", "clip": ["3", 1]},+ "_meta": {"title": "Negative (unused by FLUX at cfg 1)"}+ },+ "6": {+ "class_type": "EmptySD3LatentImage",+ "inputs": {"width": 1024, "height": 1024, "batch_size": 1},+ "_meta": {"title": "Empty Latent 1024x1024"}+ },+ "7": {+ "class_type": "KSampler",+ "inputs": {+ "model": ["3", 0],+ "positive": ["4", 0],+ "negative": ["5", 0],+ "latent_image": ["6", 0],+ "seed": 1234,+ "steps": 4,+ "cfg": 1.0,+ "sampler_name": "euler",+ "scheduler": "simple",+ "denoise": 1.0+ },+ "_meta": {"title": "KSampler (image)"}+ },+ "8": {+ "class_type": "VAEDecode",+ "inputs": {"samples": ["7", 0], "vae": ["3", 2]},+ "_meta": {"title": "VAE Decode"}+ },+ "9": {+ "class_type": "LoadBackgroundRemovalModel",+ "inputs": {"bg_removal_name": "birefnet.safetensors"},+ "_meta": {"title": "Load BiRefNet (models/background_removal)"}+ },+ "10": {+ "class_type": "RemoveBackground",+ "inputs": {"bg_removal_model": ["9", 0], "image": ["8", 0]},+ "_meta": {"title": "Foreground mask"}+ },+ "11": {+ "class_type": "EmptyImage",+ "inputs": {"width": 1024, "height": 1024, "batch_size": 1, "color": 16777215},+ "_meta": {"title": "White backdrop"}+ },+ "12": {+ "class_type": "ImageCompositeMasked",+ "inputs": {"destination": ["11", 0], "source": ["8", 0], "x": 0, "y": 0, "resize_source": false, "mask": ["10", 0]},+ "_meta": {"title": "Object on white"}+ },+ "13": {+ "class_type": "SaveImage",+ "inputs": {"images": ["12", 0], "filename_prefix": "sculptforge/text-to-3d_concept"},+ "_meta": {"title": "Save concept image"}+ },+ "20": {+ "class_type": "ImageOnlyCheckpointLoader",+ "inputs": {"ckpt_name": "hunyuan_3d_v2.1.safetensors"},+ "_meta": {"title": "Load Hunyuan3D 2.1 (models/checkpoints)"}+ },+ "21": {+ "class_type": "ModelSamplingAuraFlow",+ "inputs": {"model": ["20", 0], "shift": 1.0, "sampling": "flow"},+ "_meta": {"title": "ModelSamplingAuraFlow"}+ },+ "22": {+ "class_type": "CLIPVisionEncode",+ "inputs": {"clip_vision": ["20", 1], "image": ["12", 0], "crop": "center"},+ "_meta": {"title": "CLIP Vision Encode"}+ },+ "23": {+ "class_type": "Hunyuan3Dv2Conditioning",+ "inputs": {"clip_vision_output": ["22", 0]},+ "_meta": {"title": "Hunyuan3Dv2 Conditioning"}+ },+ "24": {+ "class_type": "EmptyLatentHunyuan3Dv2",+ "inputs": {"resolution": 4096, "batch_size": 1},+ "_meta": {"title": "Empty Latent Hunyuan3Dv2"}+ },+ "25": {+ "class_type": "KSampler",+ "inputs": {+ "model": ["21", 0],+ "positive": ["23", 0],+ "negative": ["23", 1],+ "latent_image": ["24", 0],+ "seed": 1234,+ "steps": 30,+ "cfg": 5.0,+ "sampler_name": "euler",+ "scheduler": "normal",+ "denoise": 1.0+ },+ "_meta": {"title": "KSampler (3D)"}+ },+ "26": {+ "class_type": "VAEDecodeHunyuan3D",+ "inputs": {"samples": ["25", 0], "vae": ["20", 2], "num_chunks": 8000, "octree_resolution": 256},+ "_meta": {"title": "VAE Decode Hunyuan3D"}+ },+ "27": {+ "class_type": "VoxelToMesh",+ "inputs": {"voxel": ["26", 0], "algorithm": "surface net", "threshold": 0.6},+ "_meta": {"title": "Voxel to Mesh"}+ },+ "28": {+ "class_type": "SaveGLB",+ "inputs": {"mesh": ["27", 0], "filename_prefix": "3d/sculptforge_text-to-3d"},+ "_meta": {"title": "Save GLB"}+ }+}diff --git a/tools/comfyui-smoke.sh b/tools/comfyui-smoke.shnew file mode 100755index 00000000..0312945c--- /dev/null+++ b/tools/comfyui-smoke.sh@@ -0,0 +1,190 @@+#!/usr/bin/env bash+# Runs a ComfyUI workflow end to end against an already running ComfyUI server, the way SculptForge does:+# upload an image, fill in sf_image / sf_prompt / seeds, queue it, wait for it, download the first mesh.+# Starts nothing. Needs curl and python3.+# SPDX-License-Identifier: GPL-3.0-or-later+#+# tools/comfyui-smoke.sh integrations/comfyui/workflows/sculptforge-inflate.json+# tools/comfyui-smoke.sh --server http://127.0.0.1:8191 --out /tmp/meshes WORKFLOW.json+# tools/comfyui-smoke.sh --prompt "a carved stone owl" integrations/comfyui/workflows/text-to-3d.json+set -euo pipefail++ROOT=$(cd "$(dirname "$0")/.." && pwd)+SERVER=${COMFYUI_URL:-http://127.0.0.1:8188}+IMAGE=$ROOT/assets/demo/teddy-sketch.png+PROMPT="a friendly cartoon teddy bear sitting"+OUT=.+TIMEOUT=600++usage() {+ cat <<EOF+Usage: $(basename "$0") [options] WORKFLOW.json++Options:+ --server URL ComfyUI server (default \$COMFYUI_URL or http://127.0.0.1:8188)+ --image PNG image for the sf_image node (default assets/demo/teddy-sketch.png)+ --prompt TEXT text for the sf_prompt node (default "$PROMPT")+ --out DIR where to save the mesh (default: current directory)+ --timeout SEC give up after this many seconds (default $TIMEOUT)+EOF+}++WORKFLOW=+while [ $# -gt 0 ]; do+ case $1 in+ --server) SERVER=$2; shift 2 ;;+ --image) IMAGE=$2; shift 2 ;;+ --prompt) PROMPT=$2; shift 2 ;;+ --out) OUT=$2; shift 2 ;;+ --timeout) TIMEOUT=$2; shift 2 ;;+ -h|--help) usage; exit 0 ;;+ -*) echo "unknown option: $1" >&2; usage >&2; exit 2 ;;+ *) WORKFLOW=$1; shift ;;+ esac+done+[ -n "$WORKFLOW" ] || { usage >&2; exit 2; }+[ -f "$WORKFLOW" ] || { echo "error: no such workflow: $WORKFLOW" >&2; exit 2; }+[ -f "$IMAGE" ] || { echo "error: no such image: $IMAGE" >&2; exit 2; }+SERVER=${SERVER%/}++step() { printf '\n== %s\n' "$*"; }+fail() { printf 'FAILED: %s\n' "$*" >&2; exit 1; }+# json EXPR: evaluates a Python expression over the JSON document on stdin (bound to "d").+json() { python3 -c "import json,sys; d=json.load(sys.stdin); print($1)"; }++TMP=$(mktemp -d)+trap 'rm -rf "$TMP"' EXIT++step "Server $SERVER"+curl -sf --max-time 10 "$SERVER/system_stats" -o "$TMP/stats.json" || fail "no ComfyUI answering at $SERVER/system_stats"+json '"ComfyUI %s, Python %s, devices: %s" % (d["system"].get("comfyui_version", "?"), d["system"].get("python_version", "?").split()[0], ", ".join(x["name"] for x in d.get("devices", [])))' < "$TMP/stats.json"++step "Upload $(basename "$IMAGE")"+curl -sf --max-time 60 -F "image=@$IMAGE" -F overwrite=true "$SERVER/upload/image" -o "$TMP/upload.json" \+ || fail "upload to $SERVER/upload/image failed"+UPLOADED=$(json 'd["name"] if not d.get("subfolder") else d["subfolder"] + "/" + d["name"]' < "$TMP/upload.json")+echo "stored as $UPLOADED"++step "Queue $(basename "$WORKFLOW")"+CLIENT_ID=sculptforge-smoke-$$+# Apply the SculptForge contract: sf_image (or the first LoadImage) gets the upload, sf_prompt gets the+# prompt, every seed / noise_seed (and sf_seed) gets a fresh value.+python3 - "$WORKFLOW" "$UPLOADED" "$PROMPT" "$CLIENT_ID" > "$TMP/request.json" <<'EOF'+import json, random, sys+path, image, prompt, client_id = sys.argv[1:]+wf = json.load(open(path, encoding="utf-8"))+if "nodes" in wf and "links" in wf:+ sys.exit("error: this is the UI format; export the workflow with \"Export (API)\"")+title = lambda n: n.get("_meta", {}).get("title", "")+is_link = lambda v: isinstance(v, list) and len(v) == 2+loaders = [k for k, n in wf.items() if n.get("class_type") == "LoadImage"]+targets = [k for k in loaders if title(wf[k]) == "sf_image"] or loaders[:1]+for k in targets:+ wf[k]["inputs"]["image"] = image+ print(f" image -> node {k} ({title(wf[k]) or 'LoadImage'})", file=sys.stderr)+for k, n in wf.items():+ if title(n) == "sf_prompt":+ key = next((x for x in ("text", "prompt", "string") if x in n["inputs"]), None)+ if key:+ n["inputs"][key] = prompt+ print(f" prompt -> node {k}.{key}", file=sys.stderr)+ for key in ("seed", "noise_seed") + (("value",) if title(n) == "sf_seed" else ()):+ if key in n["inputs"] and not is_link(n["inputs"][key]):+ n["inputs"][key] = random.randrange(2**32)+ print(f" seed -> node {k}.{key} = {n['inputs'][key]}", file=sys.stderr)+if not targets and not any(title(n) == "sf_prompt" for n in wf.values()):+ print(" (no LoadImage or sf_prompt node: running the workflow as is)", file=sys.stderr)+json.dump({"prompt": wf, "client_id": client_id}, sys.stdout)+EOF+HTTP=$(curl -s --max-time 60 -o "$TMP/queued.json" -w '%{http_code}' -H 'Content-Type: application/json' \+ --data-binary "@$TMP/request.json" "$SERVER/prompt") || fail "POST $SERVER/prompt failed"+if [ "$HTTP" != 200 ]; then+ echo "ComfyUI rejected the workflow (HTTP $HTTP):" >&2+ python3 - "$TMP/queued.json" >&2 <<'EOF' || cat "$TMP/queued.json" >&2+import json, sys+d = json.load(open(sys.argv[1]))+e = d.get("error", {})+print(f" {e.get('message', '')} {e.get('details', '')}".rstrip())+for node, info in d.get("node_errors", {}).items():+ for err in info.get("errors", []):+ print(f" node {node} ({info.get('class_type', '?')}): {err.get('message')}: {err.get('details')}")+EOF+ exit 1+fi+PROMPT_ID=$(json 'd["prompt_id"]' < "$TMP/queued.json")+echo "prompt_id $PROMPT_ID"++step "Run"+START=$(date +%s)+while :; do+ curl -sf --max-time 30 "$SERVER/history/$PROMPT_ID" -o "$TMP/history.json" || fail "GET /history/$PROMPT_ID failed"+ STATE=$(json '(lambda h: "pending" if not h else h.get("status", {}).get("status_str") or ("success" if h.get("outputs") else "running"))(next(iter(d.values()), None))' < "$TMP/history.json")+ case $STATE in+ success) break ;;+ error)+ python3 - "$TMP/history.json" >&2 <<'EOF'+import json, sys+h = next(iter(json.load(open(sys.argv[1])).values()))+for kind, msg in h.get("status", {}).get("messages", []):+ if kind == "execution_error":+ print(f" node {msg.get('node_id')} ({msg.get('node_type')}): {msg.get('exception_type')}: {msg.get('exception_message', '').strip()}")+EOF+ fail "the workflow raised an error" ;;+ esac+ [ $(( $(date +%s) - START )) -lt "$TIMEOUT" ] || {+ curl -s -X POST "$SERVER/interrupt" >/dev/null || true+ fail "timed out after ${TIMEOUT}s (sent /interrupt)"+ }+ sleep 1+done+echo "finished in $(( $(date +%s) - START ))s"++step "Outputs"+# Every output file, then the first mesh among them (same extensions and order as SculptForge).+python3 - "$TMP/history.json" > "$TMP/mesh.txt" <<'EOF'+import json, sys+h = next(iter(json.load(open(sys.argv[1])).values()))+mesh_ext = (".glb", ".gltf", ".obj", ".ply", ".stl", ".fbx", ".usdz")+first = None+for node, outputs in h.get("outputs", {}).items():+ for key, items in outputs.items():+ for item in items if isinstance(items, list) else []:+ if isinstance(item, dict) and item.get("filename"):+ print(f" node {node} {key}: {item.get('subfolder') or '.'}/{item['filename']} ({item.get('type', 'output')})",+ file=sys.stderr)+ if first is None and item["filename"].lower().endswith(mesh_ext):+ first = item+if first:+ print("\t".join([first["filename"], first.get("subfolder", ""), first.get("type", "output")]))+EOF+[ -s "$TMP/mesh.txt" ] || fail "the workflow finished but produced no mesh file (.glb .gltf .obj .ply .stl .fbx .usdz)"+IFS=$'\t' read -r NAME SUBFOLDER TYPE < "$TMP/mesh.txt"++step "Download $NAME"+mkdir -p "$OUT"+DEST=$OUT/$NAME+curl -sf --max-time 120 -G "$SERVER/view" --data-urlencode "filename=$NAME" --data-urlencode "subfolder=$SUBFOLDER" \+ --data-urlencode "type=$TYPE" -o "$DEST" || fail "GET /view for $NAME failed"+python3 - "$DEST" <<'EOF'+import json, os, struct, sys+path = sys.argv[1]+data = open(path, "rb").read()+print(f"{path}: {len(data):,} bytes")+if not data:+ sys.exit("FAILED: the mesh file is empty")+if path.lower().endswith(".glb"):+ magic, version, length = struct.unpack_from("<4sII", data)+ if magic != b"glTF" or length != len(data):+ sys.exit(f"FAILED: not a valid GLB (magic {magic!r}, header length {length})")+ chunk_len, chunk_type = struct.unpack_from("<I4s", data, 12)+ gltf = json.loads(data[20:20 + chunk_len])+ accessors = gltf.get("accessors", [])+ verts = tris = 0+ for mesh in gltf.get("meshes", []):+ for prim in mesh.get("primitives", []):+ verts += accessors[prim["attributes"]["POSITION"]]["count"]+ if "indices" in prim:+ tris += accessors[prim["indices"]]["count"] // 3+ print(f"GLB v{version}: {len(gltf.get('meshes', []))} mesh(es), {verts:,} vertices, {tris:,} triangles")+EOF+printf '\nOK: %s -> %s\n' "$(basename "$WORKFLOW")" "$DEST"diff --git a/tools/comfyui-validate-workflow.py b/tools/comfyui-validate-workflow.pynew file mode 100755index 00000000..d46109cd--- /dev/null+++ b/tools/comfyui-validate-workflow.py@@ -0,0 +1,285 @@+#!/usr/bin/env python3+# Checks ComfyUI API-format workflows against a ComfyUI server's node definitions (/object_info)+# and against the SculptForge workflow contract (sf_image / sf_prompt / sf_seed, a mesh-saving output).+# SPDX-License-Identifier: GPL-3.0-or-later+#+# tools/comfyui-validate-workflow.py integrations/comfyui/workflows/*.json+# tools/comfyui-validate-workflow.py --server http://127.0.0.1:8188 my-workflow.json+# tools/comfyui-validate-workflow.py --object-info object_info.json --strict my-workflow.json+#+# Errors (exit code 1): unknown node types, missing required inputs, links to nodes or outputs that+# don't exist, links whose types don't match, numbers out of range, invalid choices, cycles, no output node.+# Warnings: model files the server doesn't have, SculptForge nodes on a server without the pack+# (both errors with --strict), unused nodes, contract hints. Standard library only.+import argparse+import json+import sys+import urllib.error+import urllib.request++PACK_PREFIX = "SculptForge" # class_type prefix of the ComfyUI-SculptForge node pack+PROMPT_KEYS = ("text", "prompt", "string") # the input SculptForge fills on the "sf_prompt" node+SEED_KEYS = ("seed", "noise_seed")+MESH_SAVERS = ("SaveGLB", "Save3DAdvanced", "SculptForgeExport", "SculptForgeLODChain")+++def load_object_info(server, path):+ if path:+ with open(path, encoding="utf-8") as f:+ return json.load(f), path+ url = server.rstrip("/") + "/object_info"+ try:+ with urllib.request.urlopen(url, timeout=30) as r:+ return json.load(r), url+ except (urllib.error.URLError, OSError) as e:+ sys.exit(f"error: could not read {url}: {e}\n(start ComfyUI, pass --server URL, or use --object-info FILE)")+++def input_spec(spec):+ """(type, options, config) from an /object_info input spec, for both the old and new styles:+ [["a", "b"], {...}] and ["COMBO", {"options": [...]}] are choices, ["INT", {...}] is a typed input."""+ kind = spec[0] if spec else "*"+ config = spec[1] if len(spec) > 1 and isinstance(spec[1], dict) else {}+ if isinstance(kind, list):+ return "COMBO", kind, config+ if kind == "COMBO":+ return "COMBO", config.get("options", []), config+ return kind, None, config+++def types_match(produced, accepted):+ if produced == "*" or accepted == "*":+ return True+ have = {t.strip() for t in produced.split(",")}+ want = {t.strip() for t in accepted.split(",")}+ return bool(have & want) or "*" in want+++def is_link(value):+ return (isinstance(value, list) and len(value) == 2 and isinstance(value[0], (str, int))+ and isinstance(value[1], int) and not isinstance(value[1], bool))+++def is_file_choice(name, class_type):+ """Choices that list files on the server (models, input images): a mismatch only means+ the file isn't installed there, which is a setup issue, not a broken workflow."""+ return name.endswith("_name") or name in ("image", "model_file", "audio", "video") or "Loader" in class_type+++class Report:+ def __init__(self, strict):+ self.strict, self.errors, self.warnings, self.notes = strict, [], [], []++ def error(self, msg):+ self.errors.append(msg)++ def warn(self, msg, strict_error=False):+ (self.errors if self.strict and strict_error else self.warnings).append(msg)+++def node_label(node_id, node):+ title = node.get("_meta", {}).get("title")+ return f'node {node_id} ({node.get("class_type", "?")}{f", “{title}”" if title else ""})'+++def validate(workflow, info, rep):+ if not isinstance(workflow, dict) or not workflow:+ rep.error("not a JSON object of nodes")+ return+ if "nodes" in workflow and "links" in workflow:+ rep.error('this is ComfyUI\'s UI (editor) format; save it with "Export (API)" instead')+ return++ # The LoadImage node(s) SculptForge fills with its own upload: whatever image they name now doesn't matter.+ loaders = [nid for nid, n in workflow.items() if isinstance(n, dict) and n.get("class_type") == "LoadImage"]+ sf_image = [nid for nid in loaders if workflow[nid].get("_meta", {}).get("title") == "sf_image"]+ replaced = set(sf_image or loaders[:1])++ # Per node: its definition (or None), the inputs it was given.+ defs = {}+ for node_id, node in workflow.items():+ if not isinstance(node, dict) or "class_type" not in node or not isinstance(node.get("inputs"), dict):+ rep.error(f"node {node_id}: needs \"class_type\" and an \"inputs\" object")+ continue+ ct = node["class_type"]+ if ct in info:+ defs[node_id] = info[ct]+ elif ct.startswith(PACK_PREFIX):+ defs[node_id] = None+ rep.warn(f"{node_label(node_id, node)}: from the ComfyUI-SculptForge pack, which this server has not "+ "loaded; its inputs were not checked", strict_error=True)+ else:+ rep.error(f"{node_label(node_id, node)}: unknown node type (missing custom node pack?)")++ for node_id, node in workflow.items():+ if node_id not in defs:+ continue+ d = defs[node_id]+ label = node_label(node_id, node)+ inputs = node["inputs"]+ required = d["input"].get("required", {}) if d else {}+ optional = d["input"].get("optional", {}) if d else {}+ hidden = d["input"].get("hidden", {}) if d else {}+ if d:+ for name in required:+ if name not in inputs:+ rep.error(f"{label}: required input “{name}” is missing")+ for name in inputs:+ if name not in required and name not in optional and name not in hidden:+ rep.warn(f"{label}: input “{name}” is not used by this node type")++ for name, value in inputs.items():+ spec = required.get(name) or optional.get(name)+ kind, options, config = input_spec(spec) if spec else ("*", None, {})+ if is_link(value):+ src_id, slot = str(value[0]), value[1]+ src = workflow.get(src_id)+ if src is None:+ rep.error(f"{label}: input “{name}” links to node {src_id}, which does not exist")+ continue+ src_def = defs.get(src_id)+ if src_def is None:+ continue # unknown or pack node: already reported+ outputs = src_def.get("output", [])+ if not 0 <= slot < len(outputs):+ rep.error(f"{label}: input “{name}” links to output {slot} of {node_label(src_id, src)}, "+ f"which has {len(outputs)} output(s)")+ continue+ produced = outputs[slot]+ accepted = "COMBO" if kind == "COMBO" else kind+ if d and isinstance(produced, str) and not types_match(produced, accepted):+ if not (kind == "COMBO" and produced in ("STRING", "COMBO")) and not isinstance(produced, list):+ rep.error(f"{label}: input “{name}” expects {accepted} but {node_label(src_id, src)} "+ f"output {slot} is {produced}")+ continue+ if not d or not spec:+ continue+ if kind == "COMBO":+ if node_id in replaced and name == "image":+ continue+ if options and value not in options:+ if is_file_choice(name, node["class_type"]):+ rep.warn(f"{label}: “{value}” is not on this server ({name}); install it before running",+ strict_error=True)+ else:+ rep.error(f"{label}: “{name}” = {value!r} is not one of {options}")+ elif not options and is_file_choice(name, node["class_type"]):+ rep.warn(f"{label}: this server has no files for “{name}”; install {value!r} before running",+ strict_error=True)+ elif kind in ("INT", "FLOAT"):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or (kind == "INT" and value != int(value)):+ rep.error(f"{label}: “{name}” must be {kind}, got {value!r}")+ continue+ lo, hi = config.get("min"), config.get("max")+ if (lo is not None and value < lo) or (hi is not None and value > hi):+ rep.error(f"{label}: “{name}” = {value} is outside [{lo}, {hi}]")+ elif kind == "BOOLEAN" and not isinstance(value, bool):+ rep.error(f"{label}: “{name}” must be true or false, got {value!r}")+ elif kind == "STRING" and not isinstance(value, str):+ rep.error(f"{label}: “{name}” must be a string, got {value!r}")++ # Cycles, output nodes, and nodes that never run (not upstream of any output).+ upstream = {nid: [str(v[0]) for v in n["inputs"].values() if is_link(v) and str(v[0]) in workflow]+ for nid, n in workflow.items() if isinstance(n, dict) and isinstance(n.get("inputs"), dict)}+ state = {}++ def visit(nid, stack):+ if state.get(nid) == 1:+ rep.error(f"cycle: {' -> '.join(stack + [nid])}")+ return+ if state.get(nid) == 2:+ return+ state[nid] = 1+ for src in upstream.get(nid, []):+ visit(src, stack + [nid])+ state[nid] = 2++ for nid in upstream:+ visit(nid, [])++ outputs = [nid for nid, d in defs.items()+ if (d and d.get("output_node")) or (d is None and workflow[nid]["class_type"] in MESH_SAVERS)]+ if not outputs:+ rep.error("no output node (e.g. Save 3D Model): ComfyUI would refuse to run it")+ reached, todo = set(), list(outputs)+ while todo:+ nid = todo.pop()+ if nid not in reached:+ reached.add(nid)+ todo.extend(upstream.get(nid, []))+ for nid in workflow:+ if nid not in reached and nid in defs:+ rep.warn(f"{node_label(nid, workflow[nid])}: does not feed any output node, so it never runs")++ # The SculptForge contract.+ titled = lambda t: [nid for nid, n in workflow.items() if isinstance(n, dict) and n.get("_meta", {}).get("title") == t]+ for nid in titled("sf_image"):+ if nid not in sf_image:+ rep.warn(f"{node_label(nid, workflow[nid])}: titled sf_image but is not a LoadImage node; SculptForge ignores it")+ if sf_image:+ rep.notes.append(f"image input: node {', '.join(sf_image)} (sf_image)")+ elif loaders:+ rep.notes.append(f"image input: node {loaders[0]} (first LoadImage; title it “sf_image” to be explicit)")+ for nid in titled("sf_prompt"):+ keys = [k for k in PROMPT_KEYS if k in workflow[nid]["inputs"]]+ if not keys:+ rep.error(f"{node_label(nid, workflow[nid])}: titled sf_prompt but has no {'/'.join(PROMPT_KEYS)} input")+ elif is_link(workflow[nid]["inputs"][keys[0]]):+ rep.error(f"{node_label(nid, workflow[nid])}: sf_prompt's “{keys[0]}” is a link; it must be a plain value "+ "SculptForge can replace")+ else:+ rep.notes.append(f"prompt input: node {nid} (sf_prompt.{keys[0]})")+ seeds = [f"{nid}.{k}" for nid, n in workflow.items() if isinstance(n, dict) and isinstance(n.get("inputs"), dict)+ for k in SEED_KEYS if k in n["inputs"] and not is_link(n["inputs"][k])]+ if titled("sf_seed"):+ seeds.insert(0, f"{','.join(titled('sf_seed'))} (sf_seed)")+ if seeds:+ rep.notes.append(f"seeds: {', '.join(seeds)}")+ if not loaders and not titled("sf_prompt"):+ rep.warn("no LoadImage and no sf_prompt node: SculptForge has nothing to feed this workflow")+ savers = [nid for nid in outputs if workflow[nid]["class_type"] in MESH_SAVERS]+ if outputs and not savers:+ rep.warn("no known mesh-saving node (Save 3D Model, Save 3D Advanced, SculptForge Export); make sure an output "+ "node writes a .glb/.obj/.ply/.stl/.fbx/.usdz file or SculptForge will find no mesh")+ elif savers:+ rep.notes.append(f"mesh output: node {', '.join(savers)} ({', '.join(sorted({workflow[n]['class_type'] for n in savers}))})")+++def main():+ ap = argparse.ArgumentParser(description="Validate ComfyUI API-format workflows for SculptForge.")+ ap.add_argument("workflows", nargs="+", help="API-format workflow JSON files")+ ap.add_argument("--server", default="http://127.0.0.1:8188", help="ComfyUI URL (default %(default)s)")+ ap.add_argument("--object-info", metavar="FILE", help="use a saved /object_info JSON instead of a server")+ ap.add_argument("--strict", action="store_true",+ help="treat missing model files and an unloaded SculptForge pack as errors")+ args = ap.parse_args()++ info, source = load_object_info(args.server, args.object_info)+ print(f"Checking against {source} ({len(info)} node types)")+ failed = 0+ for path in args.workflows:+ rep = Report(args.strict)+ workflow = None+ try:+ with open(path, encoding="utf-8") as f:+ workflow = json.load(f)+ except (OSError, ValueError) as e:+ rep.error(f"cannot read: {e}")+ else:+ validate(workflow, info, rep)+ status = "FAIL" if rep.errors else "ok"+ count = f" ({len(workflow)} nodes)" if isinstance(workflow, dict) else ""+ print(f"\n{status:4} {path}{count}")+ for msg in rep.errors:+ print(f" error: {msg}")+ for msg in rep.warnings:+ print(f" warning: {msg}")+ for msg in rep.notes:+ print(f" {msg}")+ failed += bool(rep.errors)+ print(f"\n{len(args.workflows) - failed} of {len(args.workflows)} workflow(s) valid")+ return 1 if failed else 0+++if __name__ == "__main__":+ sys.exit(main())