Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Maya Live (#42): sends changed Parts by itself after each stroke, both sides, files; opt-in Live link (per-user socket/pipe, pairing code, mesh data only) so Maya follows a stroke while it is drawn
islandmed5da8b098748f
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 83b4c793..619b853d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -318,7 +318,8 @@ set_source_files_properties(third_party/qrcodegen/qrcodegen.cpp ${CMAKE_CURRENT_# --- Headless command-line tool (pipelines, build farms, AI agents) ---# The MCP server (src/cli/McpServer.cpp) is a library of its own: the tool and the tests link it, nobody compiles it twice.-add_library(sculptforge_mcp STATIC src/cli/McpServer.cpp src/cli/McpTools.cpp src/cli/McpAttach.cpp src/link/AiLink.cpp src/link/AiLinkSession.cpp)+add_library(sculptforge_mcp STATIC src/cli/McpServer.cpp src/cli/McpTools.cpp src/cli/McpAttach.cpp src/link/AiLink.cpp src/link/AiLinkSession.cpp+ src/link/MayaLink.cpp)target_compile_definitions(sculptforge_mcp PRIVATE SCULPTFORGE_VERSION="${PROJECT_VERSION}")target_link_libraries(sculptforge_mcp PUBLIC sculptforge_core sculptforge_ai)if(WIN32)diff --git a/SECURITY.md b/SECURITY.mdindex 777396f8..a4f5d155 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -27,3 +27,15 @@ API keys you enter, and studio sign-in tokens, are stored in the operating systeWindows Credential Manager, Linux Secret Service), never in settings files or logs. They are only ever sent to theservice they belong to. SculptForge opens no network listener for AI tools (MCP is stdio only) or for sign-in (thedevice authorization grant). For IT reviews, see docs/guide/security.md.++Local listeners, each off by default and only while the user has it on:++- **AI live mode** (Preferences > AI): a Unix domain socket (0600, in a folder only the user can enter, peer user+ checked) or a named pipe whose DACL grants the current user only, remote clients rejected. No TCP or UDP port.+- **Maya Live link** (File > Maya > Live link, #42): the same kind of endpoint (`maya-link.sock` /+ `\\.\pipe\sculptforge-maya-link-<user>`), never a TCP or UDP port, so browsers, other users and other computers+ can't reach it. It asks with a warning every time it is turned on, is off at every start (never remembered as on)+ and shows "Live link on" in the top bar while it is. A random 128-bit pairing code must open each connection;+ one client at a time. It carries mesh data only (names, vertices, faces, UVs; no commands, paths or scripts) in+ length-prefixed frames with a 1 GiB cap and timeouts, parsed strictly in-house (`src/link/MayaLink.cpp`,+ fuzzed in `tests/test_maya_live.cpp`).diff --git a/assets/fonts/NotoSansSC-UI.otf b/assets/fonts/NotoSansSC-UI.otfindex 8d053681..7b94d20b 100644Binary files a/assets/fonts/NotoSansSC-UI.otf and b/assets/fonts/NotoSansSC-UI.otf differdiff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otfindex 1bd2e461..8a1e656d 100644Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differdiff --git a/changes/feat-maya-live.md b/changes/feat-maya-live.mdnew file mode 100644index 00000000..b10a698c--- /dev/null+++ b/changes/feat-maya-live.md@@ -0,0 +1,28 @@+---+whats_new: **Maya Live**: turn on **File > Maya > Live** (and **Live** on the Maya shelf) and each app sends what you change by itself, 300 ms after a stroke or edit, only the Parts that changed. Thanks @tristratos (#42).+whats_new: **Maya Live link**: **File > Maya > Live link...** connects SculptForge and Maya on this computer so Maya follows your stroke while you draw it. It asks every time, is off at every start, and the ember **Live link on** chip in the top bar turns it off.+highlight: Maya follows your strokes live (thanks @tristratos, #42)+added: **Maya Live** (#42, thanks @tristratos): **File > Maya > Live** sends the Parts a stroke, undo or edit changed+ to the exchange folder by itself once the scene is still for 300 ms (never mid-stroke), written in the background;+ the Maya shelf's new **Live** button does the same for Maya edits (node-dirty callbacks, debounced). Echo guard:+ manifests carry the writer's session id, a Get is never sent back, and an object that comes back unchanged is+ skipped (no undo step). Both sides pick up sends every 250 ms (was once a second); OBJs are written to a+ temporary name and renamed.+added: **Maya Live link** (#42): opt-in, off at every start and never remembered; a warning every time it is turned+ on; an ember **Live link on** chip in the top bar (and the Forge status bar) turns it off. A per-user Unix socket+ or named pipe (never a TCP or UDP port), a 128-bit pairing code (**File > Maya > Copy pairing code**, pasted into+ the shelf's new **Link** button), one client at a time, mesh data only in strictly parsed frames (1 GiB cap,+ timeouts, fuzz-tested). SculptForge streams the vertices a stroke moves about ten times a second and sends whole+ meshes when faces change; Maya edits come back as whole meshes. Studios can forbid it with+ `"maya": {"link": "never"}`. Guide: Working with Maya > Live, Live link.+security: New local listener, the Maya Live link: per-user socket / pipe only, opt-in with a warning each time,+ pairing code, mesh data only (SECURITY.md).+testers:+ - Any OS with Maya 2022+: install the shelf again (six buttons). File > Maya > Live on in SculptForge, Live on the+ shelf; sculpt a stroke: Maya updates within about half a second; edit the mesh in Maya: SculptForge updates.+ No ping-pong (each change arrives once; no extra undo steps).+ - Live link: File > Maya > Live link... shows the warning (Cancel leaves it off); Turn on, Copy pairing code,+ Link on the shelf, paste: Maya follows a stroke while you draw it. Click Live link on in the top bar: off.+ - Windows: the same through the named pipe; a wrong code is refused.+---+Security read by input before merge (Tony approved the link 11-06 ~19:10 in the mayalive session).diff --git a/docs/guide/maya.md b/docs/guide/maya.mdindex 4fdcd6b4..40f526ac 100644--- a/docs/guide/maya.md+++ b/docs/guide/maya.md@@ -6,7 +6,8 @@ Maya object's mesh by name. It works through files in a shared folder, on Linux,The two apps exchange files through **one folder that you choose in both**, and nothing else: SculptForge opensno 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.+there. The bridge is off until you choose the folder. **Live** keeps the two in step by themselves, still through+the folder; the opt-in **[Live link](#live-link)** lets Maya follow a stroke while you draw it.## Install the shelf in Maya@@ -16,10 +17,11 @@ there. The bridge is off until you choose the folder.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**, **Auto** and- **Folder**. (Updating from an older shelf: copy the new file and run `install_shelf()` again.)+ `sculptforge_maya.install_shelf()`. A **SculptForge** shelf appears with **Send**, **Get**, **Auto**,+ **Live**, **Link** and **Folder**. (Updating from an older shelf: copy the new file and run `install_shelf()` again.)-The script uses plain `maya.cmds` and Maya's own OBJ exporter; it needs Maya 2022 or newer.+The script uses plain `maya.cmds`, Maya's own OBJ exporter and, for Live, `maya.api.OpenMaya` (all from your+own Maya: nothing of Maya's ships with SculptForge); it needs Maya 2022 or newer.## Choose the exchange folder@@ -41,7 +43,7 @@ bridge is on, the top bar has a **Send to Maya** button.parent and shading groups; a Part you added in SculptForge becomes a new object. The whole Get is one undostep in Maya.-Both sides pick up a send by checking the other side's manifest once a second (its modification time and size+Both sides pick up a send by checking the other side's manifest every 250 ms (its modification time and sizeonly), and only for sends made after the bridge started: something sent earlier waits for a manual Get.- In SculptForge, **File > Maya > Get automatically** is on once you choose the folder; turn it off to load@@ -49,6 +51,58 @@ only), and only for sends made after the bridge started: something sent earlier- In Maya, **Auto** on the shelf is on by default and starts with the first Send, Get or Folder click in a Mayasession; click it to switch to **Manual**, where only **Get** loads.+## Live++With **Live** on, you don't click Send at all: each app sends what you change by itself, and the other loads it.++- In SculptForge, turn on **File > Maya > Live**. After each stroke (once you pause for 300 ms, never in the+ middle of one), the Parts that stroke, an undo or any other edit changed go to the folder. Parts you didn't+ touch stay put, so a big scene with one Part being sculpted sends only that Part. The files are written in the+ background while you keep sculpting.+- In Maya, click **Live** on the shelf (it turns **Auto** on too). The meshes you sent or got, and the ones+ selected when you turned it on, are watched; 300 ms after you stop editing one, it goes to SculptForge.++Neither app sends back what it just loaded: a Get is never an edit to send, each manifest says which app session+wrote it, and SculptForge skips an object that comes back exactly as it went out (no extra undo step). Live is off+until you turn it on, on each side, and stays as you left it.++## Live link++The **Live link** goes further: Maya follows your stroke while you draw it. It's a connection between the two+apps on this computer, so it is **off until you turn it on, asks first every time, and is off again whenever+SculptForge starts**.++1. In SculptForge choose **File > Maya > Live link...**. A warning explains what it opens:++ > **It opens a connection on this computer.** Anything running on this computer that knows the pairing code+ > could send meshes into SculptForge. It carries meshes only: never commands, files or scripts. Other+ > computers and web pages can't reach it. Turn it off when you're not using it: click "Live link on" in the+ > top bar. It is off again every time SculptForge starts.++ Click **Turn on**. An ember **Live link on** chip appears in the top bar.+2. Choose **File > Maya > Copy pairing code**.+3. In Maya click **Link** on the SculptForge shelf, paste, and click **Link**. The button says **Linked**, and+ SculptForge sends Maya every visible Part, so both start from the same mesh.++Now sculpt: about ten times a second, the vertices your stroke moves appear in Maya. When a stroke changes the+faces (dynamic topology, remesh, divide), the whole Part goes when the stroke ends. Edit a mesh in Maya and+SculptForge gets it as soon as you pause (one undo step there). Updates that arrive in Maya over the link aren't+Maya undo steps: undo in SculptForge, and Maya follows.++**To turn it off**, click **Live link on** in SculptForge's top bar (or **File > Maya > Turn the Live link off**),+or click **Linked** in Maya. Quitting SculptForge turns it off too.++How it is kept safe:++- **No network port.** It is a Unix domain socket in a folder only you can open (Linux, macOS) or a named pipe+ only your Windows account can open, remote clients refused. Web pages, other people on the machine and other+ computers can't reach it.+- **A pairing code** (128 random bits, new each time you turn it on) must open every connection; one Maya at a+ time.+- **Meshes only.** Object names, vertices, faces and UVs, checked strictly on arrival (sizes, ranges, finite+ numbers, Maya names). Nothing that arrives is run, and it never names a file.+- Studios can forbid it with `"maya": {"link": "never"}` in the [studio policy](studios.md).+## What comes across| | Maya | SculptForge |@@ -87,5 +141,11 @@ The commands are `maya_send folder=<folder>` and `maya_receive folder=<folder>`- **Get in Maya says nothing has been sent**: choose **File > Maya > Send to Maya** in SculptForge first.- **Maya doesn't load a send by itself**: Auto starts with the first click on the shelf in a Maya session; click**Get** once (or **Send**), and check that the button says **Auto**, not **Manual**.+- **Live doesn't send from Maya**: Live watches the meshes you sent or got and the ones selected when you turned it+ on; send a new mesh once with **Send**, and it is watched from then on.+- **Link says SculptForge refused the pairing code**: the code is new each time the Live link is turned on; copy it+ again (**File > Maya > Copy pairing code**).+- **Link says SculptForge isn't offering it**: turn on **File > Maya > Live link...** in SculptForge first (it is+ off at every start).- **A mesh came in as a new object instead of replacing one**: Get matches the transform's name; renaming theobject in Maya or the Part's Maya name breaks the link.diff --git a/docs/guide/security.md b/docs/guide/security.mdindex b3e007f2..d0a10ef8 100644--- a/docs/guide/security.md+++ b/docs/guide/security.md@@ -14,7 +14,7 @@ and installs no services, drivers or background processes.| | ||---|---|| Telemetry, analytics, crash upload | **None.** Crash logs stay on the computer. |-| Listening ports | **None by default**, and never for AI tools or sign-in. Two features listen while the artist uses them: phone capture (on the local network, so the phone can reach it) and the Unreal link. With the network off by policy, they may use only this computer unless `network.localNetwork` allows the studio network. The Blender and Maya bridges exchange files. |+| Listening ports | **None by default**, and never for AI tools or sign-in. Two features listen while the artist uses them: phone capture (on the local network, so the phone can reach it) and the Unreal link. With the network off by policy, they may use only this computer unless `network.localNetwork` allows the studio network. The Blender and Maya bridges exchange files. The Maya Live link, when the artist turns it on (with a warning each time; off at every start), listens on a per-user socket or pipe on this computer only, never a port; `"maya": {"link": "never"}` forbids it. || Outbound connections | Only what the artist uses: the daily update check (a small file from the website, or your own feed), the community brush gallery, and the AI service the artist chose. With `"network": {"enabled": false}` in the policy, a single gate refuses everything except the addresses you list, before anything is sent, and follows no redirects. || AI features | Optional, and lockable off by policy. Only the request goes to the chosen service: a brush description, or the picture or text given to Generate 3D. Sculpts are never uploaded or used for training. Providers and addresses can be limited to your own gateway or local models. |diff --git a/docs/guide/studios.md b/docs/guide/studios.mdindex b67c35b5..725c987c 100644--- a/docs/guide/studios.md+++ b/docs/guide/studios.md@@ -273,6 +273,7 @@ the system file exists, `SF_POLICY` is ignored, so an artist can't loosen it."endpoints": ["https://llm.acme.internal/", "http://comfy.acme.internal:8188/"], "requireSignIn": true},"network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": false},"mcp": {"enabled": true, "live": "never", "categories": ["info", "edit", "files"]},+ "maya": {"link": "never"},"audit": {"path": "//fs01/audit/sculptforge/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},"signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1example","useFor": ["https://llm.acme.internal/"]},@@ -298,6 +299,7 @@ code 2 when it is broken); use it to check a file before you deploy it.| `network.localNetwork` | `true`: the Unreal link and phone capture may use the studio network while the network is off || `mcp.enabled` | `false`: no AI tool can connect (`sculptforge-cli --mcp` refuses to start, and **Help > Connect an AI tool** is gone) || `mcp.live` | `"never"`: AI tools work only on their own scene and can never control an open SculptForge window (the window never listens for them; **Let AI tools control this window** is locked off) |+| `maya.link` | `"never"`: the [Maya Live link](maya.md#live-link) can't be turned on (the window never listens for Maya; the folder bridge still works) || `mcp.categories` | The kinds of command AI tools may use: `info` (read the scene), `edit` (change it in memory), `files` (open, save, export, bridges), `scripts` (macros), `network` (brush gallery, Unreal), `ai` (AI generation). Left out: all || `audit.path`, `audit.maxMB`, `audit.keep` | Where the [audit log](#audit-log) goes, when it rotates (10 MB) and how many old files it keeps (5) || `audit.required` | `true`: an AI action whose audit line can't be written (the share is down) is refused |diff --git a/docs/legal/trademarks.md b/docs/legal/trademarks.mdindex 7acdb119..ed3f889f 100644--- a/docs/legal/trademarks.md+++ b/docs/legal/trademarks.md@@ -172,3 +172,13 @@ FNV-1a 64 of the lower-case word. `tests/test_legacy_names.cpp` checks `LegacyNaZBrush is a trademark of Maxon. SculptForge is not affiliated with or endorsed by Maxon. Where a page needs a noticeat all, it says: "Product names are trademarks of their respective owners."++Other apps SculptForge works with are named only to say what it works with ("Send to Maya", "Working with Maya",+"Working with Blender"): no logos, icons or look-alike art of theirs, and none of their code or SDK ships with+SculptForge (the Maya shelf script uses the `maya.cmds` and `maya.api` of the user's own Maya; the Blender add-on+uses Blender's own `bpy`).++- Autodesk and Maya are registered trademarks of Autodesk, Inc. SculptForge is not affiliated with or endorsed by+ Autodesk.+- Blender is a registered trademark of the Blender Foundation. SculptForge is not affiliated with or endorsed by the+ Blender Foundation.diff --git a/integrations/maya/README.md b/integrations/maya/README.mdindex bde6625e..949e6e34 100644--- a/integrations/maya/README.md+++ b/integrations/maya/README.md@@ -1,13 +1,17 @@# SculptForge bridge for MayaSend the selected meshes from Maya to SculptForge and get them back, the way the Bridge works between SculptForge and-other apps. One Python file (`sculptforge_maya.py`), plain `maya.cmds`, no other modules. Tested against a+other apps. One Python file (`sculptforge_maya.py`): plain `maya.cmds`, `maya.api.OpenMaya` for Live, and Python's+standard library (`socket`, `ctypes`), nothing else and nothing of Maya's shipped with it. Tested against amocked `maya.cmds` (`tests/maya/test_sculptforge_maya.py`); it uses only commands Maya has had for manyversions (Maya 2022 or newer, Python 3), but it has not been run inside a real Maya yet: please report whatyou 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).+The two apps share **one exchange folder that you pick in both**: neither app runs anything it finds in the+folder, and meshes travel as OBJ files (quads and UVs). **Live** sends what you edit by itself, still through the+folder. The opt-in **Live link** (SculptForge asks every time it is turned on, and it is off at every start) is a+connection on this computer only, never a network port: a Unix socket or a named pipe only your account can+open, opened with SculptForge's pairing code, carrying mesh data only.## Install@@ -25,7 +29,8 @@ servers, and neither app runs anything it finds in the folder. Meshes travel assculptforge_maya.install_shelf()```- A **SculptForge** shelf appears with four buttons: **Send**, **Get**, **Auto** and **Folder**. You only do+ A **SculptForge** shelf appears with six buttons: **Send**, **Get**, **Auto**, **Live**, **Link** and+ **Folder**. You only dothis once; Maya keeps the shelf. (Updating: copy the new file and run `install_shelf()` again.)## Use@@ -42,9 +47,19 @@ servers, and neither app runs anything it finds in the folder. Meshes travel asobject. The whole Get is one undo step.**Auto** is on by default and starts with the first Send, Get or Folder click in a Maya session: a background-thread looks at the modification time and size of SculptForge's manifest once a second and nothing else, and+thread looks at the modification time and size of SculptForge's manifest every 250 ms and nothing else, andthe Get itself runs in Maya's main thread. Something sent before it started waits for **Get**.+**Live** (click it; off by default) also sends by itself: the meshes you sent or got, and the ones selected when+you turned it on, are watched with Maya's node-dirty callbacks, and 300 ms after you stop editing one, it goes to+SculptForge. A Get is never sent back, and a manifest this Maya session wrote is never loaded.++**Link**: in SculptForge turn on **File > Maya > Live link...** and choose **Copy pairing code**; click **Link**+here and paste. SculptForge then streams the vertices each stroke moves (about ten times a second) and Maya+updates the mesh in place; your Maya edits go back as whole meshes. Updates over the link aren't Maya undo steps+(undo in SculptForge). Click **Linked** to disconnect. Everything that arrives is checked strictly (sizes,+ranges, finite numbers, Maya names) before it touches the scene.+## What comes across- Positions in world space and Maya's own units (SculptForge takes the numbers as they are), quads, n-gons (asdiff --git a/integrations/maya/sculptforge_maya.py b/integrations/maya/sculptforge_maya.pyindex bdc50a1c..dee9b57a 100644--- a/integrations/maya/sculptforge_maya.py+++ b/integrations/maya/sculptforge_maya.py@@ -12,16 +12,27 @@ space, Maya's own units, one object per file); a small JSON manifest per directiGet from SculptForge replaces each object's mesh by name, keeping its transform, parent and shading groups, asone undo step; objects Maya doesn't have yet are created. Auto (on by default) does the Get by itself when-SculptForge sends: once a second a background thread looks at the modification time and size of SculptForge's-manifest (nothing else in the folder), and only when they change is the Get run, in Maya's main thread. Plain-maya.cmds (maya.mel for the shelf, maya.utils for Auto) and the standard library. Install: see README.md beside-this file, or run install_shelf() once.+SculptForge sends: every 250 ms a background thread looks at the modification time and size of SculptForge's+manifest (nothing else in the folder), and only when they change is the Get run, in Maya's main thread.++Live (off by default; the shelf's Live button) also sends by itself: the meshes you sent or got are watched+(Maya's node-dirty callbacks: a flag, nothing more), and once none of them changed for 300 ms the changed ones+are sent, in Maya's main thread when it is idle. What a Get loads is never sent back (the echo guard), and a+manifest this Maya session wrote is never loaded. Still files only.++Plain maya.cmds (maya.mel for the shelf, maya.utils for Auto, maya.api.OpenMaya's callbacks for Live) and the+standard library. Install: see README.md beside this file, or run install_shelf() once."""import jsonimport osimport re+import struct+import sysimport threading+from array import array+import time+import uuidFORMAT = "sculptforge-maya"VERSION = 1@@ -36,7 +47,11 @@ FOLDER_VAR = "sculptforgeExchangeFolder"REVISION_VAR = "sculptforgeLastRevision"AUTO_VAR = "sculptforgeAutoGet"AUTO_BUTTON = "sculptforgeAutoButton"-POLL_SECONDS = 1.0+LIVE_VAR = "sculptforgeLive"+LIVE_BUTTON = "sculptforgeLiveButton"+POLL_SECONDS = 0.25+LIVE_IDLE_SECONDS = 0.3+WRITER = uuid.uuid4().hex[:16] # this Maya session's id in the manifests it writes (the echo guard)SHELF = "SculptForge"IMPORT_NAMESPACE = "sculptforge_get"OBJ_EXPORT_OPTIONS = "groups=0;ptgroups=0;materials=0;smoothing=0;normals=0"@@ -64,7 +79,7 @@ def file_name_ok(name):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=""):+def write_manifest(objects, revision, sender_version="", unit="", writer="", live=False):"""The manifest text. `objects` is a list of (name, file)."""data = {"format": FORMAT,@@ -75,6 +90,10 @@ def write_manifest(objects, revision, sender_version="", unit=""):}if unit:data["unit"] = str(unit)[:64]+ if writer:+ data["writer"] = str(writer)[:64]+ if live:+ data["live"] = Truedata["objects"] = [{"name": n, "file": f} for n, f in objects]return json.dumps(data, indent=2) + "\n"@@ -99,7 +118,7 @@ def parse_manifest(text):if (isinstance(revision, bool) or not isinstance(revision, (int, float)) or revision < 0or revision != int(revision) or revision > 2 ** 53):raise ValueError("the manifest has no valid revision")- for key in ("sender", "sender_version", "unit"):+ for key in ("sender", "sender_version", "unit", "writer"):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")@@ -119,7 +138,8 @@ def parse_manifest(text):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}+ return {"revision": int(revision), "sender": data.get("sender", ""), "writer": data.get("writer", ""),+ "live": data.get("live") is True, "objects": out}def read_manifest(box):@@ -188,15 +208,57 @@ def manifest_stamp(box):return (st.st_mtime_ns, st.st_size)+class LiveState(object):+ """Live's bookkeeping, apart from Maya so it can be tested: which watched objects changed and when, the wait+ for 300 ms of stillness, and the echo guard (changes while a Get applies SculptForge's meshes don't count)."""++ def __init__(self, idle=LIVE_IDLE_SECONDS, clock=time.monotonic):+ self.idle = idle+ self.clock = clock+ self.lock = threading.Lock()+ self.dirty = {} # transform (long name) -> when it last changed+ self.applying = 0 # > 0 while a Get (or a send) works on the scene+ self.queued = False # a send is handed to Maya's main thread already++ def mark(self, transform):+ """A watched mesh changed (called from Maya's dirty callbacks: keep it cheap)."""+ if self.applying:+ return+ with self.lock:+ self.dirty[transform] = self.clock()++ def forget(self, transforms):+ with self.lock:+ for t in transforms:+ self.dirty.pop(t, None)++ def due(self):+ """True once something changed and nothing changed for `idle` seconds (and no send is queued)."""+ with self.lock:+ if not self.dirty or self.queued or self.applying:+ return False+ return self.clock() - max(self.dirty.values()) >= self.idle++ def take(self):+ """The changed objects, in the order they first changed; clears them."""+ with self.lock:+ out = list(self.dirty)+ self.dirty.clear()+ self.queued = False+ return out++class Watcher(object):"""Auto: watches one box's manifest from a daemon thread and hands `on_change` to `defer` (Maya'sexecuteDeferred: the main thread, when Maya is idle) when it changed. What is there when it starts is old- news: Get loads it."""+ news: Get loads it. With `live`, it also hands `on_live` over once Live's wait is over."""- def __init__(self, box, defer, on_change):+ def __init__(self, box, defer, on_change, live=None, on_live=None):self.box = boxself.defer = deferself.on_change = on_change+ self.live = live+ self.on_live = on_liveself.seen = manifest_stamp(box)self.stopped = threading.Event()self.thread = None@@ -209,10 +271,20 @@ class Watcher(object):self.seen = stampreturn True+ def live_due(self):+ """One Live check: True when a send is due (it is then marked queued until it runs)."""+ if self.live is None or not self.live.due():+ return False+ with self.live.lock:+ self.live.queued = True+ return True+def _run(self):while not self.stopped.wait(POLL_SECONDS):if self.poll():self.defer(self.on_change)+ if self.live_due():+ self.defer(self.on_live)def start(self):self.thread = threading.Thread(target=self._run, name="SculptForge Auto Get", daemon=True)@@ -309,13 +381,19 @@ def _short(path):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)+ return _send(meshes, live=False)+++def _send(meshes, live):+ """Writes `meshes` ((transform, shape) pairs) to SculptForge's box: each OBJ, then the manifest (written to a+ temporary name and renamed)."""+ cmds = _cmds()if len(meshes) > MAX_OBJECTS:return _message("too many meshes selected (at most %d)" % MAX_OBJECTS, warning=True)- folder = exchange_folder()+ folder = exchange_folder(ask=not live)if not folder:return _message("no exchange folder chosen", warning=True)box = os.path.join(folder, TO_SCULPTFORGE)@@ -329,6 +407,7 @@ def send_to_sculptforge():names = unique_names([safe_name(_short(t)) for t, _ in meshes])objects = []selection = cmds.ls(selection=True, long=True) or []+ _live.applying += 1 # (selecting and exporting changes no mesh, but nothing counts while we work)try:for k, ((transform, shape), name) in enumerate(zip(meshes, names)):file_name = "%s%03d.obj" % (prefix, k)@@ -338,15 +417,22 @@ def send_to_sculptforge():preserveReferences=True, exportSelected=True)objects.append((name, file_name))finally:+ _live.applying -= 1if 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)))+ write_manifest(objects, revision, cmds.about(version=True), cmds.currentUnit(q=True, linear=True),+ WRITER, live))remove_old_sends(box, prefix)+ _watch([t for t, _ in meshes])start_auto_get()- return _message("sent %d mesh%s to SculptForge" % (len(objects), "" if len(objects) == 1 else "es"))+ text = "sent %d mesh%s to SculptForge" % (len(objects), "" if len(objects) == 1 else "es")+ if live: # (no view message for every Live send: the status line only)+ print("SculptForge: Live: " + text)+ return text+ return _message(text)def _find_transform(name):@@ -411,6 +497,7 @@ def get_from_sculptforge():_ensure_obj_plugin()done = []cmds.undoInfo(openChunk=True, chunkName="Get from SculptForge")+ _live.applying += 1 # the echo guard: what SculptForge sent is not a Maya edit to send backtry:for name, file_name in manifest["objects"]:path = object_file(box, file_name)@@ -428,7 +515,10 @@ def get_from_sculptforge():except ValueError as e:return _message("can't load what SculptForge sent: %s" % e, warning=True)finally:+ _live.applying -= 1cmds.undoInfo(closeChunk=True)+ _live.forget(done)+ _watch(done) # (their new shapes)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"))@@ -455,7 +545,7 @@ def _auto_get_new():manifest = read_manifest(os.path.join(folder, TO_MAYA))except ValueError:manifest = None # half written, or not valid: Get says why; the next change is checked again- if not manifest or not manifest["objects"]:+ if not manifest or not manifest["objects"] or manifest["writer"] == WRITER: # (never what this Maya wrote)returnif cmds.optionVar(exists=REVISION_VAR) and cmds.optionVar(q=REVISION_VAR) == manifest["revision"]:return@@ -475,11 +565,110 @@ def start_auto_get():_watcher = Noneif box:import maya.utils- _watcher = Watcher(box, maya.utils.executeDeferred, _auto_get_new)+ _watcher = Watcher(box, maya.utils.executeDeferred, _auto_get_new, _live, _live_send)_watcher.start()return _watcher+# ---- Live: send by itself what changes here ----++_live = LiveState()+_watched = {} # transform (long name) -> callback id (or None without maya.api)+++def live_on():+ cmds = _cmds()+ return cmds.optionVar(exists=LIVE_VAR) and bool(cmds.optionVar(q=LIVE_VAR))+++def _on_dirty(node, plug, *_):+ """Maya's node-dirty callback on a watched mesh shape: its mesh (or where it is) changed. Only a flag."""+ try:+ name = plug.partialName(useLongNames=True)+ if not name.startswith(("inMesh", "outMesh", "pnts", "worldMesh", "cachedInMesh")):+ return+ import maya.api.OpenMaya as om+ dag = om.MFnDagNode(node)+ _live.mark(om.MFnDagNode(dag.parent(0)).fullPathName())+ except Exception:+ pass+++def _watch(transforms):+ """Watches these meshes for Live (the ones sent or got: Send adds more). Again for a transform whose shape+ was replaced by a Get."""+ for t in transforms:+ old = _watched.pop(t, None)+ callback = None+ try:+ import maya.api.OpenMaya as om+ if old is not None:+ om.MMessage.removeCallback(old)+ shape = _mesh_shape(t)+ if shape:+ sel = om.MSelectionList()+ sel.add(shape)+ callback = om.MNodeMessage.addNodeDirtyPlugCallback(sel.getDependNode(0), _on_dirty)+ except Exception:+ callback = None # (no maya.api: the tests mark changes by hand)+ _watched[t] = callback+++def _live_send():+ """Main thread, once Live's wait is over: sends the watched meshes that changed (over the Live link when it is+ connected, else through the folder)."""+ changed = _live.take()+ linked = _link is not None and _link.connected+ if not (live_on() or linked) or not changed:+ return None+ cmds = _cmds()+ meshes = []+ for t in changed:+ if cmds.objExists(t):+ shape = _mesh_shape(t)+ if shape:+ meshes.append((cmds.ls(t, long=True)[0], shape))+ if not meshes:+ return None+ if linked:+ try:+ for transform, shape in meshes:+ _link.send(encode_mesh(_extract_mesh(transform, shape)))+ return "sent %d over the link" % len(meshes)+ except Exception as e:+ return _message("Live link: can't send to SculptForge: %s" % e, warning=True)+ try:+ return _send(meshes, live=True)+ except Exception as e: # (a folder gone, a disk full: say it, keep Maya working)+ return _message("Live: can't send to SculptForge: %s" % e, warning=True)+++def _live_label():+ return "Live" if live_on() else "Live off"+++def toggle_live():+ """The shelf's Live button: send the watched meshes by themselves after each edit (and get by itself)."""+ cmds = _cmds()+ on = not live_on()+ cmds.optionVar(iv=(LIVE_VAR, 1 if on else 0))+ if on and not auto_get_on():+ cmds.optionVar(iv=(AUTO_VAR, 1))+ if on:+ _watch([t for t, _ in _selected_meshes()]) # (and the ones sent or got this session)+ _live.forget(list(_live.dirty))+ start_auto_get()+ for button, label in ((LIVE_BUTTON, _live_label()), (AUTO_BUTTON, _auto_label())):+ try:+ if cmds.shelfButton(button, exists=True):+ cmds.shelfButton(button, edit=True, label=label, imageOverlayLabel=label)+ except Exception:+ pass+ if on:+ return _message("Live on: meshes you edit go to SculptForge by themselves (sent or got ones, and the selection)")+ return _message("Live off: click Send to send")++def _auto_label():return "Auto" if auto_get_on() else "Manual"@@ -499,8 +688,591 @@ def toggle_auto_get():return _message("Auto off: click Get to load what SculptForge sends")+# ---- The Live link: a connection to the open SculptForge (File > Maya > Live link) ----+#+# SculptForge offers it only while the user has it on (it warns every time): a Unix domain socket only this user+# can open (Linux, macOS) or a named pipe only this user can open (Windows), never a network port. The pairing+# code from SculptForge (File > Maya > Copy pairing code) opens it. Mesh data only, both ways: SculptForge streams+# the vertices a stroke moves (Points) and whole meshes when faces change (Mesh); this side sends whole meshes+# when you edit. Everything received is checked as strictly as SculptForge checks it. Plain socket / ctypes.++LINK_MAGIC = b"SFML"+LINK_VERSION = 1+LINK_HELLO, LINK_WELCOME, LINK_MESH, LINK_POINTS, LINK_BYE = 1, 2, 3, 4, 5+LINK_MAX_PAYLOAD = 1 << 30+LINK_MAX_VERTICES = 64 << 20+LINK_CODE_CHARS = 32+LINK_BUTTON = "sculptforgeLinkButton"+_HEADER = struct.Struct("<4sHHQ")+_LITTLE = sys.byteorder == "little"+++class LinkError(ValueError):+ pass+++def _f32(values):+ a = array("f", values)+ if not _LITTLE:+ a.byteswap()+ return a.tobytes()+++def _u32(values):+ a = array("I", values)+ if a.itemsize != 4:+ a = array("L", values)+ if not _LITTLE:+ a.byteswap()+ return a.tobytes()+++def _read_array(code, data, at, count):+ a = array(code)+ if code in ("I", "L") and a.itemsize != 4:+ a = array("L" if code == "I" else "I")+ end = at + a.itemsize * count+ if count < 0 or end > len(data):+ raise LinkError("a message whose size doesn't add up")+ a.frombytes(data[at:end])+ if not _LITTLE:+ a.byteswap()+ return a, end+++def frame(kind, payload=b""):+ return _HEADER.pack(LINK_MAGIC, LINK_VERSION, kind, len(payload)) + payload+++def parse_header(header):+ """(kind, payload length) of a 16-byte frame header; raises LinkError."""+ if len(header) != _HEADER.size:+ raise LinkError("a short header")+ magic, version, kind, length = _HEADER.unpack(header)+ if magic != LINK_MAGIC:+ raise LinkError("not the SculptForge link")+ if version != LINK_VERSION:+ raise LinkError("link version %d (this script speaks %d): update the older one" % (version, LINK_VERSION))+ if not LINK_HELLO <= kind <= LINK_BYE:+ raise LinkError("an unknown message")+ if length > LINK_MAX_PAYLOAD:+ raise LinkError("a message over the size cap")+ return kind, length+++def encode_hello(code, client="Maya"):+ code = normalise_code(code).encode("ascii")+ client = client.encode("ascii", "replace")[:64]+ return frame(LINK_HELLO, code + struct.pack("<H", len(client)) + client)+++def _name(name):+ raw = name.encode("ascii")+ if not raw or len(raw) > MAX_NAME or safe_name(name) != name:+ raise LinkError("a bad object name")+ return struct.pack("<H", len(raw)) + raw+++def encode_mesh(mesh):+ """A Mesh frame from {"name", "positions" (3 per vertex), "face_sizes", "indices", "uvs" (2 per corner or empty)}."""+ v = len(mesh["positions"]) // 3+ f, c = len(mesh["face_sizes"]), len(mesh["indices"])+ uvs = mesh.get("uvs") or []+ head = _name(mesh["name"]) + struct.pack("<IIIB", v, f, c, 1 if uvs else 0)+ return frame(LINK_MESH, head + _f32(mesh["positions"]) + bytes(bytearray(mesh["face_sizes"])) + _u32(mesh["indices"])+ + (_f32(uvs) if uvs else b""))+++def _read_name(data, at):+ if at + 2 > len(data):+ raise LinkError("a bad object name")+ (n,) = struct.unpack_from("<H", data, at)+ raw = data[at + 2:at + 2 + n]+ if len(raw) != n:+ raise LinkError("a bad object name")+ try:+ name = raw.decode("ascii")+ except UnicodeDecodeError:+ raise LinkError("a bad object name")+ if not name or n > MAX_NAME or safe_name(name) != name:+ raise LinkError("a bad object name")+ return name, at + 2 + n+++def _finite(values):+ for x in values:+ if x != x or x in (float("inf"), float("-inf")):+ return False+ return True+++def parse_mesh(data):+ """Checks a Mesh payload as strictly as SculptForge does; returns the dict encode_mesh takes."""+ name, at = _read_name(data, 0)+ if at + 13 > len(data):+ raise LinkError("a mesh with bad counts")+ v, f, c, flags = struct.unpack_from("<IIIB", data, at)+ at += 13+ if v == 0 or v > LINK_MAX_VERTICES or f == 0 or c < 3 * f or c > 255 * f or flags > 1:+ raise LinkError("a mesh with bad counts")+ positions, at = _read_array("f", data, at, 3 * v)+ if at + f > len(data):+ raise LinkError("a mesh whose size doesn't add up")+ sizes = bytearray(data[at:at + f])+ at += f+ indices, at = _read_array("I", data, at, c)+ uvs = array("f")+ if flags:+ uvs, at = _read_array("f", data, at, 2 * c)+ if at != len(data):+ raise LinkError("a mesh whose size doesn't add up")+ if min(sizes) < 3 or sum(sizes) != c:+ raise LinkError("a mesh whose faces don't add up")+ if max(indices) >= v:+ raise LinkError("a mesh with a vertex index out of range")+ if not _finite(positions) or not _finite(uvs):+ raise LinkError("a mesh with a number that isn't finite")+ return {"name": name, "positions": positions, "face_sizes": sizes, "indices": indices, "uvs": uvs}+++def encode_points(name, vertex_count, indices, positions):+ return frame(LINK_POINTS, _name(name) + struct.pack("<II", vertex_count, len(indices)) + _u32(indices)+ + _f32(positions))+++def parse_points(data):+ """(name, vertex count, indices, positions) of a Points payload, checked."""+ name, at = _read_name(data, 0)+ if at + 8 > len(data):+ raise LinkError("points whose size doesn't add up")+ vertex_count, n = struct.unpack_from("<II", data, at)+ at += 8+ if vertex_count == 0 or vertex_count > LINK_MAX_VERTICES or n > vertex_count:+ raise LinkError("points whose size doesn't add up")+ indices, at = _read_array("I", data, at, n)+ positions, at = _read_array("f", data, at, 3 * n)+ if at != len(data):+ raise LinkError("points whose size doesn't add up")+ if n and max(indices) >= vertex_count or not _finite(positions):+ raise LinkError("points out of range")+ return name, vertex_count, indices, positions+++def normalise_code(code):+ c = (code or "").replace("-", "").strip().lower()+ if len(c) != LINK_CODE_CHARS or any(ch not in "0123456789abcdef" for ch in c):+ raise LinkError("that isn't a pairing code (32 letters and digits, from SculptForge's File > Maya > Copy "+ "pairing code)")+ return c+++_PIPE_RE = re.compile(r"^\\\\\.\\pipe\\sculptforge-maya-link-[A-Za-z0-9_\-]+$")+++def default_endpoint():+ """Where SculptForge offers the link, by its rules (link/AiLink.cpp localEndpoint)."""+ if os.name == "nt":+ import getpass+ user = re.sub(r"[^A-Za-z0-9_\-]", "_", getpass.getuser() or "user") or "user"+ return "\\\\.\\pipe\\sculptforge-maya-link-" + user+ run = os.environ.get("XDG_RUNTIME_DIR")+ if run:+ return os.path.join(run, "sculptforge", "maya-link.sock")+ tmp = (os.environ.get("TMPDIR") or "/tmp").rstrip("/") or "/tmp"+ return os.path.join(tmp, "sculptforge-%d" % os.getuid(), "maya-link.sock")+++def parse_pairing(text):+ """(code, endpoint) from what Copy pairing code put on the clipboard ("sflink1 CODE ENDPOINT"), or a bare code.+ The endpoint must be SculptForge's: a maya-link.sock path or its named pipe, nothing else."""+ parts = (text or "").strip().split(None, 2)+ if len(parts) == 3 and parts[0] == "sflink1":+ code, endpoint = normalise_code(parts[1]), parts[2].strip()+ elif len(parts) == 1:+ code, endpoint = normalise_code(parts[0]), default_endpoint()+ else:+ raise LinkError("paste what SculptForge's File > Maya > Copy pairing code copied")+ if os.name == "nt":+ if not _PIPE_RE.match(endpoint):+ raise LinkError("that isn't SculptForge's link")+ elif not (os.path.isabs(endpoint) and os.path.basename(endpoint) == "maya-link.sock" and ".." not in endpoint):+ raise LinkError("that isn't SculptForge's link")+ return code, endpoint+++class _SocketConn(object):+ """Linux / macOS: the Unix domain socket, which must be this user's (and in a folder only this user owns)."""++ def __init__(self, endpoint):+ import socket+ st = os.lstat(endpoint)+ folder = os.lstat(os.path.dirname(endpoint))+ import stat+ if (not stat.S_ISSOCK(st.st_mode) or st.st_uid != os.getuid() or folder.st_uid != os.getuid()+ or folder.st_mode & 0o077):+ raise LinkError("the link isn't this user's: not connecting")+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ self.sock.settimeout(5.0)+ self.sock.connect(endpoint)++ def recv(self, n, timeout):+ """Up to n bytes; b"" on timeout; raises on close."""+ import socket+ self.sock.settimeout(timeout)+ try:+ data = self.sock.recv(n)+ except socket.timeout:+ return b""+ if not data:+ raise LinkError("SculptForge closed the link")+ return data++ def send(self, data):+ self.sock.settimeout(30.0)+ self.sock.sendall(data)++ def close(self):+ try:+ self.sock.close()+ except OSError:+ pass+++class _PipeConn(object):+ """Windows: SculptForge's named pipe, opened as a file; reads only what PeekNamedPipe says is there, so a+ write never waits behind a read."""++ def __init__(self, endpoint):+ import ctypes+ import msvcrt+ self.file = open(endpoint, "r+b", buffering=0)+ self.handle = msvcrt.get_osfhandle(self.file.fileno())+ self.k32 = ctypes.windll.kernel32+ self.ctypes = ctypes++ def recv(self, n, timeout):+ avail = self.ctypes.c_ulong(0)+ deadline = time.monotonic() + timeout+ while True:+ if not self.k32.PeekNamedPipe(self.ctypes.c_void_p(self.handle), None, 0, None, self.ctypes.byref(avail), None):+ raise LinkError("SculptForge closed the link")+ if avail.value:+ return self.file.read(min(n, avail.value))+ if time.monotonic() >= deadline:+ return b""+ time.sleep(0.002)++ def send(self, data):+ view = memoryview(data)+ while view:+ n = self.file.write(view[:1 << 20])+ view = view[n:]++ def close(self):+ try:+ self.file.close()+ except OSError:+ pass+++class LinkClient(object):+ """One connection to SculptForge. `handle(kind, payload)` runs on the reader thread for each Mesh or Points (it+ should only queue them); `tick()` runs there too, about every 50 ms."""++ def __init__(self, conn, code, handle, tick=None, client="Maya"):+ self.conn = conn+ self.handle = handle+ self.tick = tick+ self.lock = threading.Lock()+ self.connected = False+ self.stopped = threading.Event()+ self.error = ""+ self.conn.send(encode_hello(code, client))+ kind, payload = self._read_frame(5.0)+ if kind != LINK_WELCOME:+ raise LinkError("SculptForge refused the pairing code (copy it again: it changes each time the link "+ "is turned on)")+ self.server = payload[2:].decode("ascii", "replace")+ self.connected = True+ self.thread = threading.Thread(target=self._run, name="SculptForge Live link", daemon=True)+ self.thread.start()++ def _read_exact(self, n, first_timeout):+ out = bytearray()+ timeout = first_timeout+ while len(out) < n:+ data = self.conn.recv(n - len(out), timeout)+ if not data:+ if not out and first_timeout < 1.0:+ return None # nothing yet+ raise LinkError("the link timed out")+ out += data+ timeout = 30.0+ return bytes(out)++ def _read_frame(self, first_timeout):+ header = self._read_exact(_HEADER.size, first_timeout)+ if header is None:+ return None, None+ kind, length = parse_header(header)+ payload = self._read_exact(length, 30.0) if length else b""+ return kind, payload++ def _run(self):+ try:+ while not self.stopped.is_set():+ kind, payload = self._read_frame(0.05)+ if kind is None:+ if self.tick:+ self.tick()+ continue+ if kind == LINK_BYE:+ self.error = "SculptForge turned the link off"+ break+ if kind not in (LINK_MESH, LINK_POINTS):+ raise LinkError("an unexpected message")+ self.handle(kind, payload)+ if self.tick:+ self.tick()+ except Exception as e: # (closed, timed out, or a message that didn't check out: the link ends)+ self.error = str(e)+ self.connected = False+ self.conn.close()++ def send(self, data):+ with self.lock:+ self.conn.send(data)++ def close(self):+ self.stopped.set()+ if self.connected:+ try:+ self.send(frame(LINK_BYE))+ except Exception:+ pass+ self.connected = False+++class LinkInbox(object):+ """What came over the link, folded for Maya's main thread: the newest whole mesh per object, and per object the+ latest position of every vertex streamed since (absolute positions, so many Points become one update)."""++ def __init__(self):+ self.lock = threading.Lock()+ self.meshes = {}+ self.points = {} # name -> (vertex count, {index: (x, y, z)})+ self.order = []++ def add(self, kind, payload):+ """Reader thread: checks and folds one message. True when Maya's main thread should be woken."""+ if kind == LINK_MESH:+ mesh = parse_mesh(payload)+ with self.lock:+ self.meshes[mesh["name"]] = mesh+ self.points.pop(mesh["name"], None)+ self._touch(mesh["name"])+ else:+ name, count, indices, positions = parse_points(payload)+ with self.lock:+ old = self.points.get(name)+ moved = old[1] if old and old[0] == count else {}+ for k, i in enumerate(indices):+ moved[i] = (positions[3 * k], positions[3 * k + 1], positions[3 * k + 2])+ self.points[name] = (count, moved)+ self._touch(name)+ return True++ def _touch(self, name):+ if name in self.order:+ self.order.remove(name)+ self.order.append(name)++ def take(self):+ """[(name, mesh or None, (count, moved) or None)] in arrival order; clears."""+ with self.lock:+ out = [(n, self.meshes.pop(n, None), self.points.pop(n, None)) for n in self.order]+ self.order = []+ return out+++_link = None+_link_inbox = LinkInbox()+_link_apply_queued = threading.Event()+++def _link_handle(kind, payload):+ _link_inbox.add(kind, payload)+ if not _link_apply_queued.is_set():+ _link_apply_queued.set()+ import maya.utils+ maya.utils.executeDeferred(_link_apply)+++def _link_tick():+ if _live.due():+ with _live.lock:+ _live.queued = True+ import maya.utils+ maya.utils.executeDeferred(_live_send)+++def _om():+ import maya.api.OpenMaya as om # only inside Maya+ return om+++def _dag(node):+ om = _om()+ sel = om.MSelectionList()+ sel.add(node)+ return sel.getDagPath(0)+++def _extract_mesh(transform, shape):+ """The mesh of `shape` in world space, as the link sends it."""+ om = _om()+ fn = om.MFnMesh(_dag(shape))+ positions = array("f")+ for p in fn.getFloatPoints(om.MSpace.kWorld):+ positions.extend((p.x, p.y, p.z))+ counts, connects = fn.getVertices()+ if max(counts) > 255:+ raise LinkError("%s has a face with more than 255 corners" % _short(transform))+ uvs = array("f")+ if fn.numUVs() > 0:+ uv_counts, uv_ids = fn.getAssignedUVs()+ if list(uv_counts) == list(counts): # every face mapped+ us, vs = fn.getUVs()+ for i in uv_ids:+ uvs.extend((us[i], vs[i]))+ return {"name": safe_name(_short(transform)), "positions": positions, "face_sizes": bytearray(counts),+ "indices": list(connects), "uvs": uvs}+++def _apply_points(name, count, moved):+ """SculptForge's streamed vertices, in place (world space). Not an undo step: undo in SculptForge."""+ om = _om()+ t = _find_transform(name)+ if not t:+ return+ dag = _dag(_mesh_shape(t))+ fn = om.MFnMesh(dag)+ if fn.numVertices != count:+ return # (out of step: the stroke's end sends a whole mesh when faces changed)+ to_object = dag.inclusiveMatrixInverse()+ for i, (x, y, z) in moved.items():+ fn.setPoint(i, om.MPoint(x, y, z) * to_object)+ fn.updateSurface()+++def _apply_mesh(mesh):+ """A whole mesh from SculptForge: replaces the shape of the object with its name (keeping the transform, parent+ and shading groups), or makes a new object."""+ om = _om()+ cmds = _cmds()+ name = mesh["name"]+ existing = _find_transform(name)+ p = mesh["positions"]+ points = om.MPointArray()+ to_object = _dag(existing).inclusiveMatrixInverse() if existing else om.MMatrix()+ for k in range(0, len(p), 3):+ points.append(om.MPoint(p[k], p[k + 1], p[k + 2]) * to_object)+ fn = om.MFnMesh()+ parent = _dag(existing).node() if existing else om.MObject.kNullObj+ node = fn.create(points, list(mesh["face_sizes"]), list(mesh["indices"]), parent=parent)+ if len(mesh["uvs"]):+ uv = mesh["uvs"]+ fn.setUVs(list(uv[0::2]), list(uv[1::2]))+ fn.assignUVs(list(mesh["face_sizes"]), list(range(len(mesh["indices"]))))+ new_shape = om.MFnDagNode(fn.object()).fullPathName()+ if existing:+ 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)+ for sg in groups or ["initialShadingGroup"]:+ cmds.sets(new_shape, edit=True, forceElement=sg)+ cmds.delete(old_shape)+ cmds.rename(new_shape, old_name)+ return existing+ t = om.MFnDagNode(node).fullPathName()+ cmds.sets(new_shape, edit=True, forceElement="initialShadingGroup")+ t = cmds.rename(t, ":" + name)+ cmds.rename(_mesh_shape(t), name + "Shape")+ return cmds.ls(t, long=True)[0]+++def _link_apply():+ """Main thread: what came over the link. The echo guard holds throughout; none of it is an undo step."""+ _link_apply_queued.clear()+ cmds = _cmds()+ touched = []+ state = cmds.undoInfo(q=True, stateWithoutFlush=True)+ cmds.undoInfo(stateWithoutFlush=False)+ _live.applying += 1+ try:+ for name, mesh, points in _link_inbox.take():+ try:+ if mesh is not None:+ touched.append(_apply_mesh(mesh))+ if points is not None:+ _apply_points(name, points[0], points[1])+ except Exception as e:+ _message("Live link: can't apply %s: %s" % (name, e), warning=True)+ finally:+ _live.applying -= 1+ cmds.undoInfo(stateWithoutFlush=state)+ touched = [t for t in touched if t]+ _live.forget(touched)+ _watch(touched)+++def link_to_sculptforge(pairing=None):+ """The shelf's Link button: connects to the open SculptForge with its pairing code (asked for, unless given),+ or disconnects."""+ global _link+ if _link is not None and _link.connected:+ _link.close()+ _link = None+ _link_label_update()+ return _message("Live link off")+ cmds = _cmds()+ if pairing is None:+ answer = cmds.promptDialog(title="SculptForge Live link",+ message="In SculptForge: File > Maya > Live link, then Copy pairing code. Paste it here:",+ button=["Link", "Cancel"], defaultButton="Link", cancelButton="Cancel",+ dismissString="Cancel")+ if answer != "Link":+ return None+ pairing = cmds.promptDialog(query=True, text=True)+ try:+ code, endpoint = parse_pairing(pairing)+ conn = _PipeConn(endpoint) if os.name == "nt" else _SocketConn(endpoint)+ _link = LinkClient(conn, code, _link_handle, _link_tick, "Maya " + str(cmds.about(version=True))[:32])+ except Exception as e:+ _link = None+ _link_label_update()+ return _message("Live link: %s" % (e if isinstance(e, LinkError) else "SculptForge isn't offering it (%s)" % e),+ warning=True)+ _watch([t for t, _ in _selected_meshes()])+ _link_label_update()+ return _message("Live link on: connected to SculptForge %s" % _link.server)+++def _link_label_update():+ cmds = _cmds()+ label = "Linked" if _link is not None and _link.connected else "Link"+ try:+ if cmds.shelfButton(LINK_BUTTON, exists=True):+ cmds.shelfButton(LINK_BUTTON, edit=True, label=label, imageOverlayLabel=label)+ except Exception:+ pass++def install_shelf():- """Creates the SculptForge shelf: Send, Get, Auto and Folder buttons. Run once, after putting this file in a+ """Creates the SculptForge shelf: Send, Get, Auto, Live, Link and Folder buttons. Run once, after putting this file in afolder on Maya's script path (README.md)."""cmds = _cmds()import maya.mel as mel@@ -512,10 +1284,15 @@ def install_shelf():("Send", "Send the selected meshes to SculptForge", "send_to_sculptforge"),("Get", "Get what SculptForge sent (replaces meshes by name)", "get_from_sculptforge"),(_auto_label(), "Auto: get what SculptForge sends by itself (click to turn on or off)", "toggle_auto_get"),+ (_live_label(), "Live: send the meshes you edit by themselves, and get by itself (click to turn on or off)",+ "toggle_live"),+ ("Link", "Live link: connect to the open SculptForge with its pairing code, so Maya follows your strokes "+ "(click again to disconnect)", "link_to_sculptforge"),("Folder", "Choose the exchange folder (the same one as in SculptForge)", "choose_folder"),]for label, tip, func in buttons:- name = [AUTO_BUTTON] if func == "toggle_auto_get" else []+ name = {"toggle_auto_get": [AUTO_BUTTON], "toggle_live": [LIVE_BUTTON],+ "link_to_sculptforge": [LINK_BUTTON]}.get(func, [])cmds.shelfButton(*name, parent=shelf, label=label, imageOverlayLabel=label, annotation=tip,image="pythonFamily.png", sourceType="python",command="import sculptforge_maya\nsculptforge_maya.%s()" % func)diff --git a/src/app/App.cpp b/src/app/App.cppindex 10dae94c..5f22e063 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -3054,6 +3054,7 @@ void App::drawUi() {drawPacksUi(); // pack review, New Pack, macro confirmation and editor (PanelPacks.cpp)drawMemoryConfirm(); // "Not enough free memory" before a big mesh (MemoryConfirm.cpp)drawAiLink(); // live mode: Approve / Allow dialogs, the "AI connected" badge (PanelAiLink.cpp)+ drawMayaLinkDialog(); // the Maya Live link's warning (PanelMaya.cpp)drawConnectAi(); // Help > Connect an AI tool (PanelConnectAi.cpp)drawHelpConsoleUi(); // console, command palette, Controls (F1), Ctrl-hover help: last, on topdrawWhatsNew(); // What's New after an update or from the Help menu (WhatsNewPopup.cpp)diff --git a/src/app/App.h b/src/app/App.hindex d75111b2..e9b1bc22 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -53,6 +53,8 @@#include "core/WhatsNew.h"#include "core/Texture.h"#include "io/ArExport.h"+#include "io/MayaBridge.h"+#include "link/MayaLink.h"#include "link/PhoneLink.h"#include "link/Qr.h"#include "render/Camera.h"@@ -1375,17 +1377,61 @@ private: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.+ // (uiPrefs_.mayaFolder); with Get automatically on, that one folder's manifest is checked every 250 ms.+ // Live (uiPrefs_.mayaLive): the Parts a stroke or edit changed go to Maya by themselves once the scene has+ // been still for 300 ms, written on a worker from a copy (PanelMaya.cpp).void drawMayaMenu();void pollMaya();+ void pollMayaLive(Uint64 now);void sendToMaya();void receiveFromMaya();void chooseMayaFolder();void setMayaFolder(const std::string& folder);+ void setMayaLive(bool on);+ void mayaLiveMarkAll(); // every Part as it is now counts as exchanged (Live just turned on, a manual send)+ void finishMayaLiveSend();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;+ std::string mayaWriter_; // this session's writer id in the manifests it writes (mayaNewWriterId)+ struct MayaLiveSeen {+ uint64_t revision = 0; // the Part's undo revision when last exchanged+ uint64_t hash = 0; // mayaMeshHash then (0 = not yet hashed)+ };+ std::unordered_map<uint32_t, MayaLiveSeen> mayaLiveSeen_; // by Part id+ MayaLiveDebounce mayaLiveWait_;+ uint64_t mayaLiveKey_ = 0; // every Part's id and undo revision at the last look (a change restarts the wait)+ struct MayaLiveResult {+ bool ok = false;+ std::string message;+ std::vector<uint32_t> ids; // Parts sent+ std::vector<std::string> names; // their names in Maya+ std::vector<uint64_t> hashes; // their hashes as sent (all the Parts looked at)+ std::vector<uint32_t> hashedIds;+ std::vector<uint64_t> revisions; // the hashed Parts' undo revisions then+ };+ std::future<MayaLiveResult> mayaLiveJob_;+ int mayaLiveSends_ = 0; // Live sends that wrote something (UI tests: maya_live_sends)+ // The Maya Live link (link/MayaLink.h, PanelMaya.cpp): off at every start, never remembered as on; turned on+ // only through its warning dialog, off from the top bar's "Live link on" chip. While Maya is connected, a+ // stroke streams the vertices it moves (at most every 100 ms) and each change goes over the link instead of+ // the folder.+ void drawMayaLinkDialog();+ void startMayaLink();+ void stopMayaLink();+ void pollMayaLink(Uint64 now);+ void sendMayaLinkPart(int part);+ std::string mayaLinkName(int part); // the Part's name in Maya (its Bridge name, made unique and set)+ std::unique_ptr<link::MayaLinkServer> mayaLink_;+ bool mayaLinkAsk_ = false; // the warning dialog is open+ struct MayaLinkSent {+ std::vector<glm::vec3> positions; // what Maya has of the Part+ uint64_t topology = 0; // a hash of its triangles then (another: a whole mesh goes)+ };+ std::unordered_map<uint32_t, MayaLinkSent> mayaLinkSent_; // by Part id+ Uint64 mayaLinkStreamNs_ = 0;+ int mayaLinkStreams_ = 0; // mid-stroke Points sent (UI tests: maya_link_streams)// 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 arediff --git a/src/app/Config.cpp b/src/app/Config.cppindex 759805c8..20ced6df 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -978,6 +978,7 @@ void App::restartPrefsForTest(const std::string& uiJson) {UiPrefs defaults;defaults.mayaFolder = uiPrefs_.mayaFolder; // (maya.json, not ui.json)defaults.mayaAutoReceive = uiPrefs_.mayaAutoReceive;+ defaults.mayaLive = uiPrefs_.mayaLive;uiPrefs_ = defaults;actions_.clearOverrides();resetRadialMenus();diff --git a/src/app/Config.h b/src/app/Config.hindex 5e27e962..7b2eae46 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -139,7 +139,8 @@ struct UiPrefs {// 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 (on once a folder is chosen): check its manifest once a second+ bool mayaAutoReceive = false; // Get automatically (on once a folder is chosen): check its manifest every 250 ms+ bool mayaLive = false; // Live (opt-in): send the changed Parts by themselves after each stroke};Json toJson(const UiPrefs& prefs);diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cppindex c5bf7679..9f26a93d 100644--- a/src/app/I18nSimplifiedChinese.cpp+++ b/src/app/I18nSimplifiedChinese.cpp@@ -1838,12 +1838,49 @@ constexpr Entry kSimplifiedChinese[] = {"“按边界”会让遮罩从边界向最内侧的环淡出。"},// --- PanelMaya.cpp (tools/i18n/coverage.py) ---{"Get automatically", "自动获取"},- {"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). On once you choose the folder; off: use Get from Maya.",- "Maya 传来的内容一到就加载:SculptForge 每秒检查一次交换文件夹的列表文件(只看修改时间与大小)。选好文件夹后即开启;关闭时:"+ {"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest every "+ "250 ms (its modification time and size only). On once you choose the folder; off: use Get from Maya.",+ "Maya 传来的内容一到就加载:SculptForge 每 250 毫秒检查一次交换文件夹的列表文件(只看修改时间与大小)。选好文件夹后即开启;关闭时:""请使用“从 Maya 获取”。"},{"Turn the Maya bridge off", "关闭 Maya 桥接"},{"Forget the exchange folder; nothing in it is deleted.", "忘记交换文件夹;其中的内容不会被删除。"},+ // --- Maya Live and the Live link (PanelMaya.cpp, Shell.cpp) ---+ {"Keep Maya in step as you sculpt: after each stroke (once you pause for 300 ms), the Parts it changed go to the exchange folder by themselves, and what Maya sends loads by itself. Still files only: no network. Turn on Live on Maya's SculptForge shelf too.",+ "雕刻时让 Maya 保持同步:每一笔之后(停顿 300 毫秒时),这一笔改动的部件会自动送到交换文件夹,Maya 传来的也会自动加载。仍然只用文件:不用网络。也请在 Maya 的 SculptForge 工具架上开启 Live。"},+ {"Live link",+ "实时连接"},+ {"Maya follows your strokes as you draw them, over a connection on this computer (the shelf's Link button). Asks first, every time; off again at every start.",+ "通过这台电脑上的连接(工具架的 Link 按钮),Maya 会在你画的同时跟上每一笔。每次都会先询问;每次启动时都会关闭。"},+ {"Live link: connected to %s",+ "实时连接:已连接到 %s"},+ {"Live link on: waiting for Maya",+ "实时连接已开启:等待 Maya"},+ {"Pairing code: %s",+ "配对码:%s"},+ {"Copy pairing code",+ "复制配对码"},+ {"Turn the Live link off",+ "关闭实时连接"},+ {"Turn on the Maya Live link?",+ "要开启 Maya 实时连接吗?"},+ {"The Live link lets the SculptForge shelf in Maya follow your strokes as you sculpt.",+ "实时连接让 Maya 里的 SculptForge 工具架在你雕刻时跟上每一笔。"},+ {"It opens a connection on this computer.",+ "这会在这台电脑上打开一个连接。"},+ {"Anything running on this computer that knows the pairing code could send meshes into SculptForge. It carries meshes only: never commands, files or scripts. Other computers and web pages can't reach it.",+ "这台电脑上任何知道配对码的程序都可能把网格送进 SculptForge。它只传送网格:绝不传送命令、文件或脚本。其他电脑和网页都无法连到它。"},+ {"Turn it off when you're not using it: click \"Live link on\" in the top bar. It is off again every time SculptForge starts.",+ "不用时请关闭:点击顶部栏的“实时连接已开启”。每次启动 SculptForge 时它都会关闭。"},+ {"Turn on",+ "开启"},+ {"Live link on",+ "实时连接已开启"},+ {"Click to turn the Maya Live link off.",+ "点击即可关闭 Maya 实时连接。"},+ {"Top bar",+ "顶部栏"},+ {"Status bar",+ "状态栏"},// --- PanelPacks.cpp (tools/i18n/coverage.py) ---{"Install Pack...", "安装资源包..."},{"Install a SculptForge pack (.sfpack): brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie menus "diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cppindex 3a4da3d8..598f9efb 100644--- a/src/app/I18nSpanish.cpp+++ b/src/app/I18nSpanish.cpp@@ -2115,10 +2115,10 @@ constexpr Entry kSpanish[] = {"Por borde desvanece la máscara desde el borde hacia el anillo más interior."},// --- PanelMaya.cpp (tools/i18n/coverage.py) ---{"Get automatically", "Recibir automáticamente"},- {"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). On once you choose the folder; off: use Get from Maya.",- "Carga lo que envía Maya en cuanto llega: SculptForge comprueba el manifiesto de la carpeta de intercambio una "- "vez por segundo (solo su fecha de modificación y su tamaño). Activado al elegir la carpeta; desactivado: usa "+ {"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest every "+ "250 ms (its modification time and size only). On once you choose the folder; off: use Get from Maya.",+ "Carga lo que envía Maya en cuanto llega: SculptForge comprueba el manifiesto de la carpeta de intercambio cada "+ "250 ms (solo su fecha de modificación y su tamaño). Activado al elegir la carpeta; desactivado: usa ""Recibir de Maya."},{"Turn the Maya bridge off", "Desactivar el puente con Maya"},{"Forget the exchange folder; nothing in it is deleted.",@@ -4680,6 +4680,43 @@ constexpr Entry kSpanish[] = {"Modo estudio"},{"Studio build for %s","Versión de estudio para %s"},+ // --- Maya Live and the Live link (PanelMaya.cpp, Shell.cpp) ---+ {"Keep Maya in step as you sculpt: after each stroke (once you pause for 300 ms), the Parts it changed go to the exchange folder by themselves, and what Maya sends loads by itself. Still files only: no network. Turn on Live on Maya's SculptForge shelf too.",+ "Mantén Maya al día mientras esculpes: tras cada trazo (en cuanto pausas 300 ms), las Piezas que cambió van solas a la carpeta de intercambio, y lo que envía Maya se carga solo. Solo archivos: sin red. Activa también Live en el estante de SculptForge de Maya."},+ {"Live link",+ "Enlace en vivo"},+ {"Maya follows your strokes as you draw them, over a connection on this computer (the shelf's Link button). Asks first, every time; off again at every start.",+ "Maya sigue tus trazos mientras los dibujas, mediante una conexión en este ordenador (el botón Link del estante). Pregunta antes, cada vez; se desactiva en cada inicio."},+ {"Live link: connected to %s",+ "Enlace en vivo: conectado a %s"},+ {"Live link on: waiting for Maya",+ "Enlace en vivo activado: esperando a Maya"},+ {"Pairing code: %s",+ "Código de emparejamiento: %s"},+ {"Copy pairing code",+ "Copiar código de emparejamiento"},+ {"Turn the Live link off",+ "Desactivar el enlace en vivo"},+ {"Turn on the Maya Live link?",+ "¿Activar el enlace en vivo con Maya?"},+ {"The Live link lets the SculptForge shelf in Maya follow your strokes as you sculpt.",+ "El enlace en vivo permite que el estante de SculptForge en Maya siga tus trazos mientras esculpes."},+ {"It opens a connection on this computer.",+ "Abre una conexión en este ordenador."},+ {"Anything running on this computer that knows the pairing code could send meshes into SculptForge. It carries meshes only: never commands, files or scripts. Other computers and web pages can't reach it.",+ "Cualquier programa de este ordenador que conozca el código de emparejamiento podría enviar mallas a SculptForge. Solo transporta mallas: nunca comandos, archivos ni scripts. Otros ordenadores y las páginas web no pueden alcanzarlo."},+ {"Turn it off when you're not using it: click \"Live link on\" in the top bar. It is off again every time SculptForge starts.",+ "Desactívalo cuando no lo uses: haz clic en \"Enlace en vivo activado\" en la barra superior. Se desactiva cada vez que SculptForge se inicia."},+ {"Turn on",+ "Activar"},+ {"Live link on",+ "Enlace en vivo activado"},+ {"Click to turn the Maya Live link off.",+ "Haz clic para desactivar el enlace en vivo con Maya."},+ {"Top bar",+ "Barra superior"},+ {"Status bar",+ "Barra de estado"},};} // namespacediff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cppindex deab6e0f..0a331b1c 100644--- a/src/app/I18nTraditionalChinese.cpp+++ b/src/app/I18nTraditionalChinese.cpp@@ -1838,12 +1838,49 @@ constexpr Entry kTraditionalChinese[] = {"「依邊界」會讓遮罩從邊界向最內側的環淡出。"},// --- PanelMaya.cpp (tools/i18n/coverage.py) ---{"Get automatically", "自動取得"},- {"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). On once you choose the folder; off: use Get from Maya.",- "Maya 傳來的內容一到就載入:SculptForge 每秒檢查一次交換資料夾的清單檔(只看修改時間與大小)。選好資料夾後即開啟;關閉時:"+ {"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest every "+ "250 ms (its modification time and size only). On once you choose the folder; off: use Get from Maya.",+ "Maya 傳來的內容一到就載入:SculptForge 每 250 毫秒檢查一次交換資料夾的清單檔(只看修改時間與大小)。選好資料夾後即開啟;關閉時:""請使用「從 Maya 取得」。"},{"Turn the Maya bridge off", "關閉 Maya 橋接"},{"Forget the exchange folder; nothing in it is deleted.", "忘記交換資料夾;其中的內容不會被刪除。"},+ // --- Maya Live and the Live link (PanelMaya.cpp, Shell.cpp) ---+ {"Keep Maya in step as you sculpt: after each stroke (once you pause for 300 ms), the Parts it changed go to the exchange folder by themselves, and what Maya sends loads by itself. Still files only: no network. Turn on Live on Maya's SculptForge shelf too.",+ "雕刻時讓 Maya 保持同步:每一筆之後(停頓 300 毫秒時),這一筆改動的部件會自動送到交換資料夾,Maya 傳來的也會自動載入。仍然只用檔案:不用網路。也請在 Maya 的 SculptForge 工具架上開啟 Live。"},+ {"Live link",+ "即時連線"},+ {"Maya follows your strokes as you draw them, over a connection on this computer (the shelf's Link button). Asks first, every time; off again at every start.",+ "透過這台電腦上的連線(工具架的 Link 按鈕),Maya 會在你畫的同時跟上每一筆。每次都會先詢問;每次啟動時都會關閉。"},+ {"Live link: connected to %s",+ "即時連線:已連線到 %s"},+ {"Live link on: waiting for Maya",+ "即時連線已開啟:等待 Maya"},+ {"Pairing code: %s",+ "配對碼:%s"},+ {"Copy pairing code",+ "複製配對碼"},+ {"Turn the Live link off",+ "關閉即時連線"},+ {"Turn on the Maya Live link?",+ "要開啟 Maya 即時連線嗎?"},+ {"The Live link lets the SculptForge shelf in Maya follow your strokes as you sculpt.",+ "即時連線讓 Maya 裡的 SculptForge 工具架在你雕刻時跟上每一筆。"},+ {"It opens a connection on this computer.",+ "這會在這台電腦上開啟一個連線。"},+ {"Anything running on this computer that knows the pairing code could send meshes into SculptForge. It carries meshes only: never commands, files or scripts. Other computers and web pages can't reach it.",+ "這台電腦上任何知道配對碼的程式都可能把網格送進 SculptForge。它只傳送網格:絕不傳送指令、檔案或腳本。其他電腦和網頁都無法連到它。"},+ {"Turn it off when you're not using it: click \"Live link on\" in the top bar. It is off again every time SculptForge starts.",+ "不用時請關閉:按一下頂部列的「即時連線已開啟」。每次啟動 SculptForge 時它都會關閉。"},+ {"Turn on",+ "開啟"},+ {"Live link on",+ "即時連線已開啟"},+ {"Click to turn the Maya Live link off.",+ "按一下即可關閉 Maya 即時連線。"},+ {"Top bar",+ "頂部列"},+ {"Status bar",+ "狀態列"},// --- PanelPacks.cpp (tools/i18n/coverage.py) ---{"Install Pack...", "安裝套件..."},{"Install a SculptForge pack (.sfpack): brushes, alphas, Lit Spheres, Material Recipes, VDMs, keymaps, pie menus "diff --git a/src/app/PanelMaya.cpp b/src/app/PanelMaya.cppindex a0a053a3..7f030f12 100644--- a/src/app/PanelMaya.cpp+++ b/src/app/PanelMaya.cpp@@ -4,15 +4,22 @@// 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, on-// once a folder is chosen) 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. While the bridge is on, the top bar has a Send to-// Maya button (Shell.cpp).+// once a folder is chosen) after a modification-time check of that folder's one manifest every 250 ms, or (Live,+// opt-in) 300 ms after a stroke or edit ends, for the Parts it changed. No sockets, no ports, and nothing from+// the folder is ever run. While the bridge is on, the top bar has a Send to Maya button (Shell.cpp).#include "app/App.h"#include "app/Ui.h"#include "core/Json.h"+#include "core/ManagedPolicy.h"+#include "io/BridgeCommands.h"#include "io/MayaBridge.h"+#include "io/MayaCommands.h"+#include "app/Theme.h"+#include <SDL3/SDL_clipboard.h>++#include <chrono>#include <filesystem>#include <fstream>#include <iterator>@@ -41,7 +48,7 @@ void menuAction(App& app, const char* id) {ui::HelpAction(app, id);}-// <prefs>/maya.json: {"folder": "...", "auto_get": true}. Read strictly: a small file, a string path to an existing+// <prefs>/maya.json: {"folder": "...", "auto_get": true, "live": false}. Read strictly: a small file, a string path to an existing// folder (else the bridge stays off). Get automatically is on unless the user turned it off: "auto_get", not the// old "auto", which every earlier version wrote as false (its default was off).void loadMayaPrefs(const std::string& configDir, UiPrefs& p) {@@ -55,6 +62,7 @@ void loadMayaPrefs(const std::string& configDir, UiPrefs& p) {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_get"].asBool(true);+ p.mayaLive = !p.mayaFolder.empty() && j["live"].asBool(false);}void saveMayaPrefs(const std::string& configDir, const UiPrefs& p) {@@ -62,18 +70,315 @@ void saveMayaPrefs(const std::string& configDir, const UiPrefs& p) {Json j = Json::object();j.set("folder", p.mayaFolder);j.set("auto_get", p.mayaAutoReceive);+ j.set("live", p.mayaLive);std::ofstream f(fsPath(configDir + "maya.json"), std::ios::binary | std::ios::trunc);f << j.dump(true) << "\n";}+uint64_t partUndoRevision(const Document& doc, int i) {+ return i == doc.activePart ? doc.undo.revision() : doc.parts[size_t(i)].undo.revision();+}++// One number for every Part's id and undo revision: it moves with each stroke, undo, new or removed Part.+uint64_t partsKey(const Document& doc) {+ uint64_t h = 1469598103934665603ull ^ uint64_t(doc.partCount());+ for (int i = 0; i < doc.partCount(); ++i) {+ h = (h ^ doc.parts[size_t(i)].id) * 1099511628211ull;+ h = (h ^ partUndoRevision(doc, i)) * 1099511628211ull;+ h = (h ^ uint64_t(doc.parts[size_t(i)].visible)) * 1099511628211ull;+ }+ return h;+}+} // namespace+void App::mayaLiveMarkAll() {+ for (int i = 0; i < doc_.partCount(); ++i) {+ MayaLiveSeen& seen = mayaLiveSeen_[doc_.parts[size_t(i)].id];+ const uint64_t revision = partUndoRevision(doc_, i);+ if (seen.revision != revision) seen = {revision, 0};+ }+ mayaLiveWait_.clear();+}++void App::setMayaLive(bool on) {+ uiPrefs_.mayaLive = on && !uiPrefs_.mayaFolder.empty();+ if (uiPrefs_.mayaLive) {+ // Both ways: what Maya sends loads by itself too (from now on), and what is here now is in sync.+ if (!uiPrefs_.mayaAutoReceive) {+ uiPrefs_.mayaAutoReceive = true;+ const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);+ mayaSeenRevision_ = mayaRevision(inbox);+ mayaManifestStamp_ = mayaManifestStamp(inbox);+ }+ mayaLiveMarkAll();+ status_ = "Maya Live on: the Parts you change go to Maya by themselves after each stroke";+ } else {+ mayaLiveWait_.clear();+ status_ = "Maya Live off: Send to Maya sends";+ }+ if (!uiConfigDeterministic_) saveMayaPrefs(configDir_, uiPrefs_);+}++void App::finishMayaLiveSend() {+ if (!mayaLiveJob_.valid()) return;+ MayaLiveResult r = mayaLiveJob_.get();+ if (!r.ok) {+ status_ = r.message; // the next change tries again+ return;+ }+ for (size_t k = 0; k < r.hashedIds.size(); ++k) {+ MayaLiveSeen& seen = mayaLiveSeen_[r.hashedIds[k]];+ if (seen.revision <= r.revisions[k]) seen = {r.revisions[k], r.hashes[k]}; // (unless a get came since)+ }+ for (size_t k = 0; k < r.ids.size() && k < r.names.size(); ++k)+ for (int i = 0; i < doc_.partCount(); ++i)+ if (doc_.parts[size_t(i)].id == r.ids[k]) partBridgeName(doc_, i) = r.names[k]; // Maya's next send updates it+ if (!r.ids.empty()) {+ status_ = r.message;+ ++mayaLiveSends_;+ }+}++void App::pollMayaLive(Uint64 now) {+ if (mayaLiveJob_.valid() && mayaLiveJob_.wait_for(std::chrono::seconds(0)) == std::future_status::ready)+ finishMayaLiveSend();+ pollMayaLink(now);+ const bool link = mayaLink_ && mayaLink_->connected();+ if (!link && (!uiPrefs_.mayaLive || uiPrefs_.mayaFolder.empty())) return;+ if (const uint64_t key = partsKey(doc_); key != mayaLiveKey_) { // a stroke ended, an undo, a new Part...+ mayaLiveKey_ = key;+ mayaLiveWait_.changed(now);+ }+ const bool busy = doc_.sculptor.strokeActive() || drag_ != Drag::None || mayaLiveJob_.valid();+ // Over the link the stroke's end goes at once (its vertices are on their way already); files wait for 300 ms+ // of stillness, so a quick run of strokes is one send.+ if (link ? !mayaLiveWait_.pending() || busy : !mayaLiveWait_.due(now, busy)) {+ if (mayaLiveWait_.pending()) redrawIn(0.05); // (asleep, the loop wakes every 250 ms only)+ return;+ }+ mayaLiveWait_.clear();+ if (link) {+ for (int i = 0; i < doc_.partCount(); ++i) {+ const Part& part = doc_.parts[size_t(i)];+ const uint64_t revision = partUndoRevision(doc_, i);+ const auto seen = mayaLiveSeen_.find(part.id);+ if (seen != mayaLiveSeen_.end() && seen->second.revision == revision) continue;+ mayaLiveSeen_[part.id] = {revision, 0};+ if (part.visible && doc_.partMesh(i).triangleCount()) sendMayaLinkPart(i);+ }+ return;+ }+ // The visible Parts whose undo revision moved since they were last exchanged: a copy of what the OBJ carries+ // (a few ms for millions of triangles), hashed and written on a worker while sculpting goes on.+ struct Item {+ uint32_t id;+ uint64_t revision, lastHash;+ std::string name;+ Mesh mesh;+ };+ std::vector<Item> items;+ for (int i = 0; i < doc_.partCount() && items.size() < kMayaMaxObjects; ++i) {+ const Part& part = doc_.parts[size_t(i)];+ const uint64_t revision = partUndoRevision(doc_, i);+ const auto seen = mayaLiveSeen_.find(part.id);+ if (seen != mayaLiveSeen_.end() && seen->second.revision == revision) continue;+ if (!part.visible || doc_.partMesh(i).triangleCount() == 0) continue;+ const std::string& bridge = partBridgeName(doc_, i);+ items.push_back({part.id, revision, seen == mayaLiveSeen_.end() ? 0 : seen->second.hash,+ bridge.empty() ? part.name : bridge, mayaSendCopy(doc_.partMesh(i))});+ }+ if (items.empty()) return;+ mayaLiveJob_ = std::async(std::launch::async, [folder = uiPrefs_.mayaFolder, writer = mayaWriter_,+ items = std::move(items)]() {+ MayaLiveResult r;+ std::vector<MeshObjectRef> refs;+ for (const Item& it : items) {+ const uint64_t hash = mayaMeshHash(it.mesh);+ r.hashedIds.push_back(it.id);+ r.revisions.push_back(it.revision);+ r.hashes.push_back(hash);+ if (hash == it.lastHash) continue; // an undo back to what Maya has, a stroke that moved nothing+ refs.push_back({it.name, &it.mesh});+ r.ids.push_back(it.id);+ }+ r.ok = refs.empty() || mayaSend(refs, folder, r.message, &r.names, nullptr, writer, true);+ return r;+ });+}++// ---- The Live link ----++std::string App::mayaLinkName(int i) {+ std::string& bridge = partBridgeName(doc_, i);+ if (!bridge.empty()) return bridge;+ const std::string wanted = mayaSafeName(doc_.parts[size_t(i)].name);+ auto taken = [&](const std::string& n) {+ for (int k = 0; k < doc_.partCount(); ++k)+ if (k != i && partBridgeName(doc_, k) == n) return true;+ return false;+ };+ std::string name = wanted;+ for (int n = 1; taken(name); ++n) name = wanted + std::to_string(n);+ bridge = name; // Maya's sends of it update this Part+ return name;+}++void App::sendMayaLinkPart(int i) {+ const Mesh& mesh = doc_.partMesh(i);+ const uint32_t id = doc_.parts[size_t(i)].id;+ const std::string name = mayaLinkName(i);+ uint64_t topology = 0x5346u;+ for (const glm::uvec3& t : mesh.triangles) topology = (topology ^ (uint64_t(t.x) | uint64_t(t.y) << 21 | uint64_t(t.z) << 42)) * 0x100000001b3ull;+ MayaLinkSent& sent = mayaLinkSent_[id];+ if (sent.topology == topology && sent.positions.size() == mesh.positions.size()) {+ // The same faces: only the vertices that moved (since the last stream or send).+ link::MayaLinkPoints points = link::mayaLinkPointsBetween(name, sent.positions, mesh.positions);+ for (uint32_t v : points.indices) sent.positions[v] = mesh.positions[v];+ mayaLink_->send(std::move(points));+ return;+ }+ mayaLink_->send(link::mayaLinkMeshFrom(name, mesh));+ sent.positions = mesh.positions;+ sent.topology = topology;+}++void App::startMayaLink() {+ std::string error;+ if (!policy::mayaLinkAllowed(&error)) { // (a studio's policy: never listen)+ status_ = error;+ return;+ }+ const std::string endpoint = link::localEndpoint("maya-link", error);+ auto server = std::make_unique<link::MayaLinkServer>();+ if (endpoint.empty() || !server->start(endpoint, error)) {+ status_ = "Maya Live link: can't start: " + error;+ return;+ }+ mayaLink_ = std::move(server);+ mayaLinkSent_.clear();+ status_ = "Maya Live link on: in Maya, click Link on the SculptForge shelf and paste the pairing code "+ "(File > Maya > Copy pairing code)";+}++void App::stopMayaLink() {+ if (!mayaLink_) return;+ mayaLink_->stop();+ mayaLink_.reset();+ mayaLinkSent_.clear();+ status_ = "Maya Live link off";+}++void App::pollMayaLink(Uint64 now) {+ if (!mayaLink_) return;+ for (std::string e = mayaLink_->takeEvent(); !e.empty(); e = mayaLink_->takeEvent()) {+ if (e == "connected") {+ // Maya gets every visible Part whole, so both sides start from the same vertices.+ mayaLinkSent_.clear();+ mayaLiveMarkAll();+ for (int i = 0; i < doc_.partCount(); ++i)+ if (doc_.parts[size_t(i)].visible && doc_.partMesh(i).triangleCount()) sendMayaLinkPart(i);+ status_ = "Maya Live link: connected to " + mayaLink_->clientName();+ } else {+ status_ = "Maya Live link: " + e;+ }+ }+ if (!mayaLink_->connected()) return;+ // What Maya sent: each object updates the Part with its name (an undoable step), unless it is what we have.+ std::vector<MeshObject> objects;+ const bool canApply = !solverBusy() && !doc_.sculptor.strokeActive() && drag_ == Drag::None;+ for (link::MayaLinkMesh& m : canApply ? mayaLink_->takeReceived() : std::vector<link::MayaLinkMesh>{}) {+ MeshObject o;+ std::string error;+ o.name = m.name;+ if (link::mayaLinkMeshTo(m, o.mesh, error)) objects.push_back(std::move(o));+ else status_ = "Maya Live link: " + m.name + ": " + error;+ }+ if (!objects.empty()) {+ mayaDropUnchanged(doc_, objects);+ if (!objects.empty()) {+ std::unordered_map<uint32_t, uint64_t> before;+ for (int i = 0; i < doc_.partCount(); ++i) before[doc_.parts[size_t(i)].id] = partUndoRevision(doc_, i);+ const size_t count = objects.size();+ receiveObjects(doc_, objects, "Live link from Maya", true);+ // The echo guard: what Maya sent is what Maya has.+ for (int i = 0; i < doc_.partCount(); ++i) {+ const uint32_t id = doc_.parts[size_t(i)].id;+ const uint64_t revision = partUndoRevision(doc_, i);+ const auto was = before.find(id);+ if (was != before.end() && was->second == revision) continue;+ mayaLiveSeen_[id] = {revision, 0};+ mayaLinkSent_.erase(id);+ MayaLinkSent& sent = mayaLinkSent_[id];+ sent.positions = doc_.partMesh(i).positions;+ uint64_t topology = 0x5346u;+ for (const glm::uvec3& t : doc_.partMesh(i).triangles)+ topology = (topology ^ (uint64_t(t.x) | uint64_t(t.y) << 21 | uint64_t(t.z) << 42)) * 0x100000001b3ull;+ sent.topology = topology;+ }+ mayaLiveKey_ = partsKey(doc_);+ status_ = "Maya Live link: got " + std::to_string(count) + (count == 1 ? " object" : " objects") + " from Maya";+ }+ }+ // Mid-stroke: the active Part's moved vertices, at most every 100 ms (between the solver's batches).+ if (doc_.sculptor.strokeActive() && now - mayaLinkStreamNs_ >= link::kMayaLinkStreamNs && doc_.activePart >= 0) {+ mayaLinkStreamNs_ = now;+ const auto sent = mayaLinkSent_.find(doc_.activePartInfo().id);+ if (sent != mayaLinkSent_.end() && sent->second.positions.size() == doc_.mesh.positions.size()) {+ link::MayaLinkPoints points =+ link::mayaLinkPointsBetween(mayaLinkName(doc_.activePart), sent->second.positions, doc_.mesh.positions);+ for (uint32_t v : points.indices) sent->second.positions[v] = doc_.mesh.positions[v];+ if (!points.indices.empty()) {+ mayaLink_->send(std::move(points));+ ++mayaLinkStreams_;+ }+ }+ }+ if (doc_.sculptor.strokeActive()) redrawIn(0.1);+}++void App::drawMayaLinkDialog() {+ if (!mayaLinkAsk_) return;+ const float sc = uiScale_;+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos(ImVec2(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f),+ ImGuiCond_Always, ImVec2(0.5f, 0.5f));+ bool turnOn = false, cancel = false;+ if (ImGui::Begin(tr("Turn on the Maya Live link?###mayalinkask"), nullptr,+ ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::PushTextWrapPos(420.0f * sc);+ ImGui::TextWrapped("%s", tr("The Live link lets the SculptForge shelf in Maya follow your strokes as you sculpt."));+ ImGui::Spacing();+ ImGui::TextColored(theme::danger, "%s", tr("It opens a connection on this computer."));+ ImGui::TextWrapped("%s", tr("Anything running on this computer that knows the pairing code could send meshes into "+ "SculptForge. It carries meshes only: never commands, files or scripts. Other "+ "computers and web pages can't reach it."));+ ImGui::Spacing();+ ImGui::TextWrapped("%s", tr("Turn it off when you're not using it: click \"Live link on\" in the top bar. It is "+ "off again every time SculptForge starts."));+ ImGui::PopTextWrapPos();+ ImGui::Spacing();+ turnOn = ImGui::Button(tr("Turn on##mayalink"), ImVec2(140.0f * sc, 0));+ ImGui::SameLine();+ cancel = ImGui::Button(tr("Cancel##mayalink"), ImVec2(140.0f * sc, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape);+ }+ ImGui::End();+ if (turnOn) {+ mayaLinkAsk_ = false;+ startMayaLink();+ } else if (cancel) {+ mayaLinkAsk_ = false;+ status_ = "Maya Live link stays off";+ }+}+void App::setMayaFolder(const std::string& folder) {if (!isFolder(folder)) {status_ = "Not a folder: " + folder;return;}if (uiPrefs_.mayaFolder.empty()) uiPrefs_.mayaAutoReceive = true; // the bridge turns on with Get automatically+ mayaLiveMarkAll(); // (a new folder: Live sends what changes from now on)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);@@ -89,7 +394,12 @@ void App::sendToMaya() {chooseMayaFolder();return;}+ if (mayaLiveJob_.valid()) { // one writer at a time in the outbox+ mayaLiveJob_.wait();+ finishMayaLiveSend();+ }runCommand("maya_send", {{"folder", uiPrefs_.mayaFolder}});+ if (status_.rfind("Sent", 0) == 0) mayaLiveMarkAll(); // Maya has every visible Part as it is now}void App::receiveFromMaya() {@@ -101,8 +411,18 @@ void App::receiveFromMaya() {const std::string inbox = mayaInbox(uiPrefs_.mayaFolder);mayaSeenRevision_ = mayaRevision(inbox); // a manual get counts as seen, so polling doesn't load it againmayaManifestStamp_ = mayaManifestStamp(inbox);+ std::unordered_map<uint32_t, uint64_t> before;+ for (int i = 0; i < doc_.partCount(); ++i) before[doc_.parts[size_t(i)].id] = partUndoRevision(doc_, i);runCommand("maya_receive", {{"folder", uiPrefs_.mayaFolder}});- if (status_.rfind("Received", 0) == 0) camera_.frame(sceneBounds());+ // Echo guard: the Parts the get changed or added hold what Maya has, so Live doesn't send them back.+ for (int i = 0; i < doc_.partCount(); ++i) {+ const uint32_t id = doc_.parts[size_t(i)].id;+ const uint64_t revision = partUndoRevision(doc_, i);+ const auto was = before.find(id);+ if (was == before.end() || was->second != revision) mayaLiveSeen_[id] = {revision, 0};+ }+ // (Live keeps the view: Maya's edits arrive while you look at them.)+ if (status_.rfind("Received", 0) == 0 && !uiPrefs_.mayaLive) camera_.frame(sceneBounds());}void App::drawMayaMenu() {@@ -119,9 +439,35 @@ void App::drawMayaMenu() {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). On once you choose the folder; off: use Get from Maya.",+ "Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest every "+ "250 ms (its modification time and size only). On once you choose the folder; off: use Get from Maya.","File > Maya");+ bool live = uiPrefs_.mayaLive;+ if (ImGui::MenuItem(tr("Live##maya"), nullptr, &live, hasFolder)) setMayaLive(live);+ ui::HelpText("Live", nullptr,+ "Keep Maya in step as you sculpt: after each stroke (once you pause for 300 ms), the Parts it changed "+ "go to the exchange folder by themselves, and what Maya sends loads by itself. Still files only: no "+ "network. Turn on Live on Maya's SculptForge shelf too.",+ "File > Maya");+ ImGui::Separator();+ if (!mayaLink_) {+ if (ImGui::MenuItem(tr("Live link...##maya"), nullptr, false, policy::mayaLinkAllowed())) mayaLinkAsk_ = true;+ ui::HelpText("Live link", nullptr,+ "Maya follows your strokes as you draw them, over a connection on this computer (the shelf's Link "+ "button). Asks first, every time; off again at every start.",+ "File > Maya");+ } else {+ if (mayaLink_->connected())+ ImGui::TextColored(theme::accent, tr("Live link: connected to %s"), mayaLink_->clientName().c_str());+ else+ ImGui::TextColored(theme::accent, "%s", tr("Live link on: waiting for Maya"));+ ImGui::TextDisabled(tr("Pairing code: %s"), link::mayaLinkShowCode(mayaLink_->code()).c_str());+ if (ImGui::MenuItem(tr("Copy pairing code##maya"))) {+ SDL_SetClipboardText(link::mayaLinkPairingText(mayaLink_->code(), mayaLink_->endpoint()).c_str());+ status_ = "Pairing code copied: paste it into Maya (SculptForge shelf > Link)";+ }+ if (ImGui::MenuItem(tr("Turn the Live link off##maya"))) stopMayaLink();+ }ImGui::Separator();menuAction(*this, "file.maya_folder");if (hasFolder) {@@ -129,6 +475,7 @@ void App::drawMayaMenu() {if (ImGui::MenuItem(tr("Turn the Maya bridge off##maya"))) {uiPrefs_.mayaFolder.clear();uiPrefs_.mayaAutoReceive = false;+ uiPrefs_.mayaLive = false;if (!uiConfigDeterministic_) saveMayaPrefs(configDir_, uiPrefs_);status_ = "Maya bridge off: SculptForge no longer reads or writes the exchange folder";}@@ -145,16 +492,20 @@ void App::pollMaya() {if (!mayaInitialised_) {mayaInitialised_ = true;if (!uiConfigDeterministic_) loadMayaPrefs(configDir_, uiPrefs_);+ mayaWriter_ = mayaNewWriterId();if (!uiPrefs_.mayaFolder.empty()) { // what was sent before this start is old newsconst std::string inbox = mayaInbox(uiPrefs_.mayaFolder);mayaSeenRevision_ = mayaRevision(inbox);mayaManifestStamp_ = mayaManifestStamp(inbox);}+ mayaLiveMarkAll();+ mayaLiveKey_ = 0;}- 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;+ pollMayaLive(now);+ if (!uiPrefs_.mayaAutoReceive || uiPrefs_.mayaFolder.empty() || doc_.sculptor.strokeActive()) return;+ // UI tests check every frame (their frames are simulated); the app every 250 ms.+ const Uint64 interval = options_.uiTest.empty() ? kMayaPollNs : 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,@@ -163,8 +514,15 @@ void App::pollMaya() {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();+ MayaManifest m;+ std::string err;+ if (!readMayaManifest(mayaManifestPath(inbox), m, err)) return; // (half written: the next change is checked)+ if (m.revision == mayaSeenRevision_) return;+ if (!m.writer.empty() && m.writer == mayaWriter_) { // never load back what this session wrote+ mayaSeenRevision_ = m.revision;+ return;+ }+ receiveFromMaya();}} // namespace sfdiff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 5e3d01c4..c61c052f 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -1036,6 +1036,9 @@ void App::drawTitleStrip(const ShellGeometry& g) {10.0f * s + 2.0f * windowButtonW + 2.0f * s;if (quickSave) rightW += buttonW(tr("Save Snapshot")) + 8.0f * s;if (maya) rightW += buttonW((std::string(ICON_LC_SEND " ") + tr("Send to Maya")).c_str()) + 8.0f * s;+ const bool mayaLink = mayaLink_ != nullptr; // the Maya Live link is on: its ember chip turns it off+ const std::string linkLabel = std::string(ICON_LC_RADIO " ") + tr("Live link on") + "##mayalink.chip";+ if (mayaLink) rightW += buttonW(linkLabel.c_str()) + 8.0f * s;const float rightX = g.title.w - 8.0f * s - rightW;// Info readout and the status message, elided to fit: secondary, so in the 12 px font.@@ -1104,6 +1107,15 @@ void App::drawTitleStrip(const ShellGeometry& g) {ImGui::PushStyleColor(ImGuiCol_Button, theme::toggleOff);ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::toggleOffHover);ImGui::PushStyleColor(ImGuiCol_Text, theme::textOff);+ if (mayaLink) {+ ImGui::PushStyleColor(ImGuiCol_Button, theme::accent);+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::accentHover);+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.08f, 0.05f, 0.03f, 1.0f));+ if (ImGui::Button(linkLabel.c_str(), ImVec2(0, buttonH))) stopMayaLink();+ ImGui::PopStyleColor(3);+ ui::HelpText("Live link on", nullptr, "Click to turn the Maya Live link off.", "Top bar");+ ImGui::SameLine(0.0f, 8.0f * s);+ }if (maya) {ui::ActionButton(*this, "file.send_maya", ImVec2(0, buttonH), ui::Look::IconLabel);ImGui::SameLine(0.0f, 8.0f * s);@@ -1500,6 +1512,13 @@ void App::drawStatusBar(const ShellGeometry& g) {const float mayaX = right - mayaW;const bool maya = !uiPrefs_.mayaFolder.empty() && mayaX > menusEnd;if (maya) right = mayaX - 10.0f * s;+ // The Maya Live link is on: its ember chip, left of Send to Maya; it turns the link off (always shown while on:+ // the menus give way first).+ const std::string linkLabel = std::string(ICON_LC_RADIO) + " " + (caps ? upper(tr("Live link on")) : std::string(tr("Live link on")));+ const float linkW = textW(monoSmall, linkLabel) + 16.0f * s;+ const float linkX = right - linkW;+ const bool mayaLink = mayaLink_ != nullptr;+ if (mayaLink) right = linkX - 10.0f * s;// Modules: mode, brush, document, triangles, frame rate.std::vector<StatusModule> mods;@@ -1608,6 +1627,16 @@ void App::drawStatusBar(const ShellGeometry& g) {}}+ if (mayaLink) {+ ImGui::SetCursorScreenPos(ImVec2(linkX, o.y + (h - buttonH) * 0.5f));+ const bool clicked = ImGui::InvisibleButton((std::string(tr("Live link on")) + "##mayalink.chip").c_str(), ImVec2(linkW, buttonH));+ const bool hovered = ImGui::IsItemHovered();+ const ImVec2 p = ImGui::GetItemRectMin();+ dl->AddRectFilled(p, ImVec2(p.x + linkW, p.y + buttonH), theme::u32(hovered ? theme::accentHover : theme::accent));+ textAt(monoSmall, p.x + 8.0f * s, ImVec4(0.08f, 0.05f, 0.03f, 1.0f), linkLabel);+ if (clicked) stopMayaLink();+ ui::HelpText("Live link on", nullptr, "Click to turn the Maya Live link off.", "Status bar");+ }if (maya) {ImGui::SetCursorScreenPos(ImVec2(mayaX, o.y + (h - buttonH) * 0.5f));const bool clicked = ImGui::InvisibleButton((std::string(tr("Send to Maya")) + "##file.send_maya").c_str(), ImVec2(mayaW, buttonH));diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 3772ed00..192b42bf 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -633,6 +633,12 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "smooth_remesh") return std::round(app_.doc_.sculptor.dyntopo.smoothRemesh * 100.0f);if (name == "invert_zoom") return app_.uiPrefs_.invertZoom ? 1.0 : 0.0;if (name == "maya_zoom_horizontal") return app_.uiPrefs_.mayaZoomHorizontal ? 1.0 : 0.0;+ if (name == "maya_live") return app_.uiPrefs_.mayaLive ? 1.0 : 0.0;+ if (name == "maya_live_sends") return double(app_.mayaLiveSends_);+ if (name == "maya_get_auto") return app_.uiPrefs_.mayaAutoReceive ? 1.0 : 0.0;+ if (name == "maya_link") return app_.mayaLink_ ? 1.0 : 0.0;+ if (name == "maya_link_connected") return app_.mayaLink_ && app_.mayaLink_->connected() ? 1.0 : 0.0;+ if (name == "maya_link_streams") return double(app_.mayaLinkStreams_);if (name == "wheel_to_pointer") return app_.uiPrefs_.wheelZoomToPointer ? 1.0 : 0.0;if (name == "along_normal") return double(app_.uiPrefs_.alongNormal);if (name == "stroke_along_normal") return app_.strokeAlongNormal_ ? 1.0 : 0.0;diff --git a/src/core/ManagedPolicy.cpp b/src/core/ManagedPolicy.cppindex c7a3ab77..de29ac00 100644--- a/src/core/ManagedPolicy.cpp+++ b/src/core/ManagedPolicy.cpp@@ -118,6 +118,7 @@ Policy failClosed(const std::string& source, const std::string& error) {p.network = Lock::Off;p.mcp = Lock::Off;p.mcpLiveAllowed = false;+ p.mayaLinkAllowed = false;p.updateCheck = Lock::Off;return p;}@@ -141,7 +142,7 @@ const std::vector<std::string>& aiProviderIds() {bool parsePolicy(const std::string& text, const std::string& source, Policy& out, std::string& error) {Json j;if (!Json::parseStrict(text, j, error)) return false;- if (!checkKeys(j, {"format", "version", "organization", "ai", "network", "mcp", "audit", "signIn", "telemetry", "updates"},+ if (!checkKeys(j, {"format", "version", "organization", "ai", "network", "mcp", "maya", "audit", "signIn", "telemetry", "updates"},"", error))return false;if (j["format"].asString() != kPolicyFormat) return (error = "format must be \"sculptforge-policy\"", false);@@ -185,6 +186,15 @@ bool parsePolicy(const std::string& text, const std::string& source, Policy& out}if (p.mcp == Lock::Off) p.mcpLiveAllowed = false;}+ if (j.has("maya")) {+ const Json& m = j["maya"];+ if (!checkKeys(m, {"link"}, "maya", error)) return false;+ if (m.has("link")) {+ const std::string link = m["link"].asString();+ if (link != "never" && link != "allowed") return (error = "maya.link must be \"never\" or \"allowed\"", false);+ p.mayaLinkAllowed = link == "allowed";+ }+ }if (j.has("audit")) {const Json& a = j["audit"];if (!checkKeys(a, {"path", "maxMB", "keep", "required"}, "audit", error)) return false;@@ -337,6 +347,12 @@ bool mcpLiveAllowed(std::string* why) {return false;}+bool mayaLinkAllowed(std::string* why) {+ if (gPolicy.mayaLinkAllowed) return true;+ if (why) *why = "Your studio's policy doesn't allow the Maya Live link";+ return false;+}+std::vector<std::string> mcpCategories(std::string_view name, const std::vector<std::string>& paramNames) {static const char* kNetwork[] = {"brush_gallery_search", "brush_gallery_install", "unreal_editors", "unreal_send","export_unreal"};@@ -397,6 +413,7 @@ std::string describe(const Policy& p) {o << "; network " << (p.network == Lock::Off ? "off (allowed: " + list(p.networkAllow, "nothing") + ")" : "on");o << "; MCP " << (p.mcp == Lock::Off ? "off" : "on (tools: " + list(p.mcpCategories, "all") + "; live mode " +(p.mcpLiveAllowed ? "allowed" : "never") + ")");+ o << "; Maya Live link " << (p.mayaLinkAllowed ? "allowed" : "never");o << "; audit log " << (p.auditPath.empty() ? "default path" : p.auditPath) << (p.auditRequired ? " (required)" : "");if (p.signInConfigured()) o << "; sign-in " << p.issuer;o << "; telemetry none (SculptForge has none)";diff --git a/src/core/ManagedPolicy.h b/src/core/ManagedPolicy.hindex 794fa530..14998f52 100644--- a/src/core/ManagedPolicy.h+++ b/src/core/ManagedPolicy.h@@ -71,6 +71,7 @@ struct Policy {Lock mcp = Lock::Unset; // mcp.enabled: Off = no MCP server (sculptforge-cli --mcp refuses)bool mcpLiveAllowed = true; // mcp.live: "never" | "allowed"+ bool mayaLinkAllowed = true; // maya.link: "never" | "allowed" (the Maya Live link, link/MayaLink.h)std::vector<std::string> mcpCategories; // allowed categories; empty = allstd::string auditPath; // with {user}, {host}, {date} filled in; "" = the default@@ -117,6 +118,7 @@ bool aiProviderAllowed(std::string_view providerId, std::string* why = nullptr);bool aiEndpointAllowed(const std::string& url, std::string* why = nullptr);bool mcpAllowed(std::string* why = nullptr);bool mcpLiveAllowed(std::string* why = nullptr);+bool mayaLinkAllowed(std::string* why = nullptr);// The categories of command NAME (needs the registry's parameter names: a "path", "folder" or "file" parameter is files).std::vector<std::string> mcpCategories(std::string_view name, const std::vector<std::string>& paramNames);bool mcpToolAllowed(std::string_view name, const std::vector<std::string>& paramNames, std::string* why = nullptr);diff --git a/src/io/MayaBridge.cpp b/src/io/MayaBridge.cppindex c01de446..d8258ef8 100644--- a/src/io/MayaBridge.cpp+++ b/src/io/MayaBridge.cpp@@ -10,6 +10,8 @@#include <cctype>#include <cmath>#include <cstdio>+#include <cstring>+#include <random>#include <filesystem>#include <fstream>#include <iterator>@@ -125,8 +127,9 @@ bool parseMayaManifest(const std::string& text, MayaManifest& out, std::string&return true;};if (!optionalString("sender", m.sender) || !optionalString("sender_version", m.senderVersion) ||- !optionalString("unit", m.unit))+ !optionalString("unit", m.unit) || !optionalString("writer", m.writer))return false;+ m.live = j["live"].isBool() && j["live"].asBool();const Json& objects = j["objects"];if (!objects.isArray()) {error = "The Maya bridge manifest lists no objects";@@ -171,6 +174,8 @@ std::string writeMayaManifest(const MayaManifest& m) {s += " \"sender\": " + jsonQuote(m.sender) + ",\n";s += " \"sender_version\": " + jsonQuote(m.senderVersion) + ",\n";if (!m.unit.empty()) s += " \"unit\": " + jsonQuote(m.unit) + ",\n";+ if (!m.writer.empty()) s += " \"writer\": " + jsonQuote(m.writer) + ",\n";+ if (m.live) s += " \"live\": true,\n";s += " \"objects\": [";for (size_t i = 0; i < m.objects.size(); ++i) {s += i ? ",\n {" : "\n {";@@ -268,7 +273,7 @@ bool mayaReceive(const std::string& folder, std::vector<MeshObject>& out, MayaMa}bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& folder, std::string& message,- std::vector<std::string>* sentNames, int64_t* revision) {+ std::vector<std::string>* sentNames, int64_t* revision, const std::string& writer, bool live) {if (folder.empty()) {message = "Choose the Maya exchange folder first (File > Maya > Exchange folder...)";return false;@@ -299,6 +304,8 @@ bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& foldMayaManifest m;m.revision = std::max<int64_t>(mayaRevision(pathUtf8(outbox)), 0) + 1;m.sender = "sculptforge";+ m.writer = writer;+ m.live = live;#ifdef SCULPTFORGE_VERSIONm.senderVersion = SCULPTFORGE_VERSION;#endif@@ -324,14 +331,28 @@ bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& foldMayaObject b{name, prefix + file};std::string err;const Mesh& mesh = *objects[k].mesh;+ // Written as <file>.tmp, then renamed (a reader polling the folder never sees half of it; a leftover+ // .tmp starts with this send's prefix, so the next send removes it).+ const fs::path final = outbox / utf8Path(b.file);+ fs::path tmp = final;+ tmp += ".tmp";bool ok;if (mesh.hasFaceGroups()) {// Face groups would be OBJ groups, which Maya's importer turns into separate objects or sets.Mesh plain = mesh;plain.facegroups.clear();- ok = saveObj(pathUtf8(outbox / utf8Path(b.file)), plain, err);+ ok = saveObj(pathUtf8(tmp), plain, err);} else {- ok = saveObj(pathUtf8(outbox / utf8Path(b.file)), mesh, err);+ ok = saveObj(pathUtf8(tmp), mesh, err);+ }+ if (ok) {+ std::error_code rn;+ fs::rename(tmp, final, rn);+ if (rn) {+ fs::remove(tmp, rn);+ ok = false;+ err = "cannot rename " + pathUtf8(tmp);+ }}if (!ok) {message = "Cannot send \"" + name + "\" to Maya: " + err;@@ -354,7 +375,8 @@ bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& foldfs::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";+ message = live ? "Live: sent " + countText(objects.size()) + " to Maya"+ : "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;@@ -378,4 +400,107 @@ long long mayaManifestStamp(const std::string& box) {return static_cast<long long>(stamp | 1); // never 0 for a file that is there}+std::string mayaNewWriterId() {+ std::random_device rd;+ const unsigned long long v = (static_cast<unsigned long long>(rd()) << 32) ^ rd() ^+ static_cast<unsigned long long>(std::chrono::steady_clock::now().time_since_epoch().count());+ char text[17];+ std::snprintf(text, sizeof text, "%016llx", v);+ return text;+}++namespace {++// 64-bit words through a multiply-rotate mix: a few GB/s, enough for a 2M-triangle Part in a few ms.+template <class T>+void hashArray(uint64_t& h, const std::vector<T>& v) {+ const size_t bytes = v.size() * sizeof(T);+ const unsigned char* p = reinterpret_cast<const unsigned char*>(v.data());+ h = (h ^ bytes) * 0x9E3779B97F4A7C15ull;+ size_t i = 0;+ for (; i + 8 <= bytes; i += 8) {+ uint64_t w;+ std::memcpy(&w, p + i, 8);+ h = ((h ^ w) * 0xFF51AFD7ED558CCDull);+ h ^= h >> 29;+ }+ uint64_t tail = 0;+ if (i < bytes) std::memcpy(&tail, p + i, bytes - i);+ h = (h ^ tail) * 0xC4CEB9FE1A85EC53ull;+}++} // namespace++uint64_t mayaMeshHash(const Mesh& mesh) {+ uint64_t h = 0x5346u; // "SF"+ hashArray(h, mesh.positions);+ hashArray(h, mesh.triangles);+ hashArray(h, mesh.quadPartners);+ hashArray(h, mesh.uvs);+ hashArray(h, mesh.colors);+ return h ^ (h >> 31);+}++Mesh mayaSendCopy(const Mesh& mesh) {+ Mesh m;+ m.positions = mesh.positions;+ m.triangles = mesh.triangles;+ m.uvs = mesh.uvs;+ m.colors = mesh.colors;+ // Quads as the exporter sees them (quadPartnerAt: a pair split between face groups is two triangles), since+ // the copy has no face groups.+ if (mesh.hasQuads()) {+ m.quadPartners.resize(mesh.triangleCount());+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) m.quadPartners[t] = mesh.quadPartnerAt(t);+ }+ return m;+}++namespace {++// The faces an OBJ carries (quads as quads), each starting at its lowest vertex: what survives a round trip+// through another app, which may split a quad along its other diagonal.+std::vector<uint32_t> writtenFaces(const Mesh& m) {+ std::vector<uint32_t> out;+ out.reserve(size_t(m.triangleCount()) * 3);+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {+ glm::uvec4 f;+ const int n = m.exportFace(t, f);+ if (n == 0) continue;+ int first = 0;+ for (int c = 1; c < n; ++c)+ if (f[c] < f[first]) first = c;+ out.push_back(uint32_t(n));+ for (int c = 0; c < n; ++c) out.push_back(f[(first + c) % n]);+ }+ return out;+}++} // namespace++bool mayaMeshesMatch(const Mesh& a, const Mesh& b) {+ if (a.positions.size() != b.positions.size() || a.triangleCount() != b.triangleCount() || a.uvs.size() != b.uvs.size())+ return false;+ const bool sameTriangles = a.triangles == b.triangles;+ if (!sameTriangles && writtenFaces(a) != writtenFaces(b)) return false;+ // OBJ text rounds (7 significant digits from SculptForge, Maya's own from Maya): allow a millionth of each+ // coordinate and a hundred-thousandth of the mesh's size, far below anything a stroke does.+ glm::vec3 lo(0.0f), hi(0.0f);+ if (!a.positions.empty()) lo = hi = a.positions[0];+ for (const glm::vec3& p : a.positions) {+ lo = glm::min(lo, p);+ hi = glm::max(hi, p);+ }+ const float size = std::max({hi.x - lo.x, hi.y - lo.y, hi.z - lo.z, 1e-6f});+ for (size_t i = 0; i < a.positions.size(); ++i) {+ const glm::vec3 d = glm::abs(a.positions[i] - b.positions[i]);+ const float tol = 1e-5f * size + 1e-6f * std::max({std::abs(a.positions[i].x), std::abs(a.positions[i].y),+ std::abs(a.positions[i].z)});+ if (d.x > tol || d.y > tol || d.z > tol) return false;+ }+ for (size_t i = 0; sameTriangles && i < a.uvs.size(); ++i) // (other triangles: their corners' UVs differ in order)+ if (glm::any(glm::greaterThan(glm::abs(a.uvs[i] - b.uvs[i]), glm::vec2(1e-6f)))) return false;+ return true;+}+} // namespace sfdiff --git a/src/io/MayaBridge.h b/src/io/MayaBridge.hindex 2d291197..067cf24c 100644--- a/src/io/MayaBridge.h+++ b/src/io/MayaBridge.h@@ -15,6 +15,11 @@// 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.+//+// Live (opt-in on both sides): each side sends its changed objects by itself once it has been still for+// kMayaLiveIdleNs, still through files only. The manifest's "writer" (a random id per app session) and each+// side's own state keep an app from loading back what it just wrote; mayaMeshesMatch() drops an object that+// comes back unchanged, so an echo never becomes an undo step, let alone a loop.#pragma once#include "io/MeshObject.h"@@ -30,6 +35,8 @@ 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+inline constexpr unsigned long long kMayaLiveIdleNs = 300'000'000ull; // Live sends once the scene is this still+inline constexpr unsigned long long kMayaPollNs = 250'000'000ull; // the manifest's cheap check, this oftenstruct MayaObject {std::string name; // the Maya transform's short name (Maya characters only): the Part's bridgeName@@ -41,6 +48,8 @@ struct MayaManifest {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::string writer; // the sending app session's id (optional: "" from older versions)+ bool live = false; // sent by Live (informational)std::vector<MayaObject> objects;};@@ -65,8 +74,32 @@ bool mayaReceive(const std::string& folder, std::vector<MeshObject>& out, MayaMastd::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.+// `writer` and `live` go into the manifest. Each OBJ is written to a temporary name and renamed, then the+// manifest likewise: a reader never sees half a file.bool mayaSend(const std::vector<MeshObjectRef>& objects, const std::string& folder, std::string& message,- std::vector<std::string>* sentNames = nullptr, int64_t* revision = nullptr);+ std::vector<std::string>* sentNames = nullptr, int64_t* revision = nullptr,+ const std::string& writer = "", bool live = false);++// A new random writer id (16 hex digits) for this app session.+std::string mayaNewWriterId();+// A hash of what an OBJ send carries (positions, triangles, quads, UVs): Live skips Parts whose hash is unchanged.+uint64_t mayaMeshHash(const Mesh& mesh);+// Only what an OBJ send writes (positions, triangles, quads, UVs, vertex paint), so Live can write it off the+// main thread while sculpting goes on.+Mesh mayaSendCopy(const Mesh& mesh);+// The same faces and UVs, and every position within OBJ's 7 significant digits: what came back is what went out.+bool mayaMeshesMatch(const Mesh& a, const Mesh& b);++// Live's wait: changed() at every edit, due() once nothing changed for kMayaLiveIdleNs and no stroke is on.+struct MayaLiveDebounce {+ unsigned long long since = 0; // the last change (ns); 0 = nothing waits+ void changed(unsigned long long now) { since = now ? now : 1; }+ bool pending() const { return since != 0; }+ bool due(unsigned long long now, bool stroking) const {+ return since != 0 && !stroking && now >= since && now - since >= kMayaLiveIdleNs;+ }+ void clear() { since = 0; }+};// 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);diff --git a/src/io/MayaCommands.cpp b/src/io/MayaCommands.cppindex c5e1bb8a..4767e5df 100644--- a/src/io/MayaCommands.cpp+++ b/src/io/MayaCommands.cpp@@ -7,6 +7,16 @@namespace sf {+size_t mayaDropUnchanged(const Document& doc, std::vector<MeshObject>& objects) {+ return std::erase_if(objects, [&](const MeshObject& o) {+ for (int i = 0; i < doc.partCount(); ++i) {+ const std::string& bridge = i == doc.activePart ? doc.bridgeName : doc.parts[size_t(i)].bridgeName;+ if (bridge == o.name) return mayaMeshesMatch(doc.partMesh(i), o.mesh);+ }+ return false;+ });+}+void registerMayaCommands(CommandRegistry& reg) {using T = ParamSpec::Type;@@ -29,12 +39,17 @@ void registerMayaCommands(CommandRegistry& reg) {reg.add({"maya_receive","Load what Maya last sent with the SculptForge shelf script. Each object replaces the Part with its ""name (an undoable step on that Part) or becomes a new Part; the first object replaces a fresh "- "scene.",+ "scene. Objects that match their Part already (sent back unchanged) are skipped.",{{"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};+ // What comes back as it went out (Live's echo, or a send of untouched objects) is no new step.+ const size_t received = objects.size();+ mayaDropUnchanged(doc, objects);+ if (objects.empty()) return {true, "Maya sent " + std::string(received == 1 ? "it" : "them") ++ " back unchanged: nothing to update"};receiveObjects(doc, objects, "Get from Maya", true);return {true, msg};}});diff --git a/src/io/MayaCommands.h b/src/io/MayaCommands.hindex 1c43b868..ceb2dd06 100644--- a/src/io/MayaCommands.h+++ b/src/io/MayaCommands.h@@ -7,9 +7,16 @@#pragma once#include "core/Commands.h"+#include "io/MeshObject.h"++#include <vector>namespace sf {void registerMayaCommands(CommandRegistry& registry);+// Drops the objects whose Part (by Bridge name) already has that mesh (mayaMeshesMatch: an echo, or a send of+// untouched objects). Returns how many were dropped.+size_t mayaDropUnchanged(const Document& doc, std::vector<MeshObject>& objects);+} // namespace sfdiff --git a/src/link/AiLink.cpp b/src/link/AiLink.cppindex f68d08c3..1a1a1b23 100644--- a/src/link/AiLink.cpp+++ b/src/link/AiLink.cpp@@ -174,10 +174,12 @@ HANDLE createInstance(const std::string& endpoint, bool first) {} // namespace-std::string aiLinkEndpoint(std::string& error) {+std::string aiLinkEndpoint(std::string& error) { return localEndpoint("ai-live", error); }++std::string localEndpoint(const std::string& endpointName, std::string& error) {#if defined(_WIN32)(void)error;- std::string name = "\\\\.\\pipe\\sculptforge-ai-live-" + userName();+ std::string name = "\\\\.\\pipe\\sculptforge-" + endpointName + "-" + userName();if (const char* own = std::getenv("SF_AI_LIVE_DIR"); own && *own) // tests and isolated runs (app/main.cpp)name += "-" + std::to_string(std::hash<std::string>{}(own) % 1000000007u);return name;@@ -195,11 +197,11 @@ std::string aiLinkEndpoint(std::string& error) {}// A Unix socket path must fit sun_path (104 bytes on macOS, whose $TMPDIR and test folders are long): then a// short owner-only folder in /tmp, one per original folder so isolated runs never share the user's socket.- if (dir.size() + sizeof("/ai-live.sock") > sizeof(sockaddr_un{}.sun_path))+ if (dir.size() + endpointName.size() + sizeof("/.sock") > sizeof(sockaddr_un{}.sun_path))dir = "/tmp/sf-live-" + std::to_string(::getuid()) + "-" +std::to_string(std::hash<std::string>{}(dir) % 1000000007u);if (!safeDir(dir, error)) return {};- return dir + "/ai-live.sock";+ return dir + "/" + endpointName + ".sock";#endif}@@ -274,6 +276,20 @@ int AiLinkConn::readLine(std::string& line, int timeoutMs, size_t maxLine) {}if (handle_ == kInvalid) return -1;char chunk[16384];+ const long long got = readChunk(chunk, sizeof chunk, remainingMs(deadline));+ if (got == 0) {+ if (remainingMs(deadline) == 0) return 0;+ continue;+ }+ if (got < 0) return -1;+ buffer_.append(chunk, size_t(got));+ }+}++long long AiLinkConn::readChunk(char* chunk, size_t size, int timeoutMs) {+ const auto deadline = Clock::now() + std::chrono::milliseconds(timeoutMs);+ for (;;) {+ if (handle_ == kInvalid) return -1;long long got = 0;#if defined(_WIN32)DWORD avail = 0;@@ -283,13 +299,13 @@ int AiLinkConn::readLine(std::string& line, int timeoutMs, size_t maxLine) {}if (avail == 0) {if (remainingMs(deadline) == 0) return 0;- Sleep(5);+ Sleep(2);continue;}OVERLAPPED ov{};ov.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);DWORD n = 0;- BOOL ok = ReadFile(asHandle(handle_), chunk, DWORD(std::min<size_t>(sizeof chunk, avail)), &n, &ov);+ BOOL ok = ReadFile(asHandle(handle_), chunk, DWORD(std::min<size_t>(size, avail)), &n, &ov);if (!ok && GetLastError() == ERROR_IO_PENDING) ok = GetOverlappedResult(asHandle(handle_), &ov, &n, TRUE);CloseHandle(ov.hEvent);if (!ok || n == 0) {@@ -306,35 +322,50 @@ int AiLinkConn::readLine(std::string& line, int timeoutMs, size_t maxLine) {close();return -1;}- got = ::recv(int(handle_), chunk, sizeof chunk, 0);+ got = ::recv(int(handle_), chunk, size, 0);if (got <= 0) {if (got < 0 && (errno == EINTR || errno == EAGAIN)) continue;close();return -1;}#endif- buffer_.append(chunk, size_t(got));+ return got;+ }+}++long long AiLinkConn::readBytes(char* buffer, size_t size, int timeoutMs) {+ if (!buffer_.empty()) { // (what a readLine read past its line)+ const size_t n = std::min(size, buffer_.size());+ std::memcpy(buffer, buffer_.data(), n);+ buffer_.erase(0, n);+ return (long long)n;}+ return readChunk(buffer, size, timeoutMs);}bool AiLinkConn::writeLine(const std::string& line) {if (handle_ == kInvalid || line.find('\n') != std::string::npos) return false;const std::string data = line + "\n";+ return writeAll(data.data(), data.size());+}++bool AiLinkConn::writeAll(const char* data, size_t size) {+ if (handle_ == kInvalid) return false;size_t sent = 0;- while (sent < data.size()) {+ while (sent < size) {#if defined(_WIN32)OVERLAPPED ov{};ov.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);DWORD n = 0;- BOOL ok = WriteFile(asHandle(handle_), data.data() + sent, DWORD(std::min<size_t>(data.size() - sent, 1 << 20)), &n, &ov);+ BOOL ok = WriteFile(asHandle(handle_), data + sent, DWORD(std::min<size_t>(size - sent, 1 << 20)), &n, &ov);if (!ok && GetLastError() == ERROR_IO_PENDING) ok = GetOverlappedResult(asHandle(handle_), &ov, &n, TRUE);CloseHandle(ov.hEvent);if (!ok) return false;#else#if defined(MSG_NOSIGNAL)- const ssize_t n = ::send(int(handle_), data.data() + sent, data.size() - sent, MSG_NOSIGNAL);+ const ssize_t n = ::send(int(handle_), data + sent, size - sent, MSG_NOSIGNAL);#else- const ssize_t n = ::send(int(handle_), data.data() + sent, data.size() - sent, 0);+ const ssize_t n = ::send(int(handle_), data + sent, size - sent, 0);#endifif (n < 0 && errno == EINTR) continue;if (n <= 0) return false;diff --git a/src/link/AiLink.h b/src/link/AiLink.hindex 739f7e25..051c6744 100644--- a/src/link/AiLink.h+++ b/src/link/AiLink.h@@ -24,6 +24,9 @@ inline constexpr size_t kAiLinkMaxReplyLine = 64u << 20; // app -> client (view// The endpoint this user's app listens on ("" with `error` set when the folder can't be made safe).std::string aiLinkEndpoint(std::string& error);+// The same kind of endpoint under another name: "<folder>/<name>.sock", or \\.\pipe\sculptforge-<name>-<user>+// (the Maya link, link/MayaLink.h: "maya-link").+std::string localEndpoint(const std::string& name, std::string& error);// One connection: a socket (POSIX) or pipe handle (Windows).class AiLinkConn {@@ -39,6 +42,10 @@ public:// than `maxLine` (the connection is then closed).int readLine(std::string& line, int timeoutMs, size_t maxLine = kAiLinkMaxLine);bool writeLine(const std::string& line);+ // Binary use (the Maya link): up to `size` bytes, waiting at most `timeoutMs` for the first: the count, 0 on+ // timeout, -1 when closed. writeAll sends every byte (false: the peer is gone).+ long long readBytes(char* buffer, size_t size, int timeoutMs);+ bool writeAll(const char* data, size_t size);bool valid() const { return handle_ != kInvalid; }void close();// Unblocks a readLine waiting on another thread (the connection is closed afterwards by its owner).@@ -49,6 +56,7 @@ public:bool server_ = false; // Windows: the app's end of the pipe (disconnect before closing)private:+ long long readChunk(char* chunk, size_t size, int timeoutMs); // one read from the handle (no buffer_)std::string buffer_;};diff --git a/src/link/MayaLink.cpp b/src/link/MayaLink.cppnew file mode 100644index 00000000..a58abc39--- /dev/null+++ b/src/link/MayaLink.cpp@@ -0,0 +1,587 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "link/MayaLink.h"++#include "io/MayaBridge.h"+#include "io/TextureExport.h"++#include <algorithm>+#include <chrono>+#include <cctype>+#include <cmath>+#include <cstring>+#include <random>++namespace sf::link {++namespace {++// Little-endian writing and strict reading.+void putU16(std::string& s, uint16_t v) {+ s += char(v & 0xff);+ s += char(v >> 8);+}+void putU32(std::string& s, uint32_t v) {+ for (int i = 0; i < 4; ++i) s += char((v >> (8 * i)) & 0xff);+}+void putU64(std::string& s, uint64_t v) {+ for (int i = 0; i < 8; ++i) s += char((v >> (8 * i)) & 0xff);+}+template <class T>+void putArray(std::string& s, const std::vector<T>& v) { // (little-endian hosts: every platform we build for)+ s.append(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(T));+}++struct Reader {+ const std::string& s;+ size_t at = 0;+ bool ok = true;+ bool need(size_t n) {+ if (!ok || s.size() - at < n) ok = false;+ return ok;+ }+ uint16_t u16() {+ if (!need(2)) return 0;+ const auto* p = reinterpret_cast<const unsigned char*>(s.data() + at);+ at += 2;+ return uint16_t(p[0] | p[1] << 8);+ }+ uint32_t u32() {+ if (!need(4)) return 0;+ const auto* p = reinterpret_cast<const unsigned char*>(s.data() + at);+ at += 4;+ return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;+ }+ uint8_t u8() {+ if (!need(1)) return 0;+ return uint8_t(s[at++]);+ }+ std::string bytes(size_t n) {+ if (!need(n)) return {};+ std::string out = s.substr(at, n);+ at += n;+ return out;+ }+ template <class T>+ bool array(std::vector<T>& v, uint64_t count) {+ if (count > (s.size() - std::min(at, s.size())) / sizeof(T) || !need(size_t(count) * sizeof(T))) return ok = false;+ v.resize(size_t(count));+ if (count) std::memcpy(v.data(), s.data() + at, size_t(count) * sizeof(T));+ at += size_t(count) * sizeof(T);+ return true;+ }+ bool done() const { return ok && at == s.size(); }+};++// A Maya name as the shelf sends it: 1..kMayaMaxNameBytes of letters, digits and '_', not starting with a digit.+bool nameOk(const std::string& n) { return !n.empty() && n.size() <= kMayaMaxNameBytes && mayaSafeName(n) == n; }++bool finite(const std::vector<float>& v) {+ return std::all_of(v.begin(), v.end(), [](float f) { return std::isfinite(f); });+}++std::string readName(Reader& r, std::string& error) {+ const uint16_t n = r.u16();+ std::string name = r.bytes(n);+ if (!r.ok || !nameOk(name)) {+ error = "a bad object name";+ return {};+ }+ return name;+}++} // namespace++std::string mayaLinkNewCode() {+ std::random_device rd; // (the OS's random source)+ std::string code;+ static const char* const kHex = "0123456789abcdef";+ for (size_t i = 0; i < kMayaLinkCodeChars / 8; ++i) {+ const uint32_t v = rd();+ for (int k = 0; k < 8; ++k) code += kHex[(v >> (4 * k)) & 15];+ }+ return code;+}++std::string mayaLinkShowCode(const std::string& code) {+ std::string out;+ for (size_t i = 0; i < code.size(); ++i) {+ if (i && i % 8 == 0) out += '-';+ out += char(std::toupper(static_cast<unsigned char>(code[i])));+ }+ return out;+}++std::string mayaLinkPairingText(const std::string& code, const std::string& endpoint) {+ return "sflink1 " + mayaLinkShowCode(code) + " " + endpoint;+}++bool mayaLinkCodeMatches(const std::string& sent, const std::string& code) {+ std::string s;+ for (unsigned char c : sent)+ if (c != '-' && s.size() <= kMayaLinkCodeChars) s += char(std::tolower(c));+ unsigned diff = s.size() == code.size() && code.size() == kMayaLinkCodeChars ? 0u : 1u;+ for (size_t i = 0; i < kMayaLinkCodeChars; ++i)+ diff |= unsigned(i < s.size() ? s[i] : 0) ^ unsigned(i < code.size() ? code[i] : 1);+ return diff == 0;+}++std::string mayaLinkFrame(MayaLinkType type, const std::string& payload) {+ std::string f = "SFML";+ putU16(f, kMayaLinkVersion);+ putU16(f, uint16_t(type));+ putU64(f, payload.size());+ return f + payload;+}++bool parseMayaLinkHeader(const char* header, MayaLinkType& type, uint64_t& length, std::string& error) {+ const std::string h(header, kMayaLinkHeaderBytes);+ if (h.compare(0, 4, "SFML") != 0) {+ error = "not the Maya link";+ return false;+ }+ Reader r{h, 4};+ const uint16_t version = r.u16();+ const uint16_t t = r.u16();+ uint64_t n = 0;+ for (int i = 0; i < 8; ++i) n |= uint64_t(uint8_t(h[8 + size_t(i)])) << (8 * i);+ if (version != kMayaLinkVersion) {+ error = "link version " + std::to_string(version) + " (this SculptForge speaks " + std::to_string(kMayaLinkVersion) ++ "): update the shelf script or SculptForge";+ return false;+ }+ if (t < uint16_t(MayaLinkType::Hello) || t > uint16_t(MayaLinkType::Bye)) {+ error = "an unknown message";+ return false;+ }+ if (n > kMayaLinkMaxPayload) {+ error = "a message over the size cap";+ return false;+ }+ type = MayaLinkType(t);+ length = n;+ return true;+}++std::string encodeMayaLinkHello(const std::string& code, const std::string& client) {+ std::string p; // the code as SculptForge shows it or bare: no dashes, lower case+ for (unsigned char c : code)+ if (c != '-' && p.size() < kMayaLinkCodeChars) p += char(std::tolower(c));+ p.resize(kMayaLinkCodeChars, '0');+ const std::string c = client.substr(0, 64);+ putU16(p, uint16_t(c.size()));+ return mayaLinkFrame(MayaLinkType::Hello, p + c);+}++bool parseMayaLinkHello(const std::string& payload, std::string& code, std::string& client, std::string& error) {+ Reader r{payload};+ code = r.bytes(kMayaLinkCodeChars);+ const uint16_t n = r.u16();+ if (n > 64) r.ok = false;+ client = r.bytes(n);+ if (!r.done()) {+ error = "a bad hello";+ return false;+ }+ for (char& c : client)+ if (static_cast<unsigned char>(c) < 32 || static_cast<unsigned char>(c) > 126) c = '?';+ return true;+}++std::string encodeMayaLinkWelcome(const std::string& version) {+ std::string p;+ const std::string v = version.substr(0, 64);+ putU16(p, uint16_t(v.size()));+ return mayaLinkFrame(MayaLinkType::Welcome, p + v);+}++std::string encodeMayaLinkMesh(const MayaLinkMesh& m) {+ std::string p;+ p.reserve(32 + m.name.size() + m.positions.size() * 4 + m.faceSizes.size() + m.indices.size() * 4 + m.uvs.size() * 4);+ putU16(p, uint16_t(m.name.size()));+ p += m.name;+ putU32(p, uint32_t(m.positions.size() / 3));+ putU32(p, uint32_t(m.faceSizes.size()));+ putU32(p, uint32_t(m.indices.size()));+ p += char(m.uvs.empty() ? 0 : 1);+ putArray(p, m.positions);+ putArray(p, m.faceSizes);+ putArray(p, m.indices);+ putArray(p, m.uvs);+ return mayaLinkFrame(MayaLinkType::Mesh, p);+}++bool parseMayaLinkMesh(const std::string& payload, MayaLinkMesh& out, std::string& error) {+ Reader r{payload};+ MayaLinkMesh m;+ m.name = readName(r, error);+ if (m.name.empty()) return false;+ const uint32_t v = r.u32(), f = r.u32(), c = r.u32();+ const uint8_t flags = r.u8();+ if (!r.ok || v == 0 || v > kMayaLinkMaxVertices || f == 0 || c < 3ull * f || c > 255ull * f || flags > 1) {+ error = "a mesh with bad counts";+ return false;+ }+ if (!r.array(m.positions, 3ull * v) || !r.array(m.faceSizes, f) || !r.array(m.indices, c) ||+ (flags && !r.array(m.uvs, 2ull * c)) || !r.done()) {+ error = "a mesh whose size doesn't add up";+ return false;+ }+ uint64_t corners = 0;+ for (uint8_t n : m.faceSizes) {+ if (n < 3) {+ error = "a mesh with a face of fewer than 3 corners";+ return false;+ }+ corners += n;+ }+ if (corners != c) {+ error = "a mesh whose faces don't add up";+ return false;+ }+ if (std::any_of(m.indices.begin(), m.indices.end(), [v](uint32_t i) { return i >= v; })) {+ error = "a mesh with a vertex index out of range";+ return false;+ }+ if (!finite(m.positions) || !finite(m.uvs)) {+ error = "a mesh with a number that isn't finite";+ return false;+ }+ out = std::move(m);+ return true;+}++std::string encodeMayaLinkPoints(const MayaLinkPoints& pts) {+ std::string p;+ putU16(p, uint16_t(pts.name.size()));+ p += pts.name;+ putU32(p, pts.vertexCount);+ putU32(p, uint32_t(pts.indices.size()));+ putArray(p, pts.indices);+ putArray(p, pts.positions);+ return mayaLinkFrame(MayaLinkType::Points, p);+}++bool parseMayaLinkPoints(const std::string& payload, MayaLinkPoints& out, std::string& error) {+ Reader r{payload};+ MayaLinkPoints p;+ p.name = readName(r, error);+ if (p.name.empty()) return false;+ p.vertexCount = r.u32();+ const uint32_t n = r.u32();+ if (!r.ok || p.vertexCount == 0 || p.vertexCount > kMayaLinkMaxVertices || n > p.vertexCount ||+ !r.array(p.indices, n) || !r.array(p.positions, 3ull * n) || !r.done()) {+ error = "points whose size doesn't add up";+ return false;+ }+ if (std::any_of(p.indices.begin(), p.indices.end(), [&](uint32_t i) { return i >= p.vertexCount; }) ||+ !finite(p.positions)) {+ error = "points out of range";+ return false;+ }+ out = std::move(p);+ return true;+}++MayaLinkMesh mayaLinkMeshFrom(const std::string& name, const Mesh& mesh) {+ MayaLinkMesh m;+ m.name = mayaSafeName(name);+ m.positions.resize(mesh.positions.size() * 3);+ std::memcpy(m.positions.data(), mesh.positions.data(), m.positions.size() * sizeof(float));+ const bool uvs = hasCornerUvs(mesh);+ m.faceSizes.reserve(mesh.triangleCount());+ m.indices.reserve(size_t(mesh.triangleCount()) * 3);+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {+ glm::uvec4 f;+ glm::vec2 uv[4];+ const int corners = exportFaceUv(mesh, t, f, uv);+ if (corners == 0) continue;+ m.faceSizes.push_back(uint8_t(corners));+ for (int c = 0; c < corners; ++c) {+ m.indices.push_back(f[c]);+ if (uvs) {+ m.uvs.push_back(uv[c].x);+ m.uvs.push_back(uv[c].y);+ }+ }+ }+ return m;+}++bool mayaLinkMeshTo(const MayaLinkMesh& in, Mesh& out, std::string& error) {+ Mesh m;+ m.positions.resize(in.positions.size() / 3);+ std::memcpy(m.positions.data(), in.positions.data(), m.positions.size() * sizeof(glm::vec3));+ const bool uvs = !in.uvs.empty();+ std::vector<std::pair<uint32_t, uint32_t>> quads;+ size_t at = 0;+ for (uint8_t n : in.faceSizes) {+ for (uint8_t k = 1; k + 1 < n; ++k) { // a fan: (0, k, k+1)+ const size_t c[3] = {at, at + k, at + k + 1u};+ m.triangles.push_back({in.indices[c[0]], in.indices[c[1]], in.indices[c[2]]});+ if (uvs)+ for (size_t i : c) m.uvs.push_back({in.uvs[2 * i], in.uvs[2 * i + 1]});+ }+ if (n == 4) quads.push_back({uint32_t(m.triangles.size() - 2), uint32_t(m.triangles.size() - 1)});+ at += n;+ }+ // Degenerate triangles (a corner twice) can't be sculpted: dropped, as the OBJ reader does.+ if (m.triangles.empty()) {+ error = "the mesh has no faces";+ return false;+ }+ for (const auto& [a, b] : quads) m.pairQuad(a, b);+ if (m.hasQuads()) m.quadPartners.resize(m.triangles.size(), Mesh::kNoQuad);+ m.rebuildTopology();+ m.recomputeAllNormals();+ out = std::move(m);+ return true;+}++MayaLinkPoints mayaLinkPointsBetween(const std::string& name, const std::vector<glm::vec3>& before,+ const std::vector<glm::vec3>& now) {+ MayaLinkPoints p;+ p.name = mayaSafeName(name);+ p.vertexCount = uint32_t(now.size());+ if (before.size() != now.size()) return p;+ for (uint32_t i = 0; i < now.size(); ++i) {+ if (before[i] == now[i]) continue;+ p.indices.push_back(i);+ p.positions.insert(p.positions.end(), {now[i].x, now[i].y, now[i].z});+ }+ return p;+}++// ---------------------------------------------------------------------------+// MayaLinkServer+// ---------------------------------------------------------------------------++bool MayaLinkServer::start(const std::string& endpoint, std::string& error) {+ stop();+ if (!listener_.open(endpoint, error)) {+ if (error.find("another SculptForge") != std::string::npos)+ error = "another SculptForge window has the Maya Live link on";+ return false;+ }+ code_ = mayaLinkNewCode();+ endpoint_ = endpoint;+ refused_ = 0;+ stopping_ = false;+ running_ = true;+ thread_ = std::thread([this] { run(); });+ return true;+}++void MayaLinkServer::stop() {+ if (!running_ && !thread_.joinable()) return;+ stopping_ = true;+ if (thread_.joinable()) thread_.join();+ listener_.close();+ running_ = connected_ = false;+ std::lock_guard<std::mutex> lock(mutex_);+ outbox_.clear();+ inbox_.clear();+ client_.clear();+ code_.clear();+}++std::string MayaLinkServer::clientName() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return client_;+}++void MayaLinkServer::event(std::string text) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (events_.size() < 16) events_.push_back(std::move(text));+}++std::string MayaLinkServer::takeEvent() {+ std::lock_guard<std::mutex> lock(mutex_);+ if (events_.empty()) return {};+ std::string e = std::move(events_.front());+ events_.pop_front();+ return e;+}++void MayaLinkServer::send(MayaLinkMesh mesh) {+ if (!connected_) return;+ std::lock_guard<std::mutex> lock(mutex_);+ std::erase_if(outbox_, [&](const Outgoing& o) { return o.isMesh ? o.mesh.name == mesh.name : o.points.name == mesh.name; });+ outbox_.push_back({true, std::move(mesh), {}});+}++void MayaLinkServer::send(MayaLinkPoints points) {+ if (!connected_ || points.indices.empty()) return;+ std::lock_guard<std::mutex> lock(mutex_);+ for (auto it = outbox_.rbegin(); it != outbox_.rend(); ++it) {+ if (it->isMesh ? it->mesh.name != points.name : it->points.name != points.name) continue;+ if (!it->isMesh && it->points.vertexCount == points.vertexCount) {+ mergeMayaLinkPoints(it->points, points);+ return;+ }+ break; // a Mesh (or another vertex count) queued last: these Points go after it+ }+ outbox_.push_back({false, {}, std::move(points)});+}++void mergeMayaLinkPoints(MayaLinkPoints& into, const MayaLinkPoints& later) {+ std::vector<uint32_t> slot(into.vertexCount, ~0u); // (vertexCount is capped: kMayaLinkMaxVertices)+ for (uint32_t k = 0; k < into.indices.size(); ++k) slot[into.indices[k]] = k;+ for (size_t k = 0; k < later.indices.size(); ++k) {+ const uint32_t v = later.indices[k];+ if (v >= into.vertexCount) continue;+ if (slot[v] == ~0u) {+ slot[v] = uint32_t(into.indices.size());+ into.indices.push_back(v);+ into.positions.insert(into.positions.end(), {0.0f, 0.0f, 0.0f});+ }+ std::memcpy(&into.positions[size_t(slot[v]) * 3], &later.positions[k * 3], 3 * sizeof(float));+ }+}++std::vector<MayaLinkMesh> MayaLinkServer::takeReceived() {+ std::lock_guard<std::mutex> lock(mutex_);+ return std::move(inbox_);+}++bool MayaLinkServer::readFrame(AiLinkConn& conn, MayaLinkType& type, std::string& payload, int firstByteMs,+ std::string& error) {+ char header[kMayaLinkHeaderBytes];+ size_t got = 0;+ int wait = firstByteMs;+ while (got < sizeof header) {+ const long long n = conn.readBytes(header + got, sizeof header - got, wait);+ if (n < 0) {+ error = "closed";+ return false;+ }+ if (n == 0) {+ if (got == 0) {+ error.clear(); // nothing came: not an error+ return false;+ }+ error = "timed out";+ return false;+ }+ got += size_t(n);+ wait = kMayaLinkFrameMs;+ if (stopping_) return false;+ }+ uint64_t length = 0;+ if (!parseMayaLinkHeader(header, type, length, error)) return false;+ payload.assign(size_t(length), '\0');+ for (size_t at = 0; at < payload.size();) {+ const long long n = conn.readBytes(payload.data() + at, payload.size() - at, kMayaLinkFrameMs);+ if (n <= 0) {+ error = n < 0 ? "closed" : "timed out";+ return false;+ }+ at += size_t(n);+ if (stopping_) return false;+ }+ return true;+}++bool MayaLinkServer::flush(AiLinkConn& conn) {+ for (;;) {+ Outgoing o;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (outbox_.empty()) return true;+ o = std::move(outbox_.front());+ outbox_.pop_front();+ }+ const std::string frame = o.isMesh ? encodeMayaLinkMesh(o.mesh) : encodeMayaLinkPoints(o.points);+ if (!conn.writeAll(frame.data(), frame.size())) return false;+ }+}++bool MayaLinkServer::serve(AiLinkConn& conn) {+ std::string error, payload;+ MayaLinkType type{};+ // Pairing first: a Hello with the code within kMayaLinkHelloMs, or the connection closes.+ if (!readFrame(conn, type, payload, kMayaLinkHelloMs, error) || type != MayaLinkType::Hello) {+ if (error == "closed") return false; // (a probe: another window checking whether the link is on)+ ++refused_;+ event("refused: " + std::string(error.empty() ? "no pairing code" : error));+ return false;+ }+ std::string code, client;+ if (!parseMayaLinkHello(payload, code, client, error) || !mayaLinkCodeMatches(code, code_)) {+ ++refused_;+ event("refused: wrong pairing code");+ return false;+ }+#ifdef SCULPTFORGE_VERSION+ const std::string version = SCULPTFORGE_VERSION;+#else+ const std::string version = "dev";+#endif+ const std::string welcome = encodeMayaLinkWelcome(version);+ if (!conn.writeAll(welcome.data(), welcome.size())) return false;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ client_ = client.empty() ? "Maya" : client;+ outbox_.clear();+ }+ connected_ = true;+ event("connected");+ while (!stopping_) {+ if (!flush(conn)) {+ error = "closed";+ break;+ }+ if (!readFrame(conn, type, payload, 10, error)) {+ if (error.empty()) continue; // nothing this time+ break;+ }+ if (type == MayaLinkType::Bye) {+ error = "Maya closed the link";+ break;+ }+ if (type != MayaLinkType::Mesh) {+ error = "an unexpected message";+ ++refused_;+ break;+ }+ MayaLinkMesh mesh;+ if (!parseMayaLinkMesh(payload, mesh, error)) {+ ++refused_;+ break;+ }+ std::lock_guard<std::mutex> lock(mutex_);+ // The newest mesh per object wins (Maya sends whole meshes).+ std::erase_if(inbox_, [&](const MayaLinkMesh& m) { return m.name == mesh.name; });+ inbox_.push_back(std::move(mesh));+ }+ connected_ = false;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ client_.clear();+ }+ event("disconnected: " + (error.empty() ? std::string("link off") : error));+ return true;+}++void MayaLinkServer::run() {+ while (!stopping_) {+ AiLinkConn conn;+ bool refusedPeer = false;+ if (!listener_.accept(conn, 100, &refusedPeer)) {+ if (refusedPeer) {+ ++refused_;+ event("refused: another user");+ }+ continue;+ }+ serve(conn);+ if (conn.valid()) {+ const std::string bye = mayaLinkFrame(MayaLinkType::Bye, {});+ conn.writeAll(bye.data(), bye.size());+ }+ conn.close();+ }+ running_ = false;+}++} // namespace sf::linkdiff --git a/src/link/MayaLink.h b/src/link/MayaLink.hnew file mode 100644index 00000000..88f16e09--- /dev/null+++ b/src/link/MayaLink.h@@ -0,0 +1,143 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The Maya Live link (#42; File > Maya > Live link, opt-in, off at every start): the SculptForge shelf script for+// Maya connects to the open app for live updates, so Maya follows a stroke while it is drawn. On top of the+// exchange folder (io/MayaBridge.h), never instead of it.+//+// Where: the same kind of local endpoint as live mode (link/AiLink.h), never a TCP or UDP port: a Unix domain+// socket (0600, in a folder only this user can enter; every peer's user is checked) or a named pipe whose DACL+// grants this user only, remote clients rejected. Browsers can't open either, other users and the network can't+// reach them. On top of that, a random pairing code shown in SculptForge must open every connection, and one+// client at a time.+//+// What: mesh data only. No commands, paths, scripts or anything that is run. Little-endian frames:+// header (16 bytes): "SFML", u16 version (1), u16 type, u64 payload length (<= kMayaLinkMaxPayload)+// Hello (client first, within kMayaLinkHelloMs): 32 ASCII hex pairing code, u16 n, n bytes client name+// Welcome (app's answer): u16 n, n bytes app version+// Mesh: u16 n, name (Maya characters), u32 V, u32 F, u32 C, u8 flags (1 = UVs), f32 x3 V positions,+// u8 F face sizes (3..255, summing to C), u32 C vertex indices (< V), [f32 x2 C UVs per corner]+// Points: u16 n, name, u32 V (the mesh's vertex count), u32 N, u32 N indices (< V), f32 x3 N positions+// Bye: empty+// Everything is checked before use: sizes add up exactly, indices are in range, numbers are finite, names are+// Maya names. Anything else closes the connection.+#pragma once++#include "core/Mesh.h"+#include "link/AiLink.h"++#include <atomic>+#include <cstdint>+#include <deque>+#include <mutex>+#include <string>+#include <thread>+#include <vector>++namespace sf::link {++inline constexpr uint16_t kMayaLinkVersion = 1;+inline constexpr size_t kMayaLinkHeaderBytes = 16;+inline constexpr uint64_t kMayaLinkMaxPayload = 1ull << 30; // 1 GiB: a 20M-triangle mesh with UVs fits+inline constexpr uint32_t kMayaLinkMaxVertices = 64u << 20;+inline constexpr size_t kMayaLinkCodeChars = 32;+inline constexpr int kMayaLinkHelloMs = 5000; // to send Hello after connecting+inline constexpr int kMayaLinkFrameMs = 30000; // no byte of a started frame for this long: closed+inline constexpr unsigned long long kMayaLinkStreamNs = 100'000'000ull; // mid-stroke Points, at most this often++enum class MayaLinkType : uint16_t { Hello = 1, Welcome = 2, Mesh = 3, Points = 4, Bye = 5 };++struct MayaLinkMesh {+ std::string name;+ std::vector<float> positions; // 3 per vertex+ std::vector<uint8_t> faceSizes; // per face+ std::vector<uint32_t> indices; // per corner+ std::vector<float> uvs; // 2 per corner, or empty+};++struct MayaLinkPoints {+ std::string name;+ uint32_t vertexCount = 0;+ std::vector<uint32_t> indices;+ std::vector<float> positions; // 3 per index+};++// A new pairing code: 32 hex digits (128 random bits).+std::string mayaLinkNewCode();+// The code as shown and pasted: "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX" (upper case). Pasting takes either form.+std::string mayaLinkShowCode(const std::string& code);+// What Copy puts on the clipboard for the shelf's Link button: "sflink1 <code> <endpoint>".+std::string mayaLinkPairingText(const std::string& code, const std::string& endpoint);+// Constant-time comparison of a sent code (any case, dashes ignored) with the app's.+bool mayaLinkCodeMatches(const std::string& sent, const std::string& code);++// Frames. encode* give a whole frame (header + payload); parse* check a payload of that type strictly.+std::string mayaLinkFrame(MayaLinkType type, const std::string& payload);+// The header: false (with `error`) for a wrong magic, version, unknown type or a payload over the cap.+bool parseMayaLinkHeader(const char* header, MayaLinkType& type, uint64_t& length, std::string& error);+std::string encodeMayaLinkHello(const std::string& code, const std::string& client);+bool parseMayaLinkHello(const std::string& payload, std::string& code, std::string& client, std::string& error);+std::string encodeMayaLinkWelcome(const std::string& version);+std::string encodeMayaLinkMesh(const MayaLinkMesh& mesh);+bool parseMayaLinkMesh(const std::string& payload, MayaLinkMesh& out, std::string& error);+std::string encodeMayaLinkPoints(const MayaLinkPoints& points);+bool parseMayaLinkPoints(const std::string& payload, MayaLinkPoints& out, std::string& error);++// SculptForge's meshes as link meshes (quads as quads, UVs per corner) and back (polygons fanned into+// triangles, quads kept as pairs, normals and topology rebuilt).+MayaLinkMesh mayaLinkMeshFrom(const std::string& name, const Mesh& mesh);+bool mayaLinkMeshTo(const MayaLinkMesh& in, Mesh& out, std::string& error);+// The vertices of `now` that moved from `before` (same vertex count), as Points. Empty when none moved.+MayaLinkPoints mayaLinkPointsBetween(const std::string& name, const std::vector<glm::vec3>& before,+ const std::vector<glm::vec3>& now);++// Merges `later` into `into` (same object): the union of their vertices, `later`'s positions winning. Points+// carry absolute positions, so queued updates fold into one and a slow reader never falls behind.+void mergeMayaLinkPoints(MayaLinkPoints& into, const MayaLinkPoints& later);++// The app's end: a worker thread that listens, pairs and carries frames. Received meshes queue up for the main+// thread (takeReceived); sends queue up for the worker, which encodes them (Points for an object fold into the+// queued ones; a Mesh drops the Points queued before it). One client at a time.+class MayaLinkServer {+public:+ ~MayaLinkServer() { stop(); }+ // Starts listening on `endpoint` (localEndpoint("maya-link")) with a new pairing code.+ bool start(const std::string& endpoint, std::string& error);+ void stop();+ bool running() const { return running_; }+ bool connected() const { return connected_; }+ const std::string& code() const { return code_; }+ const std::string& endpoint() const { return endpoint_; }+ std::string clientName() const;+ // Counts for the UI and tests: refused connections (wrong code, a second client, bad frames).+ int refused() const { return refused_; }+ void send(MayaLinkMesh mesh);+ void send(MayaLinkPoints points);+ std::vector<MayaLinkMesh> takeReceived();+ std::string takeEvent(); // "connected", "disconnected: ...", "refused: ..." (one at a time, "" = none)++private:+ void run();+ bool serve(AiLinkConn& conn);+ bool readFrame(AiLinkConn& conn, MayaLinkType& type, std::string& payload, int firstByteMs, std::string& error);+ bool flush(AiLinkConn& conn);+ void event(std::string text);++ AiLinkListener listener_;+ std::thread thread_;+ std::atomic<bool> running_{false}, stopping_{false}, connected_{false};+ std::atomic<int> refused_{0};+ std::string code_, endpoint_;+ mutable std::mutex mutex_;+ std::string client_;+ struct Outgoing {+ bool isMesh = false;+ MayaLinkMesh mesh;+ MayaLinkPoints points;+ };+ std::deque<Outgoing> outbox_;+ std::vector<MayaLinkMesh> inbox_;+ std::deque<std::string> events_;+};++} // namespace sf::linkdiff --git a/tests/maya/data/link_mesh.bin b/tests/maya/data/link_mesh.binnew file mode 100644index 00000000..e5cddecaBinary files /dev/null and b/tests/maya/data/link_mesh.bin differdiff --git a/tests/maya/data/link_points.bin b/tests/maya/data/link_points.binnew file mode 100644index 00000000..1de0eb62Binary files /dev/null and b/tests/maya/data/link_points.bin differdiff --git a/tests/maya/test_sculptforge_maya.py b/tests/maya/test_sculptforge_maya.pyindex 8cf01d09..d4acd576 100644--- a/tests/maya/test_sculptforge_maya.py+++ b/tests/maya/test_sculptforge_maya.py@@ -248,7 +248,9 @@ def test_shelf(sm):sm.install_shelf()sm.install_shelf() # again: replaces the shelfbuttons = cmds.option_vars["_shelves"][sm.SHELF]- check(len(buttons) == 4 and all(t == "python" for t, _, _ in buttons), "the shelf has four Python buttons")+ check(len(buttons) == 6 and all(t == "python" for t, _, _ in buttons), "the shelf has six Python buttons")+ check(any(n == sm.LIVE_BUTTON for _, _, n in buttons) and any(n == sm.LINK_BUTTON for _, _, n in buttons),+ "the Live and Link buttons have their names (their labels show on / off)")check(any(n == sm.AUTO_BUTTON for _, _, n in buttons), "the Auto button has its name (its label shows on / off)")for _, command, _ in buttons:func = command.split("sculptforge_maya.")[1].rstrip("()")@@ -461,6 +463,236 @@ def test_auto(sm, tmp):sm._watcher.stop()+class Clock(object):+ def __init__(self):+ self.t = 100.0++ def __call__(self):+ return self.t+++def test_live(sm, tmp):+ """Live: the wait for stillness, the echo guard, sends of the changed meshes only, and never loading what this+ Maya session wrote."""+ clock = Clock()+ live = sm.LiveState(clock=clock)+ check(not live.due(), "live: nothing changed, nothing due")+ live.mark("|a")+ clock.t += 0.1+ check(not live.due(), "live: 100 ms after a change: still waiting")+ live.mark("|b")+ clock.t += 0.25+ check(not live.due(), "live: another change restarts the wait")+ clock.t += 0.1+ check(live.due() and live.take() == ["|a", "|b"] and not live.due(), "live: 300 ms of stillness: due, once")+ live.applying += 1+ live.mark("|a")+ live.applying -= 1+ clock.t += 1+ check(not live.due(), "live: changes while a Get applies don't count (the echo guard)")++ folder = os.path.join(tmp, "live")+ os.makedirs(folder)+ cmds = install_fake_maya(folder)+ sm.POLL_SECONDS = 3600+ sm._live = sm.LiveState(clock=clock)+ cmds.add_mesh("|pCube1", CUBE_OBJ)+ cmds.add_mesh("|pCube2", CUBE_OBJ)+ cmds.selection = ["|pCube1", "|pCube2"]+ sm.send_to_sculptforge() # (watched from now on)+ box = os.path.join(folder, sm.TO_SCULPTFORGE)+ m = sm.read_manifest(box)+ check(m["writer"] == sm.WRITER and not m["live"], "send: the manifest says which Maya session wrote it")+ check({"|pCube1", "|pCube2"} <= set(sm._watched), "live: what was sent is watched")++ sm.toggle_live()+ check(sm.live_on() and sm.auto_get_on(), "live on (and Auto with it)")+ cmds.nodes["|pCube2|pCube2Shape"]["obj"] = CUBE_OBJ.replace("v 1 1 1", "v 1 1.5 1")+ sm._live.mark("|pCube2") # (Maya's dirty callback)+ clock.t += 0.5+ check(sm._live.due(), "live: due after the edit")+ sm._live_send()+ m2 = sm.read_manifest(box)+ check(m2["revision"] == m["revision"] + 1 and [n for n, _ in m2["objects"]] == ["pCube2"] and m2["live"],+ "live: only the edited mesh is sent")+ check(cmds.selection == ["|pCube1", "|pCube2"], "live: the selection is left as it was")++ # A Get of what SculptForge sends doesn't send it back.+ out = os.path.join(folder, sm.TO_MAYA)+ write_sculptforge_send(sm, out, 1, ["pCube1"])+ sm.get_from_sculptforge()+ clock.t += 1+ check(not sm._live.due(), "live: a Get is not an edit to send back")++ # A manifest this Maya wrote (the user picked one folder as both): never loaded.+ sm.write_atomically(os.path.join(out, "manifest.json"),+ sm.write_manifest([("pCube1", "r1_000.obj")], 7, writer=sm.WRITER))+ before = cmds.nodes["|pCube1|pCube1Shape"]["obj"]+ cmds.nodes["|pCube1|pCube1Shape"]["obj"] = "mine"+ sm._auto_get_new()+ check(cmds.nodes["|pCube1|pCube1Shape"]["obj"] == "mine", "auto: what this Maya session wrote isn't loaded")+ cmds.nodes["|pCube1|pCube1Shape"]["obj"] = before+ sm.toggle_live()+ check(not sm.live_on(), "live off")+ sm._live.mark("|pCube1")+ clock.t += 1+ check(sm._live_send() is None, "live off: nothing is sent by itself")+ if sm._watcher:+ sm._watcher.stop()+++def test_link_codec(sm):+ """The Live link's frames: the same bytes as SculptForge's (tests/maya/data, read by test_maya_live.cpp), strict+ parsing, and random input refused without anything but LinkError."""+ data = os.path.join(HERE, "data")+ mesh = {"name": "pPlane1", "positions": [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0], "face_sizes": [4, 3],+ "indices": [0, 1, 2, 3, 1, 4, 2], "uvs": [0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1]}+ with open(os.path.join(data, "link_mesh.bin"), "rb") as f:+ check(f.read() == sm.encode_mesh(mesh), "link: the shelf writes SculptForge's Mesh bytes")+ with open(os.path.join(data, "link_points.bin"), "rb") as f:+ golden = f.read()+ check(golden == sm.encode_points("Body", 5, [1, 4], [0.5, 0.25, -1, 2, 3, 4]), "link: and its Points bytes")+ kind, length = sm.parse_header(golden[:16])+ name, count, indices, positions = sm.parse_points(golden[16:])+ check(kind == sm.LINK_POINTS and name == "Body" and count == 5 and list(indices) == [1, 4], "link: points read")+ back = sm.parse_mesh(sm.encode_mesh(mesh)[16:])+ check(list(back["indices"]) == mesh["indices"] and list(back["face_sizes"]) == [4, 3] and len(back["uvs"]) == 14,+ "link: mesh round trip")++ def refused(fn, payload, what):+ try:+ fn(payload)+ check(False, "link refuses " + what)+ except sm.LinkError:+ pass++ for bad, what in [(dict(mesh, indices=[0, 1, 2, 3, 1, 5, 2]), "an index out of range"),+ (dict(mesh, face_sizes=[2, 5]), "a face of 2"),+ (dict(mesh, face_sizes=[4, 4]), "faces that don't add up"),+ (dict(mesh, positions=[float("nan")] + mesh["positions"][1:]), "NaN")]:+ refused(sm.parse_mesh, sm.encode_mesh(bad)[16:], what)+ for name in ["", "../x", "a b", "1abc"]:+ raw = name.encode()+ refused(sm.parse_mesh, struct_name(raw) + sm.encode_mesh(mesh)[16 + 2 + 7:], "the name %r" % name)+ good = sm.encode_mesh(mesh)[16:]+ refused(sm.parse_mesh, good + b"x", "a byte too many")+ for cut in range(len(good)):+ refused(sm.parse_mesh, good[:cut], "a cut at %d" % cut)+ for header, what in [(b"GET / HTTP/1.1\r\n\r\n"[:16], "HTTP"), (b"SFML" + bytes([2, 0, 3, 0]) + bytes(8), "version 2"),+ (b"SFML" + bytes([1, 0, 9, 0]) + bytes(8), "type 9"),+ (b"SFML" + bytes([1, 0, 3, 0]) + bytes([0, 0, 0, 0x40, 1, 0, 0, 0]), "over the cap")]:+ refused(sm.parse_header, header, what)+ import random+ rng = random.Random(42)+ for i in range(3000):+ blob = bytearray(good) if i % 2 else bytearray(rng.getrandbits(8) for _ in range(rng.randrange(80)))+ if i % 2:+ for _ in range(rng.randrange(1, 5)):+ blob[rng.randrange(len(blob))] = rng.getrandbits(8)+ for fn in (sm.parse_mesh, sm.parse_points):+ try:+ r = fn(bytes(blob))+ if fn is sm.parse_mesh:+ check(max(r["indices"]) < len(r["positions"]) // 3, "fuzz: what parses is in range")+ except sm.LinkError:+ pass+ except Exception as e: # anything else would be a parser bug+ check(False, "fuzz: %r raised %r" % (bytes(blob[:16]), e))++ # Pairing: SculptForge's Copy text or a bare code; only SculptForge's endpoint names.+ code = "0123456789abcdef0123456789ABCDEF"+ shown = "-".join(code[k:k + 8].upper() for k in range(0, 32, 8))+ if os.name != "nt":+ c, e = sm.parse_pairing("sflink1 %s /run/user/1000/sculptforge/maya-link.sock" % shown)+ check(c == code.lower() and e.endswith("maya-link.sock"), "pairing: Copy's text")+ for bad in ["sflink1 %s /etc/passwd" % shown, "sflink1 %s /tmp/../x/maya-link.sock" % shown,+ "sflink1 %s relative/maya-link.sock" % shown]:+ refused(sm.parse_pairing, bad, "the endpoint in %r" % bad)+ check(sm.parse_pairing(shown)[0] == code.lower(), "pairing: a bare code")+ for bad in ["", "1234", "zz" * 16, "sflink2 %s x" % shown]:+ refused(sm.parse_pairing, bad, "the code %r" % bad)+++def struct_name(raw):+ import struct+ return struct.pack("<H", len(raw)) + raw+++class PairConn(object):+ """One end of a socket pair, as LinkClient's connection."""++ def __init__(self, sock):+ self.sock = sock++ def recv(self, n, timeout):+ import socket+ self.sock.settimeout(timeout)+ try:+ data = self.sock.recv(n)+ except socket.timeout:+ return b""+ if not data:+ raise ValueError("closed")+ return data++ def send(self, data):+ self.sock.sendall(data)++ def close(self):+ self.sock.close()+++def test_link_client(sm):+ """LinkClient against a stand-in SculptForge: the code first, Welcome, then streamed Points fold into one update+ per object, a Mesh replaces them, and Bye ends it."""+ import socket+ import time as _time+ try:+ a, b = socket.socketpair()+ except (AttributeError, OSError):+ return+ code = "0123456789abcdef0123456789abcdef"+ got = []+ inbox = sm.LinkInbox()++ def app():+ f = b.recv(16)+ kind, length = sm.parse_header(f)+ payload = b""+ while len(payload) < length:+ payload += b.recv(length - len(payload))+ got.append((kind, payload[:32]))+ b.sendall(sm.frame(sm.LINK_WELCOME, b"\x06\x000.11.11"))+ b.sendall(sm.encode_points("Body", 10, [1, 2], [1, 1, 1, 2, 2, 2]))+ b.sendall(sm.encode_points("Body", 10, [2, 3], [5, 5, 5, 3, 3, 3]))+ _time.sleep(0.2)+ b.sendall(sm.frame(sm.LINK_BYE))++ import threading+ t = threading.Thread(target=app)+ t.start()+ client = sm.LinkClient(PairConn(a), code, inbox.add)+ check(got and got[0] == (sm.LINK_HELLO, code.encode()), "link client: the pairing code goes first")+ check(client.server == "0.11.11" and client.connected, "link client: Welcome, connected")+ t.join()+ for _ in range(100):+ if not client.connected:+ break+ _time.sleep(0.01)+ check(not client.connected and "off" in client.error, "link client: Bye ends the link")+ taken = inbox.take()+ check(len(taken) == 1 and taken[0][0] == "Body" and taken[0][1] is None, "link inbox: one update for Body")+ count, moved = taken[0][2]+ check(count == 10 and sorted(moved) == [1, 2, 3] and moved[2] == (5, 5, 5), "link inbox: Points fold, later wins")+ inbox.add(sm.LINK_POINTS, sm.encode_points("Body", 10, [1], [0, 0, 0])[16:])+ inbox.add(sm.LINK_MESH, sm.encode_mesh({"name": "Body", "positions": [0, 0, 0, 1, 0, 0, 0, 1, 0], "face_sizes": [3],+ "indices": [0, 1, 2], "uvs": []})[16:])+ taken = inbox.take()+ check(taken[0][1] is not None and taken[0][2] is None, "link inbox: a whole mesh drops the Points before it")+ a.close()+ b.close()++def main():ap = argparse.ArgumentParser()ap.add_argument("--cli", help="sculptforge-cli, for the round trip through SculptForge")@@ -471,6 +703,9 @@ def main():test_format(sm, tmp)test_send_and_get(sm, tmp, args.cli)test_auto(sm, tmp)+ test_live(sm, tmp)+ test_link_codec(sm)+ test_link_client(sm)test_shelf(sm)finally:shutil.rmtree(tmp, ignore_errors=True)diff --git a/tests/test_maya_live.cpp b/tests/test_maya_live.cppnew file mode 100644index 00000000..1e2eaac0--- /dev/null+++ b/tests/test_maya_live.cpp@@ -0,0 +1,475 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Maya Live (#42): the file side's debounce, mesh hash, echo guard and manifest writer id (io/MayaBridge.h), and+// the Live link (link/MayaLink.h): strict frames (round trips, then malformed and random input refused without+// a crash), Points folding, and a real server on a per-user socket that pairs only with its code.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Primitives.h"+#include "io/MayaBridge.h"+#include "io/MayaCommands.h"+#include "io/ObjIO.h"+#include "link/MayaLink.h"++#include <chrono>+#include <cmath>+#include <cstdlib>+#include <fstream>+#include <functional>+#include <iterator>+#include <limits>+#include <filesystem>+#include <random>+#include <thread>++using namespace sf;++namespace {++namespace fs = std::filesystem;++link::MayaLinkMesh quadMesh() {+ link::MayaLinkMesh m;+ m.name = "pPlane1";+ m.positions = {0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0};+ m.faceSizes = {4, 3};+ m.indices = {0, 1, 2, 3, 1, 4, 2};+ m.uvs = {0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1};+ return m;+}++std::string payloadOf(const std::string& frame) { return frame.substr(link::kMayaLinkHeaderBytes); }++bool waitFor(const std::function<bool()>& f, int ms = 3000) {+ for (int i = 0; i < ms / 5; ++i) {+ if (f()) return true;+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ }+ return f();+}++bool readFrame(link::AiLinkConn& c, link::MayaLinkType& type, std::string& payload) {+ char header[link::kMayaLinkHeaderBytes];+ size_t got = 0;+ while (got < sizeof header) {+ const long long n = c.readBytes(header + got, sizeof header - got, 3000);+ if (n <= 0) return false;+ got += size_t(n);+ }+ uint64_t length = 0;+ std::string error;+ if (!link::parseMayaLinkHeader(header, type, length, error)) return false;+ payload.assign(size_t(length), '\0');+ for (size_t at = 0; at < payload.size();) {+ const long long n = c.readBytes(payload.data() + at, payload.size() - at, 3000);+ if (n <= 0) return false;+ at += size_t(n);+ }+ return true;+}++} // namespace++TEST(maya_live_debounce_and_hash) {+ MayaLiveDebounce d;+ CHECK(!d.pending() && !d.due(1'000'000'000ull, false));+ d.changed(1'000'000'000ull);+ CHECK(d.pending() && !d.due(1'100'000'000ull, false)); // 100 ms: still waiting+ CHECK(!d.due(1'400'000'000ull, true)); // still, but mid-stroke: never+ CHECK(d.due(1'300'000'000ull, false) && d.due(1'400'000'000ull, false)); // 300 ms of stillness+ d.changed(1'350'000'000ull); // another edit restarts the wait+ CHECK(!d.due(1'400'000'000ull, false) && d.due(1'650'000'000ull, false));+ d.clear();+ CHECK(!d.pending());++ Mesh a = makeCube(2);+ a.uvs.assign(a.triangleCount() * 3, glm::vec2(0.5f));+ Mesh b = mayaSendCopy(a);+ CHECK(b.positions == a.positions && b.triangles == a.triangles && b.uvs == a.uvs && b.hasQuads() == a.hasQuads());+ CHECK(b.layers.empty() && !b.hasFaceGroups() && !b.texture);+ CHECK(mayaMeshHash(a) == mayaMeshHash(b));+ b.positions[3].x += 1e-4f;+ CHECK(mayaMeshHash(a) != mayaMeshHash(b));++ // The echo guard: OBJ's rounding is the same mesh; a real move or other faces are not.+ Mesh c = a;+ for (glm::vec3& p : c.positions) p += glm::vec3(3e-7f);+ CHECK(mayaMeshesMatch(a, c));+ c.positions[0].y += 0.01f;+ CHECK(!mayaMeshesMatch(a, c));+ CHECK(!mayaMeshesMatch(a, makeCube(3)));+}++TEST(maya_live_manifest_writer_and_echo) {+ MayaManifest m;+ m.revision = 7;+ m.sender = "sculptforge";+ m.writer = mayaNewWriterId();+ m.live = true;+ CHECK(m.writer.size() == 16 && m.writer != mayaNewWriterId());+ MayaManifest back;+ std::string err;+ CHECK(parseMayaManifest(writeMayaManifest(m), back, err));+ CHECK(back.writer == m.writer && back.live && back.revision == 7);+ // Older manifests (no writer) still read; a writer that isn't a short string is refused.+ CHECK(parseMayaManifest(R"({"format": "sculptforge-maya", "version": 1, "revision": 1, "objects": []})", back, err) &&+ back.writer.empty() && !back.live);+ CHECK(!parseMayaManifest(R"({"format": "sculptforge-maya", "version": 1, "revision": 1, "writer": 5, "objects": []})", back, err));++ // A Live send: writer and live in the manifest, files renamed into place (no .tmp left).+ const fs::path root = fs::temp_directory_path() / "sf_maya_live";+ fs::remove_all(root);+ fs::create_directories(root);+ Mesh cube = makeCube(2);+ std::string msg;+ std::vector<std::string> names;+ CHECK(mayaSend({{"Body", &cube}}, root.string(), msg, &names, nullptr, m.writer, true));+ CHECK(msg.rfind("Live: sent 1 object", 0) == 0);+ CHECK(readMayaManifest(mayaManifestPath(mayaOutbox(root.string())), back, err) && back.writer == m.writer && back.live);+ for (const auto& e : fs::directory_iterator(root / "sculptforge_to_maya"))+ CHECK(e.path().extension() != ".tmp");++ // maya_receive skips what Maya sends back unchanged (no undo step), loads what changed.+ CommandRegistry reg;+ Document doc = makeDoc(makeCube(2));+ doc.bridgeName = "Body";+ const fs::path inbox = root / "maya_to_sculptforge";+ fs::create_directories(inbox);+ CHECK(saveObj((inbox / "r1_000.obj").string(), doc.mesh, err));+ std::ofstream(inbox / "manifest.json") << R"({"format": "sculptforge-maya", "version": 1, "revision": 1,+ "objects": [{"name": "Body", "file": "r1_000.obj"}]})";+ CommandResult r = reg.execute(doc, "maya_receive", {{"folder", root.string()}});+ CHECK(r.ok && r.message.find("unchanged") != std::string::npos && !doc.undo.canUndo());+ Mesh moved = doc.mesh;+ for (glm::vec3& p : moved.positions) p.x += 0.5f;+ CHECK(saveObj((inbox / "r2_000.obj").string(), moved, err));+ std::ofstream(inbox / "manifest.json") << R"({"format": "sculptforge-maya", "version": 1, "revision": 2,+ "objects": [{"name": "Body", "file": "r2_000.obj"}]})";+ r = reg.execute(doc, "maya_receive", {{"folder", root.string()}});+ CHECK(r.ok && r.message.find("Received 1 object") != std::string::npos && doc.undo.canUndo());+ fs::remove_all(root);+}++TEST(maya_link_frames_round_trip) {+ using namespace link;+ const std::string code = mayaLinkNewCode();+ CHECK(code.size() == kMayaLinkCodeChars && code != mayaLinkNewCode());+ const std::string shown = mayaLinkShowCode(code);+ CHECK(shown.size() == 35 && shown[8] == '-');+ CHECK(mayaLinkCodeMatches(shown, code) && mayaLinkCodeMatches(code, code));+ CHECK(!mayaLinkCodeMatches(mayaLinkNewCode(), code) && !mayaLinkCodeMatches("", code) &&+ !mayaLinkCodeMatches(code.substr(0, 31), code) && !mayaLinkCodeMatches(code + "0", code));+ CHECK(mayaLinkPairingText(code, "/run/x/maya-link.sock") == "sflink1 " + shown + " /run/x/maya-link.sock");++ std::string c, client, err;+ CHECK(parseMayaLinkHello(payloadOf(encodeMayaLinkHello(code, "Maya 2026")), c, client, err) && c == code &&+ client == "Maya 2026");++ const MayaLinkMesh m = quadMesh();+ const std::string f = encodeMayaLinkMesh(m);+ MayaLinkType type{};+ uint64_t length = 0;+ CHECK(parseMayaLinkHeader(f.data(), type, length, err) && type == MayaLinkType::Mesh && length == f.size() - 16);+ MayaLinkMesh back;+ CHECK(parseMayaLinkMesh(payloadOf(f), back, err));+ CHECK(back.name == m.name && back.positions == m.positions && back.faceSizes == m.faceSizes &&+ back.indices == m.indices && back.uvs == m.uvs);++ // To a SculptForge mesh and back: a quad stays a quad, the triangle a triangle, UVs per corner.+ Mesh mesh;+ CHECK(mayaLinkMeshTo(back, mesh, err));+ CHECK(mesh.vertexCount() == 5 && mesh.triangleCount() == 3 && mesh.quadCount() == 1 && mesh.uvs.size() == 9);+ const MayaLinkMesh again = mayaLinkMeshFrom("pPlane1", mesh);+ CHECK(again.faceSizes.size() == 2 && again.indices.size() == 7 && again.uvs.size() == 14);++ MayaLinkPoints p = mayaLinkPointsBetween("pPlane1", mesh.positions, mesh.positions);+ CHECK(p.indices.empty() && p.vertexCount == 5);+ std::vector<glm::vec3> now = mesh.positions;+ now[1].z = 0.5f;+ now[4].z = -0.5f;+ p = mayaLinkPointsBetween("pPlane1", mesh.positions, now);+ CHECK((p.indices == std::vector<uint32_t>{1, 4}) && p.positions.size() == 6);+ MayaLinkPoints pb;+ CHECK(parseMayaLinkPoints(payloadOf(encodeMayaLinkPoints(p)), pb, err) && pb.indices == p.indices &&+ pb.positions == p.positions && pb.vertexCount == 5);++ // Folding: the union of the vertices, the later positions winning.+ MayaLinkPoints later = p;+ later.indices = {4, 2};+ later.positions = {9, 9, 9, 7, 7, 7};+ mergeMayaLinkPoints(p, later);+ CHECK((p.indices == std::vector<uint32_t>{1, 4, 2}) && p.positions[3] == 9.0f && p.positions[6] == 7.0f &&+ p.positions[0] == now[1].x);+}++// The shelf script's encoder wrote these (tests/maya/data; tests/maya/test_sculptforge_maya.py checks it still+// writes the same bytes): both sides speak one format.+TEST(maya_link_reads_the_shelf_scripts_frames) {+ using namespace link;+ auto read = [](const char* name) {+ std::ifstream f(fs::path(SF_TEST_DATA_DIR) / ".." / "maya" / "data" / name, std::ios::binary);+ return std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ };+ const std::string mesh = read("link_mesh.bin");+ CHECK(mesh == encodeMayaLinkMesh(quadMesh()));+ MayaLinkType type{};+ uint64_t length = 0;+ std::string err;+ MayaLinkMesh m;+ CHECK(mesh.size() > 16 && parseMayaLinkHeader(mesh.data(), type, length, err) && type == MayaLinkType::Mesh &&+ parseMayaLinkMesh(payloadOf(mesh), m, err) && m.name == "pPlane1" && m.faceSizes.size() == 2);+ const std::string points = read("link_points.bin");+ MayaLinkPoints p;+ CHECK(points.size() > 16 && parseMayaLinkPoints(payloadOf(points), p, err) && p.name == "Body" && p.vertexCount == 5 &&+ (p.indices == std::vector<uint32_t>{1, 4}) && p.positions[0] == 0.5f && p.positions[5] == 4.0f);+}++TEST(maya_link_refuses_malformed) {+ using namespace link;+ std::string err;+ MayaLinkType type{};+ uint64_t length = 0;+ auto header = [](const char* magic, uint16_t version, uint16_t t, uint64_t n) {+ std::string h(magic, 4);+ h += char(version & 0xff);+ h += char(version >> 8);+ h += char(t & 0xff);+ h += char(t >> 8);+ for (int i = 0; i < 8; ++i) h += char((n >> (8 * i)) & 0xff);+ return h;+ };+ CHECK(!parseMayaLinkHeader(header("GET ", 1, 3, 10).data(), type, length, err)); // (HTTP, a browser: refused)+ CHECK(!parseMayaLinkHeader(header("SFML", 2, 3, 10).data(), type, length, err));+ CHECK(!parseMayaLinkHeader(header("SFML", 1, 0, 10).data(), type, length, err));+ CHECK(!parseMayaLinkHeader(header("SFML", 1, 9, 10).data(), type, length, err));+ CHECK(!parseMayaLinkHeader(header("SFML", 1, 3, kMayaLinkMaxPayload + 1).data(), type, length, err));+ CHECK(parseMayaLinkHeader(header("SFML", 1, 3, 10).data(), type, length, err));++ MayaLinkMesh out;+ auto refused = [&](MayaLinkMesh m) { return !parseMayaLinkMesh(payloadOf(encodeMayaLinkMesh(m)), out, err); };+ MayaLinkMesh m = quadMesh();+ m.indices[2] = 5; // out of range+ CHECK(refused(m));+ m = quadMesh();+ m.faceSizes = {2, 5}; // a face of 2+ CHECK(refused(m));+ m = quadMesh();+ m.faceSizes = {4, 4}; // faces that don't add up+ CHECK(refused(m));+ m = quadMesh();+ m.positions[4] = std::nanf("");+ CHECK(refused(m));+ m = quadMesh();+ m.uvs[3] = std::numeric_limits<float>::infinity();+ CHECK(refused(m));+ for (const char* name : {"", "../x", "a b", "1abc", "C:\\x"}) {+ m = quadMesh();+ m.name = name;+ CHECK(refused(m));+ }+ const std::string good = payloadOf(encodeMayaLinkMesh(quadMesh()));+ CHECK(!parseMayaLinkMesh(good + "x", out, err)); // a byte too many+ CHECK(!parseMayaLinkMesh(good.substr(0, good.size() - 1), out, err)); // one too few+ for (size_t cut = 0; cut < good.size(); ++cut) CHECK(!parseMayaLinkMesh(good.substr(0, cut), out, err));++ // Fuzz: random bytes, and the good payload with random bytes changed, never crash or read out of bounds (run+ // under the sanitizers in CI); whatever parses still holds only in-range indices and finite numbers.+ std::mt19937 rng(42);+ for (int i = 0; i < 20000; ++i) {+ std::string s = i % 2 ? good : std::string(size_t(rng() % 96), '\0');+ if (i % 2 == 0)+ for (char& ch : s) ch = char(rng());+ else+ for (int k = 0; k < 1 + int(rng() % 4); ++k) s[rng() % s.size()] = char(rng());+ MayaLinkMesh fm;+ if (parseMayaLinkMesh(s, fm, err)) {+ for (uint32_t v : fm.indices) CHECK(v < fm.positions.size() / 3);+ for (float x : fm.positions) CHECK(std::isfinite(x));+ }+ MayaLinkPoints fp;+ if (parseMayaLinkPoints(s, fp, err))+ for (uint32_t v : fp.indices) CHECK(v < fp.vertexCount);+ std::string c, cl;+ parseMayaLinkHello(s, c, cl, err);+ if (s.size() >= kMayaLinkHeaderBytes) parseMayaLinkHeader(s.data(), type, length, err);+ }+ // Counts that claim more than the payload holds (a 4 GB allocation attempt) are refused before allocating.+ std::string huge;+ huge += char(1);+ huge += char(0);+ huge += 'a';+ for (int i = 0; i < 3; ++i) huge += std::string("\xff\xff\xff\x03", 4);+ huge += char(0);+ CHECK(!parseMayaLinkMesh(huge, out, err));+}++#ifndef _WIN32+TEST(maya_link_server_pairs_and_streams) {+ using namespace link;+ const fs::path dir = fs::temp_directory_path() / ("sf_maya_link_" + std::to_string(std::random_device{}() % 100000));+ fs::create_directories(dir);+ setenv("SF_AI_LIVE_DIR", dir.string().c_str(), 1);+ std::string err;+ const std::string endpoint = localEndpoint("maya-link", err);+ CHECK(!endpoint.empty() && endpoint.find("maya-link.sock") != std::string::npos);+ MayaLinkServer server;+ CHECK(server.start(endpoint, err));+ CHECK(aiLinkFileMode(endpoint) == 0600);+ // A second server on the same endpoint: refused (another window has it on).+ MayaLinkServer second;+ CHECK(!second.start(endpoint, err));++ // A wrong code: the connection closes, nothing connected.+ {+ AiLinkConn c;+ CHECK(aiLinkConnect(c, endpoint, err));+ const std::string hello = encodeMayaLinkHello(mayaLinkNewCode(), "intruder");+ CHECK(c.writeAll(hello.data(), hello.size()));+ MayaLinkType t{};+ std::string p;+ CHECK(!readFrame(c, t, p) || t == MayaLinkType::Bye);+ CHECK(waitFor([&] { return server.refused() == 1; }) && !server.connected());+ }+ // Something that isn't the link at all (an HTTP request): refused too.+ {+ AiLinkConn c;+ CHECK(aiLinkConnect(c, endpoint, err));+ const std::string http = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";+ CHECK(c.writeAll(http.data(), http.size()));+ CHECK(waitFor([&] { return server.refused() == 2; }) && !server.connected());+ }+ // The right code: Welcome, then meshes both ways.+ AiLinkConn c;+ CHECK(aiLinkConnect(c, endpoint, err));+ const std::string hello = encodeMayaLinkHello(mayaLinkShowCode(server.code()), "Maya 2026");+ CHECK(c.writeAll(hello.data(), hello.size()));+ MayaLinkType t{};+ std::string p;+ CHECK(readFrame(c, t, p) && t == MayaLinkType::Welcome);+ CHECK(waitFor([&] { return server.connected(); }) && server.clientName() == "Maya 2026");+ std::string e;+ for (int i = 0; i < 4 && e != "connected"; ++i) e = server.takeEvent();+ CHECK(e == "connected");++ const std::string mesh = encodeMayaLinkMesh(quadMesh());+ CHECK(c.writeAll(mesh.data(), mesh.size()));+ std::vector<MayaLinkMesh> got;+ CHECK(waitFor([&] {+ for (auto& m : server.takeReceived()) got.push_back(std::move(m));+ return !got.empty();+ }));+ CHECK(got.size() == 1 && got[0].name == "pPlane1" && got[0].indices.size() == 7);++ // App -> Maya: Points queued together fold into one frame.+ MayaLinkPoints a;+ a.name = "Body";+ a.vertexCount = 100;+ a.indices = {1};+ a.positions = {1, 2, 3};+ server.send(a);+ MayaLinkMesh whole = quadMesh();+ whole.name = "Body2";+ server.send(whole);+ CHECK(readFrame(c, t, p));+ CHECK(t == MayaLinkType::Points || t == MayaLinkType::Mesh);++ // Maya says Bye: the server is free for the next client.+ const std::string bye = mayaLinkFrame(MayaLinkType::Bye, {});+ CHECK(c.writeAll(bye.data(), bye.size()));+ CHECK(waitFor([&] { return !server.connected(); }));+ server.stop();+ CHECK(aiLinkFileMode(endpoint) < 0); // the socket file is gone when the link is off+ unsetenv("SF_AI_LIVE_DIR");+ fs::remove_all(dir);+}+#endif++#ifndef _WIN32+// SF_MAYA_BENCH=1 sculptforge_tests maya_live_bench: what each way costs on a 1M-triangle and a Lucy-size+// (28M-triangle) quad mesh with UVs: the folder (OBJ write, read) and the link (encode, carry through the real+// socket, parse, rebuild), and a stroke's Points (2% of the vertices). Not part of the suite (it times).+TEST(maya_live_bench) {+ if (!std::getenv("SF_MAYA_BENCH")) return;+ using namespace link;+ using Clock = std::chrono::steady_clock;+ auto ms = [](Clock::time_point a) { return std::chrono::duration<double, std::milli>(Clock::now() - a).count(); };+ for (int res : {289, 1528}) {+ Mesh mesh = makeCube(res);+ mesh.uvs.assign(size_t(mesh.triangleCount()) * 3, glm::vec2(0.5f));+ std::printf("\n%u triangles, %zu vertices\n", mesh.triangleCount(), mesh.positions.size());+ const fs::path root = fs::temp_directory_path() / "sf_maya_bench";+ fs::remove_all(root);+ fs::create_directories(root);+ std::string msg, err;+ auto t = Clock::now();+ Mesh copy = mayaSendCopy(mesh);+ std::printf(" copy for the worker %8.1f ms\n", ms(t));+ t = Clock::now();+ const uint64_t h = mayaMeshHash(copy);+ std::printf(" hash %8.1f ms (%llx)\n", ms(t), (unsigned long long)(h & 0xffff));+ t = Clock::now();+ CHECK(mayaSend({{"Body", ©}}, root.string(), msg, nullptr, nullptr, "bench", true));+ std::printf(" folder: OBJ write %8.1f ms (%.0f MB)\n", ms(t),+ double(fs::file_size(root / "sculptforge_to_maya" / "r1_000.obj")) / 1e6);+ fs::rename(root / "sculptforge_to_maya", root / "maya_to_sculptforge");+ std::vector<MeshObject> back;+ t = Clock::now();+ CHECK(mayaReceive(root.string(), back, nullptr, msg));+ std::printf(" folder: OBJ read %8.1f ms\n", ms(t));+ t = Clock::now();+ CHECK(back.size() == 1 && mayaMeshesMatch(mesh, back[0].mesh));+ std::printf(" echo check %8.1f ms\n", ms(t));+ back.clear();+ fs::remove_all(root);++ t = Clock::now();+ const MayaLinkMesh lm = mayaLinkMeshFrom("Body", mesh);+ const std::string frame = encodeMayaLinkMesh(lm);+ std::printf(" link: encode %8.1f ms (%.0f MB)\n", ms(t), double(frame.size()) / 1e6);+ // Carried through a real link: this test plays Maya, sending to the app's server.+ const fs::path dir = fs::temp_directory_path() / "sf_maya_bench_link";+ fs::create_directories(dir);+ setenv("SF_AI_LIVE_DIR", dir.string().c_str(), 1);+ const std::string endpoint = localEndpoint("maya-link", err);+ MayaLinkServer server;+ CHECK(server.start(endpoint, err));+ AiLinkConn c;+ CHECK(aiLinkConnect(c, endpoint, err));+ const std::string hello = encodeMayaLinkHello(server.code(), "bench");+ c.writeAll(hello.data(), hello.size());+ MayaLinkType type{};+ std::string p;+ CHECK(readFrame(c, type, p) && type == MayaLinkType::Welcome);+ std::vector<MayaLinkMesh> got;+ t = Clock::now();+ std::thread writer([&] { c.writeAll(frame.data(), frame.size()); });+ CHECK(waitFor([&] {+ for (auto& m : server.takeReceived()) got.push_back(std::move(m));+ return !got.empty();+ }, 120000));+ writer.join();+ std::printf(" link: carry + parse %8.1f ms\n", ms(t));+ t = Clock::now();+ Mesh rebuilt;+ CHECK(!got.empty() && mayaLinkMeshTo(got[0], rebuilt, err));+ std::printf(" link: rebuild mesh %8.1f ms\n", ms(t));+ got.clear();++ std::vector<glm::vec3> moved = mesh.positions;+ for (size_t i = 0; i < moved.size(); i += 50) moved[i].y += 0.01f;+ t = Clock::now();+ const MayaLinkPoints pts = mayaLinkPointsBetween("Body", mesh.positions, moved);+ std::printf(" stroke: diff (%zu moved) %7.1f ms\n", pts.indices.size(), ms(t));+ t = Clock::now();+ const std::string pf = encodeMayaLinkPoints(pts);+ MayaLinkPoints pb;+ CHECK(parseMayaLinkPoints(payloadOf(pf), pb, err));+ std::printf(" stroke: Points encode+parse %4.1f ms (%.1f MB)\n", ms(t), double(pf.size()) / 1e6);+ server.stop();+ unsetenv("SF_AI_LIVE_DIR");+ fs::remove_all(dir);+ }+}+#endifdiff --git a/tests/test_studio_policy.cpp b/tests/test_studio_policy.cppindex 5c064e5b..80ee2d96 100644--- a/tests/test_studio_policy.cpp+++ b/tests/test_studio_policy.cpp@@ -95,6 +95,7 @@ constexpr const char* kFullPolicy = R"({"ai": {"enabled": true, "providers": ["litellm", "comfyui"], "endpoints": ["https://llm.acme.internal/"], "requireSignIn": true},"network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": true},"mcp": {"enabled": true, "live": "never", "categories": ["info", "edit"]},+ "maya": {"link": "never"},"audit": {"path": "/mnt/audit/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},"signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1abc", "scopes": ["openid", "email"],"useFor": ["https://llm.acme.internal/"]},@@ -110,12 +111,14 @@ TEST(studio_policy_parses_every_key) {CHECK(p.ai == policy::Lock::On && p.aiProviders.size() == 2 && p.aiEndpoints.size() == 1 && p.requireSignIn);CHECK(p.network == policy::Lock::Off && p.networkAllow.size() == 1 && p.localNetwork);CHECK(p.mcp == policy::Lock::On && !p.mcpLiveAllowed && p.mcpCategories.size() == 2);+ CHECK(!p.mayaLinkAllowed && policy::describe(p).find("Maya Live link never") != std::string::npos);CHECK(p.auditPath == "/mnt/audit/{user}@{host}.jsonl" && p.auditMaxMB == 20 && p.auditKeep == 10 && p.auditRequired);CHECK(p.signInConfigured() && p.clientId == "0oa1abc" && p.scopes.size() == 2 && p.signInUseFor.size() == 1);CHECK(p.updateCheck == policy::Lock::On && p.updateChannel == "stable" && !p.updateFeed.empty());// Everything is optional: the smallest policy manages nothing.const policy::Policy empty = parsed(R"({"format": "sculptforge-policy", "version": 1})");- CHECK(empty.ai == policy::Lock::Unset && empty.network == policy::Lock::Unset && empty.mcpLiveAllowed);+ CHECK(empty.ai == policy::Lock::Unset && empty.network == policy::Lock::Unset && empty.mcpLiveAllowed &&+ empty.mayaLinkAllowed);CHECK(policy::describe(p).find("telemetry none") != std::string::npos);}@@ -131,6 +134,8 @@ TEST(studio_policy_rejects_mistakes) {CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"endpoints": ["ftp://x/"]}})").empty());CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"categories": ["everything"]}})").empty());CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"live": "sometimes"}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "maya": {"link": true}})").empty());+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "maya": {"port": 1}})").empty());// There is no telemetry to turn on.CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "telemetry": true})").find("no telemetry") !=std::string::npos);@@ -150,7 +155,7 @@ TEST(studio_policy_fails_closed) {const policy::Policy broken = policy::loadPolicyFile(dir + "/policy.json", "test", &messages);CHECK(broken.present && broken.broken && !messages.empty());CHECK(broken.ai == policy::Lock::Off && broken.network == policy::Lock::Off && broken.mcp == policy::Lock::Off);- CHECK(!broken.mcpLiveAllowed && broken.updateCheck == policy::Lock::Off);+ CHECK(!broken.mcpLiveAllowed && !broken.mayaLinkAllowed && broken.updateCheck == policy::Lock::Off);const policy::Policy missing = policy::loadPolicyFile(dir + "/none.json", "test");CHECK(missing.broken && missing.ai == policy::Lock::Off);std::ofstream(dir + "/good.json") << kFullPolicy;diff --git a/tests/ui/maya_live.sfui b/tests/ui/maya_live.sfuinew file mode 100644index 00000000..3b0ae960--- /dev/null+++ b/tests/ui/maya_live.sfui@@ -0,0 +1,94 @@+# Maya Live (File > Maya > Live, #42): off until turned on; then a stroke's Part goes to the exchange folder by+# itself once the scene is still (300 ms), and only the changed Part. The Live link (File > Maya > Live link...):+# a warning every time it is turned on (Cancel leaves it off), then the ember "Live link on" chip in the top bar,+# the pairing code in the menu, and one click on the chip turns it off.+run ui_look look=classic layout=classic+run new_sphere subdivisions=3+copy data/maya/send1 sf_ui_maya_live/maya_to_sculptforge+choose_file maya_folder sf_ui_maya_live+wait 0.3+expect_value maya_live == 0++click "File##palette.file"+hover "Maya"+wait 0.2+expect "Live##maya"+expect "Live link...##maya"+hold ctrl+hover "Live##maya"+expect_help "after each stroke"+hold none+shot menu_live_off+click "Live##maya"+expect_value maya_live == 1+expect_value maya_get_auto == 1+expect_status "Maya Live on"++# A stroke: once it ends and the scene is still, the Part goes to Maya by itself.+stroke 0.3 0.5 0.7 0.5+wait_value maya_live_sends >= 1 10+expect_status "Live: sent 1 object to Maya"+click "File##palette.file"+hover "Maya"+wait 0.2+shot menu_live_on+key escape+key escape++# The Live link: asks first, every time.+click "File##palette.file"+hover "Maya"+wait 0.2+click "Live link...##maya"+wait 0.3+expect "Turn on##mayalink"+expect_text It opens a connection on this computer.+shot link_warning+click "Cancel##mayalink"+wait 0.2+expect_value maya_link == 0+expect_not "Live link on##mayalink.chip"+click "File##palette.file"+hover "Maya"+wait 0.2+click "Live link...##maya"+wait 0.3+click "Turn on##mayalink"+wait 0.3+expect_value maya_link == 1+expect_value maya_link_connected == 0+expect "Live link on##mayalink.chip"+shot link_chip+click "File##palette.file"+hover "Maya"+wait 0.2+expect_text Live link on: waiting for Maya+expect_text Pairing code:+expect "Copy pairing code##maya"+shot link_menu+key escape+key escape++# The chip turns it off.+click "Live link on##mayalink.chip"+wait 0.2+expect_value maya_link == 0+expect_status "Maya Live link off"+expect_not "Live link on##mayalink.chip"++# The Forge look's status bar shows the chip too (turned on in the Classic look's menu, then the look switched).+click "File##palette.file"+hover "Maya"+wait 0.2+click "Live link...##maya"+wait 0.3+click "Turn on##mayalink"+wait 0.3+run ui_look look=forge layout=sculptforge+wait 0.3+expect "Live link on##mayalink.chip"+shot forge_link_chip+click "Live link on##mayalink.chip"+wait 0.2+expect_value maya_link == 0+expect_not "Live link on##mayalink.chip"