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.

Maya bridge (#42): File > Maya and a SculptForge shelf script for Maya, exchanging OBJ through one user-picked folder

islandmedf3265f058734
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c9fa304c..88af4977 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -195,6 +195,8 @@ jobs:
run: |
python3 addons/blender/build_addon.py --check --version "${TAG#v}" --out dist
cp "dist/sculptforge_bridge-${TAG#v}.zip" dist/sculptforge_bridge.zip
+ - name: Maya shelf script (Python source and its README; nothing to build)
+ run: python3 -m zipfile -c dist/sculptforge_maya.zip integrations/maya/sculptforge_maya.py integrations/maya/README.md
- name: ZBrush ZTool Export plug-in (ZScript source; ZBrush compiles it)
run: cp integrations/zbrush/SculptForgeZToolExport.txt dist/
- name: Checksums
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 48a643f3..94f17908 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,15 @@ All notable changes to SculptForge are listed here. The format follows
## [Unreleased]
+### Added
+- Maya bridge (#42): **File > Maya** and a SculptForge shelf for Maya (`integrations/maya/sculptforge_maya.py`,
+ plain `maya.cmds`, released as `sculptforge_maya.zip`). Send the selected meshes from Maya, sculpt, then
+ **Send to Maya**: each object gets its new mesh by name, keeping its transform, parent and shading groups (one
+ undo step in Maya). Meshes travel as OBJ (quads, UVs) through one exchange folder you pick in both apps, with
+ a small, strictly checked manifest; no ports or connections, nothing in the folder is ever run, and the bridge
+ is off until you choose the folder. **Get automatically** (off by default) checks that folder once a second
+ (`maya_send` / `maya_receive folder=<folder>`; Help > User Guide > Working with Maya).
+
## [0.10.4] - 2026-11-01
### Added
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 82085b91..84353922 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -124,6 +124,8 @@ add_library(sculptforge_core STATIC
src/io/GozCommands.cpp
src/io/BlenderBridge.cpp
src/io/BlenderCommands.cpp
+ src/io/MayaBridge.cpp
+ src/io/MayaCommands.cpp
src/io/StlIO.cpp
src/io/ArExport.cpp
)
@@ -274,6 +276,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelPerformance.cpp
src/app/PanelGoz.cpp
src/app/PanelBlender.cpp
+ src/app/PanelMaya.cpp
src/app/PanelPhone.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
@@ -531,6 +534,9 @@ if(SCULPTFORGE_BUILD_TESTS)
# 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 Maya shelf script (integrations/maya, #42) with a mocked maya.cmds, round-tripped through sculptforge-cli.
+ add_test(NAME maya_shelf_script COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/maya/test_sculptforge_maya.py
+ --cli ${SCULPTFORGE_CLI_RUNNER})
# 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)
diff --git a/docs/guide/exporting.md b/docs/guide/exporting.md
index 079c14e8..abb98598 100644
--- a/docs/guide/exporting.md
+++ b/docs/guide/exporting.md
@@ -233,9 +233,15 @@ To sculpt Blender objects in SculptForge and send them back into the same object
add-on and **File > Blender**: see [Working with Blender](blender.md). For a one-off exchange, OBJ, FBX and glTF
all carry SubTools, UVs and quads both ways.
+## Maya
+
+To sculpt Maya meshes in SculptForge and send them back into the same objects, use the SculptForge shelf for
+Maya and **File > Maya**: see [Working with Maya](maya.md).
+
## See also
- [Working with Blender](blender.md): the Blender add-on
+- [Working with Maya](maya.md): the Maya shelf script
- [Projects, autosave and QuickSave](projects.md): save everything, not just the mesh
- [SubTools](subtools.md): which SubTools are exported
- [Layers and blend shapes](layers.md): what becomes morph targets
diff --git a/docs/guide/index.md b/docs/guide/index.md
index 424c5aa5..99ef9308 100644
--- a/docs/guide/index.md
+++ b/docs/guide/index.md
@@ -55,16 +55,17 @@ You can read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<
31. [Exporting, Unreal and ZBrush](exporting.md)
32. [Export presets](export-presets.md)
33. [Working with Blender](blender.md)
-34. [Projects, autosave and QuickSave](projects.md)
-35. [Scripting and automation](scripting.md)
-36. [SculptForge for studios](studios.md)
+34. [Working with Maya](maya.md)
+35. [Projects, autosave and QuickSave](projects.md)
+36. [Scripting and automation](scripting.md)
+37. [SculptForge for studios](studios.md)
## Reference
-37. [Keyboard and mouse](shortcuts.md)
-38. [Performance and big meshes](performance.md)
-39. [Troubleshooting and FAQ](troubleshooting.md)
-40. [Glossary](glossary.md)
+38. [Keyboard and mouse](shortcuts.md)
+39. [Performance and big meshes](performance.md)
+40. [Troubleshooting and FAQ](troubleshooting.md)
+41. [Glossary](glossary.md)
## Getting help
diff --git a/docs/guide/maya.md b/docs/guide/maya.md
new file mode 100644
index 00000000..e29abd68
--- /dev/null
+++ b/docs/guide/maya.md
@@ -0,0 +1,82 @@
+# Working with Maya
+
+Keep Maya for the scene, rigging and animation, and sculpt in SculptForge: the **SculptForge shelf** for Maya
+sends the selected meshes to SculptForge, and **File > Maya > Send to Maya** sends them back, replacing each
+Maya object's mesh by name. It works like GoZ between ZBrush and other apps, on Linux, Windows and macOS.
+
+The two apps exchange files through **one folder that you choose in both**, and nothing else: SculptForge opens
+no ports or connections for this, reads and writes only inside that folder, and never runs anything it finds
+there. The bridge is off until you choose the folder.
+
+## Install the shelf in Maya
+
+1. Download `sculptforge_maya.zip` from the
+ [latest release](https://github.com/islandmed/SculptForge/releases/latest/download/sculptforge_maya.zip) and
+ unzip it.
+2. Copy `sculptforge_maya.py` into your Maya scripts folder: `Documents\maya\scripts\` on Windows,
+ `~/Library/Preferences/Autodesk/maya/scripts/` on macOS, `~/maya/scripts/` on Linux.
+3. In Maya open the **Script Editor**, and in a **Python** tab run `import sculptforge_maya` and then
+ `sculptforge_maya.install_shelf()`. A **SculptForge** shelf appears with **Send**, **Get** and **Folder**.
+
+The script uses plain `maya.cmds` and Maya's own OBJ exporter; it needs Maya 2022 or newer.
+
+## Choose the exchange folder
+
+1. In SculptForge choose **File > Maya > Exchange folder...** and pick a folder of your own, for example an
+ empty `Documents/SculptForge Maya`.
+2. In Maya click **Folder** on the SculptForge shelf and pick the same folder.
+
+**File > Maya** shows the folder; **Turn the Maya bridge off** forgets it (nothing in it is deleted).
+
+## A round trip
+
+1. In Maya select one or more meshes and click **Send** on the SculptForge shelf.
+2. In SculptForge choose **File > Maya > Get from Maya**. Each mesh becomes a SubTool with its Maya name; a
+ SubTool with that name already there is replaced (one undo step on that SubTool).
+3. Sculpt, paint, divide, remesh: anything SculptForge does.
+4. Choose **File > Maya > Send to Maya**. Every visible SubTool goes.
+5. In Maya click **Get**. Each object that came from Maya gets the new mesh and keeps its transform, parent and
+ shading groups; a SubTool you added in SculptForge becomes a new object. The whole Get is one undo step in
+ Maya.
+
+**Get automatically** (in **File > Maya**, off by default) loads what Maya sends as soon as it arrives:
+SculptForge checks the folder's manifest once a second.
+
+## What comes across
+
+| | Maya | SculptForge |
+|---|---|---|
+| Shape | The mesh, in world space | The SubTool, as placed in Maya's scene |
+| Faces | Quads and triangles; n-gons as triangles | Triangles and quads (PolyF shows the quads) |
+| UVs | The current UV set | UVs |
+| Name | The transform's name | SubTool name |
+| Units | Maya's linear unit (cm by default) | Taken as they are: 1 cm in Maya is 1 unit here |
+
+Polygroups, the mask and polypaint stay in SculptForge. Normals, creases, construction history, deformers and
+skinning stay in Maya: **Get** replaces the mesh shape, so send a copy of a skinned or deformed mesh. A SubTool
+named "Body Hi" arrives in Maya as `Body_Hi` (Maya names allow letters, digits and `_`), and comes back to the
+same SubTool.
+
+## The exchange folder
+
+```
+<folder>/maya_to_sculptforge/manifest.json + r<revision>_<k>.obj written by Maya
+<folder>/sculptforge_to_maya/manifest.json + r<revision>_<k>.obj written by SculptForge
+```
+
+Each manifest is a small JSON file: `{"format": "sculptforge-maya", "version": 1, "revision": 3,
+"sender": "maya", "unit": "cm", "objects": [{"name": "pCube1", "file": "r3_000.obj"}]}`. Both sides check it
+strictly before reading anything: at most 256 KiB and 256 objects, every field of the right type, and each file
+must be a plain `.obj` name in the manifest's own folder (no folders, no `..`, no absolute paths, no links).
+Each send removes the files of the previous one; anything else in the folder is left alone.
+
+The commands are `maya_send folder=<folder>` and `maya_receive folder=<folder>` (see
+[Scripting and automation](scripting.md)).
+
+## Troubleshooting
+
+- **"Nothing has been sent from Maya yet"**: check that both apps use the same folder (open **File > Maya** in
+ SculptForge; click **Folder** in Maya to see or change it).
+- **Get in Maya says nothing has been sent**: choose **File > Maya > Send to Maya** in SculptForge first.
+- **A mesh came in as a new object instead of replacing one**: Get matches the transform's name; renaming the
+ object in Maya or the SubTool's Maya name breaks the link.
diff --git a/integrations/maya/README.md b/integrations/maya/README.md
new file mode 100644
index 00000000..217e9fc9
--- /dev/null
+++ b/integrations/maya/README.md
@@ -0,0 +1,67 @@
+# SculptForge bridge for Maya
+
+Send the selected meshes from Maya to SculptForge and get them back, the way GoZ works between ZBrush and
+other apps. One Python file (`sculptforge_maya.py`), plain `maya.cmds`, no other modules. Tested against a
+mocked `maya.cmds` (`tests/maya/test_sculptforge_maya.py`); it uses only commands Maya has had for many
+versions (Maya 2022 or newer, Python 3), but it has not been run inside a real Maya yet: please report what
+you find on the [issue tracker](https://github.com/islandmed/SculptForge/issues/42).
+
+The two apps share **one exchange folder that you pick in both** and nothing else: no ports, sockets or
+servers, and neither app runs anything it finds in the folder. Meshes travel as OBJ files (quads and UVs).
+
+## Install
+
+1. Download `sculptforge_maya.zip` from the
+ [latest SculptForge release](https://github.com/islandmed/SculptForge/releases/latest/download/sculptforge_maya.zip)
+ and unzip it (or take `sculptforge_maya.py` from this folder).
+2. Copy `sculptforge_maya.py` into your Maya scripts folder:
+ - Windows: `Documents\maya\scripts\`
+ - macOS: `~/Library/Preferences/Autodesk/maya/scripts/`
+ - Linux: `~/maya/scripts/`
+3. Start Maya, open the **Script Editor** (Windows > General Editors > Script Editor), and in a **Python** tab run:
+
+ ```python
+ import sculptforge_maya
+ sculptforge_maya.install_shelf()
+ ```
+
+ A **SculptForge** shelf appears with three buttons: **Send**, **Get** and **Folder**. You only do this once;
+ Maya keeps the shelf.
+
+## Use
+
+1. In SculptForge choose **File > Maya > Exchange folder...** and pick a folder (an empty one of your own, for
+ example `Documents/SculptForge Maya`). In Maya click **Folder** on the SculptForge shelf and pick the same
+ folder.
+2. In Maya select one or more meshes and click **Send**.
+3. In SculptForge choose **File > Maya > Get from Maya** (or turn on **Get automatically**, which checks the
+ folder once a second). Each mesh becomes a SubTool with its Maya name.
+4. Sculpt, then choose **File > Maya > Send to Maya**.
+5. In Maya click **Get**. Each object that came from Maya gets its new mesh, keeping its transform, parent and
+ shading groups; a SubTool you added in SculptForge becomes a new object. The whole Get is one undo step.
+
+## What comes across
+
+- Positions in world space and Maya's own units (SculptForge takes the numbers as they are), quads, n-gons (as
+ triangles), UVs.
+- Not: polygroups, masks and polypaint stay in SculptForge; normals, creases, history, deformers and skinning
+ stay in Maya. Get replaces the mesh shape, so a skinned or deformed mesh loses its deformers: send a copy of
+ those.
+- Maya node names: SculptForge sends names made of letters, digits and `_` (a SubTool called "Body Hi" arrives
+ as `Body_Hi`).
+
+## The folder
+
+```
+<folder>/maya_to_sculptforge/manifest.json + r<revision>_<k>.obj written by Maya (Send)
+<folder>/sculptforge_to_maya/manifest.json + r<revision>_<k>.obj written by SculptForge (Send to Maya)
+```
+
+```json
+{"format": "sculptforge-maya", "version": 1, "revision": 3, "sender": "maya", "sender_version": "2026",
+ "unit": "cm", "objects": [{"name": "pCube1", "file": "r3_000.obj"}]}
+```
+
+Both sides read the manifest strictly: at most 256 KiB and 256 objects, every field of the right type, names
+reduced to Maya's characters, and files must be plain `*.obj` names in the manifest's own folder (no folders,
+no `..`, no absolute paths, no links). Each send removes the files of the previous one.
diff --git a/integrations/maya/sculptforge_maya.py b/integrations/maya/sculptforge_maya.py
new file mode 100644
index 00000000..f54e07cc
--- /dev/null
+++ b/integrations/maya/sculptforge_maya.py
@@ -0,0 +1,405 @@
+# SculptForge - open source digital sculpting
+# SPDX-License-Identifier: GPL-3.0-or-later
+"""SculptForge bridge for Maya (SculptForge issue #42).
+
+Sends the selected meshes from Maya to SculptForge and gets them back, through ONE exchange folder that you
+pick in both apps (the way GoZ works between ZBrush and other apps). Nothing else is shared: no ports, sockets
+or servers, and neither side runs anything it finds in the folder. Meshes travel as OBJ (quads and UVs, world
+space, Maya's own units, one object per file); a small JSON manifest per direction lists the objects:
+
+ <folder>/maya_to_sculptforge/manifest.json + r<rev>_<k>.obj written here (Send to SculptForge)
+ <folder>/sculptforge_to_maya/manifest.json + r<rev>_<k>.obj written by SculptForge (File > Maya > Send to Maya)
+
+Get from SculptForge replaces each object's mesh by name, keeping its transform, parent and shading groups, as
+one undo step; objects Maya doesn't have yet are created. Plain maya.cmds (and maya.mel for the shelf); no other
+modules. Install: see README.md beside this file, or run install_shelf() once.
+"""
+
+import json
+import os
+import re
+
+FORMAT = "sculptforge-maya"
+VERSION = 1
+TO_SCULPTFORGE = "maya_to_sculptforge"
+TO_MAYA = "sculptforge_to_maya"
+MAX_MANIFEST_BYTES = 256 * 1024
+MAX_OBJECTS = 256
+MAX_NAME = 128
+MAX_FILE_NAME = 64
+
+FOLDER_VAR = "sculptforgeExchangeFolder"
+REVISION_VAR = "sculptforgeLastRevision"
+SHELF = "SculptForge"
+IMPORT_NAMESPACE = "sculptforge_get"
+OBJ_EXPORT_OPTIONS = "groups=0;ptgroups=0;materials=0;smoothing=0;normals=0"
+
+_FILE_CHARS = re.compile(r"^[A-Za-z0-9_.\-]+$")
+_NAME_BAD = re.compile(r"[^A-Za-z0-9_]")
+
+
+# ---- The exchange format (no Maya needed: tests/maya/test_sculptforge_maya.py runs these with plain Python) ----
+
+def safe_name(name):
+ """A Maya node name: letters, digits and '_' only, not starting with a digit, at most MAX_NAME bytes."""
+ s = _NAME_BAD.sub("_", (name or "").encode("utf-8", "replace").decode("ascii", "replace").replace("�", "_"))
+ s = s[:MAX_NAME]
+ if not s:
+ return "SubTool"
+ if s[0].isdigit():
+ s = ("_" + s)[:MAX_NAME]
+ return s
+
+
+def file_name_ok(name):
+ """A file a manifest may list: a plain *.obj name inside the manifest's own folder."""
+ return (isinstance(name, str) and 4 < len(name) <= MAX_FILE_NAME and not name.startswith(".")
+ and ".." not in name and _FILE_CHARS.match(name) is not None and name.lower().endswith(".obj"))
+
+
+def write_manifest(objects, revision, sender_version="", unit=""):
+ """The manifest text. `objects` is a list of (name, file)."""
+ data = {
+ "format": FORMAT,
+ "version": VERSION,
+ "revision": int(revision),
+ "sender": "maya",
+ "sender_version": str(sender_version)[:64],
+ }
+ if unit:
+ data["unit"] = str(unit)[:64]
+ data["objects"] = [{"name": n, "file": f} for n, f in objects]
+ return json.dumps(data, indent=2) + "\n"
+
+
+def parse_manifest(text):
+ """Checks a manifest as strictly as SculptForge does. Returns {"revision", "sender", "objects": [(name, file)]};
+ raises ValueError with the reason."""
+ if len(text) > MAX_MANIFEST_BYTES:
+ raise ValueError("the manifest is too big")
+ try:
+ data = json.loads(text)
+ except (ValueError, RecursionError) as e:
+ raise ValueError("the manifest is not valid JSON (%s)" % e)
+ if not isinstance(data, dict) or data.get("format") != FORMAT:
+ raise ValueError("not a SculptForge Maya bridge manifest")
+ version = data.get("version")
+ if isinstance(version, bool) or not isinstance(version, (int, float)) or version < 1 or version != int(version):
+ raise ValueError("the manifest has no valid version")
+ if version > VERSION:
+ raise ValueError("the manifest is from a newer SculptForge (version %d): update this script" % version)
+ revision = data.get("revision")
+ if (isinstance(revision, bool) or not isinstance(revision, (int, float)) or revision < 0
+ or revision != int(revision) or revision > 2 ** 53):
+ raise ValueError("the manifest has no valid revision")
+ for key in ("sender", "sender_version", "unit"):
+ if key in data and (not isinstance(data[key], str) or len(data[key]) > 64):
+ raise ValueError("the manifest has a bad %r" % key)
+ objects = data.get("objects")
+ if not isinstance(objects, list):
+ raise ValueError("the manifest lists no objects")
+ if len(objects) > MAX_OBJECTS:
+ raise ValueError("the manifest lists too many objects (%d, at most %d)" % (len(objects), MAX_OBJECTS))
+ out, files = [], set()
+ for o in objects:
+ if not isinstance(o, dict) or not isinstance(o.get("name"), str) or not isinstance(o.get("file"), str):
+ raise ValueError("the manifest has an object without a name and a file")
+ if not file_name_ok(o["file"]):
+ raise ValueError("the manifest names a file this script won't read: %r" % o["file"][:MAX_FILE_NAME])
+ if o["file"] in files:
+ raise ValueError("the manifest lists %r twice" % o["file"])
+ if len(o["name"].encode("utf-8")) > 4 * MAX_NAME:
+ raise ValueError("the manifest has a name that is too long")
+ files.add(o["file"])
+ out.append((safe_name(o["name"]), o["file"]))
+ return {"revision": int(revision), "sender": data.get("sender", ""), "objects": out}
+
+
+def read_manifest(box):
+ """The parsed manifest in `box`, or None when nothing has been sent. Raises ValueError when it is not valid."""
+ path = os.path.join(box, "manifest.json")
+ if not os.path.lexists(path):
+ return None
+ if os.path.islink(path) or not os.path.isfile(path):
+ raise ValueError("%s is not a plain file" % path)
+ if os.path.getsize(path) > MAX_MANIFEST_BYTES:
+ raise ValueError("the manifest is too big")
+ with open(path, "r", encoding="utf-8") as f:
+ return parse_manifest(f.read(MAX_MANIFEST_BYTES + 1))
+
+
+def object_file(box, file_name):
+ """The full path of a file a manifest lists, checked: a plain file directly inside `box`."""
+ if not file_name_ok(file_name):
+ raise ValueError("bad file name %r" % file_name)
+ path = os.path.join(box, file_name)
+ real_box = os.path.realpath(box)
+ if os.path.dirname(os.path.realpath(path)) != real_box or os.path.islink(path) or not os.path.isfile(path):
+ raise ValueError("%s is missing or not a plain file in the exchange folder" % file_name)
+ return path
+
+
+def remove_entry(path):
+ """Removes a file or link (never what a link points to), so a planted link can't redirect a write."""
+ if os.path.lexists(path) and not os.path.isdir(path) or os.path.islink(path):
+ os.remove(path)
+
+
+def write_atomically(path, text):
+ tmp = path + ".tmp"
+ remove_entry(tmp)
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
+ f.write(text)
+ os.replace(tmp, path)
+
+
+def next_revision(box):
+ try:
+ m = read_manifest(box)
+ except ValueError:
+ m = None
+ return (m["revision"] if m else 0) + 1
+
+
+def remove_old_sends(box, keep_prefix):
+ """Removes r<n>_* files of earlier sends (and nothing else)."""
+ for n in os.listdir(box):
+ if re.match(r"^r[0-9]+_", n) and not n.startswith(keep_prefix):
+ try:
+ os.remove(os.path.join(box, n))
+ except OSError:
+ pass # open elsewhere: the next send tries again
+
+
+def unique_names(names):
+ out = []
+ for name in names:
+ n, k = name, 1
+ while n in out:
+ n = "%s%d" % (name, k)
+ k += 1
+ out.append(n)
+ return out
+
+
+# ---- Maya ----
+
+def _cmds():
+ import maya.cmds as cmds # only inside Maya
+ return cmds
+
+
+def _message(text, warning=False):
+ cmds = _cmds()
+ if warning:
+ cmds.warning("SculptForge: " + text)
+ else:
+ print("SculptForge: " + text)
+ try:
+ cmds.inViewMessage(amg=text, pos="topCenter", fade=True)
+ except Exception:
+ pass
+ return text
+
+
+def choose_folder():
+ """Asks for the exchange folder (pick the same one in SculptForge's File > Maya > Exchange folder...)."""
+ cmds = _cmds()
+ start = cmds.optionVar(q=FOLDER_VAR) if cmds.optionVar(exists=FOLDER_VAR) else ""
+ picked = cmds.fileDialog2(fileMode=3, caption="SculptForge exchange folder", okCaption="Use this folder",
+ startingDirectory=start or None)
+ if not picked:
+ return ""
+ folder = picked[0]
+ cmds.optionVar(sv=(FOLDER_VAR, folder))
+ _message("exchange folder: " + folder)
+ return folder
+
+
+def exchange_folder(ask=True):
+ cmds = _cmds()
+ folder = cmds.optionVar(q=FOLDER_VAR) if cmds.optionVar(exists=FOLDER_VAR) else ""
+ if folder and os.path.isdir(folder):
+ return folder
+ return choose_folder() if ask else ""
+
+
+def _ensure_obj_plugin():
+ cmds = _cmds()
+ if not cmds.pluginInfo("objExport", q=True, loaded=True):
+ cmds.loadPlugin("objExport", quiet=True)
+
+
+def _mesh_shape(transform):
+ shapes = _cmds().listRelatives(transform, shapes=True, type="mesh", noIntermediate=True, fullPath=True) or []
+ return shapes[0] if shapes else None
+
+
+def _selected_meshes():
+ """(transform, shape) for each selected mesh, in selection order (a selected shape counts as its transform)."""
+ cmds = _cmds()
+ out, seen = [], set()
+ for node in cmds.ls(selection=True, long=True, objectsOnly=True) or []:
+ transform = node
+ if cmds.nodeType(node) == "mesh":
+ transform = (cmds.listRelatives(node, parent=True, fullPath=True) or [node])[0]
+ shape = _mesh_shape(transform)
+ if shape and transform not in seen:
+ seen.add(transform)
+ out.append((transform, shape))
+ return out
+
+
+def _short(path):
+ return path.split("|")[-1].split(":")[-1]
+
+
+def send_to_sculptforge():
+ """Writes the selected meshes to the exchange folder; SculptForge loads them with File > Maya > Get from Maya
+ (or by itself with Get automatically on)."""
+ cmds = _cmds()
+ meshes = _selected_meshes()
+ if not meshes:
+ return _message("select one or more meshes to send", warning=True)
+ if len(meshes) > MAX_OBJECTS:
+ return _message("too many meshes selected (at most %d)" % MAX_OBJECTS, warning=True)
+ folder = exchange_folder()
+ if not folder:
+ return _message("no exchange folder chosen", warning=True)
+ box = os.path.join(folder, TO_SCULPTFORGE)
+ if os.path.islink(box):
+ return _message("%s is a link, not a folder" % box, warning=True)
+ if not os.path.isdir(box):
+ os.makedirs(box)
+ _ensure_obj_plugin()
+ revision = next_revision(box)
+ prefix = "r%d_" % revision
+ names = unique_names([safe_name(_short(t)) for t, _ in meshes])
+ objects = []
+ selection = cmds.ls(selection=True, long=True) or []
+ try:
+ for k, ((transform, shape), name) in enumerate(zip(meshes, names)):
+ file_name = "%s%03d.obj" % (prefix, k)
+ remove_entry(os.path.join(box, file_name))
+ cmds.select(shape, replace=True) # the shape alone: not the transform's children
+ cmds.file(os.path.join(box, file_name), force=True, options=OBJ_EXPORT_OPTIONS, type="OBJexport",
+ preserveReferences=True, exportSelected=True)
+ objects.append((name, file_name))
+ finally:
+ if selection:
+ cmds.select(selection, replace=True)
+ else:
+ cmds.select(clear=True)
+ write_atomically(os.path.join(box, "manifest.json"),
+ write_manifest(objects, revision, cmds.about(version=True), cmds.currentUnit(q=True, linear=True)))
+ remove_old_sends(box, prefix)
+ return _message("sent %d mesh%s to SculptForge" % (len(objects), "" if len(objects) == 1 else "es"))
+
+
+def _find_transform(name):
+ cmds = _cmds()
+ for t in cmds.ls(name, long=True, type="transform") or []:
+ if _short(t) == name and _mesh_shape(t):
+ return t
+ return None
+
+
+def _import_obj(path):
+ """Imports one OBJ; returns (transform, shape) of the new mesh."""
+ cmds = _cmds()
+ nodes = cmds.file(path, i=True, type="OBJ", options="mo=0", returnNewNodes=True, ignoreVersion=True,
+ namespace=IMPORT_NAMESPACE, mergeNamespacesOnClash=True, preserveReferences=True) or []
+ for n in nodes:
+ if cmds.nodeType(n) == "transform":
+ shape = _mesh_shape(n)
+ if shape:
+ return cmds.ls(n, long=True)[0], shape
+ raise ValueError("%s holds no mesh" % os.path.basename(path))
+
+
+def _replace_mesh(existing, new_transform, new_shape):
+ """Puts the imported (world-space) mesh under `existing`, in its object space, in place of its mesh shape;
+ the transform, parent and shading groups stay."""
+ cmds = _cmds()
+ old_shape = _mesh_shape(existing)
+ groups = []
+ for sg in cmds.listConnections(old_shape, type="shadingEngine") or []:
+ if sg not in groups:
+ groups.append(sg)
+ old_name = _short(old_shape)
+ # World space -> the object's space: place the import at the inverse of the object's world matrix and bake it.
+ cmds.xform(new_transform, matrix=cmds.getAttr(existing + ".worldInverseMatrix[0]"), worldSpace=True)
+ cmds.makeIdentity(new_transform, apply=True, translate=True, rotate=True, scale=True, normal=0,
+ preserveNormals=True)
+ moved = cmds.parent(new_shape, existing, shape=True, relative=True)[0]
+ moved = cmds.ls(moved, long=True)[0] if cmds.ls(moved, long=True) else moved
+ for sg in groups or ["initialShadingGroup"]:
+ cmds.sets(moved, edit=True, forceElement=sg)
+ cmds.delete(old_shape)
+ cmds.delete(new_transform)
+ return cmds.rename(moved, old_name)
+
+
+def get_from_sculptforge():
+ """Loads what SculptForge last sent: each object replaces the mesh of the Maya object with its name (one undo
+ step), or becomes a new object."""
+ cmds = _cmds()
+ folder = exchange_folder()
+ if not folder:
+ return _message("no exchange folder chosen", warning=True)
+ box = os.path.join(folder, TO_MAYA)
+ try:
+ manifest = read_manifest(box) if os.path.isdir(box) and not os.path.islink(box) else None
+ except ValueError as e:
+ return _message("can't read what SculptForge sent: %s" % e, warning=True)
+ if not manifest or not manifest["objects"]:
+ return _message("nothing has been sent from SculptForge yet (File > Maya > Send to Maya)", warning=True)
+ _ensure_obj_plugin()
+ done = []
+ cmds.undoInfo(openChunk=True, chunkName="Get from SculptForge")
+ try:
+ for name, file_name in manifest["objects"]:
+ path = object_file(box, file_name)
+ new_transform, new_shape = _import_obj(path)
+ existing = _find_transform(name)
+ if existing:
+ _replace_mesh(existing, new_transform, new_shape)
+ done.append(existing)
+ else:
+ t = cmds.rename(new_transform, ":" + name)
+ cmds.rename(_mesh_shape(t), name + "Shape")
+ done.append(t)
+ if cmds.namespace(exists=IMPORT_NAMESPACE):
+ cmds.namespace(removeNamespace=IMPORT_NAMESPACE, mergeNamespaceWithRoot=True)
+ except ValueError as e:
+ return _message("can't load what SculptForge sent: %s" % e, warning=True)
+ finally:
+ cmds.undoInfo(closeChunk=True)
+ cmds.optionVar(iv=(REVISION_VAR, manifest["revision"]))
+ cmds.select([d for d in done if cmds.objExists(d)] or None, replace=True)
+ return _message("got %d mesh%s from SculptForge" % (len(done), "" if len(done) == 1 else "es"))
+
+
+def install_shelf():
+ """Creates the SculptForge shelf: Send, Get and Folder buttons. Run once, after putting this file in a
+ folder on Maya's script path (README.md)."""
+ cmds = _cmds()
+ import maya.mel as mel
+ top = mel.eval("$sculptforgeTmp = $gShelfTopLevel")
+ if cmds.shelfLayout(SHELF, exists=True):
+ cmds.deleteUI(SHELF, layout=True)
+ shelf = cmds.shelfLayout(SHELF, parent=top)
+ buttons = [
+ ("Send", "Send the selected meshes to SculptForge", "send_to_sculptforge"),
+ ("Get", "Get what SculptForge sent (replaces meshes by name)", "get_from_sculptforge"),
+ ("Folder", "Choose the exchange folder (the same one as in SculptForge)", "choose_folder"),
+ ]
+ for label, tip, func in buttons:
+ cmds.shelfButton(parent=shelf, label=label, imageOverlayLabel=label, annotation=tip,
+ image="pythonFamily.png", sourceType="python",
+ command="import sculptforge_maya\nsculptforge_maya.%s()" % func)
+ try:
+ mel.eval("saveAllShelves $gShelfTopLevel")
+ except Exception:
+ pass
+ return _message("SculptForge shelf installed")
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 32c25ef4..fd0a47cb 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -383,6 +383,7 @@ int App::runUiTest(int w, int h, int fps) {
pollUnreal();
pollGenerator();
pollBlender(); // (demo recordings leave the user's Blender bridge alone)
+ pollMaya(); // (tests and recordings never read the user's Maya folder: maya.json isn't loaded)
pollPhone();
pollAutoUv();
pollBake();
@@ -903,6 +904,7 @@ int App::run() {
pollUnreal();
pollGoz();
pollBlender();
+ pollMaya();
pollPhone();
pollAutoUv();
pollBake();
diff --git a/src/app/App.h b/src/app/App.h
index 295a80c1..3dab7b8e 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -874,6 +874,18 @@ private:
bool blenderAutoReceive_ = true; // load whatever Blender sends while SculptForge runs
int64_t blenderSeenRevision_ = -1; // revision last loaded (or present at start, which is not loaded)
Uint64 blenderLastPollNs_ = 0, blenderLastBeatNs_ = 0;
+ // Maya bridge (PanelMaya.cpp, io/MayaBridge.h, #42): off until the user picks an exchange folder
+ // (uiPrefs_.mayaFolder); with Get automatically on, that one folder's manifest is checked once a second.
+ void drawMayaMenu();
+ void pollMaya();
+ void sendToMaya();
+ void receiveFromMaya();
+ void chooseMayaFolder();
+ void setMayaFolder(const std::string& folder);
+ int64_t mayaSeenRevision_ = -1; // revision last loaded (or present when the folder was chosen / at start)
+ long long mayaManifestStamp_ = 0; // its modification time and size then (the cheap check before reading it)
+ bool mayaInitialised_ = false;
+ Uint64 mayaLastPollNs_ = 0;
// Phone link (PanelPhone.cpp, link/PhoneLink.h): File > Capture from phone. The server runs only while the
// window is open; captures land in <library>/Captures and run the command for their kind; AR models are
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 4f4b8c33..4b5a9e0e 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -112,7 +112,7 @@ void fromJson(const Json& j, UiPrefs& p) {
namespace {
-enum UiFileKind { kSaveUi, kLoadUi, kRunScript, kLibraryFolder, kBlenderKeymap, kUiFileKinds };
+enum UiFileKind { kSaveUi, kLoadUi, kRunScript, kLibraryFolder, kBlenderKeymap, kMayaFolder, kUiFileKinds };
struct UiFileRequest {
App* app = nullptr;
@@ -384,6 +384,19 @@ void App::initActions() {
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.");
+ // Maya bridge (PanelMaya.cpp, integrations/maya, #42): off until an exchange folder is chosen.
+ add("file.send_maya", "Send to Maya", "File > Maya", nullptr, [this] { sendToMaya(); }, ICON_LC_SEND, "maya_send",
+ nullptr, nullptr,
+ "Send the visible SubTools to Maya (OBJ with quads and UVs) through the exchange folder you chose; Get from "
+ "SculptForge on Maya's SculptForge shelf loads them, replacing the objects they came from by name.");
+ add("file.receive_maya", "Get from Maya", "File > Maya", nullptr, [this] { receiveFromMaya(); }, nullptr,
+ "maya_receive", nullptr, nullptr,
+ "Load what Maya last sent with the shelf's Send to SculptForge. Each object replaces the SubTool with its name "
+ "(undoable) or becomes a new one.");
+ add("file.maya_folder", "Exchange folder...", "File > Maya", nullptr, [this] { chooseMayaFolder(); },
+ ICON_LC_FOLDER_OPEN, nullptr, nullptr, nullptr,
+ "Choose the folder SculptForge and Maya exchange meshes through (pick the same one in Maya's shelf script). "
+ "SculptForge reads and writes only there, and only when you send or get.");
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,
@@ -705,6 +718,12 @@ void App::importBlenderKeymapDialog() {
SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kBlenderKeymap], window_, kBlenderKeymapFilters, 2, nullptr, false);
}
+void App::chooseMayaFolder() { // the only way the Maya bridge gets a folder: the user picks it (PanelMaya.cpp)
+ const std::string start = uiPrefs_.mayaFolder;
+ SDL_ShowOpenFolderDialog(onUiFileChosen, &g_requests[kMayaFolder], window_, start.empty() ? nullptr : start.c_str(),
+ false);
+}
+
void App::loadUiDialog() {
SDL_ShowOpenFileDialog(onUiFileChosen, &g_requests[kLoadUi], window_, kUiFilters, 1, nullptr, false);
}
@@ -815,6 +834,8 @@ void App::drawHelpConsoleUi() {
}
} else if (kind == kBlenderKeymap) {
importBlenderKeymap(path);
+ } else if (kind == kMayaFolder) {
+ setMayaFolder(path);
} else if (kind == kRunScript) {
setConsoleOpen(true);
console_.queueScriptFile(path);
diff --git a/src/app/Config.h b/src/app/Config.h
index a66de5e4..0b036524 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -57,6 +57,10 @@ struct UiPrefs {
// Preferences > Display: the view's background (#21), a gradient or a flat display (sRGB) colour.
bool gradientBackground = true;
glm::vec3 backgroundColor{0.165f, 0.165f, 0.173f};
+ // File > Maya (#42). Kept in <prefs>/maya.json, never in ui.json, so a shared UI layout can't point the bridge
+ // at a folder: it is set only by the user's own pick (App::setMayaFolder).
+ std::string mayaFolder; // "" = the bridge is off
+ bool mayaAutoReceive = false; // Get automatically: check that folder's manifest once a second
};
Json toJson(const UiPrefs& prefs);
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index a9f645a3..10ccb0f0 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -367,6 +367,7 @@ void App::drawPalette_File() {
ImGui::Separator();
drawGozMenu();
drawBlenderMenu(); // the Blender bridge (PanelBlender.cpp)
+ drawMayaMenu(); // the Maya bridge (PanelMaya.cpp)
menuAction(*this, "file.capture_phone"); // the phone link (PanelPhone.cpp)
ImGui::Separator();
menuAction(*this, "file.quit");
diff --git a/src/app/PanelMaya.cpp b/src/app/PanelMaya.cpp
new file mode 100644
index 00000000..17cdaf70
--- /dev/null
+++ b/src/app/PanelMaya.cpp
@@ -0,0 +1,167 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// File > Maya (#42): the file-exchange bridge to the SculptForge shelf script for Maya (io/MayaBridge.h,
+// integrations/maya). Off until the user picks an exchange folder with the native folder dialog; SculptForge
+// then reads and writes only inside that folder, only when the user sends or gets, or (Get automatically, off
+// by default) after a once-a-second modification-time check of that folder's one manifest. No sockets, no
+// ports, and nothing from the folder is ever run.
+#include "app/App.h"
+#include "app/Ui.h"
+
+#include "core/Json.h"
+#include "io/MayaBridge.h"
+
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+namespace sf {
+
+namespace {
+
+std::filesystem::path fsPath(const std::string& utf8) { return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); }
+
+bool isFolder(const std::string& path) {
+ std::error_code ec;
+ return !path.empty() && std::filesystem::is_directory(fsPath(path), ec);
+}
+
+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);
+}
+
+// <prefs>/maya.json: {"folder": "...", "auto": false}. Read strictly: a small file, a string path to an existing
+// folder (else the bridge stays off).
+void loadMayaPrefs(const std::string& configDir, UiPrefs& p) {
+ if (configDir.empty()) return;
+ std::ifstream f(fsPath(configDir + "maya.json"), std::ios::binary);
+ if (!f) return;
+ std::string text(std::istreambuf_iterator<char>(f), {});
+ Json j;
+ std::string err;
+ if (text.size() > 16384 || !Json::parse(text, j, err) || !j.isObject()) return;
+ if (j["folder"].isString() && j["folder"].asString().size() < 4096 && isFolder(j["folder"].asString()))
+ p.mayaFolder = j["folder"].asString();
+ p.mayaAutoReceive = !p.mayaFolder.empty() && j["auto"].asBool(false);
+}
+
+void saveMayaPrefs(const std::string& configDir, const UiPrefs& p) {
+ if (configDir.empty()) return;
+ Json j = Json::object();
+ j.set("folder", p.mayaFolder);
+ j.set("auto", p.mayaAutoReceive);
+ std::ofstream f(fsPath(configDir + "maya.json"), std::ios::binary | std::ios::trunc);
+ f << j.dump(true) << "\n";
+}
+
+} // namespace
+
+void App::setMayaFolder(const std::string& folder) {
+ if (!isFolder(folder)) {
+ status_ = "Not a folder: " + folder;
+ return;
+ }
+ uiPrefs_.mayaFolder = folder;
+ // What is already there is old news: Get from Maya loads it, Get automatically waits for the next send.
+ const std::string inbox = mayaInbox(folder);
+ mayaSeenRevision_ = mayaRevision(inbox);
+ mayaManifestStamp_ = mayaManifestStamp(inbox);
+ if (!uiConfigDeterministic_) saveMayaPrefs(configDir_, uiPrefs_);
+ status_ = "Maya exchange folder: " + folder + " (choose the same one in Maya's SculptForge shelf)";
+}
+
+void App::sendToMaya() {
+ if (uiPrefs_.mayaFolder.empty()) {
+ status_ = "Choose the folder to exchange meshes with Maya through";
+ chooseMayaFolder();
+ return;
+ }
+ runCommand("maya_send", {{"folder", uiPrefs_.mayaFolder}});
+}
+
+void App::receiveFromMaya() {
+ if (uiPrefs_.mayaFolder.empty()) {
+ status_ = "Choose the folder to exchange meshes with Maya through";
+ chooseMayaFolder();
+ return;
+ }
+ const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);
+ mayaSeenRevision_ = mayaRevision(inbox); // a manual get counts as seen, so polling doesn't load it again
+ mayaManifestStamp_ = mayaManifestStamp(inbox);
+ runCommand("maya_receive", {{"folder", uiPrefs_.mayaFolder}});
+ if (status_.rfind("Received", 0) == 0) camera_.frame(sceneBounds());
+}
+
+void App::drawMayaMenu() {
+ if (!ImGui::BeginMenu("Maya")) return;
+ menuAction(*this, "file.send_maya");
+ menuAction(*this, "file.receive_maya");
+ const bool hasFolder = !uiPrefs_.mayaFolder.empty();
+ if (ImGui::MenuItem("Get automatically##maya", nullptr, &uiPrefs_.mayaAutoReceive, hasFolder)) {
+ if (uiPrefs_.mayaAutoReceive) { // from now on: what is there already waits for Get from Maya
+ const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);
+ mayaSeenRevision_ = mayaRevision(inbox);
+ mayaManifestStamp_ = mayaManifestStamp(inbox);
+ }
+ if (!uiConfigDeterministic_) saveMayaPrefs(configDir_, uiPrefs_);
+ }
+ ui::HelpText("Get automatically", nullptr,
+ "Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest once a "
+ "second (its modification time and size only). Off by default; off: use Get from Maya.",
+ "File > Maya");
+ ImGui::Separator();
+ menuAction(*this, "file.maya_folder");
+ if (hasFolder) {
+ ImGui::TextDisabled("Folder: %s", uiPrefs_.mayaFolder.c_str());
+ if (ImGui::MenuItem("Turn the Maya bridge off##maya")) {
+ uiPrefs_.mayaFolder.clear();
+ uiPrefs_.mayaAutoReceive = false;
+ if (!uiConfigDeterministic_) saveMayaPrefs(configDir_, uiPrefs_);
+ status_ = "Maya bridge off: SculptForge no longer reads or writes the exchange folder";
+ }
+ ui::HelpText("Turn the Maya bridge off", nullptr, "Forget the exchange folder; nothing in it is deleted.",
+ "File > Maya");
+ } else {
+ ImGui::TextDisabled("Off: choose an exchange folder first.");
+ }
+ ImGui::TextDisabled("Needs the SculptForge shelf script in Maya\n(Help > User Guide > Working with Maya).");
+ ImGui::EndMenu();
+}
+
+void App::pollMaya() {
+ if (!mayaInitialised_) {
+ mayaInitialised_ = true;
+ if (!uiConfigDeterministic_) loadMayaPrefs(configDir_, uiPrefs_);
+ if (!uiPrefs_.mayaFolder.empty()) { // what was sent before this start is old news
+ const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);
+ mayaSeenRevision_ = mayaRevision(inbox);
+ mayaManifestStamp_ = mayaManifestStamp(inbox);
+ }
+ }
+ if (!uiPrefs_.mayaAutoReceive || uiPrefs_.mayaFolder.empty() || doc_.sculptor.strokeActive()) return;
+ // 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 (mayaLastPollNs_ != 0 && now - mayaLastPollNs_ < interval) return;
+ mayaLastPollNs_ = now;
+ // The cheap check first: the manifest's modification time and size. Only when they changed is the (small,
+ // size-capped) manifest read for its revision.
+ const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);
+ const long long t = mayaManifestStamp(inbox);
+ if (t == 0 || t == mayaManifestStamp_) return;
+ mayaManifestStamp_ = t;
+ const int64_t revision = mayaRevision(inbox);
+ if (revision >= 0 && revision != mayaSeenRevision_) receiveFromMaya();
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 6ec9dcde..90e1fbc2 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -1174,6 +1174,14 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
if (file.is_relative()) file = std::filesystem::path(std::u8string(scriptDir_.begin(), scriptDir_.end())) / file;
const auto u8 = file.lexically_normal().u8string();
run([this, path = std::string(u8.begin(), u8.end())] { app_.openPathConfirmed(path); });
+ } else if (verb == "choose_file" && w.size() > 2 && w[1] == "maya_folder") {
+ // choose_file maya_folder <folder>: what File > Maya > Exchange folder's dialog would answer (relative to the
+ // working directory, like copy's destination).
+ run([this, to = w[2]] {
+ const std::string d = expandLibrary(to);
+ const auto u8 = std::filesystem::absolute(std::filesystem::path(std::u8string(d.begin(), d.end()))).lexically_normal().u8string();
+ app_.setMayaFolder(std::string(u8.begin(), u8.end()));
+ });
} else if (verb == "choose_file") { // choose_file insert|append <path>: what a native file dialog would answer
if (!need(2)) return false;
App::FileAction action;
diff --git a/src/app/UserGuide.cpp b/src/app/UserGuide.cpp
index d01a8d41..84998eef 100644
--- a/src/app/UserGuide.cpp
+++ b/src/app/UserGuide.cpp
@@ -435,6 +435,7 @@ std::string UserGuide::chapterFor(const std::string& palette, const std::string&
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 > Maya")) return "maya.md";
if (starts("File > Capture from phone") || actionId == "file.capture_phone") return "phone-capture.md";
if (starts("File > Export") || idStarts("file.export") || actionId == "file.send_unreal" || actionId == "file.save_splats" ||
starts("File > GoZ"))
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index de3ea564..4f29bd38 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -37,6 +37,7 @@
#include "io/BlenderCommands.h"
#include "io/GozCommands.h"
#include "io/GozIO.h"
+#include "io/MayaCommands.h"
#include "io/ObjIO.h"
#include "io/PlyIO.h"
#include "io/StlIO.h"
@@ -813,6 +814,7 @@ CommandRegistry::CommandRegistry() {
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)
+ registerMayaCommands(*this); // maya_send/receive (io/MayaCommands.cpp)
registerBakeCommands(*this); // bake (core/Bake.cpp)
registerFaceCommands(*this); // face_shapes_generate, face_weights, ... (core/FaceCommands.cpp)
registerProjectCommands(*this); // keep last (core/Project.cpp)
diff --git a/src/io/MayaBridge.cpp b/src/io/MayaBridge.cpp
new file mode 100644
index 00000000..e33514ba
--- /dev/null
+++ b/src/io/MayaBridge.cpp
@@ -0,0 +1,381 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/MayaBridge.h"
+
+#include "core/Json.h"
+#include "io/ObjIO.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+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());
+}
+
+// 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;
+}
+
+bool isAsciiAlnum(unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
+
+// A plain folder (not a link) inside the exchange folder.
+bool plainFolder(const fs::path& p) {
+ std::error_code ec;
+ const fs::file_status s = fs::symlink_status(p, ec);
+ return !ec && fs::is_directory(s);
+}
+
+std::string countText(size_t n) { return std::to_string(n) + (n == 1 ? " object" : " objects"); }
+
+} // namespace
+
+std::string mayaInbox(const std::string& folder) { return pathUtf8(utf8Path(folder) / "maya_to_sculptforge"); }
+std::string mayaOutbox(const std::string& folder) { return pathUtf8(utf8Path(folder) / "sculptforge_to_maya"); }
+std::string mayaManifestPath(const std::string& box) { return pathUtf8(utf8Path(box) / "manifest.json"); }
+
+std::string mayaSafeName(const std::string& name) {
+ std::string s;
+ for (unsigned char c : name) {
+ if (s.size() >= kMayaMaxNameBytes) break;
+ s += isAsciiAlnum(c) || c == '_' ? char(c) : '_';
+ }
+ if (s.empty()) return "SubTool";
+ if (s[0] >= '0' && s[0] <= '9') {
+ s.insert(s.begin(), '_');
+ if (s.size() > kMayaMaxNameBytes) s.pop_back();
+ }
+ return s;
+}
+
+bool mayaFileNameOk(const std::string& file) {
+ if (file.empty() || file.size() > kMayaMaxFileNameBytes || file[0] == '.') return false;
+ if (file.find("..") != std::string::npos) return false;
+ for (unsigned char c : file)
+ if (!isAsciiAlnum(c) && c != '_' && c != '.' && c != '-') return false; // no '/', '\\', ':', spaces...
+ if (file.size() < 5) return false;
+ std::string ext = file.substr(file.size() - 4);
+ for (char& c : ext) c = char(std::tolower(static_cast<unsigned char>(c)));
+ return ext == ".obj";
+}
+
+bool parseMayaManifest(const std::string& text, MayaManifest& out, std::string& error) {
+ if (text.size() > kMayaManifestMaxBytes) {
+ error = "The Maya bridge manifest is too big";
+ return false;
+ }
+ Json j;
+ if (!Json::parse(text, j, error)) {
+ error = "The Maya bridge manifest is not valid JSON: " + error;
+ return false;
+ }
+ if (!j.isObject() || !j["format"].isString() || j["format"].asString() != "sculptforge-maya") {
+ error = "Not a SculptForge Maya bridge manifest";
+ return false;
+ }
+ const Json& version = j["version"];
+ if (!version.isNumber() || version.asNumber() < 1 || version.asNumber() != std::floor(version.asNumber())) {
+ error = "The Maya bridge manifest has no valid version";
+ return false;
+ }
+ if (version.asNumber() > 1) {
+ error = "The Maya bridge manifest is from a newer shelf script or SculptForge (version " +
+ std::to_string(int(std::min(version.asNumber(), 1e9))) + "); update the older one";
+ return false;
+ }
+ const Json& revision = j["revision"];
+ if (!revision.isNumber() || revision.asNumber() < 0 || revision.asNumber() > 9007199254740992.0 ||
+ revision.asNumber() != std::floor(revision.asNumber())) {
+ error = "The Maya bridge manifest has no valid revision";
+ return false;
+ }
+ MayaManifest m;
+ m.revision = int64_t(revision.asNumber());
+ auto optionalString = [&](const char* key, std::string& to) {
+ const Json& v = j[key];
+ if (v.isNull()) return true;
+ if (!v.isString() || v.asString().size() > 64) {
+ error = std::string("The Maya bridge manifest has a bad \"") + key + "\"";
+ return false;
+ }
+ to = v.asString();
+ return true;
+ };
+ if (!optionalString("sender", m.sender) || !optionalString("sender_version", m.senderVersion) ||
+ !optionalString("unit", m.unit))
+ return false;
+ const Json& objects = j["objects"];
+ if (!objects.isArray()) {
+ error = "The Maya bridge manifest lists no objects";
+ return false;
+ }
+ if (objects.size() > kMayaMaxObjects) {
+ error = "The Maya bridge manifest lists too many objects (" + std::to_string(objects.size()) + ", at most " +
+ std::to_string(kMayaMaxObjects) + ")";
+ return false;
+ }
+ for (const Json& o : objects.items()) {
+ if (!o.isObject() || !o["name"].isString() || !o["file"].isString()) {
+ error = "The Maya bridge manifest has an object without a name and a file";
+ return false;
+ }
+ MayaObject b;
+ b.file = o["file"].asString();
+ if (!mayaFileNameOk(b.file)) {
+ error = "The Maya bridge manifest names a file SculptForge won't read: \"" +
+ b.file.substr(0, kMayaMaxFileNameBytes) + "\" (only plain .obj names in the same folder)";
+ return false;
+ }
+ for (const MayaObject& seen : m.objects)
+ if (seen.file == b.file) {
+ error = "The Maya bridge manifest lists \"" + b.file + "\" twice";
+ return false;
+ }
+ if (o["name"].asString().size() > 4 * kMayaMaxNameBytes) {
+ error = "The Maya bridge manifest has a name that is too long";
+ return false;
+ }
+ b.name = mayaSafeName(o["name"].asString());
+ m.objects.push_back(std::move(b));
+ }
+ out = std::move(m);
+ return true;
+}
+
+std::string writeMayaManifest(const MayaManifest& m) {
+ std::string s = "{\n \"format\": \"sculptforge-maya\",\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";
+ if (!m.unit.empty()) s += " \"unit\": " + jsonQuote(m.unit) + ",\n";
+ s += " \"objects\": [";
+ for (size_t i = 0; i < m.objects.size(); ++i) {
+ s += i ? ",\n {" : "\n {";
+ s += "\"name\": " + jsonQuote(m.objects[i].name) + ", \"file\": " + jsonQuote(m.objects[i].file) + "}";
+ }
+ s += m.objects.empty() ? "]\n}\n" : "\n ]\n}\n";
+ return s;
+}
+
+bool readMayaManifest(const std::string& path, MayaManifest& out, std::string& error) {
+ const fs::path p = utf8Path(path);
+ std::error_code ec;
+ const fs::file_status st = fs::symlink_status(p, ec);
+ if (ec || !fs::exists(st)) {
+ error = "Nothing has been sent yet (no " + path + ")";
+ return false;
+ }
+ if (!fs::is_regular_file(st)) {
+ error = path + " is not a plain file";
+ return false;
+ }
+ const auto size = fs::file_size(p, ec);
+ if (ec || size > kMayaManifestMaxBytes) {
+ error = "The Maya bridge manifest is too big";
+ return false;
+ }
+ std::ifstream f(p, std::ios::binary);
+ if (!f) {
+ error = "Cannot read " + path;
+ return false;
+ }
+ std::string text(size_t(size), '\0');
+ f.read(text.data(), std::streamsize(size));
+ text.resize(size_t(f.gcount()));
+ return parseMayaManifest(text, out, error);
+}
+
+bool mayaReceive(const std::string& folder, std::vector<MeshObject>& out, MayaManifest* manifest,
+ std::string& message) {
+ if (folder.empty()) {
+ message = "Choose the Maya exchange folder first (File > Maya > Exchange folder...)";
+ return false;
+ }
+ const fs::path inbox = utf8Path(mayaInbox(folder));
+ if (!plainFolder(inbox)) {
+ message = "Nothing has been sent from Maya yet";
+ return false;
+ }
+ MayaManifest m;
+ if (!readMayaManifest(mayaManifestPath(pathUtf8(inbox)), m, message)) {
+ if (message.rfind("Nothing", 0) == 0) message = "Nothing has been sent from Maya yet";
+ return false;
+ }
+ if (m.objects.empty()) {
+ message = "Maya sent no objects";
+ return false;
+ }
+ std::vector<MeshObject> objects;
+ std::vector<std::string> names;
+ for (const MayaObject& b : m.objects) {
+ const fs::path file = inbox / utf8Path(b.file); // a plain name (checked): stays in the inbox
+ std::error_code ec;
+ const fs::file_status st = fs::symlink_status(file, ec);
+ if (ec || !fs::is_regular_file(st)) {
+ message = "Cannot load \"" + b.name + "\" from Maya: " + b.file + " is missing or not a plain file";
+ return false;
+ }
+ if (fs::file_size(file, ec) > kMayaMaxObjBytes || ec) {
+ message = "Cannot load \"" + b.name + "\" from Maya: " + b.file + " is too big";
+ return false;
+ }
+ MeshObject obj;
+ // Maya's own duplicates (the same short name under different parents): keep them apart.
+ obj.name = b.name;
+ for (int n = 1; std::find(names.begin(), names.end(), obj.name) != names.end(); ++n)
+ obj.name = b.name + std::to_string(n);
+ names.push_back(obj.name);
+ std::string err;
+ if (!loadObj(pathUtf8(file), obj.mesh, err)) {
+ message = "Cannot load \"" + obj.name + "\" from Maya: " + err;
+ return false;
+ }
+ if (obj.mesh.triangleCount() == 0) {
+ message = "Cannot load \"" + obj.name + "\" from Maya: " + b.file + " has no faces";
+ return false;
+ }
+ objects.push_back(std::move(obj));
+ }
+ size_t triangles = 0;
+ for (const auto& o : objects) triangles += o.mesh.triangleCount();
+ message = "Received " + countText(objects.size()) + " from Maya (" + std::to_string(triangles) + " triangles)";
+ out = std::move(objects);
+ if (manifest) *manifest = std::move(m);
+ return true;
+}
+
+bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& folder, std::string& message,
+ std::vector<std::string>* sentNames, int64_t* revision) {
+ if (folder.empty()) {
+ message = "Choose the Maya exchange folder first (File > Maya > Exchange folder...)";
+ return false;
+ }
+ if (objects.empty()) {
+ message = "Nothing visible to send to Maya";
+ return false;
+ }
+ if (objects.size() > kMayaMaxObjects) {
+ message = "Too many SubTools to send to Maya at once (at most " + std::to_string(kMayaMaxObjects) + ")";
+ return false;
+ }
+ std::error_code ec;
+ if (!fs::is_directory(utf8Path(folder), ec)) {
+ message = "The Maya exchange folder is gone: " + folder;
+ return false;
+ }
+ const fs::path outbox = utf8Path(mayaOutbox(folder));
+ if (fs::exists(fs::symlink_status(outbox, ec)) && !plainFolder(outbox)) {
+ message = pathUtf8(outbox) + " is not a plain folder";
+ return false;
+ }
+ fs::create_directories(outbox, ec);
+ if (ec) {
+ message = "Cannot create " + pathUtf8(outbox) + ": " + ec.message();
+ return false;
+ }
+ MayaManifest m;
+ m.revision = std::max<int64_t>(mayaRevision(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) + "_";
+ // Nothing already in the way of this send's files may redirect them: a planted link named like one of them
+ // (or the manifest's temporary file) is removed, not written through.
+ for (const auto& entry : fs::directory_iterator(outbox, ec)) {
+ const std::string n = pathUtf8(entry.path().filename());
+ if (n.rfind(prefix, 0) == 0 || n == "manifest.json.tmp") {
+ std::error_code rm;
+ fs::remove(entry.path(), rm);
+ }
+ }
+ std::vector<std::string> names;
+ for (size_t k = 0; k < objects.size(); ++k) {
+ // Maya's names for duplicates: Name, Name1, Name2...
+ const std::string wanted = mayaSafeName(objects[k].name);
+ std::string name = wanted;
+ for (int n = 1; std::find(names.begin(), names.end(), name) != names.end(); ++n) name = wanted + std::to_string(n);
+ names.push_back(name);
+ char file[32];
+ std::snprintf(file, sizeof file, "%03zu.obj", k);
+ MayaObject b{name, prefix + file};
+ std::string err;
+ const Mesh& mesh = *objects[k].mesh;
+ bool ok;
+ if (mesh.hasPolygroups()) {
+ // Polygroups would be OBJ groups, which Maya's importer turns into separate objects or sets.
+ Mesh plain = mesh;
+ plain.polygroups.clear();
+ ok = saveObj(pathUtf8(outbox / utf8Path(b.file)), plain, err);
+ } else {
+ ok = saveObj(pathUtf8(outbox / utf8Path(b.file)), mesh, err);
+ }
+ if (!ok) {
+ message = "Cannot send \"" + name + "\" to Maya: " + err;
+ return false;
+ }
+ m.objects.push_back(std::move(b));
+ }
+ if (!writeAtomically(outbox / "manifest.json", writeMayaManifest(m))) {
+ message = "Cannot write " + pathUtf8(outbox / "manifest.json");
+ return false;
+ }
+ // Earlier sends' files (r<n>_...): the shelf script has read them, or never will.
+ for (const auto& entry : fs::directory_iterator(outbox, ec)) {
+ const std::string n = pathUtf8(entry.path().filename());
+ size_t digits = 1;
+ while (digits < n.size() && n[digits] >= '0' && n[digits] <= '9') ++digits;
+ const bool ours = n.size() > 2 && n[0] == 'r' && digits > 1 && digits < n.size() && n[digits] == '_';
+ if (ours && n.rfind(prefix, 0) != 0) {
+ std::error_code rm;
+ fs::remove(entry.path(), rm); // may be open on Windows; the next send tries again
+ }
+ }
+ message = "Sent " + countText(objects.size()) + " to Maya: click Get from SculptForge on Maya's SculptForge shelf";
+ if (sentNames) *sentNames = std::move(names);
+ if (revision) *revision = m.revision;
+ return true;
+}
+
+int64_t mayaRevision(const std::string& box) {
+ MayaManifest m;
+ std::string err;
+ return readMayaManifest(mayaManifestPath(box), m, err) ? m.revision : -1;
+}
+
+long long mayaManifestStamp(const std::string& box) {
+ if (box.empty()) return 0;
+ std::error_code ec;
+ const fs::path p = utf8Path(mayaManifestPath(box));
+ const auto t = fs::last_write_time(p, ec);
+ if (ec) return 0;
+ const auto size = fs::file_size(p, ec);
+ if (ec) return 0;
+ const unsigned long long stamp = static_cast<unsigned long long>(t.time_since_epoch().count()) * 1000003ull + size;
+ return static_cast<long long>(stamp | 1); // never 0 for a file that is there
+}
+
+} // namespace sf
diff --git a/src/io/MayaBridge.h b/src/io/MayaBridge.h
new file mode 100644
index 00000000..46a5ab31
--- /dev/null
+++ b/src/io/MayaBridge.h
@@ -0,0 +1,77 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The Maya bridge (#42): SculptForge and the SculptForge shelf script for Maya (integrations/maya) exchange
+// meshes through ONE folder the user picks on both sides, the way GoZ apps do with ZBrush. Nothing else is
+// shared: no sockets, ports or other IPC, and nothing in the folder is ever run. Meshes travel as OBJ (quads,
+// UVs; one object per file, world space, Maya's Y-up and units as they are); a small JSON manifest per
+// direction lists the objects, their Maya names and a revision number so each side sees what is new.
+// docs/guide/maya.md describes the folder and the manifest.
+//
+// <folder>/maya_to_sculptforge/manifest.json + r<rev>_<k>.obj written by Maya
+// <folder>/sculptforge_to_maya/manifest.json + r<rev>_<k>.obj written by SculptForge
+//
+// What SculptForge reads is checked strictly (it may come from anything that can write to the folder): the
+// manifest's size, version and every field's type; at most kMayaMaxObjects objects; names are reduced to Maya's
+// characters; files must be plain *.obj names in the manifest's own folder (no folders, no "..", no absolute
+// paths, no links) and regular files no bigger than kMayaMaxObjBytes.
+#pragma once
+
+#include "io/MeshObject.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+inline constexpr size_t kMayaManifestMaxBytes = 256 * 1024;
+inline constexpr size_t kMayaMaxObjects = 256;
+inline constexpr size_t kMayaMaxNameBytes = 128;
+inline constexpr size_t kMayaMaxFileNameBytes = 64;
+inline constexpr unsigned long long kMayaMaxObjBytes = 8ull << 30; // 8 GiB: a 30M-triangle OBJ with UVs fits
+
+struct MayaObject {
+ std::string name; // the Maya transform's short name (Maya characters only): the SubTool's gozName
+ std::string file; // OBJ file name inside the manifest's folder
+};
+
+struct MayaManifest {
+ int64_t revision = 0; // changes on every send (each side keeps the last one it loaded)
+ std::string sender; // "maya" or "sculptforge"
+ std::string senderVersion;
+ std::string unit; // Maya's linear unit when Maya sent ("cm" by default); informational, OBJ is taken 1:1
+ std::vector<MayaObject> objects;
+};
+
+std::string mayaInbox(const std::string& folder); // <folder>/maya_to_sculptforge
+std::string mayaOutbox(const std::string& folder); // <folder>/sculptforge_to_maya
+std::string mayaManifestPath(const std::string& box); // <box>/manifest.json
+
+// A name Maya accepts as is: letters, digits and '_' (anything else becomes '_'), not starting with a digit,
+// at most kMayaMaxNameBytes; "" becomes "SubTool".
+std::string mayaSafeName(const std::string& name);
+// A file name a manifest may list: 1..kMayaMaxFileNameBytes of [A-Za-z0-9_.-], not starting with '.', no "..",
+// ending in ".obj".
+bool mayaFileNameOk(const std::string& file);
+
+bool parseMayaManifest(const std::string& text, MayaManifest& out, std::string& error);
+std::string writeMayaManifest(const MayaManifest& manifest);
+// Reads at most kMayaManifestMaxBytes (a bigger file is refused unread).
+bool readMayaManifest(const std::string& path, MayaManifest& out, std::string& error);
+
+// Loads what Maya sent (<folder>/maya_to_sculptforge): every object's OBJ, named after its Maya object.
+bool mayaReceive(const std::string& folder, std::vector<MeshObject>& out, MayaManifest* manifest,
+ std::string& message);
+// Writes the objects to <folder>/sculptforge_to_maya with the next revision (names made Maya-safe and unique;
+// `sentNames` receives them) and removes the files of earlier sends.
+bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& folder, std::string& message,
+ std::vector<std::string>* sentNames = nullptr, int64_t* revision = nullptr);
+
+// The revision of the manifest in `box`, or -1 when there is none (or it is not valid).
+int64_t mayaRevision(const std::string& box);
+// The modification time and size of <box>/manifest.json in one number (0 when missing): the cheap check polling
+// makes before reading it. (The size too: a copied file can keep its time, and some drives store it coarsely.)
+long long mayaManifestStamp(const std::string& box);
+
+} // namespace sf
diff --git a/src/io/MayaCommands.cpp b/src/io/MayaCommands.cpp
new file mode 100644
index 00000000..2815a81d
--- /dev/null
+++ b/src/io/MayaCommands.cpp
@@ -0,0 +1,43 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/MayaCommands.h"
+
+#include "io/GozCommands.h"
+#include "io/MayaBridge.h"
+
+namespace sf {
+
+void registerMayaCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+
+ reg.add({"maya_send",
+ "Send the visible SubTools to Maya through the exchange folder the SculptForge shelf script reads "
+ "(OBJ with quads and UVs, plus a manifest). Objects that came from Maya replace their mesh there by "
+ "name; the others become new objects.",
+ {{"folder", T::String, "The exchange folder (the same one chosen in Maya's shelf script).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<int> indices;
+ const auto objects = gozObjects(doc, indices);
+ std::vector<std::string> sent;
+ std::string msg;
+ if (!mayaSend(objects, argString(a, "folder"), msg, &sent)) return {false, msg};
+ // Maya'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({"maya_receive",
+ "Load what Maya last sent with the SculptForge shelf script. Each object replaces the SubTool with its "
+ "name (an undoable step on that SubTool) or becomes a new SubTool; the first object replaces a fresh "
+ "scene.",
+ {{"folder", T::String, "The exchange folder (the same one chosen in Maya's shelf script).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<MeshObject> objects;
+ std::string msg;
+ if (!mayaReceive(argString(a, "folder"), objects, nullptr, msg)) return {false, msg};
+ receiveObjects(doc, objects, "Get from Maya", true);
+ return {true, msg};
+ }});
+}
+
+} // namespace sf
diff --git a/src/io/MayaCommands.h b/src/io/MayaCommands.h
new file mode 100644
index 00000000..1c43b868
--- /dev/null
+++ b/src/io/MayaCommands.h
@@ -0,0 +1,15 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Maya bridge commands: maya_send and maya_receive (io/MayaBridge.h). Both take the exchange folder explicitly:
+// the app passes the one the user picked (File > Maya > Exchange folder...). Registered by CommandRegistry's
+// constructor.
+#pragma once
+
+#include "core/Commands.h"
+
+namespace sf {
+
+void registerMayaCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/tests/maya/test_sculptforge_maya.py b/tests/maya/test_sculptforge_maya.py
new file mode 100644
index 00000000..4734dfe2
--- /dev/null
+++ b/tests/maya/test_sculptforge_maya.py
@@ -0,0 +1,413 @@
+# SculptForge - open source digital sculpting
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# python3 tests/maya/test_sculptforge_maya.py [--cli path/to/sculptforge-cli]
+#
+# The Maya shelf script (integrations/maya/sculptforge_maya.py, #42) without Maya: its manifest code with plain
+# Python, and Send / Get against a small mocked maya.cmds (a scene of transforms and mesh shapes whose OBJ
+# "export" and "import" read and write real files). With --cli, what the script sends goes through SculptForge
+# (maya_receive, then maya_send) and comes back into the mocked scene, replacing the meshes by name.
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import types
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "..", "integrations", "maya"))
+
+failures = 0
+
+
+def check(cond, what):
+ global failures
+ if not cond:
+ failures += 1
+ print("FAILED: " + what)
+
+
+# A cube of six quads with UVs, as Maya's OBJ exporter writes one (world space).
+CUBE_OBJ = """# Maya OBJ export
+v -1 -1 1
+v 1 -1 1
+v -1 1 1
+v 1 1 1
+v -1 1 -1
+v 1 1 -1
+v -1 -1 -1
+v 1 -1 -1
+vt 0 0
+vt 1 0
+vt 0 1
+vt 1 1
+f 1/1 2/2 4/4 3/3
+f 3/1 4/2 6/4 5/3
+f 5/1 6/2 8/4 7/3
+f 7/1 8/2 2/4 1/3
+f 2/1 8/2 6/4 4/3
+f 7/1 1/2 3/4 5/3
+"""
+
+
+class FakeCmds(types.ModuleType):
+ """Just enough of maya.cmds for the shelf script: nodes are long paths ("|grp|pCube1")."""
+
+ def __init__(self, dialog_folder):
+ super().__init__("maya.cmds")
+ self.nodes = {} # long path -> {"type", "obj" (mesh text), "sgs"}
+ self.selection = []
+ self.option_vars = {}
+ self.dialog_folder = dialog_folder
+ self.plugins = set()
+ self.undo = []
+ self.calls = []
+ self.namespaces = set()
+ self.warnings = []
+
+ # scene helpers
+ def add_mesh(self, transform, obj_text, sgs=("blinn1SG",)):
+ self.nodes[transform] = {"type": "transform"}
+ shape = transform + "|" + transform.split("|")[-1] + "Shape"
+ self.nodes[shape] = {"type": "mesh", "obj": obj_text, "sgs": list(sgs)}
+ return shape
+
+ def _long(self, name):
+ if name in self.nodes:
+ return name
+ hits = [n for n in self.nodes if n.split("|")[-1] == name]
+ return hits[0] if hits else None
+
+ # maya.cmds
+ def optionVar(self, q=None, exists=None, sv=None, iv=None):
+ if exists is not None:
+ return exists in self.option_vars
+ if q is not None:
+ return self.option_vars.get(q, "")
+ for pair in (sv, iv):
+ if pair:
+ self.option_vars[pair[0]] = pair[1]
+
+ def fileDialog2(self, **kw):
+ return [self.dialog_folder] if self.dialog_folder else None
+
+ def warning(self, text):
+ self.warnings.append(text)
+
+ def inViewMessage(self, **kw):
+ pass
+
+ def pluginInfo(self, name, q=False, loaded=False):
+ return name in self.plugins
+
+ def loadPlugin(self, name, quiet=False):
+ self.plugins.add(name)
+
+ def about(self, version=False):
+ return "2026"
+
+ def currentUnit(self, q=False, linear=False):
+ return "cm"
+
+ def ls(self, *names, selection=False, long=False, objectsOnly=False, type=None):
+ if selection:
+ return list(self.selection)
+ out = []
+ for n in names:
+ if isinstance(n, (list, tuple)):
+ out += self.ls(*n, long=long, type=type)
+ continue
+ for node, data in self.nodes.items():
+ if (node == n or node.split("|")[-1] == n) and (type is None or data["type"] == type):
+ out.append(node)
+ return out
+
+ def objExists(self, n):
+ return self._long(n) is not None
+
+ def nodeType(self, n):
+ return self.nodes[self._long(n)]["type"]
+
+ def listRelatives(self, n, shapes=False, parent=False, type=None, noIntermediate=False, fullPath=False):
+ node = self._long(n)
+ if parent:
+ return [node.rsplit("|", 1)[0]] if node.count("|") > 1 else None
+ kids = [k for k in self.nodes if k.rsplit("|", 1)[0] == node and self.nodes[k]["type"] == "mesh"]
+ return kids or None
+
+ def select(self, *items, replace=False, clear=False):
+ if clear or not items or items[0] is None:
+ self.selection = []
+ return
+ sel = items[0] if isinstance(items[0], (list, tuple)) else list(items)
+ self.selection = [self._long(s) for s in sel]
+
+ def file(self, path, i=False, force=False, options="", type="", exportSelected=False, returnNewNodes=False,
+ **kw):
+ self.calls.append(("file", type, options))
+ if type == "OBJexport":
+ assert "objExport" in self.plugins and exportSelected and len(self.selection) == 1
+ shape = self.selection[0]
+ assert self.nodes[shape]["type"] == "mesh", "the script selects the shape alone"
+ with open(path, "w") as f:
+ f.write(self.nodes[shape]["obj"])
+ return path
+ assert i and type == "OBJ" and returnNewNodes
+ with open(path) as f:
+ text = f.read()
+ ns = kw.get("namespace", "")
+ self.namespaces.add(ns)
+ t = "|%s:polySurface1" % ns
+ self.nodes[t] = {"type": "transform"}
+ self.nodes[t + "|%s:polySurfaceShape1" % ns] = {"type": "mesh", "obj": text, "sgs": ["initialShadingGroup"]}
+ return [t, t + "|%s:polySurfaceShape1" % ns]
+
+ def listConnections(self, n, type=None):
+ return list(self.nodes[self._long(n)].get("sgs", []))
+
+ def getAttr(self, attr):
+ return [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0]
+
+ def xform(self, n, matrix=None, worldSpace=False):
+ self.calls.append(("xform", self._long(n)))
+
+ def makeIdentity(self, n, **kw):
+ self.calls.append(("makeIdentity", self._long(n)))
+
+ def parent(self, child, new_parent, shape=False, relative=False):
+ assert shape and relative
+ old, p = self._long(child), self._long(new_parent)
+ moved = p + "|" + old.split("|")[-1]
+ self.nodes[moved] = self.nodes.pop(old)
+ return [moved.split("|")[-1]]
+
+ def sets(self, n, edit=False, forceElement=None):
+ node = self.nodes[self._long(n)]
+ node["sgs"] = [forceElement] if node.get("sgs") == ["initialShadingGroup"] else node["sgs"] + [forceElement]
+
+ def delete(self, n):
+ node = self._long(n)
+ for k in [k for k in self.nodes if k == node or k.startswith(node + "|")]:
+ del self.nodes[k]
+
+ def rename(self, n, new):
+ old = self._long(n)
+ new = new.lstrip(":")
+ moved = old.rsplit("|", 1)[0] + "|" + new
+ for k in [k for k in self.nodes if k == old or k.startswith(old + "|")]:
+ self.nodes[moved + k[len(old):]] = self.nodes.pop(k)
+ return new
+
+ def namespace(self, exists=None, removeNamespace=None, mergeNamespaceWithRoot=False):
+ if exists is not None:
+ return exists in self.namespaces
+ self.namespaces.discard(removeNamespace)
+
+ def undoInfo(self, openChunk=False, closeChunk=False, chunkName=""):
+ self.undo.append("open" if openChunk else "close")
+
+ def shelfLayout(self, name, exists=False, parent=None):
+ if exists:
+ return name in self.option_vars.get("_shelves", {})
+ self.option_vars.setdefault("_shelves", {})[name] = []
+ return name
+
+ def deleteUI(self, name, layout=False):
+ self.option_vars["_shelves"].pop(name)
+
+ def shelfButton(self, parent=None, command="", sourceType="", **kw):
+ self.option_vars["_shelves"][parent].append((sourceType, command))
+
+
+def install_fake_maya(folder):
+ cmds = FakeCmds(folder)
+ mel = types.ModuleType("maya.mel")
+ mel.eval = lambda text: "ShelfLayout"
+ maya = types.ModuleType("maya")
+ maya.cmds = cmds
+ maya.mel = mel
+ sys.modules["maya"] = maya
+ sys.modules["maya.cmds"] = cmds
+ sys.modules["maya.mel"] = mel
+ return cmds
+
+
+def test_shelf(sm):
+ cmds = install_fake_maya("")
+ sm.install_shelf()
+ sm.install_shelf() # again: replaces the shelf
+ buttons = cmds.option_vars["_shelves"][sm.SHELF]
+ check(len(buttons) == 3 and all(t == "python" for t, _ in buttons), "the shelf has three Python buttons")
+ for _, command in buttons:
+ func = command.split("sculptforge_maya.")[1].rstrip("()")
+ check(callable(getattr(sm, func, None)), "shelf button calls sculptforge_maya.%s" % func)
+
+
+def faces(obj_text):
+ return [line.split()[1:] for line in obj_text.splitlines() if line.startswith("f ")]
+
+
+def test_format(sm, tmp):
+ check(sm.safe_name("pCube1") == "pCube1" and sm.safe_name("Body Hi") == "Body_Hi", "safe names")
+ check(sm.safe_name("3D") == "_3D" and sm.safe_name("") == "SubTool", "safe names: digits, empty")
+ check(sm.safe_name("Body Hi \u00fc") == "Body_Hi___", "safe names match SculptForge's (one '_' per byte)")
+ check(len(sm.safe_name("x" * 1000)) == sm.MAX_NAME, "names are capped")
+ for bad in ["", ".obj", "../x.obj", "a..b.obj", "/etc/x.obj", "C:\\x.obj", "c:x.obj", "a/b.obj", "x.mel",
+ "x.py", "x obj.obj", ".hidden.obj", "x" * 70 + ".obj"]:
+ check(not sm.file_name_ok(bad), "file name refused: %r" % bad)
+ check(sm.file_name_ok("r1_000.obj") and sm.file_name_ok("A-b.c.OBJ"), "plain file names accepted")
+
+ text = sm.write_manifest([("pCube1", "r3_000.obj"), ("Body_Hi", "r3_001.obj")], 3, "2026", "cm")
+ m = sm.parse_manifest(text)
+ check(m["revision"] == 3 and m["objects"] == [("pCube1", "r3_000.obj"), ("Body_Hi", "r3_001.obj")],
+ "manifest round trip")
+
+ def refused(text, what):
+ try:
+ sm.parse_manifest(text)
+ check(False, "refused: " + what)
+ except ValueError:
+ pass
+
+ base = '{"format": "sculptforge-maya", "version": 1, "revision": 1, "objects": [%s]}'
+ for bad in ["../x.obj", "/tmp/x.obj", "C:\\\\x.obj", "sub/x.obj", "x.mel", ".."]:
+ refused(base % ('{"name": "a", "file": "%s"}' % bad), "traversal " + bad)
+ refused("not json", "not JSON")
+ refused("[" * 5000 + "]" * 5000, "deep nesting")
+ refused('{"format": "sculptforge-maya", "version": 2, "revision": 1, "objects": []}', "newer version")
+ refused('{"format": "sculptforge-maya", "version": 1, "revision": -1, "objects": []}', "negative revision")
+ refused('{"format": "sculptforge-maya", "version": 1, "revision": true, "objects": []}', "bool revision")
+ refused('{"format": "sculptforge-maya", "version": 1, "revision": 1}', "no objects")
+ refused(base % '{"name": 1, "file": "a.obj"}', "name not a string")
+ refused(base % '{"name": "a", "file": "a.obj"}, {"name": "b", "file": "a.obj"}', "a file twice")
+ refused(base % ", ".join('{"name": "a", "file": "f%d.obj"}' % i for i in range(sm.MAX_OBJECTS + 1)), "too many")
+ refused(base % "" + " " * sm.MAX_MANIFEST_BYTES, "too big")
+
+ # object_file: only plain files directly inside the box.
+ box = os.path.join(tmp, "box")
+ os.makedirs(box)
+ with open(os.path.join(tmp, "outside.obj"), "w") as f:
+ f.write(CUBE_OBJ)
+ if hasattr(os, "symlink"):
+ try:
+ os.symlink(os.path.join(tmp, "outside.obj"), os.path.join(box, "link.obj"))
+ try:
+ sm.object_file(box, "link.obj")
+ check(False, "a link out of the folder is refused")
+ except ValueError:
+ pass
+ except OSError:
+ pass # no symlinks here (Windows without the privilege)
+ try:
+ sm.object_file(box, "missing.obj")
+ check(False, "a missing file is refused")
+ except ValueError:
+ pass
+
+
+def test_send_and_get(sm, tmp, cli):
+ folder = os.path.join(tmp, "exchange")
+ os.makedirs(folder)
+ cmds = install_fake_maya(folder)
+ cube_shape = cmds.add_mesh("|pCube1", CUBE_OBJ)
+ cmds.nodes["|grp"] = {"type": "transform"}
+ cmds.add_mesh("|grp|Body", CUBE_OBJ.replace("v -1 -1 1", "v -1.5 -1 1"), sgs=("skinSG",))
+ cmds.selection = ["|pCube1", "|grp|Body|BodyShape"] # a transform and a shape
+
+ sm.send_to_sculptforge()
+ check(not cmds.warnings, "send: no warnings (%s)" % cmds.warnings)
+ check(cmds.option_vars.get(sm.FOLDER_VAR) == folder, "the folder picked in the dialog is remembered")
+ box = os.path.join(folder, sm.TO_SCULPTFORGE)
+ m = sm.read_manifest(box)
+ check(m is not None and m["revision"] == 1 and [n for n, _ in m["objects"]] == ["pCube1", "Body"],
+ "send: manifest lists the selection by short name")
+ check(all(os.path.isfile(os.path.join(box, f)) for _, f in m["objects"]), "send: one OBJ per mesh")
+ check(cmds.selection == ["|pCube1", "|grp|Body|BodyShape"], "send: the selection is restored")
+ check(("file", "OBJexport", sm.OBJ_EXPORT_OPTIONS) in cmds.calls, "send: Maya's OBJ exporter, no groups")
+ victim = os.path.join(tmp, "victim.txt")
+ with open(victim, "w") as f:
+ f.write("keep me")
+ try: # a link planted where the next send writes is replaced, not written through
+ os.symlink(victim, os.path.join(box, "r2_000.obj"))
+ os.symlink(victim, os.path.join(box, "manifest.json.tmp"))
+ except (OSError, AttributeError):
+ pass
+ sm.send_to_sculptforge()
+ with open(victim) as f:
+ check(f.read() == "keep me", "send: a planted link is not written through")
+ m2 = sm.read_manifest(box)
+ check(m2["revision"] == 2 and not os.path.exists(os.path.join(box, m["objects"][0][1])),
+ "a second send: next revision, old files removed")
+
+ out = os.path.join(folder, sm.TO_MAYA)
+ if cli:
+ r = subprocess.run([cli, "-c", 'maya_receive folder="%s"; maya_send folder="%s"' % (folder, folder)],
+ capture_output=True, text=True)
+ check(r.returncode == 0, "sculptforge-cli maya_receive; maya_send (%s %s)" % (r.stdout, r.stderr))
+ else: # what SculptForge's maya_send writes
+ os.makedirs(out)
+ for name in ("r1_000.obj", "r1_001.obj"):
+ with open(os.path.join(out, name), "w") as f:
+ f.write(CUBE_OBJ.replace("# Maya OBJ export", "# SculptForge"))
+ sm.write_atomically(os.path.join(out, "manifest.json"),
+ sm.write_manifest([("pCube1", "r1_000.obj"), ("Body", "r1_001.obj")], 1)
+ .replace('"maya"', '"sculptforge"'))
+ sent = sm.read_manifest(out)
+ check(sent is not None and [n for n, _ in sent["objects"]] == ["pCube1", "Body"],
+ "SculptForge sends the objects back under their Maya names")
+
+ # A new object in SculptForge too: it becomes a new Maya object.
+ shutil.copy(os.path.join(out, sent["objects"][0][1]), os.path.join(out, "r9_extra.obj"))
+ with open(os.path.join(out, "manifest.json")) as f:
+ data = json.load(f)
+ data["objects"].append({"name": "Extra", "file": "r9_extra.obj"})
+ sm.write_atomically(os.path.join(out, "manifest.json"), json.dumps(data))
+
+ cmds.undo = []
+ sm.get_from_sculptforge()
+ check(not cmds.warnings, "get: no warnings (%s)" % cmds.warnings)
+ check(cmds.undo == ["open", "close"], "get: one undo chunk")
+ shape = cmds.nodes.get("|pCube1|pCube1Shape")
+ check(shape is not None and shape["obj"] != CUBE_OBJ, "get: pCube1 keeps its transform and shape name, new mesh")
+ check(shape is not None and shape["sgs"] == ["blinn1SG"], "get: pCube1 keeps its shading group")
+ check(shape is not None and len(faces(shape["obj"])) == 6 and all(len(f) == 4 for f in faces(shape["obj"])),
+ "get: six quads come back as six quads")
+ check(shape is not None and all("/" in v for f in faces(shape["obj"]) for v in f), "get: UVs come back")
+ body = cmds.nodes.get("|grp|Body|BodyShape")
+ check(body is not None and body["sgs"] == ["skinSG"], "get: Body stays under its parent with its shading group")
+ check(("xform", "|sculptforge_get:polySurface1") in cmds.calls and any(c[0] == "makeIdentity" for c in cmds.calls),
+ "get: the world-space import is moved into the object's space")
+ check("|Extra" in cmds.nodes and "|Extra|ExtraShape" in cmds.nodes, "get: a new object is created")
+ check(not any("sculptforge_get" in n for n in cmds.nodes), "get: nothing left in the import namespace")
+ check(cmds.option_vars.get(sm.REVISION_VAR) == sent["revision"], "get: the revision is remembered")
+
+ # A manifest that points outside the folder: nothing is imported.
+ before = dict(cmds.nodes)
+ sm.write_atomically(os.path.join(out, "manifest.json"),
+ '{"format": "sculptforge-maya", "version": 1, "revision": 99, '
+ '"objects": [{"name": "pCube1", "file": "../outside.obj"}]}')
+ cmds.warnings = []
+ sm.get_from_sculptforge()
+ check(cmds.warnings and cmds.nodes == before, "get: a traversal attempt is refused and nothing changes")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--cli", help="sculptforge-cli, for the round trip through SculptForge")
+ args = ap.parse_args()
+ import sculptforge_maya as sm
+ tmp = tempfile.mkdtemp(prefix="sf_maya_")
+ try:
+ test_format(sm, tmp)
+ test_send_and_get(sm, tmp, args.cli)
+ test_shelf(sm)
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+ print("%s: %d failure(s)" % (os.path.basename(__file__), failures))
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_maya_bridge.cpp b/tests/test_maya_bridge.cpp
new file mode 100644
index 00000000..d77a2415
--- /dev/null
+++ b/tests/test_maya_bridge.cpp
@@ -0,0 +1,221 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The Maya bridge (io/MayaBridge.h, #42): strict manifest parsing (traversal, oversized and malformed manifests
+// are refused), Maya-safe names, and a round trip maya_send -> maya_receive through a temporary exchange folder.
+// tests/maya/test_sculptforge_maya.py does the shelf script's side with a mocked maya.cmds.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "io/MayaBridge.h"
+#include "io/ObjIO.h"
+
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+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;
+}
+
+std::string manifestWith(const std::string& objects) {
+ return "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": 2, \"sender\": \"maya\", \"objects\": [" +
+ objects + "]}";
+}
+
+} // namespace
+
+TEST(maya_names_and_files) {
+ CHECK(mayaSafeName("pCube1") == "pCube1");
+ CHECK(mayaSafeName("Body Hi") == "Body_Hi");
+ CHECK(mayaSafeName("3D head") == "_3D_head");
+ CHECK(mayaSafeName("") == "SubTool");
+ CHECK(mayaSafeName("a|b:c/../d") == "a_b_c____d");
+ CHECK(mayaSafeName(std::string(1000, 'x')).size() == kMayaMaxNameBytes);
+ CHECK(mayaSafeName("9" + std::string(1000, 'x')).size() == kMayaMaxNameBytes);
+
+ CHECK(mayaFileNameOk("r1_000.obj") && mayaFileNameOk("pCube1.OBJ") && mayaFileNameOk("a-b.c.obj"));
+ for (const char* bad : {"", ".obj", "../x.obj", "..obj", "a..b.obj", "/etc/x.obj", "C:\\x.obj", "c:x.obj",
+ "a/b.obj", "a\\b.obj", "x.mel", "x.py", "x.obj.py", "x obj.obj", ".hidden.obj", "x\n.obj"})
+ CHECK(!mayaFileNameOk(bad));
+ CHECK(!mayaFileNameOk(std::string(70, 'a') + ".obj"));
+}
+
+TEST(maya_manifest_parse_and_write) {
+ MayaManifest m;
+ std::string err;
+ CHECK(parseMayaManifest(manifestWith(R"({"name": "pCube1", "file": "r2_000.obj"},
+ {"name": "Body Hi ü", "file": "r2_001.obj"})"),
+ m, err));
+ CHECK(m.revision == 2 && m.sender == "maya" && m.objects.size() == 2);
+ CHECK(m.objects[0].name == "pCube1" && m.objects[0].file == "r2_000.obj");
+ CHECK(m.objects[1].name == "Body_Hi___"); // sanitised to Maya's characters (ü is two bytes)
+
+ m.unit = "cm";
+ m.senderVersion = "1.2 \"x\"";
+ MayaManifest back;
+ CHECK(parseMayaManifest(writeMayaManifest(m), back, err));
+ CHECK(back.revision == 2 && back.unit == "cm" && back.senderVersion == m.senderVersion);
+ CHECK(back.objects.size() == 2 && back.objects[1].file == "r2_001.obj" && back.objects[1].name == "Body_Hi___");
+
+ // Path traversal and other files: refused, whatever the spelling.
+ for (const char* bad : {"../x.obj", "..\\\\x.obj", "/tmp/x.obj", "C:\\\\x.obj", "sub/x.obj", "x.mel", "..", "",
+ "~/x.obj", "%2e%2e/x.obj"}) {
+ CHECK(!parseMayaManifest(manifestWith(std::string("{\"name\": \"a\", \"file\": \"") + bad + "\"}"), back, err));
+ CHECK(err.find("file") != std::string::npos);
+ }
+ // Malformed: other JSON, wrong types, missing fields, newer versions, duplicate files.
+ const std::vector<std::string> malformed = {
+ "not json",
+ "[]",
+ "{\"format\": \"sculptforge-bridge\", \"version\": 1, \"revision\": 1, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"revision\": 1, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"version\": \"1\", \"revision\": 1, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": -1, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": 1.5, \"objects\": []}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": 1}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": 1, \"objects\": {}}",
+ "{\"format\": \"sculptforge-maya\", \"version\": 1, \"revision\": 1, \"sender\": 5, \"objects\": []}",
+ manifestWith("{\"name\": \"a\"}"),
+ manifestWith("{\"file\": \"a.obj\"}"),
+ manifestWith("{\"name\": 1, \"file\": \"a.obj\"}"),
+ manifestWith("\"a.obj\""),
+ manifestWith("{\"name\": \"a\", \"file\": \"a.obj\"}, {\"name\": \"b\", \"file\": \"a.obj\"}"),
+ manifestWith("{\"name\": \"" + std::string(2000, 'n') + "\", \"file\": \"a.obj\"}"),
+ std::string(300, '[') + std::string(300, ']'),
+ };
+ for (const std::string& text : malformed) CHECK(!parseMayaManifest(text, back, err));
+ const std::string newer = R"({"format": "sculptforge-maya", "version": 2, "revision": 1, "objects": []})";
+ CHECK(!parseMayaManifest(newer, back, err) && err.find("newer") != std::string::npos);
+
+ // Oversized: too many objects, too many bytes.
+ std::string many;
+ for (size_t i = 0; i <= kMayaMaxObjects; ++i)
+ many += (i ? ", " : "") + std::string("{\"name\": \"a\", \"file\": \"f") + std::to_string(i) + ".obj\"}";
+ CHECK(!parseMayaManifest(manifestWith(many), back, err) && err.find("too many") != std::string::npos);
+ const std::string huge = manifestWith("") + std::string(kMayaManifestMaxBytes, ' ');
+ CHECK(!parseMayaManifest(huge, back, err) && err.find("too big") != std::string::npos);
+ const fs::path dir = fs::temp_directory_path() / "sf_maya_manifest";
+ fs::remove_all(dir);
+ writeText(dir / "manifest.json", huge);
+ CHECK(!readMayaManifest((dir / "manifest.json").string(), back, err) && err.find("too big") != std::string::npos);
+ CHECK(mayaRevision(dir.string()) == -1);
+ fs::remove_all(dir);
+}
+
+TEST(maya_bridge_round_trip) {
+ const fs::path root = fs::temp_directory_path() / "sf_maya_bridge";
+ fs::remove_all(root);
+ fs::create_directories(root);
+ const std::string folder = root.string();
+ CommandRegistry reg;
+ std::string err;
+
+ // Off until a folder is given; a folder that isn't there is refused.
+ Document doc = makeDoc(makeCube(3)); // quads
+ doc.subtools[0].name = "Body Hi";
+ doc.mesh.uvs.assign(doc.mesh.triangleCount() * 3, glm::vec2(0.25f, 0.75f));
+ doc.mesh.ensurePolygroups();
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t) { // one group per cube side (quads stay whole)
+ const auto& tri = doc.mesh.triangles[t];
+ const glm::vec3 n = glm::abs(glm::cross(doc.mesh.positions[tri[1]] - doc.mesh.positions[tri[0]],
+ doc.mesh.positions[tri[2]] - doc.mesh.positions[tri[0]]));
+ doc.mesh.polygroups[t] = n.x > n.y && n.x > n.z ? 1 : n.y > n.z ? 2 : 3;
+ }
+ CHECK(!reg.execute(doc, "maya_send", {{"folder", std::string()}}).ok);
+ CHECK(!reg.execute(doc, "maya_send", {{"folder", (root / "missing").string()}}).ok);
+ CHECK(!fs::exists(root / "missing"));
+
+ // Send: OBJ with quads and UVs (polygroups stay home), a Maya-safe name, the manifest.
+ const size_t quads = doc.mesh.quadCount();
+ const size_t triangles = doc.mesh.triangleCount();
+ CHECK(quads > 0);
+ CommandResult r = reg.execute(doc, "maya_send", {{"folder", folder}});
+ CHECK(r.ok && r.message.find("Sent 1 object to Maya") != std::string::npos);
+ MayaManifest sent;
+ CHECK(readMayaManifest(mayaManifestPath(mayaOutbox(folder)), sent, err));
+ CHECK(sent.revision == 1 && sent.sender == "sculptforge" && sent.objects.size() == 1);
+ CHECK(sent.objects[0].name == "Body_Hi" && doc.gozName == "Body_Hi");
+ Mesh obj;
+ CHECK(loadObj((root / "sculptforge_to_maya" / sent.objects[0].file).string(), obj, err));
+ CHECK(obj.triangleCount() == triangles && obj.quadCount() == quads && obj.hasUvs() && !obj.hasPolygroups());
+
+ // "Maya" sends it back changed (here: the file SculptForge wrote, moved up), plus a new object.
+ const fs::path inbox = root / "maya_to_sculptforge";
+ fs::create_directories(inbox);
+ for (glm::vec3& p : obj.positions) p.y += 1.0f;
+ CHECK(saveObj((inbox / "r5_000.obj").string(), obj, err));
+ CHECK(saveObj((inbox / "r5_001.obj").string(), makeIcosphere(1), err));
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-maya", "version": 1, "revision": 5,
+ "sender": "maya", "unit": "cm", "objects": [
+ {"name": "Body_Hi", "file": "r5_000.obj"}, {"name": "pSphere1", "file": "r5_001.obj"}]})");
+ CHECK(mayaRevision(inbox.string()) == 5 && mayaManifestStamp(inbox.string()) != 0);
+ r = reg.execute(doc, "maya_receive", {{"folder", folder}});
+ CHECK(r.ok && r.message.find("Received 2 objects from Maya") != std::string::npos);
+ // Replaced by name (undoably), the new one added.
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 0 && doc.subtools[0].name == "Body Hi");
+ CHECK(doc.mesh.quadCount() == quads && doc.mesh.hasUvs() && doc.undo.canUndo());
+ CHECK(std::abs(doc.mesh.positions[0].y - obj.positions[0].y) < 1e-5f);
+ CHECK(doc.subtools[1].name == "pSphere1" && doc.subtools[1].gozName == "pSphere1");
+
+ // A second send: the next revision, the first send's files removed, others in the folder left alone.
+ writeText(root / "sculptforge_to_maya" / "notes.txt", "mine");
+ const std::string firstFile = sent.objects[0].file;
+ CHECK(reg.execute(doc, "maya_send", {{"folder", folder}}).ok);
+ CHECK(mayaRevision(mayaOutbox(folder)) == 2);
+ CHECK(!fs::exists(root / "sculptforge_to_maya" / firstFile));
+ CHECK(fs::exists(root / "sculptforge_to_maya" / "notes.txt"));
+ CHECK(readMayaManifest(mayaManifestPath(mayaOutbox(folder)), sent, err) && sent.objects.size() == 2);
+ CHECK(sent.objects[0].name == "Body_Hi" && sent.objects[1].name == "pSphere1");
+
+#ifndef _WIN32
+ {
+ // A link planted where the next send writes is replaced, not written through.
+ writeText(root / "victim.txt", "keep me");
+ std::error_code ec;
+ fs::create_symlink(root / "victim.txt", root / "sculptforge_to_maya" / "r3_000.obj", ec);
+ fs::create_symlink(root / "victim.txt", root / "sculptforge_to_maya" / "manifest.json.tmp", ec);
+ CHECK(reg.execute(doc, "maya_send", {{"folder", folder}}).ok);
+ std::ifstream victim(root / "victim.txt");
+ std::string text((std::istreambuf_iterator<char>(victim)), std::istreambuf_iterator<char>());
+ CHECK(text == "keep me" && !fs::is_symlink(root / "sculptforge_to_maya" / "r3_000.obj"));
+ CHECK(mayaRevision(mayaOutbox(folder)) == 3);
+ }
+#endif
+ // A traversal attempt in the manifest: nothing outside the folder is read.
+ writeText(root / "outside.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n");
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-maya", "version": 1, "revision": 6,
+ "objects": [{"name": "x", "file": "../outside.obj"}]})");
+ const int before = doc.subtoolCount();
+ r = reg.execute(doc, "maya_receive", {{"folder", folder}});
+ CHECK(!r.ok && doc.subtoolCount() == before);
+#ifndef _WIN32
+ // A link inside the folder that points out of it is not a plain file: refused.
+ std::error_code ec;
+ fs::create_symlink(root / "outside.obj", inbox / "link.obj", ec);
+ if (!ec) {
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-maya", "version": 1, "revision": 7,
+ "objects": [{"name": "x", "file": "link.obj"}]})");
+ r = reg.execute(doc, "maya_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("plain file") != std::string::npos && doc.subtoolCount() == before);
+ }
+#endif
+ // A missing file says which.
+ writeText(inbox / "manifest.json", R"({"format": "sculptforge-maya", "version": 1, "revision": 8,
+ "objects": [{"name": "Gone", "file": "gone.obj"}]})");
+ r = reg.execute(doc, "maya_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("Gone") != std::string::npos);
+ fs::remove_all(root);
+ r = reg.execute(doc, "maya_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("Nothing has been sent from Maya") != std::string::npos);
+}
diff --git a/tests/ui/data/maya/send1/manifest.json b/tests/ui/data/maya/send1/manifest.json
new file mode 100644
index 00000000..af24a2aa
--- /dev/null
+++ b/tests/ui/data/maya/send1/manifest.json
@@ -0,0 +1,2 @@
+{"format": "sculptforge-maya", "version": 1, "revision": 1, "sender": "maya", "sender_version": "2026", "unit": "cm",
+ "objects": [{"name": "pCube1", "file": "r1_000.obj"}]}
diff --git a/tests/ui/data/maya/send1/r1_000.obj b/tests/ui/data/maya/send1/r1_000.obj
new file mode 100644
index 00000000..fb4cc160
--- /dev/null
+++ b/tests/ui/data/maya/send1/r1_000.obj
@@ -0,0 +1,19 @@
+# Maya OBJ export (test data)
+v -1 -1 1
+v 1 -1 1
+v -1 1 1
+v 1 1 1
+v -1 1 -1
+v 1 1 -1
+v -1 -1 -1
+v 1 -1 -1
+vt 0 0
+vt 1 0
+vt 0 1
+vt 1 1
+f 1/1 2/2 4/4 3/3
+f 3/1 4/2 6/4 5/3
+f 5/1 6/2 8/4 7/3
+f 7/1 8/2 2/4 1/3
+f 2/1 8/2 6/4 4/3
+f 7/1 1/2 3/4 5/3
diff --git a/tests/ui/data/maya/send2/manifest.json b/tests/ui/data/maya/send2/manifest.json
new file mode 100644
index 00000000..69889b60
--- /dev/null
+++ b/tests/ui/data/maya/send2/manifest.json
@@ -0,0 +1,3 @@
+{"format": "sculptforge-maya", "version": 1, "revision": 2, "sender": "maya", "sender_version": "2026", "unit": "cm",
+ "objects": [{"name": "pCube1", "file": "r2_000.obj"},
+ {"name": "pCube2", "file": "r2_001.obj"}]}
diff --git a/tests/ui/data/maya/send2/r2_000.obj b/tests/ui/data/maya/send2/r2_000.obj
new file mode 100644
index 00000000..4d0edc61
--- /dev/null
+++ b/tests/ui/data/maya/send2/r2_000.obj
@@ -0,0 +1,19 @@
+# Maya OBJ export (test data)
+v -1 -1.5 1
+v 1 -1.5 1
+v -1 1.5 1
+v 1 1.5 1
+v -1 1.5 -1
+v 1 1.5 -1
+v -1 -1.5 -1
+v 1 -1.5 -1
+vt 0 0
+vt 1 0
+vt 0 1
+vt 1 1
+f 1/1 2/2 4/4 3/3
+f 3/1 4/2 6/4 5/3
+f 5/1 6/2 8/4 7/3
+f 7/1 8/2 2/4 1/3
+f 2/1 8/2 6/4 4/3
+f 7/1 1/2 3/4 5/3
diff --git a/tests/ui/data/maya/send2/r2_001.obj b/tests/ui/data/maya/send2/r2_001.obj
new file mode 100644
index 00000000..05f942f0
--- /dev/null
+++ b/tests/ui/data/maya/send2/r2_001.obj
@@ -0,0 +1,19 @@
+# Maya OBJ export (test data)
+v 2 -1.5 1
+v 4 -1.5 1
+v 2 1.5 1
+v 4 1.5 1
+v 2 1.5 -1
+v 4 1.5 -1
+v 2 -1.5 -1
+v 4 -1.5 -1
+vt 0 0
+vt 1 0
+vt 0 1
+vt 1 1
+f 1/1 2/2 4/4 3/3
+f 3/1 4/2 6/4 5/3
+f 5/1 6/2 8/4 7/3
+f 7/1 8/2 2/4 1/3
+f 2/1 8/2 6/4 4/3
+f 7/1 1/2 3/4 5/3
diff --git a/tests/ui/maya_bridge.sfui b/tests/ui/maya_bridge.sfui
new file mode 100644
index 00000000..6171716a
--- /dev/null
+++ b/tests/ui/maya_bridge.sfui
@@ -0,0 +1,63 @@
+# The Maya bridge (File > Maya, #42): off until an exchange folder is chosen (here: what the native folder
+# dialog would answer), then Get from Maya loads what the shelf script sent, Send to Maya writes the SubTools
+# back, and with Get automatically on a second send from Maya replaces the SubTool by name (undoable) and adds
+# the new object. The sends are staged from tests/ui/data/maya into a folder in the working directory (the build
+# folder under ctest).
+run new_sphere subdivisions=3
+copy data/maya/send1 sf_ui_maya/maya_to_sculptforge
+
+# The menu: File > Maya, with Ctrl-hover help on its items; off until a folder is chosen.
+click "File##palette.file"
+hover "Maya"
+wait 0.2
+expect "Send to Maya##file.send_maya"
+expect "Get from Maya##file.receive_maya"
+expect "Exchange folder...##file.maya_folder"
+expect_text Off: choose an exchange folder first.
+shot menu_off
+hold ctrl
+hover "Send to Maya##file.send_maya"
+expect_help "exchange folder"
+hover "Exchange folder...##file.maya_folder"
+expect_help "only there"
+hold none
+
+# What File > Maya > Exchange folder's dialog answers. Nothing loads by itself (Get automatically is off).
+choose_file maya_folder sf_ui_maya
+wait 0.2
+expect_status "Maya exchange folder:"
+expect_value subtools == 1
+hover "Maya"
+wait 0.2
+expect_text Folder:
+click "Get from Maya##file.receive_maya"
+expect_status "Received 1 object from Maya"
+expect_value subtools == 1
+expect_text pCube1
+expect_value quads > 0
+shot received
+
+# Get automatically: the next send from Maya loads by itself.
+click "File##palette.file"
+hover "Maya"
+wait 0.2
+click "Get automatically##maya"
+copy data/maya/send2 sf_ui_maya/maya_to_sculptforge
+wait 0.3
+expect_status "Received 2 objects from Maya"
+expect_value subtools == 2
+expect_text pCube2
+expect_value can_undo == 1
+shot updated
+
+# Send to Maya: both SubTools, under their Maya names.
+click "File##palette.file"
+hover "Maya"
+wait 0.2
+click "Send to Maya##file.send_maya"
+expect_status "Sent 2 objects to Maya"
+# Both receives into pCube1 are undo steps: the update, then the first one (which replaced the fresh sphere).
+key ctrl+z
+expect_value can_undo == 1
+key ctrl+z
+expect_value can_undo == 0