Skip to content

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

Blender bridge: exchange folder + manifest, blender_send/blender_receive, File > Blender menu, and the SculptForge Bridge add-on

islandmed37292570bd00
diff --git a/.gitignore b/.gitignore
index adc5f81b..dfb87cd9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ imgui.ini
.DS_Store
*.user
Testing/
+__pycache__/
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 17462518..ac9a97bb 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -89,6 +89,8 @@ add_library(sculptforge_core STATIC
src/io/Zip.cpp
src/io/GozIO.cpp
src/io/GozCommands.cpp
+ src/io/BlenderBridge.cpp
+ src/io/BlenderCommands.cpp
src/io/StlIO.cpp
)
target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace)
@@ -187,6 +189,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelRetopo.cpp
src/app/PanelPerformance.cpp
src/app/PanelGoz.cpp
+ src/app/PanelBlender.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
src/app/Tablet.cpp
@@ -357,6 +360,15 @@ if(SCULPTFORGE_BUILD_PYTHON)
endif()
endif()
+# --- Blender add-on (addons/blender): `cmake --build build --target blender_addon` writes its zips ---
+find_package(Python3 COMPONENTS Interpreter QUIET)
+if(Python3_Interpreter_FOUND)
+ add_custom_target(blender_addon
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/addons/blender/build_addon.py --check
+ --version ${PROJECT_VERSION} --out ${CMAKE_CURRENT_BINARY_DIR}/blender-addon
+ COMMENT "Packaging the Blender add-on (sculptforge_bridge-${PROJECT_VERSION}.zip)")
+endif()
+
# --- Tests ---
if(SCULPTFORGE_BUILD_TESTS)
# tests/test_main.cpp plus every tests/test_*.cpp (add a file to add tests; see tests/TestHarness.h).
@@ -401,6 +413,24 @@ if(SCULPTFORGE_BUILD_TESTS)
${CMAKE_CURRENT_SOURCE_DIR}/tools/brush-gallery/repo --check --cli ${SCULPTFORGE_CLI_RUNNER})
# The user guide (docs/guide): every link, anchor and image resolves, only characters the app's font has,
# and the website pages build.
+ # The Blender add-on's exchange code (addons/blender) against sculptforge-cli: a round trip through the
+ # bridge is the identity (needs numpy, which Blender bundles).
+ execute_process(COMMAND ${Python3_EXECUTABLE} -c "import numpy" RESULT_VARIABLE SCULPTFORGE_NO_NUMPY OUTPUT_QUIET ERROR_QUIET)
+ if(SCULPTFORGE_NO_NUMPY EQUAL 0)
+ add_test(NAME blender_exchange COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/blender/test_exchange.py
+ --cli ${SCULPTFORGE_CLI_RUNNER})
+ endif()
+ # The add-on's zips build and its manifest passes the checks Blender's validator makes.
+ add_test(NAME blender_addon_package COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/addons/blender/build_addon.py
+ --check --version ${PROJECT_VERSION} --out ${CMAKE_CURRENT_BINARY_DIR}/blender-addon)
+ # The add-on inside a real Blender, when one is installed (tests/blender/test_in_blender.py).
+ find_program(SCULPTFORGE_BLENDER blender)
+ if(SCULPTFORGE_BLENDER)
+ add_test(NAME blender_addon COMMAND ${SCULPTFORGE_BLENDER} -b --factory-startup -noaudio --python-exit-code 1
+ --python ${CMAKE_CURRENT_SOURCE_DIR}/tests/blender/test_in_blender.py
+ -- --cli ${SCULPTFORGE_CLI_RUNNER})
+ set_tests_properties(blender_addon PROPERTIES TIMEOUT 300)
+ endif()
add_test(NAME guide_site COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/guide/build_site.py --check
--out ${CMAKE_CURRENT_BINARY_DIR}/guide-site)
endif()
diff --git a/addons/blender/build_addon.py b/addons/blender/build_addon.py
new file mode 100644
index 00000000..036c7daf
--- /dev/null
+++ b/addons/blender/build_addon.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python3
+# SculptForge - package the Blender add-on
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# python3 addons/blender/build_addon.py --out DIR [--version X.Y.Z] [--check]
+#
+# Writes two zips of addons/blender/sculptforge_bridge:
+# sculptforge_bridge-X.Y.Z.zip a Blender 4.2+ extension (blender_manifest.toml at the zip's root):
+# Edit > Preferences > Get Extensions > Install from Disk
+# sculptforge_bridge-X.Y.Z-legacy.zip the same as a legacy add-on (a sculptforge_bridge/ folder):
+# Edit > Preferences > Add-ons > Install from Disk
+# --version stamps the version into the manifest and bl_info (the release workflow passes the tag's).
+# --check also validates the manifest the way Blender's extension validator does (the parts that can be
+# checked without Blender) and that every file compiles; CMake runs it as a test (blender_addon_package).
+import argparse
+import os
+import py_compile
+import re
+import sys
+import tempfile
+import zipfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SOURCE = os.path.join(HERE, "sculptforge_bridge")
+LICENSE = os.path.join(HERE, "..", "..", "LICENSE")
+FILES = ["__init__.py", "exchange.py"]
+EPOCH = (2026, 1, 1, 0, 0, 0) # fixed timestamps: the same sources give the same zip
+
+
+def read(name):
+ with open(os.path.join(SOURCE, name), "r", encoding="utf-8") as f:
+ return f.read()
+
+
+def manifest_value(text, key):
+ m = re.search(r'^%s\s*=\s*"([^"]*)"' % re.escape(key), text, re.M)
+ return m.group(1) if m else None
+
+
+def stamp(manifest, init, version):
+ manifest = re.sub(r'^version = "[^"]*"', 'version = "%s"' % version, manifest, flags=re.M)
+ nums = ", ".join(str(int(x)) for x in version.split(".")[:3])
+ init = re.sub(r'"version": \([^)]*\)', '"version": (%s)' % nums, init, count=1)
+ return manifest, init
+
+
+def check(manifest, init):
+ errors = []
+ for key in ("schema_version", "id", "version", "name", "tagline", "maintainer", "type", "blender_version_min"):
+ if not manifest_value(manifest, key):
+ errors.append("blender_manifest.toml: missing %s" % key)
+ tagline = manifest_value(manifest, "tagline") or ""
+ if len(tagline) > 64 or tagline[-1:] in ".!?,;:":
+ errors.append("tagline must be at most 64 characters without closing punctuation")
+ if manifest_value(manifest, "id") != "sculptforge_bridge":
+ errors.append("id must match the package folder (sculptforge_bridge)")
+ if not re.fullmatch(r"\d+\.\d+\.\d+", manifest_value(manifest, "version") or ""):
+ errors.append("version must be X.Y.Z")
+ if 'license = ["SPDX:GPL-3.0-or-later"]' not in manifest:
+ errors.append("license must be SPDX:GPL-3.0-or-later (like SculptForge)")
+ for reason in re.findall(r'^\w+\s*=\s*"([^"]*)"', manifest.split("[permissions]", 1)[-1], re.M):
+ if reason.endswith("."):
+ errors.append("permission reasons must not end with a period")
+ nums = re.search(r'"version": \(([^)]*)\)', init)
+ if not nums or ".".join(x.strip() for x in nums.group(1).split(",")) != manifest_value(manifest, "version"):
+ errors.append("bl_info version must match blender_manifest.toml")
+ if re.search(r"^\s*import\s+sculptforge_bridge|^\s*from\s+sculptforge_bridge", init, re.M):
+ errors.append("extensions must use relative imports")
+ with tempfile.TemporaryDirectory() as tmp:
+ for name in FILES:
+ try:
+ py_compile.compile(os.path.join(SOURCE, name), cfile=os.path.join(tmp, name + "c"), doraise=True)
+ except py_compile.PyCompileError as e:
+ errors.append(str(e))
+ return errors
+
+
+def write_zip(path, entries):
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
+ for arcname, data in entries:
+ info = zipfile.ZipInfo(arcname, EPOCH)
+ info.external_attr = 0o644 << 16
+ info.compress_type = zipfile.ZIP_DEFLATED
+ z.writestr(info, data)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--version")
+ ap.add_argument("--check", action="store_true")
+ args = ap.parse_args()
+ manifest, init = read("blender_manifest.toml"), read("__init__.py")
+ if args.version:
+ manifest, init = stamp(manifest, init, args.version)
+ version = manifest_value(manifest, "version")
+ if args.check:
+ errors = check(manifest, init)
+ for e in errors:
+ print("error:", e)
+ if errors:
+ return 1
+ files = {"__init__.py": init, "exchange.py": read("exchange.py")}
+ with open(LICENSE, "r", encoding="utf-8") as f:
+ files["LICENSE"] = f.read()
+ os.makedirs(args.out, exist_ok=True)
+ ext = os.path.join(args.out, "sculptforge_bridge-%s.zip" % version)
+ legacy = os.path.join(args.out, "sculptforge_bridge-%s-legacy.zip" % version)
+ write_zip(ext, [("blender_manifest.toml", manifest)] + sorted(files.items()))
+ write_zip(legacy, [("sculptforge_bridge/" + k, v) for k, v in sorted(files.items())])
+ print(ext)
+ print(legacy)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/addons/blender/sculptforge_bridge/__init__.py b/addons/blender/sculptforge_bridge/__init__.py
new file mode 100644
index 00000000..b3edfab0
--- /dev/null
+++ b/addons/blender/sculptforge_bridge/__init__.py
@@ -0,0 +1,556 @@
+# SculptForge bridge for Blender
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Send the selected meshes to SculptForge, sculpt them there, send them back: the objects update in
+# place (transform, materials and modifiers kept), the way GoZ / GoB work with ZBrush. Ideas and the
+# .GoZ conventions come from GoB (github.com/JoseConseco/GoB, GPL) by Daniel Grauer, JoseConseco and
+# contributors. The exchange itself (folder, manifest, .GoZ reading and writing) is in exchange.py.
+#
+# What travels: positions (object space, with each object's matrix_world in the manifest), triangles
+# and quads (n-gons as triangle fans), the active UV map, the active colour attribute (polypaint),
+# the sculpt mask (.sculpt_mask) and face sets (.sculpt_face_set, SculptForge's polygroups).
+
+bl_info = { # legacy add-on install (Blender 4.2+ reads blender_manifest.toml instead)
+ "name": "SculptForge Bridge",
+ "author": "SculptForge contributors",
+ "version": (0, 7, 0),
+ "blender": (4, 2, 0),
+ "location": "3D View > Sidebar > SculptForge, Object menu, File > Import / Export",
+ "description": "Send meshes to SculptForge and back, updating the objects in place (like GoZ)",
+ "doc_url": "https://islandmed.github.io/SculptForge/guide/blender.html",
+ "category": "Import-Export",
+}
+
+import os
+import time
+import traceback
+
+import bpy
+import numpy as np
+from bpy.props import BoolProperty, EnumProperty, StringProperty
+
+from . import exchange
+
+APPLIED_KEY = "sculptforge_applied_modifiers"
+MASK = ".sculpt_mask"
+FACE_SETS = ".sculpt_face_set"
+
+
+class _State:
+ sent = False # this session sent something: what SculptForge sends back loads by itself
+ inbox_time = 0 # last seen modification time of to_blender/manifest.json
+ seen = -1 # revision last loaded (or present when the add-on started)
+ message = "" # last result, shown in the panel
+
+
+state = _State()
+
+
+def prefs(context=None):
+ context = context or bpy.context
+ addon = context.preferences.addons.get(__package__)
+ return addon.preferences if addon else None
+
+
+def exchange_root(p=None):
+ p = p or prefs()
+ folder = p.exchange_folder if p else ""
+ return bpy.path.abspath(folder) if folder else exchange.default_root()
+
+
+# --------------------------------------------------------------------------------------------------
+# Blender mesh -> arrays
+# --------------------------------------------------------------------------------------------------
+
+
+def _get(collection, prop, count, dtype, width=1):
+ out = np.empty(count * width, dtype=dtype)
+ if count:
+ collection.foreach_get(prop, out)
+ return out.reshape(-1, width) if width > 1 else out
+
+
+def mesh_topology(me, mirrored=False):
+ """(loops, face_polygon, faces) of the GoZ faces for `me` (exchange.polygon_corners)."""
+ starts = _get(me.polygons, "loop_start", len(me.polygons), np.int32)
+ totals = _get(me.polygons, "loop_total", len(me.polygons), np.int32)
+ loop_vert = _get(me.loops, "vertex_index", len(me.loops), np.int32)
+ loops, face_poly = exchange.polygon_corners(starts, totals, mirrored)
+ return loops, face_poly, exchange.faces_from_loops(loops, loop_vert), loop_vert
+
+
+def mesh_arrays(me, mirrored):
+ """Everything write_goz takes, from a Blender mesh (object space)."""
+ nv = len(me.vertices)
+ loops, face_poly, faces, loop_vert = mesh_topology(me, mirrored)
+ out = {"positions": _get(me.vertices, "co", nv, np.float32, 3), "faces": faces}
+ safe = np.maximum(loops, 0)
+ uv_layer = me.uv_layers.active
+ if uv_layer is not None and len(me.loops):
+ uv = _get(uv_layer.data, "uv", len(me.loops), np.float32, 2)
+ out["uvs"] = uv[safe]
+ color = me.color_attributes.active_color
+ if color is not None and color.domain in {"POINT", "CORNER"}:
+ rgba = _get(color.data, "color_srgb", len(color.data), np.float32, 4)
+ if color.domain == "POINT":
+ out["colors"] = rgba[:, :3]
+ else: # one colour per vertex: the mean of its corners
+ sums = np.zeros((nv, 3))
+ np.add.at(sums, loop_vert, rgba[:, :3])
+ out["colors"] = sums / np.maximum(np.bincount(loop_vert, minlength=nv), 1)[:, None]
+ mask = me.attributes.get(MASK)
+ if mask is not None and mask.domain == "POINT" and mask.data_type == "FLOAT":
+ out["mask"] = _get(mask.data, "value", nv, np.float32)
+ sets = me.attributes.get(FACE_SETS)
+ if sets is not None and sets.domain == "FACE" and sets.data_type == "INT":
+ # Face sets start at 1; SculptForge's polygroups at 0.
+ out["groups"] = np.maximum(_get(sets.data, "value", len(me.polygons), np.int32)[face_poly] - 1, 0)
+ return out
+
+
+# --------------------------------------------------------------------------------------------------
+# Arrays -> Blender mesh
+# --------------------------------------------------------------------------------------------------
+
+
+def set_geometry(me, positions, faces):
+ """Replaces the mesh's geometry (materials stay; attributes go). Returns the loop of each face corner."""
+ quad = faces[:, 3] != exchange.NO_INDEX
+ totals = np.where(quad, 4, 3).astype(np.int32)
+ starts = (np.cumsum(totals) - totals).astype(np.int32)
+ loop_vert = faces[np.arange(4)[None, :] < totals[:, None]].astype(np.int32)
+ me.clear_geometry()
+ me.vertices.add(len(positions))
+ me.vertices.foreach_set("co", np.ascontiguousarray(positions, dtype=np.float32).ravel())
+ me.loops.add(len(loop_vert))
+ me.loops.foreach_set("vertex_index", loop_vert)
+ me.polygons.add(len(faces))
+ me.polygons.foreach_set("loop_start", starts)
+ try:
+ me.polygons.foreach_set("loop_total", totals) # read-only (and implied) in newer versions
+ except (AttributeError, TypeError, RuntimeError):
+ pass
+ me.update(calc_edges=True)
+ return np.where(np.arange(4)[None, :] < totals[:, None], starts[:, None] + np.arange(4)[None, :], -1)
+
+
+def write_attributes(me, g, loops, corner, face_poly, names):
+ """Received UVs, polypaint, mask and polygroups into `me`. `loops[i, s]` is the loop of corner s of face i
+ and `corner[i, s]` the received face's corner at that vertex; `names` the attribute names to (re)use."""
+ nl, nv = len(me.loops), len(me.vertices)
+ valid = loops >= 0
+ if g.uvs is not None and nl:
+ layer = me.uv_layers.get(names.get("uv", "")) or me.uv_layers.active or me.uv_layers.new(name=names.get("uv") or "UVMap")
+ uv = _get(layer.data, "uv", nl, np.float32, 2)
+ picked = np.take_along_axis(g.uvs, corner[:, :, None].repeat(2, axis=2), axis=1)
+ uv[loops[valid]] = picked[valid]
+ layer.data.foreach_set("uv", uv.ravel())
+ me.uv_layers.active = layer
+ if g.colors is not None:
+ name = names.get("color", "")
+ attr = me.color_attributes.get(name) if name else None
+ if attr is None or attr.domain not in {"POINT", "CORNER"}:
+ attr = me.color_attributes.new(name or "Color", "FLOAT_COLOR", "POINT")
+ rgba = np.ones((nv, 4), dtype=np.float32)
+ rgba[:, :3] = g.colors
+ if attr.domain == "CORNER":
+ rgba = rgba[_get(me.loops, "vertex_index", nl, np.int32)]
+ attr.data.foreach_set("color_srgb", rgba.ravel())
+ me.color_attributes.active_color = attr
+ try:
+ me.color_attributes.render_color_index = me.color_attributes.active_color_index
+ except (AttributeError, TypeError):
+ pass
+ mask = me.attributes.get(MASK)
+ if g.mask is not None:
+ if mask is None:
+ mask = me.attributes.new(MASK, "FLOAT", "POINT")
+ mask.data.foreach_set("value", g.mask.astype(np.float32))
+ elif mask is not None: # SculptForge leaves the mask out when nothing is masked
+ me.attributes.remove(mask)
+ if g.groups is not None and len(me.polygons):
+ sets = me.attributes.get(FACE_SETS)
+ if sets is None:
+ sets = me.attributes.new(FACE_SETS, "INT", "FACE")
+ values = _get(sets.data, "value", len(me.polygons), np.int32)
+ values[face_poly] = g.groups + 1
+ sets.data.foreach_set("value", values)
+
+
+def update_object(obj, g):
+ """Puts a received mesh (world space) into an existing object, keeping its transform, materials and
+ modifiers. Returns "updated" (same topology: positions and attributes only) or "rebuilt"."""
+ m = np.array(obj.matrix_world, dtype=np.float64)
+ positions = exchange.transform_points(np.linalg.inv(m), g.positions)
+ # A mirrored object (negative scale) was sent with every polygon reversed (polygon_corners), so its
+ # normals point out once SculptForge placed it: compare with that, and reverse only when rebuilding.
+ mirrored = np.linalg.det(m[:3, :3]) < 0
+ me = obj.data
+ loops, face_poly, sent, _ = mesh_topology(me, mirrored)
+ names = {"uv": me.uv_layers.active.name if me.uv_layers.active else "",
+ "color": me.color_attributes.active_color.name if me.color_attributes.active_color else ""}
+ if len(me.vertices) == len(positions) and exchange.same_topology(sent, g.faces):
+ flat = np.ascontiguousarray(positions, dtype=np.float32).ravel()
+ me.vertices.foreach_set("co", flat)
+ if me.shape_keys is not None: # the basis is what shows; other keys keep their shapes
+ me.shape_keys.reference_key.data.foreach_set("co", flat)
+ write_attributes(me, g, loops, exchange.corner_map(sent, g.faces), face_poly, names)
+ result = "updated"
+ else:
+ if mirrored:
+ g.faces, g.uvs = exchange.reverse_faces(g.faces, g.uvs)
+ if me.shape_keys is not None:
+ obj.shape_key_clear()
+ loops = set_geometry(me, positions, g.faces)
+ corner = np.tile(np.arange(4), (len(g.faces), 1))
+ write_attributes(me, g, loops, corner, np.arange(len(g.faces)), names)
+ result = "rebuilt"
+ me.update()
+ return result
+
+
+def new_object(context, name, g):
+ me = bpy.data.meshes.new(name)
+ loops = set_geometry(me, g.positions, g.faces)
+ write_attributes(me, g, loops, np.tile(np.arange(4), (len(g.faces), 1)), np.arange(len(g.faces)), {})
+ me.update()
+ obj = bpy.data.objects.new(name, me)
+ collection = getattr(context, "collection", None) or context.scene.collection
+ collection.objects.link(obj)
+ return obj
+
+
+# --------------------------------------------------------------------------------------------------
+# Modes (meshes are updated in Object Mode; the previous mode comes back afterwards)
+# --------------------------------------------------------------------------------------------------
+
+_MODE_SET = {"EDIT_MESH": "EDIT", "SCULPT": "SCULPT", "PAINT_VERTEX": "VERTEX_PAINT",
+ "PAINT_WEIGHT": "WEIGHT_PAINT", "PAINT_TEXTURE": "TEXTURE_PAINT"}
+
+
+def _override(context):
+ window = context.window or next(iter(context.window_manager.windows), None)
+ if window is None:
+ return {}
+ for area in window.screen.areas:
+ if area.type == "VIEW_3D":
+ region = next((r for r in area.regions if r.type == "WINDOW"), None)
+ return {"window": window, "area": area, "region": region}
+ return {"window": window}
+
+
+def _set_mode(context, mode):
+ with context.temp_override(**_override(context)):
+ bpy.ops.object.mode_set(mode=mode)
+
+
+# --------------------------------------------------------------------------------------------------
+# Send and receive
+# --------------------------------------------------------------------------------------------------
+
+
+def send(context):
+ """Writes the selected meshes for SculptForge and starts it if needed. Returns (level, message)."""
+ p = prefs(context)
+ root = exchange_root(p)
+ objects = [o for o in context.selected_objects if o.type == "MESH"]
+ if not objects and context.active_object is not None and context.active_object.type == "MESH":
+ objects = [context.active_object]
+ if not objects:
+ return "ERROR", "Select one or more mesh objects to send"
+ if context.mode == "EDIT_MESH":
+ for obj in objects:
+ obj.update_from_editmode()
+ apply = p is not None and p.modifiers == "APPLY"
+ folder = exchange.outbox(root)
+ first = not os.path.isdir(folder)
+ os.makedirs(folder, exist_ok=True)
+ prefix = exchange.next_file_prefix(folder)
+ depsgraph = context.evaluated_depsgraph_get() if apply else None
+ entries = []
+ for k, obj in enumerate(objects):
+ mirrored = obj.matrix_world.determinant() < 0
+ if apply:
+ evaluated = obj.evaluated_get(depsgraph)
+ me = evaluated.to_mesh()
+ try:
+ arrays = mesh_arrays(me, mirrored)
+ finally:
+ evaluated.to_mesh_clear()
+ obj[APPLIED_KEY] = [m.name for m in obj.modifiers if m.show_viewport]
+ else:
+ arrays = mesh_arrays(obj.data, mirrored)
+ if APPLIED_KEY in obj:
+ del obj[APPLIED_KEY]
+ if len(arrays["faces"]) == 0:
+ continue
+ file = "%s%03d.GoZ" % (prefix, k)
+ exchange.write_goz(os.path.join(folder, file), obj.name, **arrays)
+ entries.append({"name": obj.name, "file": file, "matrix_world": [list(row) for row in obj.matrix_world]})
+ if not entries:
+ return "ERROR", "The selected meshes have no faces"
+ exchange.write_manifest(folder, entries, bpy.app.version_string)
+ state.sent = True
+ count = "%d object%s" % (len(entries), "" if len(entries) == 1 else "s")
+ # A running SculptForge loads it within a second (it beats only once the folder exists: wait for that).
+ if exchange.sculptforge_running(root) or (first and exchange.wait_for_heartbeat(root, 2.5)):
+ return "INFO", "Sent %s to SculptForge" % count
+ path = exchange.find_sculptforge(root, p.sculptforge_path if p else "")
+ if not path:
+ return "WARNING", ("Sent %s, but SculptForge was not found: set its path in the add-on's preferences, or "
+ "start it and use File > Blender > Receive from Blender" % count)
+ try:
+ exchange.launch_sculptforge(path)
+ except OSError as e:
+ return "WARNING", "Sent %s, but SculptForge could not be started (%s): %s" % (count, path, e)
+ return "INFO", "Sent %s; starting SculptForge" % count
+
+
+def receive(context):
+ """Loads what SculptForge sent into the scene. Returns (level, message)."""
+ root = exchange_root()
+ folder = exchange.inbox(root)
+ try:
+ manifest = exchange.read_manifest(folder)
+ except ValueError as e:
+ return "ERROR", str(e)
+ if manifest is None:
+ return "ERROR", "Nothing has been sent from SculptForge yet (File > Blender > Send to Blender)"
+ state.seen = int(manifest.get("revision", 0))
+ state.inbox_time = exchange.file_time(exchange.manifest_path(folder))
+ entries = manifest.get("objects", [])
+ meshes = []
+ for entry in entries:
+ try:
+ meshes.append((entry.get("name") or "Object", exchange.read_goz(os.path.join(folder, entry["file"]))))
+ except (OSError, ValueError) as e:
+ return "ERROR", "Cannot read %s from SculptForge: %s" % (entry.get("name", "?"), e)
+
+ def target(name):
+ obj = bpy.data.objects.get(name)
+ return obj if obj is not None and obj.type == "MESH" and obj.library is None else None
+
+ # Meshes change in Object Mode; come back to the mode we were in.
+ active = context.view_layer.objects.active
+ previous = context.mode
+ if any(t is not None and t.mode != "OBJECT" for t in (target(n) for n, _ in meshes)):
+ try:
+ _set_mode(context, "OBJECT")
+ except RuntimeError as e:
+ return "ERROR", "Leave %s to receive from SculptForge (%s)" % (previous.replace("_", " ").title(), e)
+ counts = {"updated": 0, "rebuilt": 0, "new": 0}
+ disabled = 0
+ try:
+ for name, g in meshes:
+ obj = target(name)
+ if obj is None:
+ new_object(context, name, g)
+ counts["new"] += 1
+ continue
+ counts[update_object(obj, g)] += 1
+ applied = obj.get(APPLIED_KEY)
+ if applied is not None: # those modifiers are in the mesh now
+ for m in obj.modifiers:
+ if m.name in applied and m.show_viewport:
+ m.show_viewport = m.show_render = False
+ disabled += 1
+ del obj[APPLIED_KEY]
+ finally:
+ if previous in _MODE_SET and context.mode != previous and active is not None and active.name in bpy.data.objects:
+ try:
+ _set_mode(context, _MODE_SET[previous])
+ except RuntimeError:
+ pass
+ parts = []
+ if counts["updated"]:
+ parts.append("%d updated" % counts["updated"])
+ if counts["rebuilt"]:
+ parts.append("%d with new topology" % counts["rebuilt"])
+ if counts["new"]:
+ parts.append("%d new" % counts["new"])
+ message = "Received %d object%s from SculptForge (%s)" % (len(meshes), "" if len(meshes) == 1 else "s", ", ".join(parts))
+ if disabled:
+ message += "; turned off %d modifier%s applied when sending" % (disabled, "" if disabled == 1 else "s")
+ return "INFO", message
+
+
+def _redraw(context):
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == "VIEW_3D":
+ area.tag_redraw()
+
+
+def _poll_inbox():
+ """Timer: load what SculptForge sends back, once this session has sent something."""
+ try:
+ p = prefs()
+ if p is None or not p.auto_receive or not state.sent:
+ return 1.0
+ folder = exchange.inbox(exchange_root(p))
+ t = exchange.file_time(exchange.manifest_path(folder))
+ if t == 0 or t == state.inbox_time:
+ return 1.0
+ state.inbox_time = t
+ rev = exchange.revision(folder)
+ if rev < 0 or rev == state.seen:
+ return 1.0
+ level, state.message = receive(bpy.context)
+ print("SculptForge:", state.message)
+ if level == "INFO":
+ try:
+ bpy.ops.ed.undo_push(message="Receive from SculptForge")
+ except RuntimeError:
+ pass
+ _redraw(bpy.context)
+ except Exception: # never let the timer die
+ traceback.print_exc()
+ return 1.0
+
+
+# --------------------------------------------------------------------------------------------------
+# UI
+# --------------------------------------------------------------------------------------------------
+
+
+class SCULPTFORGE_OT_send(bpy.types.Operator):
+ bl_idname = "sculptforge.send"
+ bl_label = "Send to SculptForge"
+ bl_description = ("Send the selected meshes to SculptForge (starting it if needed); each becomes a SubTool. "
+ "Send them back from SculptForge with File > Blender > Send to Blender")
+ bl_options = {"REGISTER"}
+
+ @classmethod
+ def poll(cls, context):
+ return any(o.type == "MESH" for o in context.selected_objects) or (
+ context.active_object is not None and context.active_object.type == "MESH")
+
+ def execute(self, context):
+ level, state.message = send(context)
+ self.report({level}, state.message)
+ return {"CANCELLED"} if level == "ERROR" else {"FINISHED"}
+
+
+class SCULPTFORGE_OT_receive(bpy.types.Operator):
+ bl_idname = "sculptforge.receive"
+ bl_label = "Receive from SculptForge"
+ bl_description = ("Load what SculptForge last sent: objects that came from here update in place (transform, "
+ "materials and modifiers kept), new SubTools become new objects")
+ bl_options = {"REGISTER", "UNDO"}
+
+ def execute(self, context):
+ level, state.message = receive(context)
+ self.report({level}, state.message)
+ return {"CANCELLED"} if level == "ERROR" else {"FINISHED"}
+
+
+class SCULPTFORGE_PT_panel(bpy.types.Panel):
+ bl_label = "SculptForge"
+ bl_space_type = "VIEW_3D"
+ bl_region_type = "UI"
+ bl_category = "SculptForge"
+
+ def draw(self, context):
+ layout = self.layout
+ p = prefs(context)
+ col = layout.column(align=True)
+ col.scale_y = 1.3
+ col.operator(SCULPTFORGE_OT_send.bl_idname, icon="EXPORT")
+ col.operator(SCULPTFORGE_OT_receive.bl_idname, icon="IMPORT")
+ if p is not None:
+ layout.prop(p, "modifiers", text="Modifiers")
+ layout.prop(p, "auto_receive")
+ running = exchange.sculptforge_running(exchange_root(p))
+ layout.label(text="SculptForge is running" if running else "SculptForge is not running",
+ icon="CHECKMARK" if running else "INFO")
+ if state.message:
+ box = layout.box()
+ for line in _wrap(state.message, 36):
+ box.label(text=line)
+
+
+def _wrap(text, width):
+ lines, line = [], ""
+ for word in text.split():
+ if line and len(line) + 1 + len(word) > width:
+ lines.append(line)
+ line = word
+ else:
+ line = (line + " " + word).strip()
+ return lines + ([line] if line else [])
+
+
+class SculptForgePreferences(bpy.types.AddonPreferences):
+ bl_idname = __package__
+
+ sculptforge_path: StringProperty(
+ name="SculptForge",
+ description="The SculptForge program (sculptforge, sculptforge.exe, the .AppImage or SculptForge.app). "
+ "Empty: found automatically (SculptForge records where it is each time it starts)",
+ subtype="FILE_PATH")
+ exchange_folder: StringProperty(
+ name="Exchange folder",
+ description="Folder both programs use. Empty: SculptForge's per-user folder (set the same folder with "
+ "SCULPTFORGE_BLENDER_EXCHANGE for SculptForge if you change it)",
+ subtype="DIR_PATH")
+ modifiers: EnumProperty(
+ name="Modifiers",
+ description="What to send of objects with modifiers",
+ items=[("PRESERVE", "Keep live", "Send the mesh under the modifiers; they keep working on the sculpt in Blender"),
+ ("APPLY", "Apply", "Send the result of the modifiers; when it comes back they are turned off (the mesh has them)")],
+ default="PRESERVE")
+ auto_receive: BoolProperty(
+ name="Receive automatically",
+ description="After a send, load what SculptForge sends back as soon as it arrives (checked once a second)",
+ default=True)
+
+ def draw(self, context):
+ layout = self.layout
+ layout.prop(self, "sculptforge_path")
+ found = exchange.find_sculptforge(exchange_root(self), self.sculptforge_path)
+ layout.label(text="Found: " + found if found else "SculptForge not found: set its path above", icon="FILE_TICK" if found else "ERROR")
+ layout.prop(self, "exchange_folder")
+ layout.label(text="Exchange folder: " + exchange_root(self))
+ layout.prop(self, "modifiers")
+ layout.prop(self, "auto_receive")
+
+
+def _object_menu(self, context):
+ self.layout.separator()
+ self.layout.operator(SCULPTFORGE_OT_send.bl_idname, icon="EXPORT")
+ self.layout.operator(SCULPTFORGE_OT_receive.bl_idname, icon="IMPORT")
+
+
+def _export_menu(self, context):
+ self.layout.operator(SCULPTFORGE_OT_send.bl_idname, text="SculptForge (send)")
+
+
+def _import_menu(self, context):
+ self.layout.operator(SCULPTFORGE_OT_receive.bl_idname, text="SculptForge (receive)")
+
+
+CLASSES = (SculptForgePreferences, SCULPTFORGE_OT_send, SCULPTFORGE_OT_receive, SCULPTFORGE_PT_panel)
+
+
+def register():
+ for cls in CLASSES:
+ bpy.utils.register_class(cls)
+ bpy.types.VIEW3D_MT_object.append(_object_menu)
+ bpy.types.TOPBAR_MT_file_export.append(_export_menu)
+ bpy.types.TOPBAR_MT_file_import.append(_import_menu)
+ # What SculptForge sent before Blender started is not loaded by itself (Receive loads it).
+ folder = exchange.inbox(exchange_root())
+ state.seen = exchange.revision(folder)
+ state.inbox_time = exchange.file_time(exchange.manifest_path(folder))
+ if not bpy.app.timers.is_registered(_poll_inbox):
+ bpy.app.timers.register(_poll_inbox, first_interval=1.0, persistent=True)
+
+
+def unregister():
+ if bpy.app.timers.is_registered(_poll_inbox):
+ bpy.app.timers.unregister(_poll_inbox)
+ bpy.types.TOPBAR_MT_file_import.remove(_import_menu)
+ bpy.types.TOPBAR_MT_file_export.remove(_export_menu)
+ bpy.types.VIEW3D_MT_object.remove(_object_menu)
+ for cls in reversed(CLASSES):
+ bpy.utils.unregister_class(cls)
diff --git a/addons/blender/sculptforge_bridge/blender_manifest.toml b/addons/blender/sculptforge_bridge/blender_manifest.toml
new file mode 100644
index 00000000..d558106f
--- /dev/null
+++ b/addons/blender/sculptforge_bridge/blender_manifest.toml
@@ -0,0 +1,17 @@
+schema_version = "1.0.0"
+
+id = "sculptforge_bridge"
+version = "0.7.0"
+name = "SculptForge Bridge"
+tagline = "Send meshes to SculptForge and back, updated in place like GoZ"
+maintainer = "SculptForge contributors"
+type = "add-on"
+website = "https://islandmed.github.io/SculptForge/guide/blender.html"
+tags = ["Import-Export", "Sculpt"]
+
+blender_version_min = "4.2.0"
+
+license = ["SPDX:GPL-3.0-or-later"]
+
+[permissions]
+files = "Exchange meshes with SculptForge through a folder in your user data"
diff --git a/addons/blender/sculptforge_bridge/exchange.py b/addons/blender/sculptforge_bridge/exchange.py
new file mode 100644
index 00000000..ed527ebb
--- /dev/null
+++ b/addons/blender/sculptforge_bridge/exchange.py
@@ -0,0 +1,450 @@
+# SculptForge bridge for Blender - exchange with SculptForge
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Everything here works without bpy, so it can be tested with plain Python and numpy
+# (tests/blender/test_exchange.py). The add-on (__init__.py) moves data between these arrays and
+# Blender meshes.
+#
+# The two programs share a per-user folder (docs/blender.md):
+# <root>/to_sculptforge/manifest.json + r<rev>_<k>.GoZ written here
+# <root>/to_blender/manifest.json + r<rev>_<k>.GoZ written by SculptForge
+# <root>/app.json where SculptForge is installed (it writes this when it starts)
+# <root>/alive.json SculptForge's heartbeat (pid, time), rewritten every 2 s while it runs
+# Meshes travel as ZBrush .GoZ files, which SculptForge reads and writes already. The .GoZ layout and
+# the axis convention follow GoB (github.com/JoseConseco/GoB, GPL), the Blender GoZ add-on by Daniel
+# Grauer, JoseConseco and contributors: many thanks to them.
+
+import glob
+import json
+import os
+import shutil
+import struct
+import subprocess
+import sys
+import time
+
+import numpy as np
+
+FORMAT = "sculptforge-bridge"
+VERSION = 1
+NO_INDEX = 0xFFFFFFFF
+HEARTBEAT_SECONDS = 6.0 # SculptForge rewrites alive.json every 2 s
+
+# --------------------------------------------------------------------------------------------------
+# Folder and manifest
+# --------------------------------------------------------------------------------------------------
+
+
+def default_root():
+ """The exchange folder SculptForge uses: <its user data folder>/blender."""
+ custom = os.environ.get("SCULPTFORGE_BLENDER_EXCHANGE")
+ if custom:
+ return custom
+ if sys.platform == "win32":
+ base = os.environ.get("APPDATA") or os.path.join(os.path.expanduser("~"), "AppData", "Roaming")
+ return os.path.join(base, "SculptForge", "SculptForge", "blender")
+ if sys.platform == "darwin":
+ return os.path.expanduser("~/Library/Application Support/SculptForge/SculptForge/blender")
+ xdg = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
+ return os.path.join(xdg, "SculptForge", "SculptForge", "blender")
+
+
+def inbox(root):
+ """Where SculptForge writes for Blender."""
+ return os.path.join(root, "to_blender")
+
+
+def outbox(root):
+ """Where Blender writes for SculptForge."""
+ return os.path.join(root, "to_sculptforge")
+
+
+def manifest_path(folder):
+ return os.path.join(folder, "manifest.json")
+
+
+def file_time(path):
+ try:
+ return os.stat(path).st_mtime_ns
+ except OSError:
+ return 0
+
+
+def read_manifest(folder):
+ """The manifest in `folder` as a dict, or None when there is none. Raises ValueError when it is bad."""
+ try:
+ with open(manifest_path(folder), "rb") as f:
+ data = json.loads(f.read().decode("utf-8"))
+ except FileNotFoundError:
+ return None
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
+ raise ValueError("Cannot read the bridge manifest: %s" % e)
+ if not isinstance(data, dict) or data.get("format") != FORMAT:
+ raise ValueError("Not a SculptForge bridge manifest")
+ if data.get("version", 1) > VERSION:
+ raise ValueError("The manifest is from a newer SculptForge; update the add-on")
+ for obj in data.get("objects", []):
+ name = obj.get("file", "")
+ if not name or os.path.basename(name) != name or name in (".", ".."):
+ raise ValueError("The manifest names a bad file: %r" % name)
+ return data
+
+
+def revision(folder):
+ try:
+ m = read_manifest(folder)
+ except ValueError:
+ return -1
+ return -1 if m is None else int(m.get("revision", 0))
+
+
+def _write_atomically(path, data):
+ tmp = path + ".tmp"
+ with open(tmp, "wb") as f:
+ f.write(data)
+ os.replace(tmp, path)
+
+
+def write_manifest(folder, objects, sender_version=""):
+ """Writes manifest.json for `objects` (dicts with name, file and optionally matrix_world as 4 rows) with
+ the next revision, then removes the files of earlier sends. Returns the revision."""
+ os.makedirs(folder, exist_ok=True)
+ rev = max(revision(folder), 0) + 1
+ manifest = {
+ "format": FORMAT,
+ "version": VERSION,
+ "revision": rev,
+ "sender": "blender",
+ "sender_version": sender_version,
+ "time": time.time(),
+ "objects": objects,
+ }
+ _write_atomically(manifest_path(folder), json.dumps(manifest, indent=2).encode("utf-8"))
+ keep = {o["file"] for o in objects}
+ for path in glob.glob(os.path.join(folder, "r*_*")):
+ if os.path.basename(path) not in keep and not os.path.basename(path).startswith("r%d_" % rev):
+ try:
+ os.remove(path)
+ except OSError:
+ pass # still open on Windows: the next send tries again
+ return rev
+
+
+def next_file_prefix(folder):
+ """File name prefix of the next send (r<revision>_), so files never overwrite ones still being read."""
+ return "r%d_" % (max(revision(folder), 0) + 1)
+
+
+# --------------------------------------------------------------------------------------------------
+# Axes: Blender is Z-up, ZBrush (GoZ) Y-down. GoB maps GoZ (x, y, z) to Blender (x, z, -y).
+# SculptForge reads GoZ as Y-up (x, -y, -z), so Blender (x, y, z) arrives as (x, z, -y): metres both.
+# --------------------------------------------------------------------------------------------------
+
+
+def blender_to_goz(co):
+ co = np.asarray(co, dtype=np.float64).reshape(-1, 3)
+ return np.stack([co[:, 0], -co[:, 2], co[:, 1]], axis=1)
+
+
+def goz_to_blender(co):
+ co = np.asarray(co, dtype=np.float64).reshape(-1, 3)
+ return np.stack([co[:, 0], co[:, 2], -co[:, 1]], axis=1)
+
+
+def transform_points(matrix, co):
+ """`matrix` (4x4, rows as Blender prints it) applied to points (N, 3)."""
+ m = np.asarray(matrix, dtype=np.float64)
+ return np.asarray(co, dtype=np.float64) @ m[:3, :3].T + m[:3, 3]
+
+
+# --------------------------------------------------------------------------------------------------
+# Faces: Blender polygons -> GoZ faces (triangles and quads; n-gons as triangle fans)
+# --------------------------------------------------------------------------------------------------
+
+
+def polygon_corners(loop_start, loop_total, mirrored=False):
+ """GoZ faces for Blender polygons, as loop indices.
+
+ Returns (loops, face_polygon): loops is (F, 4) with -1 in the 4th column of triangles, face_polygon (F,)
+ the polygon each face comes from. Triangles and quads stay as they are; an n-gon becomes the fan
+ (0, i, i+1). `mirrored` reverses every polygon's winding (for objects with a negative scale, whose
+ normals would point inwards once SculptForge places them).
+ """
+ start = np.asarray(loop_start, dtype=np.int64)
+ n = np.asarray(loop_total, dtype=np.int64)
+ k = np.where(n <= 4, 1, n - 2)
+ face_poly = np.repeat(np.arange(len(n), dtype=np.int64), k)
+ first = np.cumsum(k) - k
+ j = np.arange(len(face_poly), dtype=np.int64) - first[face_poly]
+ nn = n[face_poly]
+ small = nn <= 4
+ c = np.empty((len(face_poly), 4), dtype=np.int64)
+ c[:, 0] = 0
+ c[:, 1] = np.where(small, 1, j + 1)
+ c[:, 2] = np.where(small, 2, j + 2)
+ c[:, 3] = np.where(nn == 4, 3, -1)
+ if mirrored:
+ c = np.where(c > 0, nn[:, None] - c, c)
+ loops = np.where(c >= 0, start[face_poly][:, None] + c, -1)
+ return loops, face_poly
+
+
+def faces_from_loops(loops, loop_vertex):
+ """Vertex indices (F, 4, uint32, NO_INDEX for the missing 4th corner of triangles)."""
+ lv = np.asarray(loop_vertex, dtype=np.int64)
+ out = np.where(loops >= 0, lv[np.maximum(loops, 0)], NO_INDEX)
+ return out.astype(np.uint32)
+
+
+def reverse_faces(faces, corner_data=None):
+ """Reverses the winding of GoZ faces (a, b, c, d) -> (a, d, c, b), (a, b, c) -> (a, c, b), and the same
+ for per-corner data (F, 4, ...)."""
+ faces = np.asarray(faces)
+ quad = faces[:, 3] != NO_INDEX
+ perm = np.where(quad[:, None], np.array([0, 3, 2, 1]), np.array([0, 2, 1, 3]))
+ out = np.take_along_axis(faces, perm, axis=1)
+ if corner_data is None:
+ return out, None
+ data = np.asarray(corner_data)
+ idx = perm.reshape(perm.shape + (1,) * (data.ndim - 2))
+ return out, np.take_along_axis(data, np.broadcast_to(idx, data.shape), axis=1)
+
+
+def canonical_faces(faces):
+ """Each face rotated to start at its smallest vertex (winding kept), and the rotation used (F,)."""
+ f = np.asarray(faces, dtype=np.int64)
+ quad = f[:, 3] != NO_INDEX
+ k = np.where(quad, 4, 3)
+ valid = np.arange(4)[None, :] < k[:, None]
+ r = np.argmin(np.where(valid, f, np.iinfo(np.int64).max), axis=1)
+ idx = (r[:, None] + np.arange(4)[None, :]) % k[:, None]
+ out = np.take_along_axis(f, idx, axis=1)
+ out[~quad, 3] = NO_INDEX
+ return out, r
+
+
+def same_topology(sent_faces, received_faces):
+ """True when SculptForge sent back the faces it was given (in order; each may start at another corner)."""
+ a, b = np.asarray(sent_faces), np.asarray(received_faces)
+ if a.shape != b.shape:
+ return False
+ return bool(np.array_equal(canonical_faces(a)[0], canonical_faces(b)[0]))
+
+
+def corner_map(sent_faces, received_faces):
+ """For each sent face corner, the received face's corner at the same vertex: (F, 4), for faces with the
+ same topology (same_topology)."""
+ _, rs = canonical_faces(sent_faces)
+ _, rr = canonical_faces(received_faces)
+ k = np.where(np.asarray(sent_faces)[:, 3] != NO_INDEX, 4, 3)
+ s = np.arange(4)[None, :]
+ return np.where(s < k[:, None], (s - rs[:, None] + rr[:, None]) % k[:, None], 3)
+
+
+# --------------------------------------------------------------------------------------------------
+# .GoZ files (docs/goz.md)
+# --------------------------------------------------------------------------------------------------
+
+TAG_MESH_NAME = 0x1389
+TAG_VERTICES = 0x2711
+TAG_FACES = 0x4E21
+TAG_UVS = 0x61A9
+TAG_MASK = 0x7532
+TAG_POLYPAINT = 0x88B9
+TAG_POLYGROUPS = 0x9C41
+HEADER = b"GoZb 1.0 ZBrush GoZ Binary" + b"." * 6
+
+
+def goz_name(name):
+ """GoZ object names: ASCII letters, digits, '_' and '-' (GoB's escaping); the manifest keeps the real name."""
+ out = ""
+ for ch in name:
+ if ch.isascii() and (ch.isalnum() or ch in "_-"):
+ out += ch
+ elif not out.endswith("_"):
+ out += "_"
+ out = out.strip("_-")
+ return out or "Object"
+
+
+def _section(tag, payload, count):
+ return struct.pack("<IIQ", tag, len(payload) + 16, count) + payload
+
+
+def write_goz(path, name, positions, faces, uvs=None, colors=None, mask=None, groups=None):
+ """Writes a .GoZ file.
+
+ positions (N, 3) Blender coordinates; faces (F, 4) vertex indices with NO_INDEX as the 4th of
+ triangles; uvs (F, 4, 2) per face corner (V up, as Blender has it); colors (N, 3) sRGB 0..1; mask (N,)
+ 0 = free, 1 = masked; groups (F,) polygroup ids (0..65535).
+ """
+ name = goz_name(name).encode("ascii")
+ pos = blender_to_goz(positions).astype("<f4")
+ faces = np.ascontiguousarray(faces, dtype="<u4").reshape(-1, 4)
+ parts = [HEADER, struct.pack("<IIQ", 1, len(name) + 24, 1), b"GoZMesh_", name,
+ struct.pack("<IIQI", TAG_MESH_NAME, 20, 1, 0),
+ _section(TAG_VERTICES, pos.tobytes(), len(pos)),
+ _section(TAG_FACES, faces.tobytes(), len(faces))]
+ if uvs is not None:
+ uv = np.array(uvs, dtype="<f4").reshape(-1, 4, 2)
+ uv[:, :, 1] = 1.0 - uv[:, :, 1] # GoZ stores V downwards
+ uv[faces[:, 3] == NO_INDEX, 3] = (0.0, 1.0) # GoB's padding for triangles
+ parts.append(_section(TAG_UVS, uv.tobytes(), len(faces)))
+ if colors is not None:
+ c = np.clip(np.asarray(colors, dtype=np.float64).reshape(-1, 3), 0.0, 1.0)
+ bgra = np.zeros((len(c), 4), dtype=np.uint8)
+ bgra[:, :3] = np.floor(c[:, ::-1] * 255.0 + 0.5).astype(np.uint8)
+ parts.append(_section(TAG_POLYPAINT, bgra.tobytes(), len(c)))
+ if mask is not None:
+ m = np.clip(np.asarray(mask, dtype=np.float64), 0.0, 1.0)
+ parts.append(_section(TAG_MASK, np.floor((1.0 - m) * 65535.0 + 0.5).astype("<u2").tobytes(), len(m)))
+ if groups is not None:
+ g = np.asarray(groups, dtype=np.int64)
+ if len(g) and (g.min() < 0 or g.max() > 0xFFFF): # GoZ groups are 16-bit: renumber 0, 1, 2...
+ g = np.unique(g, return_inverse=True)[1] & 0xFFFF
+ parts.append(_section(TAG_POLYGROUPS, g.astype("<u2").tobytes(), len(g)))
+ parts.append(b"\0" * 16)
+ _write_atomically(path, b"".join(parts))
+
+
+class GozMesh:
+ """A .GoZ file read into Blender coordinates (see write_goz for the arrays)."""
+
+ def __init__(self):
+ self.name = ""
+ self.positions = np.zeros((0, 3))
+ self.faces = np.zeros((0, 4), dtype=np.uint32)
+ self.uvs = None
+ self.colors = None
+ self.mask = None
+ self.groups = None
+
+
+def read_goz(path):
+ with open(path, "rb") as f:
+ data = f.read()
+ if len(data) < 40 or data[:4] != b"GoZb":
+ raise ValueError("Not a GoZ file: %s" % path)
+ out = GozMesh()
+ (name_len,) = struct.unpack_from("<I", data, 36)
+ if name_len >= 24 and 32 + name_len <= len(data):
+ out.name = data[56:32 + name_len].decode("ascii", "replace")
+ pos = 32 + max(name_len, 8)
+ while pos + 8 <= len(data):
+ tag, length = struct.unpack_from("<II", data, pos)
+ if tag == 0 or length < 8:
+ break
+ body = data[pos + 8:min(pos + length, len(data))]
+ pos += length
+ if len(body) < 8:
+ continue
+ (count,) = struct.unpack_from("<Q", body, 0)
+ payload = body[8:]
+
+ def records(size):
+ return min(count, len(payload) // size)
+
+ if tag == TAG_VERTICES:
+ v = np.frombuffer(payload, dtype="<f4", count=records(12) * 3).reshape(-1, 3)
+ out.positions = goz_to_blender(v)
+ elif tag == TAG_FACES:
+ out.faces = np.frombuffer(payload, dtype="<u4", count=records(16) * 4).reshape(-1, 4).copy()
+ elif tag == TAG_UVS:
+ uv = np.frombuffer(payload, dtype="<f4", count=records(32) * 8).reshape(-1, 4, 2).astype(np.float64)
+ uv[:, :, 1] = 1.0 - uv[:, :, 1]
+ out.uvs = uv
+ elif tag == TAG_POLYPAINT:
+ c = np.frombuffer(payload, dtype=np.uint8, count=records(4) * 4).reshape(-1, 4)
+ out.colors = c[:, 2::-1].astype(np.float64) / 255.0
+ elif tag == TAG_MASK:
+ out.mask = 1.0 - np.frombuffer(payload, dtype="<u2", count=records(2)).astype(np.float64) / 65535.0
+ elif tag == TAG_POLYGROUPS:
+ out.groups = np.frombuffer(payload, dtype="<u2", count=records(2)).astype(np.int64)
+ nv, nf = len(out.positions), len(out.faces)
+ if nv == 0 or nf == 0:
+ raise ValueError("GoZ file has no %s: %s" % ("vertices" if nv == 0 else "faces", path))
+ quad = out.faces[:, 3] != NO_INDEX
+ corners = np.where(quad[:, None], out.faces, np.where(np.arange(4) < 3, out.faces, 0))
+ if corners.max() >= nv:
+ raise ValueError("GoZ file has faces with bad vertex indices: %s" % path)
+ if out.uvs is not None and len(out.uvs) != nf:
+ out.uvs = None
+ if out.colors is not None and len(out.colors) != nv:
+ out.colors = None
+ if out.mask is not None and len(out.mask) != nv:
+ out.mask = None
+ if out.groups is not None and len(out.groups) != nf:
+ out.groups = None
+ return out
+
+
+# --------------------------------------------------------------------------------------------------
+# SculptForge: running? installed where? start it
+# --------------------------------------------------------------------------------------------------
+
+
+def sculptforge_running(root):
+ try:
+ with open(os.path.join(root, "alive.json"), "rb") as f:
+ beat = json.loads(f.read().decode("utf-8"))
+ return abs(time.time() - float(beat.get("time", 0))) < HEARTBEAT_SECONDS
+ except (OSError, ValueError, AttributeError):
+ return False
+
+
+def wait_for_heartbeat(root, seconds):
+ end = time.time() + seconds
+ while time.time() < end:
+ if sculptforge_running(root):
+ return True
+ time.sleep(0.2)
+ return sculptforge_running(root)
+
+
+def find_sculptforge(root, override=""):
+ """Path of SculptForge: the add-on preference, else where SculptForge said it is (app.json), else PATH
+ and the usual install folders. Empty when not found."""
+ candidates = []
+ if override:
+ candidates.append(os.path.expanduser(override))
+ try:
+ with open(os.path.join(root, "app.json"), "rb") as f:
+ candidates.append(json.loads(f.read().decode("utf-8")).get("path", ""))
+ except (OSError, ValueError, AttributeError):
+ pass
+ for name in ("sculptforge", "SculptForge"):
+ found = shutil.which(name)
+ if found:
+ candidates.append(found)
+ if sys.platform == "win32":
+ for base in filter(None, (os.environ.get("ProgramFiles"), os.environ.get("LOCALAPPDATA"))):
+ candidates += sorted(glob.glob(os.path.join(base, "SculptForge*", "bin", "sculptforge.exe")), reverse=True)
+ candidates += sorted(glob.glob(os.path.join(base, "SculptForge*", "sculptforge.exe")), reverse=True)
+ elif sys.platform == "darwin":
+ candidates += ["/Applications/SculptForge.app", os.path.expanduser("~/Applications/SculptForge.app")]
+ else:
+ for folder in ("~/Applications", "~/.local/bin", "~/Downloads", "/opt"):
+ candidates += sorted(glob.glob(os.path.join(os.path.expanduser(folder), "SculptForge*.AppImage")), reverse=True)
+ candidates += ["/usr/bin/sculptforge", "/usr/local/bin/sculptforge", "/opt/sculptforge/bin/sculptforge"]
+ for c in candidates:
+ if c and os.path.exists(c):
+ return c
+ return ""
+
+
+def launch_sculptforge(path):
+ """Starts SculptForge with --blender (it loads what was sent), detached from Blender."""
+ if path.endswith(".app"):
+ args = ["open", "-n", path, "--args", "--blender"]
+ else:
+ args = [path, "--blender"]
+ kwargs = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, "close_fds": True}
+ if sys.platform == "win32":
+ kwargs["creationflags"] = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
+ else:
+ kwargs["start_new_session"] = True
+ env = dict(os.environ)
+ for key in ("PYTHONHOME", "PYTHONPATH"): # Blender's Python, not SculptForge's
+ env.pop(key, None)
+ kwargs["env"] = env
+ subprocess.Popen(args, **kwargs)
diff --git a/src/app/App.cpp b/src/app/App.cpp
index e0339058..9dcfdf81 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -19,6 +19,7 @@
#include "core/ImageTo3D.h"
#include "core/Project.h"
#include "core/Script.h"
+#include "io/BlenderBridge.h"
#include "render/GL.h"
#include <imgui.h>
@@ -264,6 +265,8 @@ bool App::init(const AppOptions& options) {
void App::shutdown() {
flushBrushEdits();
+ if (blenderInitialised_) writeBridgeHeartbeat(blenderExchangeRoot(), true); // the add-on starts a new one
+
if (refTexture_) gl::DeleteTextures(1, &refTexture_);
gallery_.reset(); // its preview textures need the GL context
thumbs_.clear();
@@ -494,6 +497,7 @@ int App::runRecording() {
animateLayers(dt);
pollBrushRequest();
pollUnreal();
+ if (!options_.uiTest.empty()) pollBlender(); // (demos and recordings leave the user's bridge alone)
pollAutoUv();
pollBake();
pollQRemesh();
@@ -560,6 +564,7 @@ int App::run() {
pollGenerator();
pollUnreal();
pollGoz();
+ pollBlender();
pollAutoUv();
pollBake();
pollQRemesh();
diff --git a/src/app/App.h b/src/app/App.h
index 32d64d47..8d5e4e38 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -47,6 +47,7 @@ namespace sf {
struct AppOptions {
std::string openPath; // model or image to open at start
+ bool blender = false; // started by the Blender add-on: load what it sent (--blender)
std::string script; // commands to run after start-up (same language as sculptforge-cli)
std::string renderPath; // headless: render a PNG and exit
int width = 1024, height = 1024;
@@ -511,6 +512,15 @@ private:
long long gozListTime_ = 0; // last seen modification time of the object list
Uint64 gozLastPollNs_ = 0;
bool gozInitialised_ = false;
+ // Blender bridge (PanelBlender.cpp, io/BlenderBridge.h): the add-on's exchange folder, polled once a second.
+ void drawBlenderMenu();
+ void pollBlender();
+ void receiveFromBlender();
+ bool blenderInitialised_ = false;
+ bool blenderAutoReceive_ = true; // load whatever Blender sends while SculptForge runs
+ long long blenderInboxTime_ = 0; // last seen modification time of to_sculptforge/manifest.json
+ int64_t blenderSeenRevision_ = -1; // revision last loaded (or present at start, which is not loaded)
+ Uint64 blenderLastPollNs_ = 0, blenderLastBeatNs_ = 0;
// Projects, unsaved-changes safety, recent files and autosave (PanelProject.cpp).
bool interactive() const; // false for --render, --record and demos: never prompt
void initProject(); // end of init(): recent files, autosave restore offer
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index d1b792fe..ff3190fe 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -240,6 +240,15 @@ void App::initActions() {
add("file.send_unreal", "Send to Unreal", "File > Export", "Ctrl+U", [this] { sendToUnreal(); }, ICON_LC_SEND, nullptr,
nullptr, [this] { return !pendingUnreal_.valid(); },
"Export a game-ready FBX and import it into the running Unreal Editor (Python remote execution).");
+ // Blender bridge (PanelBlender.cpp, addons/blender).
+ add("file.send_blender", "Send to Blender", "File > Blender", nullptr, [this] { runCommand("blender_send"); },
+ ICON_LC_SEND, "blender_send", nullptr, nullptr,
+ "Send the visible SubTools back to Blender (the SculptForge add-on): objects that came from Blender update "
+ "in place, keeping their transform, materials and modifiers; new SubTools become new objects.");
+ add("file.receive_blender", "Receive from Blender", "File > Blender", nullptr, [this] { receiveFromBlender(); },
+ nullptr, "blender_receive", nullptr, nullptr,
+ "Load what Blender last sent with the add-on's Send to SculptForge. Each object updates its SubTool (undoable) "
+ "or becomes a new one; this happens by itself while Receive automatically is on.");
add("brush.paste", "Paste brush", "Brush", "Ctrl+V", [this] { pasteBrush(); }, ICON_LC_CLIPBOARD_PASTE, nullptr, nullptr,
nullptr, "Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.");
add("brush.size_down", "Smaller brush", "Draw", "[", [this] { radiusPx_ = std::max(2.0f, radiusPx_ / 1.1f); }, nullptr,
diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cpp
index b4049644..fa3976c1 100644
--- a/src/app/LightBox.cpp
+++ b/src/app/LightBox.cpp
@@ -1003,7 +1003,8 @@ void App::initLightBox() {
[this] { quickSave(); });
// ZBrush opens the LightBox at startup on the Project tab (never in tests, renders or recordings).
- if (uiPrefs_.lightboxAtStartup && interactive() && options_.uiTest.empty() && options_.openPath.empty())
+ if (uiPrefs_.lightboxAtStartup && interactive() && options_.uiTest.empty() && options_.openPath.empty() &&
+ !options_.blender)
lightbox_.show(LibraryTab::Project);
}
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 62614b9f..88a45543 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -218,6 +218,7 @@ void App::drawPalette_File() {
menuAction(*this, "file.save_splats");
ImGui::Separator();
drawGozMenu();
+ drawBlenderMenu(); // the Blender bridge (PanelBlender.cpp)
ImGui::Separator();
menuAction(*this, "file.quit");
}
diff --git a/src/app/PanelBlender.cpp b/src/app/PanelBlender.cpp
new file mode 100644
index 00000000..acc519fb
--- /dev/null
+++ b/src/app/PanelBlender.cpp
@@ -0,0 +1,110 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// File > Blender: the bridge to the SculptForge add-on for Blender (io/BlenderBridge.h, addons/blender).
+// Blender writes to_sculptforge/manifest.json; this polls it once a second and loads each new revision.
+#include "app/App.h"
+#include "app/Ui.h"
+
+#include "io/BlenderBridge.h"
+
+#include <cstdlib>
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+// What the add-on should start: the AppImage itself (not its temporary mount), the .app bundle on macOS, else
+// this executable.
+std::string bridgeExecutable() {
+ if (const char* appimage = std::getenv("APPIMAGE"); appimage && *appimage) return appimage;
+ const char* base = SDL_GetBasePath();
+ if (!base) return {};
+ std::string dir = base;
+#ifdef __APPLE__
+ if (const size_t app = dir.find(".app/"); app != std::string::npos) return dir.substr(0, app + 4);
+#endif
+#ifdef _WIN32
+ return dir + "sculptforge.exe";
+#else
+ return dir + "sculptforge";
+#endif
+}
+
+// A menu row for an action, as in the palettes (label, shortcut, Ctrl-hover help).
+void menuAction(App& app, const char* id) {
+ const Action* a = app.actions().find(id);
+ if (!a) return;
+ const std::string shortcut = app.actions().shortcutText(id);
+ const std::string label = a->label + "##" + a->id;
+ if (ImGui::MenuItem(label.c_str(), shortcut.empty() ? nullptr : shortcut.c_str(), false, !a->enabled || a->enabled()) &&
+ a->run) {
+ app.actions().touch(a->id);
+ a->run();
+ }
+ ui::HelpAction(app, id);
+}
+
+} // namespace
+
+void App::receiveFromBlender() {
+ const std::string root = blenderExchangeRoot();
+ if (!root.empty()) { // a manual receive counts as seen, so polling doesn't load it again
+ blenderInboxTime_ = bridgeFileTime(bridgeManifestPath(blenderInbox(root)));
+ blenderSeenRevision_ = bridgeRevision(blenderInbox(root));
+ }
+ runCommand("blender_receive");
+ if (status_.rfind("Received", 0) == 0) camera_.frame(sceneBounds());
+}
+
+void App::drawBlenderMenu() {
+ if (!ImGui::BeginMenu("Blender")) return;
+ menuAction(*this, "file.send_blender");
+ menuAction(*this, "file.receive_blender");
+ ImGui::MenuItem("Receive automatically##blender", nullptr, &blenderAutoReceive_);
+ ui::HelpText("Receive automatically", nullptr,
+ "Load what Blender sends as soon as it arrives (checked once a second). Off: use Receive from "
+ "Blender.",
+ "File > Blender");
+ const std::string root = blenderExchangeRoot();
+ ImGui::TextDisabled("Needs the SculptForge add-on in Blender\n(Help > User Guide > Blender).");
+ if (ImGui::IsItemHovered() && !root.empty()) ImGui::SetTooltip("Exchange folder: %s", root.c_str());
+ ImGui::EndMenu();
+}
+
+void App::pollBlender() {
+ const std::string root = blenderExchangeRoot();
+ if (root.empty()) return;
+ const std::string inbox = blenderInbox(root);
+ const std::string manifest = bridgeManifestPath(inbox);
+ if (!blenderInitialised_) {
+ blenderInitialised_ = true;
+ writeBridgeAppInfo(root, bridgeExecutable(), SCULPTFORGE_VERSION);
+ // What was sent before this start is old news, unless the add-on started us to load it.
+ blenderInboxTime_ = bridgeFileTime(manifest);
+ blenderSeenRevision_ = bridgeRevision(inbox);
+ if (options_.blender && blenderInboxTime_) receiveFromBlender();
+ }
+ // UI tests check every frame (their frames are simulated); the app once a second.
+ const Uint64 now = SDL_GetTicksNS();
+ const Uint64 interval = options_.uiTest.empty() ? 1'000'000'000ull : 0;
+ if (now - blenderLastPollNs_ < interval) return;
+ blenderLastPollNs_ = now;
+
+ std::error_code ec;
+ if (!std::filesystem::is_directory(std::filesystem::path(std::u8string(inbox.begin(), inbox.end())), ec))
+ return; // the add-on has never sent anything: no heartbeat either
+ if (now - blenderLastBeatNs_ >= 2'000'000'000ull) {
+ blenderLastBeatNs_ = now;
+ writeBridgeHeartbeat(root);
+ }
+ if (!blenderAutoReceive_ || doc_.sculptor.strokeActive()) return;
+ const long long t = bridgeFileTime(manifest);
+ if (t == 0 || t == blenderInboxTime_) return;
+ blenderInboxTime_ = t;
+ const int64_t revision = bridgeRevision(inbox);
+ if (revision >= 0 && revision != blenderSeenRevision_) receiveFromBlender();
+}
+
+} // namespace sf
diff --git a/src/app/UserGuide.cpp b/src/app/UserGuide.cpp
index b0fb3357..975aba37 100644
--- a/src/app/UserGuide.cpp
+++ b/src/app/UserGuide.cpp
@@ -426,6 +426,7 @@ std::string UserGuide::chapterFor(const std::string& palette, const std::string&
: "sculpting.md";
if (starts("Draw") || starts("Stroke") || starts("Alpha")) return "sculpting.md";
if (starts("Color") || starts("Material")) return "polypaint.md";
+ if (starts("File > Blender")) return "blender.md";
if (starts("File > Export") || idStarts("file.export") || actionId == "file.send_unreal" || actionId == "file.save_splats" ||
starts("File > GoZ"))
return "exporting.md";
diff --git a/src/app/main.cpp b/src/app/main.cpp
index b2677930..2512def6 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -36,6 +36,7 @@ void usage() {
" --ui-test FILE.sfui Run a UI test script headless and exit (0 = pass); settings are isolated\n"
" --ui-out DIR Where UI tests save screenshots\n"
" --fullscreen Start filling the screen (F11 toggles)\n"
+ " --blender Load what the Blender add-on sent (it starts SculptForge this way)\n"
" --bench Run the performance benchmark (with GPU upload and orbit timings) and exit\n"
" --bench-sizes 4,16,32 Benchmark sizes in millions of triangles\n"
" --bench-dabs N Dabs per benchmark stroke (default 40)\n"
@@ -98,6 +99,7 @@ int main(int argc, char** argv) {
else if (a == "--supersample") options.supersample = std::clamp(std::atoi(next().c_str()), 1, 4);
else if (a == "--ui-test") options.uiTest = next();
else if (a == "--fullscreen") options.fullscreen = true;
+ else if (a == "--blender") options.blender = true;
else if (a == "--ui-out") options.uiOutDir = next();
else if (a == "-h" || a == "--help") {
usage();
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 6365e973..473263de 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -24,6 +24,7 @@
#include "core/Voxel.h"
#include "io/FbxIO.h"
#include "io/GltfIO.h"
+#include "io/BlenderCommands.h"
#include "io/GozCommands.h"
#include "io/GozIO.h"
#include "io/ObjIO.h"
@@ -770,6 +771,7 @@ CommandRegistry::CommandRegistry() {
registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)
registerPaintCommands(*this); // core/Polypaint.cpp
registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
+ registerBlenderCommands(*this); // blender_send/receive (io/BlenderCommands.cpp)
registerBakeCommands(*this); // bake (core/Bake.cpp)
registerProjectCommands(*this); // keep last (core/Project.cpp)
}
diff --git a/src/io/BlenderBridge.cpp b/src/io/BlenderBridge.cpp
new file mode 100644
index 00000000..77ff3f93
--- /dev/null
+++ b/src/io/BlenderBridge.cpp
@@ -0,0 +1,354 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/BlenderBridge.h"
+
+#include "core/BrushLibrary.h"
+#include "core/Json.h"
+#include "io/GozIO.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <sstream>
+
+#ifdef _WIN32
+#include <process.h>
+#else
+#include <unistd.h>
+#endif
+
+namespace sf {
+
+namespace {
+
+namespace fs = std::filesystem;
+
+fs::path utf8Path(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }
+std::string pathUtf8(const fs::path& p) {
+ auto u = p.u8string();
+ return std::string(u.begin(), u.end());
+}
+
+std::string envValue(const char* name) {
+#ifdef _WIN32
+ char* value = nullptr;
+ size_t len = 0;
+ if (_dupenv_s(&value, &len, name) != 0 || !value) return {};
+ std::string s = value;
+ std::free(value);
+ return s;
+#else
+ const char* v = std::getenv(name);
+ return v ? v : "";
+#endif
+}
+
+bool readFile(const fs::path& p, std::string& out) {
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return false;
+ out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
+ return true;
+}
+
+// Writes through a temporary file and a rename, so a reader never sees half a file.
+bool writeAtomically(const fs::path& p, const std::string& text) {
+ fs::path tmp = p;
+ tmp += ".tmp";
+ {
+ std::ofstream f(tmp, std::ios::binary);
+ if (!f || !f.write(text.data(), std::streamsize(text.size()))) return false;
+ }
+ std::error_code ec;
+ fs::rename(tmp, p, ec);
+ if (ec) fs::remove(tmp, ec);
+ return !ec;
+}
+
+std::string number(double v) {
+ char buf[40];
+ std::snprintf(buf, sizeof buf, "%.17g", v);
+ return buf;
+}
+
+double nowSeconds() {
+ return std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();
+}
+
+// A file name the manifest may name: no folders, nothing that leaves the folder.
+bool plainFileName(const std::string& name) {
+ return !name.empty() && name != "." && name != ".." && name.find_first_of("/\\:") == std::string::npos;
+}
+
+// Point (x, y, z) -> (x, z, -y) as a matrix (and its inverse, the transpose).
+glm::dmat4 axesBlenderToSf() {
+ glm::dmat4 a(0.0);
+ a[0][0] = 1.0; // column 0: x -> x
+ a[1][2] = -1.0; // column 1: y -> -z
+ a[2][1] = 1.0; // column 2: z -> y
+ a[3][3] = 1.0;
+ return a;
+}
+
+} // namespace
+
+std::string blenderExchangeRoot() {
+ const std::string custom = envValue("SCULPTFORGE_BLENDER_EXCHANGE");
+ if (!custom.empty()) return custom;
+ const std::string base = appDataDir();
+ return base.empty() ? std::string() : pathUtf8(utf8Path(base) / "blender");
+}
+
+std::string blenderInbox(const std::string& root) { return pathUtf8(utf8Path(root) / "to_sculptforge"); }
+std::string blenderOutbox(const std::string& root) { return pathUtf8(utf8Path(root) / "to_blender"); }
+std::string bridgeManifestPath(const std::string& folder) { return pathUtf8(utf8Path(folder) / "manifest.json"); }
+
+glm::dvec3 blenderToSculptForge(const glm::dvec3& p) { return {p.x, p.z, -p.y}; }
+glm::dvec3 sculptForgeToBlender(const glm::dvec3& p) { return {p.x, -p.z, p.y}; }
+glm::dmat4 blenderMatrixToSculptForge(const glm::dmat4& m) {
+ const glm::dmat4 a = axesBlenderToSf();
+ return a * m * glm::transpose(a);
+}
+
+bool parseBridgeManifest(const std::string& text, BridgeManifest& out, std::string& error) {
+ Json j;
+ if (!Json::parse(text, j, error)) {
+ error = "Bridge manifest is not valid JSON: " + error;
+ return false;
+ }
+ if (!j.isObject() || j["format"].asString() != "sculptforge-bridge") {
+ error = "Not a SculptForge bridge manifest";
+ return false;
+ }
+ if (j["version"].asNumber(1) > 1) {
+ error = "The bridge manifest is from a newer add-on or SculptForge (version " +
+ std::to_string(int(j["version"].asNumber())) + "); update the older one";
+ return false;
+ }
+ BridgeManifest m;
+ m.revision = int64_t(j["revision"].asNumber(0));
+ m.sender = j["sender"].asString();
+ m.senderVersion = j["sender_version"].asString();
+ for (const Json& o : j["objects"].items()) {
+ BridgeObject b;
+ b.name = o["name"].asString();
+ b.file = o["file"].asString();
+ if (!plainFileName(b.file)) {
+ error = "Bridge manifest names a bad file: \"" + b.file + "\"";
+ return false;
+ }
+ const Json& mw = o["matrix_world"];
+ if (mw.isArray()) {
+ // Rows, as Blender prints a Matrix: matrix_world[row][column].
+ bool ok = mw.size() == 4;
+ for (size_t r = 0; ok && r < 4; ++r) {
+ ok = mw[r].isArray() && mw[r].size() == 4;
+ for (size_t c = 0; ok && c < 4; ++c) {
+ ok = mw[r][c].isNumber() && std::isfinite(mw[r][c].asNumber());
+ if (ok) b.matrix[int(c)][int(r)] = mw[r][c].asNumber();
+ }
+ }
+ if (!ok) {
+ error = "Bridge manifest has a bad matrix_world for \"" + b.name + "\"";
+ return false;
+ }
+ b.hasMatrix = true;
+ }
+ m.objects.push_back(std::move(b));
+ }
+ out = std::move(m);
+ return true;
+}
+
+std::string writeBridgeManifest(const BridgeManifest& m) {
+ std::string s = "{\n \"format\": \"sculptforge-bridge\",\n \"version\": 1,\n";
+ s += " \"revision\": " + std::to_string(m.revision) + ",\n";
+ s += " \"sender\": " + jsonQuote(m.sender) + ",\n";
+ s += " \"sender_version\": " + jsonQuote(m.senderVersion) + ",\n";
+ s += " \"time\": " + number(nowSeconds()) + ",\n";
+ s += " \"objects\": [";
+ for (size_t i = 0; i < m.objects.size(); ++i) {
+ const BridgeObject& o = m.objects[i];
+ s += i ? ",\n {" : "\n {";
+ s += "\"name\": " + jsonQuote(o.name) + ", \"file\": " + jsonQuote(o.file);
+ if (o.hasMatrix) {
+ s += ", \"matrix_world\": [";
+ for (int r = 0; r < 4; ++r) {
+ s += r ? ", [" : "[";
+ for (int c = 0; c < 4; ++c) s += (c ? ", " : "") + number(o.matrix[c][r]);
+ s += "]";
+ }
+ s += "]";
+ }
+ s += "}";
+ }
+ s += m.objects.empty() ? "]\n}\n" : "\n ]\n}\n";
+ return s;
+}
+
+bool readBridgeManifest(const std::string& path, BridgeManifest& out, std::string& error) {
+ std::string text;
+ if (!readFile(utf8Path(path), text)) {
+ error = "Nothing has been sent yet (no " + path + ")";
+ return false;
+ }
+ return parseBridgeManifest(text, out, error);
+}
+
+bool blenderReceive(const std::string& root, std::vector<MeshObject>& out, BridgeManifest* manifest,
+ std::string& message) {
+ if (root.empty()) {
+ message = "No Blender exchange folder (no user data folder)";
+ return false;
+ }
+ const std::string inbox = blenderInbox(root);
+ BridgeManifest m;
+ if (!readBridgeManifest(bridgeManifestPath(inbox), m, message)) {
+ if (message.rfind("Nothing", 0) == 0) message = "Nothing has been sent from Blender yet";
+ return false;
+ }
+ if (m.objects.empty()) {
+ message = "Blender sent no objects";
+ return false;
+ }
+ std::vector<MeshObject> objects;
+ std::string warnings;
+ for (const BridgeObject& b : m.objects) {
+ MeshObject obj;
+ obj.name = b.name.empty() ? "Object" : b.name;
+ std::string err;
+ if (!loadGoz(pathUtf8(utf8Path(inbox) / utf8Path(b.file)), obj.mesh, err)) {
+ message = "Cannot load \"" + obj.name + "\" from Blender: " + err;
+ return false;
+ }
+ if (!err.empty()) warnings += "; " + obj.name + ": " + err;
+ if (b.hasMatrix) {
+ // Into the scene: the add-on sends object-space meshes and each object's matrix_world.
+ const glm::dmat4 t = blenderMatrixToSculptForge(b.matrix);
+ for (glm::vec3& p : obj.mesh.positions) p = glm::vec3(t * glm::dvec4(glm::dvec3(p), 1.0));
+ obj.mesh.recomputeAllNormals();
+ }
+ objects.push_back(std::move(obj));
+ }
+ size_t triangles = 0;
+ for (const auto& o : objects) triangles += o.mesh.triangleCount();
+ message = "Received " + std::to_string(objects.size()) + (objects.size() == 1 ? " object" : " objects") +
+ " from Blender (" + std::to_string(triangles) + " triangles)" + warnings;
+ out = std::move(objects);
+ if (manifest) *manifest = std::move(m);
+ return true;
+}
+
+bool blenderSend(const std::vector<MeshObjectRef>& objects, const std::string& root, std::string& message,
+ std::vector<std::string>* sentNames, int64_t* revision) {
+ if (root.empty()) {
+ message = "No Blender exchange folder (no user data folder)";
+ return false;
+ }
+ if (objects.empty()) {
+ message = "Nothing visible to send to Blender";
+ return false;
+ }
+ const fs::path outbox = utf8Path(blenderOutbox(root));
+ std::error_code ec;
+ fs::create_directories(outbox, ec);
+ if (ec) {
+ message = "Cannot create " + pathUtf8(outbox) + ": " + ec.message();
+ return false;
+ }
+ BridgeManifest m;
+ m.revision = std::max<int64_t>(bridgeRevision(pathUtf8(outbox)), 0) + 1;
+ m.sender = "sculptforge";
+#ifdef SCULPTFORGE_VERSION
+ m.senderVersion = SCULPTFORGE_VERSION;
+#endif
+ const std::string prefix = "r" + std::to_string(m.revision) + "_";
+ std::vector<std::string> names;
+ for (size_t k = 0; k < objects.size(); ++k) {
+ // Blender's names for duplicates: Name, Name.001, Name.002...
+ const std::string wanted = objects[k].name.empty() ? "Object" : objects[k].name;
+ std::string name = wanted;
+ for (int n = 1; std::find(names.begin(), names.end(), name) != names.end(); ++n) {
+ char suffix[16];
+ std::snprintf(suffix, sizeof suffix, ".%03d", n);
+ name = wanted + suffix;
+ }
+ names.push_back(name);
+ char file[48];
+ std::snprintf(file, sizeof file, "%03zu.GoZ", k);
+ BridgeObject b;
+ b.name = name;
+ b.file = prefix + file;
+ GozWriteOptions o;
+ o.quads = objects[k].mesh->hasQuads(); // only kept quads: triangles of n-gons must stay triangles
+ std::string err;
+ if (!saveGoz(pathUtf8(outbox / utf8Path(b.file)), *objects[k].mesh, name, err, o)) {
+ message = "Cannot send \"" + name + "\" to Blender: " + err;
+ return false;
+ }
+ m.objects.push_back(std::move(b));
+ }
+ if (!writeAtomically(outbox / "manifest.json", writeBridgeManifest(m))) {
+ message = "Cannot write " + pathUtf8(outbox / "manifest.json");
+ return false;
+ }
+ // Earlier sends' files (the add-on has read them, or never will).
+ for (const auto& entry : fs::directory_iterator(outbox, ec)) {
+ const std::string n = pathUtf8(entry.path().filename());
+ if (n.size() > 1 && n[0] == 'r' && n.rfind(prefix, 0) != 0 && n.find('_') != std::string::npos) {
+ std::error_code rm;
+ fs::remove(entry.path(), rm); // may be open on Windows; the next send tries again
+ }
+ }
+ message = "Sent " + std::to_string(objects.size()) + (objects.size() == 1 ? " object" : " objects") +
+ " to Blender: press Receive in Blender's SculptForge panel if it doesn't update by itself";
+ if (sentNames) *sentNames = std::move(names);
+ if (revision) *revision = m.revision;
+ return true;
+}
+
+long long bridgeFileTime(const std::string& path) {
+ if (path.empty()) return 0;
+ std::error_code ec;
+ auto t = fs::last_write_time(utf8Path(path), ec);
+ return ec ? 0 : static_cast<long long>(t.time_since_epoch().count());
+}
+
+int64_t bridgeRevision(const std::string& folder) {
+ BridgeManifest m;
+ std::string err;
+ return readBridgeManifest(bridgeManifestPath(folder), m, err) ? m.revision : -1;
+}
+
+void writeBridgeAppInfo(const std::string& root, const std::string& executable, const std::string& version) {
+ if (root.empty() || executable.empty()) return;
+ const std::string text = "{\n \"path\": " + jsonQuote(executable) + ",\n \"version\": " + jsonQuote(version) + "\n}\n";
+ const fs::path p = utf8Path(root) / "app.json";
+ std::string old;
+ if (readFile(p, old) && old == text) return;
+ std::error_code ec;
+ fs::create_directories(utf8Path(root), ec);
+ writeAtomically(p, text);
+}
+
+void writeBridgeHeartbeat(const std::string& root, bool remove) {
+ if (root.empty()) return;
+ const fs::path p = utf8Path(root) / "alive.json";
+ std::error_code ec;
+ if (remove) {
+ fs::remove(p, ec);
+ return;
+ }
+#ifdef _WIN32
+ const long long pid = _getpid();
+#else
+ const long long pid = getpid();
+#endif
+ writeAtomically(p, "{\"pid\": " + std::to_string(pid) + ", \"time\": " + number(nowSeconds()) + "}\n");
+}
+
+} // namespace sf
diff --git a/src/io/BlenderBridge.h b/src/io/BlenderBridge.h
new file mode 100644
index 00000000..621da3b9
--- /dev/null
+++ b/src/io/BlenderBridge.h
@@ -0,0 +1,84 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The Blender bridge: SculptForge and the SculptForge add-on for Blender
+// (addons/blender) exchange meshes through a per-user folder, the way GoZ apps
+// do with ZBrush. Meshes travel as .GoZ files (io/GozIO.h: quads, UVs,
+// polypaint, mask, polygroups); a small JSON manifest per direction lists the
+// objects, their Blender names and transforms, and a revision number so each
+// side sees what is new. No sockets: each side polls the other's manifest.
+// docs/blender.md describes the folder and the manifest.
+//
+// <root>/to_sculptforge/manifest.json + r<rev>_<k>.GoZ written by Blender
+// <root>/to_blender/manifest.json + r<rev>_<k>.GoZ written by SculptForge
+// <root>/app.json where SculptForge is installed (the add-on starts it)
+// <root>/alive.json SculptForge's heartbeat, so the add-on knows it is running
+#pragma once
+
+#include "io/MeshObject.h"
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+// One object in a manifest.
+struct BridgeObject {
+ std::string name; // the Blender object name (UTF-8, exact): the SubTool's gozName
+ std::string file; // .GoZ file name inside the manifest's folder
+ bool hasMatrix = false; // the mesh is in object space and `matrix` places it in the scene
+ glm::dmat4 matrix{1.0}; // Blender's matrix_world (Z-up, metres; glm column-major)
+};
+
+struct BridgeManifest {
+ int64_t revision = 0; // changes on every send (each side keeps the last one it loaded)
+ std::string sender; // "blender" or "sculptforge"
+ std::string senderVersion;
+ std::vector<BridgeObject> objects;
+};
+
+// The exchange folder: $SCULPTFORGE_BLENDER_EXCHANGE, else <app data>/blender
+// (~/.local/share/SculptForge/SculptForge/blender, %APPDATA%\SculptForge\SculptForge\blender,
+// ~/Library/Application Support/SculptForge/SculptForge/blender). The add-on computes the same path.
+std::string blenderExchangeRoot();
+std::string blenderInbox(const std::string& root); // <root>/to_sculptforge
+std::string blenderOutbox(const std::string& root); // <root>/to_blender
+std::string bridgeManifestPath(const std::string& folder); // <folder>/manifest.json
+
+bool parseBridgeManifest(const std::string& text, BridgeManifest& out, std::string& error);
+std::string writeBridgeManifest(const BridgeManifest& manifest);
+bool readBridgeManifest(const std::string& path, BridgeManifest& out, std::string& error);
+
+// Blender is Z-up, SculptForge Y-up, both in metres: p_sf = (x, z, -y). These convert points and
+// Blender object matrices (M_sf = A * M_blender * A^-1).
+glm::dvec3 blenderToSculptForge(const glm::dvec3& p);
+glm::dvec3 sculptForgeToBlender(const glm::dvec3& p);
+glm::dmat4 blenderMatrixToSculptForge(const glm::dmat4& m);
+
+// Loads what Blender sent (<root>/to_sculptforge): every object's .GoZ, moved by its matrix into place, named
+// after its Blender object. `manifest` receives the manifest (for its revision).
+bool blenderReceive(const std::string& root, std::vector<MeshObject>& out, BridgeManifest* manifest,
+ std::string& message);
+
+// Writes the objects to <root>/to_blender (world space, so the add-on puts each mesh back into its object's own
+// space) with the next revision, and removes the files of earlier sends. Names are kept exactly (duplicates
+// get .001, .002... as Blender would name them); `sentNames` receives them.
+bool blenderSend(const std::vector<MeshObjectRef>& objects, const std::string& root, std::string& message,
+ std::vector<std::string>* sentNames = nullptr, int64_t* revision = nullptr);
+
+// Modification time of a file (0 when missing), for cheap polling.
+long long bridgeFileTime(const std::string& path);
+// The revision of the manifest in `folder`, or -1 when there is none.
+int64_t bridgeRevision(const std::string& folder);
+
+// Records where SculptForge is installed (<root>/app.json), so the add-on can start it. Writes only when the
+// content changes.
+void writeBridgeAppInfo(const std::string& root, const std::string& executable, const std::string& version);
+// The heartbeat (<root>/alive.json: process id and time); the add-on treats SculptForge as running while it
+// is fresh. `remove` deletes it (on exit).
+void writeBridgeHeartbeat(const std::string& root, bool remove = false);
+
+} // namespace sf
diff --git a/src/io/BlenderCommands.cpp b/src/io/BlenderCommands.cpp
new file mode 100644
index 00000000..03ed89ab
--- /dev/null
+++ b/src/io/BlenderCommands.cpp
@@ -0,0 +1,45 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/BlenderCommands.h"
+
+#include "io/BlenderBridge.h"
+#include "io/GozCommands.h"
+
+namespace sf {
+
+void registerBlenderCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+
+ reg.add({"blender_send",
+ "Send the visible SubTools to Blender through the SculptForge add-on's exchange folder. Objects that "
+ "came from Blender update in place there (keeping their transform, materials and modifiers); the "
+ "others become new objects.",
+ {{"folder", T::String, "Exchange folder. Default: the per-user one the add-on uses.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string root = argString(a, "folder", blenderExchangeRoot());
+ std::vector<int> indices;
+ const auto objects = gozObjects(doc, indices);
+ std::vector<std::string> sent;
+ std::string msg;
+ if (!blenderSend(objects, root, msg, &sent)) return {false, msg};
+ // Blender's next send of these objects updates the same SubTools.
+ for (size_t k = 0; k < sent.size() && k < indices.size(); ++k) subtoolGozName(doc, indices[k]) = sent[k];
+ return {true, msg};
+ }});
+
+ reg.add({"blender_receive",
+ "Load what Blender last sent with the SculptForge add-on. Each object updates the SubTool it was sent "
+ "from (an undoable step on that SubTool) or becomes a new SubTool, placed as it is in Blender's scene; "
+ "the first object replaces a fresh scene.",
+ {{"folder", T::String, "Exchange folder. Default: the per-user one the add-on uses.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<MeshObject> objects;
+ std::string msg;
+ if (!blenderReceive(argString(a, "folder", blenderExchangeRoot()), objects, nullptr, msg))
+ return {false, msg};
+ receiveObjects(doc, objects, "Receive from Blender", true);
+ return {true, msg};
+ }});
+}
+
+} // namespace sf
diff --git a/src/io/BlenderCommands.h b/src/io/BlenderCommands.h
new file mode 100644
index 00000000..62e0513d
--- /dev/null
+++ b/src/io/BlenderCommands.h
@@ -0,0 +1,14 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Blender bridge commands: blender_send and blender_receive (io/BlenderBridge.h).
+// Registered by CommandRegistry's constructor.
+#pragma once
+
+#include "core/Commands.h"
+
+namespace sf {
+
+void registerBlenderCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/io/GozCommands.cpp b/src/io/GozCommands.cpp
index cfb34f1e..3e69dbfd 100644
--- a/src/io/GozCommands.cpp
+++ b/src/io/GozCommands.cpp
@@ -36,13 +36,12 @@ std::string sendName(const Document& doc, const Args& a) {
return name;
}
-// The GoZ name of SubTool `i` (active or not).
+} // namespace
+
std::string& subtoolGozName(Document& doc, int i) {
return i == doc.activeSubtool ? doc.gozName : doc.subtools[size_t(i)].gozName;
}
-// Visible SubTools with triangles, as the GoZ objects to write: the name each came from ZBrush with,
-// else its SubTool name. `indices` receives the SubTool of each object.
std::vector<MeshObjectRef> gozObjects(Document& doc, std::vector<int>& indices) {
std::vector<MeshObjectRef> out;
for (int i = 0; i < doc.subtoolCount(); ++i) {
@@ -54,7 +53,36 @@ std::vector<MeshObjectRef> gozObjects(Document& doc, std::vector<int>& indices)
return out;
}
-} // namespace
+// Each object updates the SubTool with its GoZ name (undoable), or the single SubTool of a fresh scene, or
+// becomes a new SubTool. The active SubTool stays selected.
+void receiveObjects(Document& doc, std::vector<MeshObject>& objects, const std::string& undoLabel, bool renameFresh) {
+ const int original = doc.activeSubtool; // new SubTools go to the end, so this index stays valid
+ auto findGoz = [&](const std::string& name) {
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ if (!name.empty() && subtoolGozName(doc, i) == name) return i;
+ return -1;
+ };
+ for (size_t k = 0; k < objects.size(); ++k) {
+ MeshObject& obj = objects[k];
+ int target = findGoz(obj.name);
+ // The first object sent into a fresh scene (one SubTool, not from ZBrush or Blender) replaces it.
+ const bool fresh = target < 0 && k == 0 && doc.subtoolCount() == 1 && doc.gozName.empty();
+ if (fresh) target = 0;
+ if (target < 0) {
+ const int i = doc.addSubtool(std::move(obj.mesh), obj.name, false);
+ subtoolGozName(doc, i) = obj.name;
+ continue;
+ }
+ doc.selectSubtool(target);
+ if (doc.mesh.triangleCount()) doc.replaceMeshUndoable(std::move(obj.mesh), undoLabel);
+ else doc.replaceActiveMesh(std::move(obj.mesh));
+ doc.gozName = obj.name;
+ if (fresh && (renameFresh || objects.size() > 1)) doc.activeSubtoolInfo().name = doc.uniqueSubtoolName(obj.name);
+ }
+ doc.selectSubtool(original);
+ doc.path.clear();
+ doc.modified = true;
+}
void registerGozCommands(CommandRegistry& reg) {
using T = ParamSpec::Type;
@@ -154,32 +182,7 @@ void registerGozCommands(CommandRegistry& reg) {
std::vector<MeshObject> objects;
std::string msg;
if (!gozReceive(argString(a, "folder"), objects, msg)) return {false, msg};
- const int original = doc.activeSubtool; // new SubTools go to the end, so this index stays valid
- auto findGoz = [&](const std::string& name) {
- for (int i = 0; i < doc.subtoolCount(); ++i)
- if (!name.empty() && subtoolGozName(doc, i) == name) return i;
- return -1;
- };
- for (size_t k = 0; k < objects.size(); ++k) {
- MeshObject& obj = objects[k];
- int target = findGoz(obj.name);
- // The first object sent into a fresh scene (one SubTool, not from ZBrush) replaces it.
- const bool fresh = target < 0 && k == 0 && doc.subtoolCount() == 1 && doc.gozName.empty();
- if (fresh) target = 0;
- if (target < 0) {
- const int i = doc.addSubtool(std::move(obj.mesh), obj.name, false);
- subtoolGozName(doc, i) = obj.name;
- continue;
- }
- doc.selectSubtool(target);
- if (doc.mesh.triangleCount()) doc.replaceMeshUndoable(std::move(obj.mesh), "Receive from ZBrush");
- else doc.replaceActiveMesh(std::move(obj.mesh));
- doc.gozName = obj.name;
- if (fresh && objects.size() > 1) doc.activeSubtoolInfo().name = doc.uniqueSubtoolName(obj.name);
- }
- doc.selectSubtool(original);
- doc.path.clear();
- doc.modified = true;
+ receiveObjects(doc, objects, "Receive from ZBrush", false);
return {true, msg};
}});
diff --git a/src/io/GozCommands.h b/src/io/GozCommands.h
index 0bca32fd..924eda92 100644
--- a/src/io/GozCommands.h
+++ b/src/io/GozCommands.h
@@ -6,9 +6,25 @@
#pragma once
#include "core/Commands.h"
+#include "io/MeshObject.h"
+
+#include <string>
+#include <vector>
namespace sf {
void registerGozCommands(CommandRegistry& registry);
+// Shared with the Blender bridge (io/BlenderCommands.cpp):
+// The GoZ name of SubTool `i` (active or not): the object it came from (ZBrush or Blender) or was sent as.
+std::string& subtoolGozName(Document& doc, int i);
+// Visible SubTools with triangles as objects to send: the GoZ name each came with, else its SubTool name.
+// `indices` receives the SubTool of each object.
+std::vector<MeshObjectRef> gozObjects(Document& doc, std::vector<int>& indices);
+// Puts received objects into the scene: each updates the SubTool with its GoZ name (an undoable `undoLabel` step
+// in that SubTool's history), the first one replaces a fresh scene (one SubTool that came from nowhere, renamed
+// after the object when `renameFresh` or several objects arrive), the others become new SubTools. The active
+// SubTool stays selected.
+void receiveObjects(Document& doc, std::vector<MeshObject>& objects, const std::string& undoLabel, bool renameFresh);
+
} // namespace sf
diff --git a/tests/blender/test_exchange.py b/tests/blender/test_exchange.py
new file mode 100644
index 00000000..994dc1cf
--- /dev/null
+++ b/tests/blender/test_exchange.py
@@ -0,0 +1,274 @@
+# SculptForge - Blender bridge: the add-on's exchange code (no Blender needed, only numpy)
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# python3 tests/blender/test_exchange.py [--cli path/to/sculptforge-cli]
+#
+# With --cli, meshes written the way the add-on writes them go through SculptForge (blender_receive, then
+# blender_send) and must come back identical: positions, faces and their winding, UVs, polypaint, mask and
+# polygroups, for objects with a rotation, a scale, a negative scale (mirrored) and n-gons. CMake runs this
+# when it finds Python 3 with numpy (ctest -R blender_exchange).
+import argparse
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+# exchange.py alone: the package's __init__ needs bpy.
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "addons", "blender", "sculptforge_bridge"))
+import exchange # noqa: E402
+
+N = exchange.NO_INDEX
+failures = []
+
+
+def check(cond, what):
+ if not cond:
+ failures.append(what)
+ print("FAIL:", what)
+
+
+# ---------------------------------------------------------------------------- a Blender-like mesh
+
+
+def grid_with_ngon():
+ """A 3x3 grid of quads (z = bumpy), a pentagon and a triangle hanging off it, as Blender stores
+ polygons: vertex positions, loop_start / loop_total and the loops' vertices."""
+ co = []
+ for j in range(4):
+ for i in range(4):
+ co.append((i * 0.5, j * 0.5, 0.1 * np.sin(i + 2 * j)))
+ polys = []
+ for j in range(3):
+ for i in range(3):
+ a = j * 4 + i
+ polys.append([a, a + 1, a + 5, a + 4])
+ base = len(co)
+ co += [(2.0, 0.0, 0.2), (2.4, 0.6, 0.3), (2.1, 1.2, 0.25)]
+ polys.append([3, base, base + 1, base + 2, 7]) # pentagon on the grid's right edge
+ polys.append([7, base + 2, 11]) # a triangle
+ starts, totals, loop_vert = [], [], []
+ for p in polys:
+ starts.append(len(loop_vert))
+ totals.append(len(p))
+ loop_vert += p
+ return np.array(co), np.array(starts), np.array(totals), np.array(loop_vert)
+
+
+def only_ngons():
+ """A hexagon and two triangles: a mesh with no quads at all (SculptForge must not pair its fans)."""
+ co = [(np.cos(a), np.sin(a), 0.0) for a in np.linspace(0, 2 * np.pi, 7)[:-1]] + [(0.0, 0.0, 1.0), (1.5, 0.0, 0.5)]
+ polys = [[0, 1, 2, 3, 4, 5], [0, 6, 1], [5, 7, 0]]
+ starts, totals, loop_vert = [], [], []
+ for p in polys:
+ starts.append(len(loop_vert))
+ totals.append(len(p))
+ loop_vert += p
+ return np.array(co), np.array(starts), np.array(totals), np.array(loop_vert)
+
+
+def rotation(axis, degrees):
+ a = np.radians(degrees)
+ c, s = np.cos(a), np.sin(a)
+ x, y, z = np.asarray(axis, float) / np.linalg.norm(axis)
+ return np.array([[c + x * x * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s],
+ [y * x * (1 - c) + z * s, c + y * y * (1 - c), y * z * (1 - c) - x * s],
+ [z * x * (1 - c) - y * s, z * y * (1 - c) + x * s, c + z * z * (1 - c)]])
+
+
+def matrix(rot, scale, translate):
+ m = np.eye(4)
+ m[:3, :3] = rot @ np.diag(scale)
+ m[:3, 3] = translate
+ return m
+
+
+def object_arrays(mesh, mirrored, seed):
+ co, starts, totals, loop_vert = mesh
+ rng = np.random.default_rng(seed)
+ loops, face_poly = exchange.polygon_corners(starts, totals, mirrored)
+ faces = exchange.faces_from_loops(loops, loop_vert)
+ # Values that survive the file exactly: UVs in float32, colours in bytes, mask in 1/65535 steps.
+ loop_uv = rng.random((len(loop_vert), 2)).astype(np.float32).astype(np.float64)
+ colors = rng.integers(0, 256, (len(co), 3)) / 255.0
+ mask = rng.integers(0, 65536, len(co)) / 65535.0
+ polygroups = rng.integers(0, 5, len(starts))
+ return {"positions": co, "faces": faces, "uvs": loop_uv[np.maximum(loops, 0)], "colors": colors,
+ "mask": mask, "groups": polygroups[face_poly]}, loops
+
+
+# ---------------------------------------------------------------------------- unit tests
+
+
+def test_polygon_corners():
+ co, starts, totals, loop_vert = grid_with_ngon()
+ loops, face_poly = exchange.polygon_corners(starts, totals)
+ check(len(loops) == 9 + 3 + 1, "9 quads, a pentagon as 3 triangles, 1 triangle")
+ check(list(loops[9]) == [36, 37, 38, -1] and list(loops[10]) == [36, 38, 39, -1] and list(loops[11]) == [36, 39, 40, -1],
+ "pentagon fan (0, i, i+1)")
+ check(list(face_poly[9:13]) == [9, 9, 9, 10], "fan faces point at their polygon")
+ m, _ = exchange.polygon_corners(starts, totals, mirrored=True)
+ check(list(m[0]) == [0, 3, 2, 1], "mirrored quad reversed")
+ check(list(m[12]) == [41, 43, 42, -1], "mirrored triangle reversed")
+ # Mirrored fan = fan of the reversed polygon (0, 4, 3, 2, 1).
+ check([list(r) for r in m[9:12]] == [[36, 40, 39, -1], [36, 39, 38, -1], [36, 38, 37, -1]], "mirrored pentagon fan")
+
+
+def test_canonical_and_reverse():
+ f = np.array([[5, 2, 7, 1], [4, 9, 3, N]], dtype=np.uint32)
+ c, r = exchange.canonical_faces(f)
+ check(c.tolist() == [[1, 5, 2, 7], [3, 4, 9, N]] and r.tolist() == [3, 2], "canonical rotation keeps winding")
+ rev, data = exchange.reverse_faces(f, np.arange(8).reshape(2, 4))
+ check(rev.tolist() == [[5, 1, 7, 2], [4, 3, 9, N]], "reverse_faces")
+ check(data.tolist() == [[0, 3, 2, 1], [4, 6, 5, 7]], "reverse_faces moves corner data along")
+ check(exchange.same_topology(f, np.roll(f[:1], 1, axis=1).tolist() + [[9, 3, 4, N]]), "rotated faces are the same")
+ check(not exchange.same_topology(f, rev), "reversed faces are not")
+ rotated = np.array([[7, 1, 5, 2], [3, 4, 9, N]], dtype=np.uint32)
+ cm = exchange.corner_map(f, rotated)
+ check(all(f[i, s] == rotated[i, cm[i, s]] for i in range(2) for s in range(3)) and f[0, 3] == rotated[0, cm[0, 3]],
+ "corner_map finds each corner's vertex")
+
+
+def test_goz_round_trip(tmp):
+ arrays, _ = object_arrays(grid_with_ngon(), False, 1)
+ path = os.path.join(tmp, "t.GoZ")
+ exchange.write_goz(path, "Grid Ünïcode.001", **arrays)
+ g = exchange.read_goz(path)
+ check(g.name == "Grid_n_code_001", "GoZ name escaped like GoB (got %r)" % g.name)
+ check(np.allclose(g.positions, arrays["positions"], atol=1e-6), "GoZ positions")
+ check(np.array_equal(g.faces, arrays["faces"]), "GoZ faces")
+ tri = arrays["faces"][:, 3] == N
+ check(np.allclose(g.uvs[~tri], arrays["uvs"][~tri]) and np.allclose(g.uvs[tri, :3], arrays["uvs"][tri, :3]), "GoZ UVs")
+ check(np.allclose(g.colors, arrays["colors"]), "GoZ polypaint")
+ check(np.allclose(g.mask, arrays["mask"], atol=1e-9), "GoZ mask")
+ check(np.array_equal(g.groups, arrays["groups"]), "GoZ polygroups")
+ with open(path, "rb") as f:
+ head = f.read(64)
+ check(head.startswith(b"GoZb 1.0 ZBrush GoZ Binary......"), "GoZ header as GoB writes it")
+
+
+def test_manifest(tmp):
+ folder = os.path.join(tmp, "m")
+ check(exchange.revision(folder) == -1, "no manifest yet")
+ r1 = exchange.write_manifest(folder, [{"name": "A", "file": "r1_000.GoZ"}])
+ open(os.path.join(folder, "r1_000.GoZ"), "wb").close()
+ check(exchange.next_file_prefix(folder) == "r2_", "next prefix")
+ open(os.path.join(folder, "r2_000.GoZ"), "wb").close()
+ r2 = exchange.write_manifest(folder, [{"name": "A", "file": "r2_000.GoZ"}])
+ check((r1, r2) == (1, 2), "revisions count up")
+ check(not os.path.exists(os.path.join(folder, "r1_000.GoZ")), "old files removed")
+ check(os.path.exists(os.path.join(folder, "r2_000.GoZ")), "current files kept")
+ with open(exchange.manifest_path(folder), "w") as f:
+ f.write('{"format": "sculptforge-bridge", "objects": [{"name": "x", "file": "../evil"}]}')
+ try:
+ exchange.read_manifest(folder)
+ check(False, "a manifest naming ../evil is refused")
+ except ValueError:
+ pass
+
+
+# ---------------------------------------------------------------------------- through SculptForge
+
+
+def test_round_trip_through_sculptforge(tmp, cli):
+ root = os.path.join(tmp, "exchange")
+ out = exchange.outbox(root)
+ os.makedirs(out)
+ rot = rotation((1.0, 2.0, 0.5), 37.0)
+ objects = [
+ ("Grid", grid_with_ngon(), matrix(rot, (1.0, 1.0, 1.0), (0.3, -1.2, 2.0))),
+ ("Grid.scaled", grid_with_ngon(), matrix(rot.T, (2.0, 0.5, 3.0), (-4.0, 1.0, 0.0))),
+ ("Mirrored", grid_with_ngon(), matrix(np.eye(3), (-1.0, 1.0, 1.0), (1.0, 1.0, 1.0))),
+ ("Hexagon ünïcode", only_ngons(), matrix(rotation((0, 0, 1), 90), (1, 1, 1), (0, 0, 5))),
+ ]
+ sent = {}
+ entries = []
+ for k, (name, mesh, m) in enumerate(objects):
+ mirrored = np.linalg.det(m[:3, :3]) < 0
+ arrays, _ = object_arrays(mesh, mirrored, k + 10)
+ file = "r1_%03d.GoZ" % k
+ exchange.write_goz(os.path.join(out, file), name, **arrays)
+ entries.append({"name": name, "file": file, "matrix_world": m.tolist()})
+ sent[name] = (mesh, m, arrays)
+ exchange.write_manifest(out, entries, "test")
+
+ r = subprocess.run([cli, "-c", 'blender_receive folder="%s"; blender_send folder="%s"' % (root, root)],
+ capture_output=True, text=True)
+ print(r.stdout.strip())
+ check(r.returncode == 0, "sculptforge-cli ran (%s)" % r.stderr.strip())
+ if r.returncode:
+ return
+ manifest = exchange.read_manifest(exchange.inbox(root))
+ names = [o["name"] for o in manifest["objects"]]
+ check(names == [o[0] for o in objects], "every object comes back under its Blender name (got %s)" % names)
+ for entry in manifest["objects"]:
+ name = entry["name"]
+ if name not in sent:
+ continue
+ mesh, m, arrays = sent[name]
+ g = exchange.read_goz(os.path.join(exchange.inbox(root), entry["file"]))
+ # What the add-on does on receive (update_object): into object space, and the faces compared with the
+ # ones it sent (reversed for a mirrored object).
+ local = exchange.transform_points(np.linalg.inv(m), g.positions)
+ mirrored = np.linalg.det(m[:3, :3]) < 0
+ co, starts, totals, loop_vert = mesh
+ loops, face_poly = exchange.polygon_corners(starts, totals, mirrored)
+ expect = exchange.faces_from_loops(loops, loop_vert)
+ same = exchange.same_topology(expect, g.faces)
+ check(same, "%s: same faces and winding" % name)
+ err = np.abs(local - co).max()
+ check(err < 1e-5, "%s: positions back in object space (max error %.2g)" % (name, err))
+ # World placement in SculptForge's file: Blender world space.
+ world = exchange.transform_points(m, co)
+ check(np.abs(g.positions - world).max() < 1e-5, "%s: placed in the scene as in Blender" % name)
+ # Placed with a negative scale, the reversed faces wind outwards again: the normals SculptForge sees
+ # point the way Blender's do (here: the grid's first quad, whose Blender normal is +z before the matrix).
+ f0 = g.faces[0]
+ n = np.cross(g.positions[f0[1]] - g.positions[f0[0]], g.positions[f0[2]] - g.positions[f0[0]])
+ p = co[mesh[3][mesh[1][0]:mesh[1][0] + 3]]
+ nb = np.cross(p[1] - p[0], p[2] - p[0])
+ expect_n = np.linalg.inv(m[:3, :3]).T @ nb
+ check(np.dot(n, expect_n) > 0, "%s: winding faces outwards in SculptForge" % name)
+ if not same:
+ continue
+ cm = exchange.corner_map(expect, g.faces)
+ # Per loop: the UV that was sent and the one that came back.
+ loop_uv_sent = np.zeros((len(loop_vert), 2))
+ loop_uv_sent[loops[loops >= 0]] = arrays["uvs"][loops >= 0]
+ back = np.take_along_axis(g.uvs, cm[:, :, None].repeat(2, axis=2), axis=1)
+ loop_uv_back = np.zeros_like(loop_uv_sent)
+ loop_uv_back[loops[loops >= 0]] = back[loops >= 0]
+ check(np.allclose(loop_uv_back, loop_uv_sent, atol=1e-6), "%s: UVs" % name)
+ check(g.colors is not None and np.allclose(g.colors, arrays["colors"]), "%s: polypaint" % name)
+ check(g.mask is not None and np.allclose(g.mask, arrays["mask"], atol=1e-9), "%s: mask" % name)
+ check(g.groups is not None and np.array_equal(g.groups, arrays["groups"]), "%s: polygroups" % name)
+
+ # A second send from SculptForge: the next revision, the previous files gone.
+ r = subprocess.run([cli, "-c", 'blender_receive folder="%s"; blender_send folder="%s"' % (root, root)],
+ capture_output=True, text=True)
+ check(exchange.revision(exchange.inbox(root)) == 2, "SculptForge's revision counts up")
+ left = sorted(f for f in os.listdir(exchange.inbox(root)) if f.startswith("r1_"))
+ check(not left, "SculptForge removes its earlier files (left: %s)" % left)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--cli", help="sculptforge-cli, for the round trip through SculptForge")
+ args = ap.parse_args()
+ with tempfile.TemporaryDirectory() as tmp:
+ test_polygon_corners()
+ test_canonical_and_reverse()
+ test_goz_round_trip(tmp)
+ test_manifest(tmp)
+ if args.cli:
+ test_round_trip_through_sculptforge(tmp, args.cli)
+ if failures:
+ print("%d check(s) failed" % len(failures))
+ return 1
+ print("all checks passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/blender/test_in_blender.py b/tests/blender/test_in_blender.py
new file mode 100644
index 00000000..807d0e93
--- /dev/null
+++ b/tests/blender/test_in_blender.py
@@ -0,0 +1,160 @@
+# SculptForge - Blender bridge: the add-on inside a real Blender (4.2+), headless
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# blender -b --factory-startup -noaudio --python-exit-code 1 --python tests/blender/test_in_blender.py -- \
+# --cli build/sculptforge-cli
+#
+# Sends a small scene to SculptForge (sculptforge-cli stands in for the app: blender_receive, then
+# blender_send), receives it back and checks that the objects are unchanged: positions, n-gons,
+# transforms, materials, modifiers, UVs, colours, mask and face sets. Then a topology change (subdivide)
+# and a new SubTool come back as a rebuilt mesh and a new object. CMake runs it when `blender` is found.
+import os
+import subprocess
+import sys
+import tempfile
+
+import bpy
+import numpy as np
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "..", "addons", "blender"))
+
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+CLI = argv[argv.index("--cli") + 1] if "--cli" in argv else "sculptforge-cli"
+ROOT = tempfile.mkdtemp(prefix="sf_blender_test_")
+os.environ["SCULPTFORGE_BLENDER_EXCHANGE"] = ROOT
+
+import addon_utils # noqa: E402
+
+# Enabled as an add-on (so it has its preferences) straight from the source folder on sys.path.
+addon_utils.enable("sculptforge_bridge", default_set=True)
+import sculptforge_bridge as bridge # noqa: E402
+from sculptforge_bridge import exchange # noqa: E402
+
+failures = []
+
+
+def check(cond, what):
+ print(("ok " if cond else "FAIL ") + what)
+ if not cond:
+ failures.append(what)
+
+
+def arr(collection, prop, width, dtype=np.float64):
+ out = np.empty(len(collection) * width, dtype=dtype)
+ collection.foreach_get(prop, out)
+ return out.reshape(-1, width) if width > 1 else out
+
+
+def snapshot(obj):
+ me = obj.data
+ s = {"co": arr(me.vertices, "co", 3), "matrix": np.array(obj.matrix_world),
+ "polys": [tuple(p.vertices) for p in me.polygons], "materials": [m.name for m in me.materials],
+ "modifiers": [(m.name, m.show_viewport) for m in obj.modifiers]}
+ if me.uv_layers.active:
+ s["uv"] = arr(me.uv_layers.active.data, "uv", 2)
+ if me.color_attributes.active_color:
+ s["color"] = arr(me.color_attributes.active_color.data, "color_srgb", 4)
+ if me.attributes.get(".sculpt_face_set"):
+ s["sets"] = arr(me.attributes[".sculpt_face_set"].data, "value", 1, np.int32)
+ if me.attributes.get(".sculpt_mask"):
+ s["mask"] = arr(me.attributes[".sculpt_mask"].data, "value", 1)
+ return s
+
+
+def sculptforge(commands):
+ r = subprocess.run([CLI, "-c", "; ".join(c + ' folder="%s"' % ROOT if c.startswith("blender_") else c for c in commands)],
+ capture_output=True, text=True)
+ print(r.stdout.strip())
+ check(r.returncode == 0, "sculptforge-cli: " + "; ".join(commands) + (" (%s)" % r.stderr.strip() if r.returncode else ""))
+
+
+def build_scene():
+ for obj in list(bpy.data.objects): # (not read_factory_settings: it would disable the add-on)
+ bpy.data.objects.remove(obj)
+ mat = bpy.data.materials.new("Clay")
+ # A cube (quads, UVs) with a live modifier, rotated and scaled.
+ bpy.ops.mesh.primitive_cube_add(size=2.0, location=(1.0, 2.0, 0.5), rotation=(0.3, 0.2, 0.9))
+ cube = bpy.context.active_object
+ cube.name = "Box"
+ cube.scale = (1.0, 2.0, 0.5)
+ cube.data.materials.append(mat)
+ cube.modifiers.new("Bevel", "BEVEL")
+ me = cube.data
+ colors = me.color_attributes.new("Paint", "FLOAT_COLOR", "POINT")
+ rgba = np.random.default_rng(1).integers(0, 256, (len(me.vertices), 4)) / 255.0
+ rgba[:, 3] = 1.0
+ colors.data.foreach_set("color_srgb", rgba.astype(np.float32).ravel())
+ me.color_attributes.active_color = colors
+ sets = me.attributes.new(".sculpt_face_set", "INT", "FACE")
+ sets.data.foreach_set("value", np.array([1, 1, 2, 2, 3, 3], dtype=np.int32))
+ mask = me.attributes.new(".sculpt_mask", "FLOAT", "POINT")
+ mask.data.foreach_set("value", (np.arange(len(me.vertices)) / 7.0).astype(np.float32))
+ # An n-gon disc, mirrored.
+ bpy.ops.mesh.primitive_circle_add(vertices=7, radius=1.0, fill_type="NGON", location=(-3.0, 0.0, 1.0))
+ disc = bpy.context.active_object
+ disc.name = "Disc ü"
+ disc.scale = (-1.0, 1.0, 1.0)
+ # Monkey: triangles and quads, with UVs.
+ bpy.ops.mesh.primitive_monkey_add(location=(0.0, -3.0, 0.0))
+ bpy.context.active_object.name = "Suzanne"
+ bpy.ops.object.select_all(action="SELECT")
+ return ["Box", "Disc ü", "Suzanne"]
+
+
+def main():
+ check(bridge.prefs() is not None, "add-on enabled with its preferences")
+ # No real SculptForge here: never start one.
+ exchange.find_sculptforge = lambda root, override="": ""
+ names = build_scene()
+ before = {n: snapshot(bpy.data.objects[n]) for n in names}
+
+ check(bpy.ops.sculptforge.send() == {"FINISHED"}, "Send to SculptForge")
+ manifest = exchange.read_manifest(exchange.outbox(ROOT))
+ check([o["name"] for o in manifest["objects"]] == names, "manifest lists the selected objects by name")
+
+ # SculptForge loads them and sends them straight back: everything must be as it was.
+ sculptforge(["blender_receive", "blender_send"])
+ check(bpy.ops.sculptforge.receive() == {"FINISHED"}, "Receive from SculptForge: " + bridge.state.message)
+ check("3 updated" in bridge.state.message, "all three updated in place")
+ check(sorted(o.name for o in bpy.data.objects) == sorted(names), "no objects added")
+ for n in names:
+ a, b = before[n], snapshot(bpy.data.objects[n])
+ check(np.abs(a["co"] - b["co"]).max() < 1e-5, n + ": positions")
+ check(np.allclose(a["matrix"], b["matrix"]), n + ": transform kept")
+ check(a["polys"] == b["polys"], n + ": polygons (n-gons included) kept")
+ check(a["materials"] == b["materials"] and a["modifiers"] == b["modifiers"], n + ": materials and modifiers kept")
+ for key in ("uv", "color", "sets"):
+ if key in a:
+ check(key in b and np.allclose(a[key], b[key], atol=1e-6), n + ": " + key)
+ if "mask" in a:
+ check("mask" in b and np.allclose(a["mask"], b["mask"], atol=1e-4), n + ": mask")
+
+ # Subdivide the box in SculptForge and add a SubTool: the box is rebuilt (transform, material and modifier
+ # kept), the new SubTool becomes a new object.
+ sculptforge(["blender_receive", "subtool_select name=Box", "subdivide", "subtool_append type=cube name=Extra",
+ "blender_send"])
+ check(bpy.ops.sculptforge.receive() == {"FINISHED"}, "Receive the changed scene: " + bridge.state.message)
+ box = bpy.data.objects["Box"]
+ check(len(box.data.polygons) > len(before["Box"]["polys"]), "Box: new topology")
+ check(np.allclose(np.array(box.matrix_world), before["Box"]["matrix"]), "Box: transform kept")
+ check([m.name for m in box.data.materials] == ["Clay"] and box.modifiers.get("Bevel") is not None,
+ "Box: material and modifier kept")
+ check("Extra" in bpy.data.objects, "the new SubTool is a new object")
+
+ # Apply modifiers: the result is sent, and the modifier is turned off when it comes back.
+ bridge.prefs().modifiers = "APPLY"
+ bpy.ops.object.select_all(action="DESELECT")
+ box.select_set(True)
+ bpy.context.view_layer.objects.active = box
+ check(bpy.ops.sculptforge.send() == {"FINISHED"}, "send with modifiers applied")
+ sculptforge(["blender_receive", "blender_send"])
+ bpy.ops.sculptforge.receive()
+ check(not box.modifiers["Bevel"].show_viewport, "the applied modifier is turned off")
+
+ addon_utils.disable("sculptforge_bridge")
+ print("%d failure(s)" % len(failures))
+ sys.exit(1 if failures else 0)
+
+
+main()
diff --git a/tests/test_blender_bridge.cpp b/tests/test_blender_bridge.cpp
new file mode 100644
index 00000000..3d1c101c
--- /dev/null
+++ b/tests/test_blender_bridge.cpp
@@ -0,0 +1,220 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The Blender bridge (io/BlenderBridge.h): manifest parsing, axes, and a round trip through the exchange
+// folder with blender_receive / blender_send. tests/blender/test_exchange.py does the same from the add-on's
+// side (its Python writer and reader against sculptforge-cli).
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "io/BlenderBridge.h"
+#include "io/GozIO.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <cmath>
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+
+using namespace sf;
+
+namespace {
+
+namespace fs = std::filesystem;
+
+void writeText(const fs::path& p, const std::string& text) {
+ fs::create_directories(p.parent_path());
+ std::ofstream f(p, std::ios::binary);
+ f << text;
+}
+
+float maxDistance(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {
+ if (a.size() != b.size()) return 1e30f;
+ float d = 0.0f;
+ for (size_t i = 0; i < a.size(); ++i) d = std::max(d, glm::length(a[i] - b[i]));
+ return d;
+}
+
+// A Blender matrix_world: rotation, non-uniform scale, translation (Z-up).
+glm::dmat4 blenderMatrix(double sx) {
+ glm::dmat4 m = glm::translate(glm::dmat4(1.0), glm::dvec3(1.5, -2.0, 0.75));
+ m = glm::rotate(m, glm::radians(33.0), glm::normalize(glm::dvec3(1.0, 2.0, 0.5)));
+ return glm::scale(m, glm::dvec3(sx, 0.5, 1.25));
+}
+
+std::string matrixJson(const glm::dmat4& m) {
+ std::string s = "[";
+ for (int r = 0; r < 4; ++r) {
+ s += r ? ", [" : "[";
+ for (int c = 0; c < 4; ++c) {
+ char v[40];
+ std::snprintf(v, sizeof v, "%.17g", m[c][r]);
+ s += (c ? ", " : "") + std::string(v);
+ }
+ s += "]";
+ }
+ return s + "]";
+}
+
+} // namespace
+
+TEST(blender_manifest_parse_and_write) {
+ BridgeManifest m;
+ std::string err;
+ const std::string text = R"({"format": "sculptforge-bridge", "version": 1, "revision": 7, "sender": "blender",
+ "sender_version": "4.2.3", "objects": [
+ {"name": "Suzanne.001 ü", "file": "r7_000.GoZ",
+ "matrix_world": [[1, 0, 0, 5], [0, 0, -1, 6], [0, 1, 0, 7], [0, 0, 0, 1]]},
+ {"name": "Plain", "file": "r7_001.GoZ"}]})";
+ CHECK(parseBridgeManifest(text, m, err));
+ CHECK(m.revision == 7 && m.sender == "blender" && m.senderVersion == "4.2.3" && m.objects.size() == 2);
+ CHECK(m.objects[0].name == "Suzanne.001 ü" && m.objects[0].hasMatrix && !m.objects[1].hasMatrix);
+ // Rows as Blender prints them: the translation is the last column.
+ CHECK(m.objects[0].matrix[3][0] == 5.0 && m.objects[0].matrix[3][1] == 6.0 && m.objects[0].matrix[3][2] == 7.0);
+ CHECK(m.objects[0].matrix[2][1] == -1.0 && m.objects[0].matrix[1][2] == 1.0);
+
+ // Written and read back unchanged (full double precision).
+ m.objects[0].matrix[0][0] = 0.1234567890123456789;
+ BridgeManifest back;
+ CHECK(parseBridgeManifest(writeBridgeManifest(m), back, err));
+ CHECK(back.revision == 7 && back.objects.size() == 2 && back.objects[0].name == m.objects[0].name);
+ CHECK(back.objects[0].matrix == m.objects[0].matrix && back.objects[1].file == "r7_001.GoZ");
+
+ // Refused: other JSON, newer versions, files outside the folder, broken matrices.
+ CHECK(!parseBridgeManifest("{\"format\": \"other\"}", back, err));
+ CHECK(!parseBridgeManifest("not json", back, err));
+ CHECK(!parseBridgeManifest(R"({"format": "sculptforge-bridge", "version": 2, "objects": []})", back, err));
+ CHECK(err.find("newer") != std::string::npos);
+ for (const char* bad : {"../x.GoZ", "a/b.GoZ", "c:\\\\x.GoZ", ".."})
+ CHECK(!parseBridgeManifest(std::string(R"({"format": "sculptforge-bridge", "objects": [{"name": "x", "file": ")") +
+ bad + "\"}]}",
+ back, err));
+ CHECK(!parseBridgeManifest(
+ R"({"format": "sculptforge-bridge", "objects": [{"name": "x", "file": "a.GoZ", "matrix_world": [[1, 0, 0]]}]})", back,
+ err));
+}
+
+TEST(blender_axes) {
+ // Blender Z-up -> SculptForge Y-up, metres both: up stays up, Blender's front (-Y) faces the SculptForge camera (+Z).
+ CHECK(blenderToSculptForge({0, 0, 1}) == glm::dvec3(0, 1, 0));
+ CHECK(blenderToSculptForge({0, -1, 0}) == glm::dvec3(0, 0, 1));
+ CHECK(blenderToSculptForge({1, 0, 0}) == glm::dvec3(1, 0, 0));
+ CHECK(sculptForgeToBlender(blenderToSculptForge({0.3, -0.7, 2.0})) == glm::dvec3(0.3, -0.7, 2.0));
+ // Matrices convert so that converting then moving == moving then converting.
+ const glm::dmat4 mb = blenderMatrix(2.0), ms = blenderMatrixToSculptForge(mb);
+ const glm::dvec3 p(0.25, -1.5, 3.0);
+ const glm::dvec3 a = blenderToSculptForge(glm::dvec3(mb * glm::dvec4(p, 1.0)));
+ const glm::dvec3 b = glm::dvec3(ms * glm::dvec4(blenderToSculptForge(p), 1.0));
+ CHECK(glm::length(a - b) < 1e-12);
+ CHECK(std::abs(glm::determinant(ms) - glm::determinant(mb)) < 1e-12);
+}
+
+TEST(blender_bridge_round_trip) {
+ const fs::path root = fs::temp_directory_path() / "sf_blender_bridge";
+ fs::remove_all(root);
+ const std::string folder = root.string();
+ CommandRegistry reg;
+ std::string err;
+
+ // What the add-on writes: object-space meshes as .GoZ (here written by SculptForge's own writer, whose
+ // file holds Blender local coordinates for a mesh given in SculptForge axes) and each matrix_world.
+ Mesh cube = makeCube(3); // quads
+ Mesh ball = makeIcosphere(2);
+ ball.ensurePolygroups();
+ for (uint32_t t = 0; t < ball.triangleCount(); ++t) ball.polygroups[t] = t % 3;
+ ball.uvs.assign(ball.triangleCount() * 3, glm::vec2(0.25f, 0.75f));
+ const fs::path inbox = root / "to_sculptforge";
+ fs::create_directories(inbox);
+ CHECK(saveGoz((inbox / "r3_000.GoZ").string(), cube, "Cube", err));
+ CHECK(saveGoz((inbox / "r3_001.GoZ").string(), ball, "Ball", err));
+ const glm::dmat4 mCube = blenderMatrix(1.0), mBall = blenderMatrix(-1.0); // the ball is mirrored
+ writeText(inbox / "manifest.json",
+ R"({"format": "sculptforge-bridge", "version": 1, "revision": 3, "sender": "blender", "objects": [
+ {"name": "Cube", "file": "r3_000.GoZ", "matrix_world": )" + matrixJson(mCube) + R"(},
+ {"name": "Ball ü", "file": "r3_001.GoZ", "matrix_world": )" + matrixJson(mBall) + "}]}");
+ CHECK(bridgeRevision(inbox.string()) == 3);
+
+ // Into a fresh scene: the cube replaces it (renamed after the object), the ball is added.
+ Document doc = makeDoc(makeIcosphere(1));
+ CommandResult r = reg.execute(doc, "blender_receive", {{"folder", folder}});
+ CHECK(r.ok && r.message.find("Received 2 objects") != std::string::npos);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 0);
+ CHECK(doc.subtools[0].name == "Cube" && doc.gozName == "Cube");
+ CHECK(doc.subtools[1].name == "Ball ü" && doc.subtools[1].gozName == "Ball ü");
+ CHECK(doc.mesh.quadCount() == cube.quadCount() && doc.mesh.quadCount() > 0);
+ CHECK(doc.subtoolMesh(1).polygroups.size() == ball.triangleCount() && doc.subtoolMesh(1).hasUvs());
+ // Placed as in Blender's scene: p_sf = A * M_blender * A^-1 * p.
+ const glm::dmat4 placed = blenderMatrixToSculptForge(mCube);
+ std::vector<glm::vec3> expect;
+ for (const glm::vec3& p : cube.positions) expect.push_back(glm::vec3(placed * glm::dvec4(glm::dvec3(p), 1.0)));
+ CHECK(maxDistance(doc.mesh.positions, expect) < 1e-5f);
+
+ // Sculpt, then send back: world space, under the exact Blender names, faces exactly as they came.
+ doc.mesh.positions[0] += glm::vec3(0.0f, 0.1f, 0.0f);
+ r = reg.execute(doc, "blender_send", {{"folder", folder}});
+ CHECK(r.ok);
+ BridgeManifest sent;
+ CHECK(readBridgeManifest(bridgeManifestPath(blenderOutbox(folder)), sent, err));
+ CHECK(sent.revision == 1 && sent.sender == "sculptforge" && sent.objects.size() == 2);
+ CHECK(sent.objects[0].name == "Cube" && sent.objects[1].name == "Ball ü" && !sent.objects[0].hasMatrix);
+ Mesh cubeBack, ballBack;
+ CHECK(loadGoz((root / "to_blender" / sent.objects[0].file).string(), cubeBack, err));
+ CHECK(loadGoz((root / "to_blender" / sent.objects[1].file).string(), ballBack, err));
+ CHECK(maxDistance(cubeBack.positions, doc.mesh.positions) < 1e-6f);
+ // (GoZ quads come in split as (a,b,c) + (a,c,d): compare with the SubTool as it was received.)
+ CHECK(cubeBack.triangles == doc.mesh.triangles && cubeBack.quadCount() == cube.quadCount());
+ CHECK(ballBack.triangles == ball.triangles && ballBack.polygroups == ball.polygroups && ballBack.uvs == ball.uvs);
+ // Undoing the placement gives the object-space mesh back (what the add-on does with matrix_world).
+ const glm::dmat4 unplace = glm::inverse(blenderMatrixToSculptForge(mBall));
+ std::vector<glm::vec3> local;
+ for (const glm::vec3& p : ballBack.positions) local.push_back(glm::vec3(unplace * glm::dvec4(glm::dvec3(p), 1.0)));
+ CHECK(maxDistance(local, ball.positions) < 1e-5f);
+
+ // Blender sends the cube again: it updates its SubTool (undoably) instead of adding one.
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-bridge", "revision": 4, "objects": [
+ {"name": "Cube", "file": "r3_000.GoZ"}]})");
+ r = reg.execute(doc, "blender_receive", {{"folder", folder}});
+ CHECK(r.ok && doc.subtoolCount() == 2 && doc.activeSubtool == 0);
+ CHECK(maxDistance(doc.mesh.positions, cube.positions) < 1e-6f); // no matrix: as stored
+ CHECK(doc.undo.canUndo());
+
+ // A second send: the next revision, the first send's files removed.
+ const std::string firstFile = sent.objects[0].file;
+ CHECK(reg.execute(doc, "blender_send", {{"folder", folder}}).ok);
+ CHECK(bridgeRevision(blenderOutbox(folder)) == 2);
+ CHECK(!fs::exists(root / "to_blender" / firstFile));
+
+ // Errors say what to do.
+ fs::remove_all(root);
+ r = reg.execute(doc, "blender_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("Nothing has been sent from Blender") != std::string::npos);
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-bridge", "objects": [{"name": "Gone", "file": "r1_000.GoZ"}]})");
+ r = reg.execute(doc, "blender_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("Gone") != std::string::npos);
+ fs::remove_all(root);
+}
+
+TEST(blender_bridge_names_and_app_info) {
+ const fs::path root = fs::temp_directory_path() / "sf_blender_names";
+ fs::remove_all(root);
+ const std::string folder = root.string();
+ // Duplicate names get Blender's .001 suffixes.
+ Mesh a = makeIcosphere(0), b = makeIcosphere(0);
+ std::vector<std::string> names;
+ std::string msg;
+ CHECK(blenderSend({{"Rock", &a}, {"Rock", &b}}, folder, msg, &names));
+ CHECK(names.size() == 2 && names[0] == "Rock" && names[1] == "Rock.001");
+ CHECK(!blenderSend({}, folder, msg) && msg.find("Nothing") != std::string::npos);
+
+ writeBridgeAppInfo(folder, "/opt/SculptForge/bin/sculptforge", "1.2.3");
+ std::ifstream f(root / "app.json");
+ const std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ CHECK(text.find("\"/opt/SculptForge/bin/sculptforge\"") != std::string::npos && text.find("1.2.3") != std::string::npos);
+ writeBridgeHeartbeat(folder);
+ CHECK(fs::exists(root / "alive.json"));
+ writeBridgeHeartbeat(folder, true);
+ CHECK(!fs::exists(root / "alive.json"));
+ fs::remove_all(root);
+}