Skip to content

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

Facial shapes core: ICT-FaceKit template (MIT), fit, deformation transfer, 52 ARKit layers, face_weights fast path, takes, glTF/USD animation, Blender shape keys

islandmed87ce709581c0
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 79828697..84e17efc 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -98,6 +98,13 @@ add_library(sculptforge_core STATIC
src/io/BlenderCommands.cpp
src/io/StlIO.cpp
)
+# Facial shapes (core/Face.h): the template head with the 52 ARKit shapes, built from ICT-FaceKit (MIT) by
+# tools/face/build_ict_template.py, embedded so the app, the CLI and the tests all have it.
+include(cmake/EmbedFile.cmake)
+embed_files(${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFace.cpp sf::assets
+ faceTemplateData ${CMAKE_CURRENT_SOURCE_DIR}/assets/face/ict-arkit.sfface)
+target_sources(sculptforge_core PRIVATE src/core/Face.cpp src/core/FaceCommands.cpp
+ ${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFace.cpp)
target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace third_party/tinyexr)
# Third-party C code: compile quietly.
if(MSVC)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 708ea4f1..7f01c6fd 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -17,6 +17,7 @@ licenses require.
| [tinyexr](https://github.com/syoyo/tinyexr) | 1.0.13 | BSD 3-Clause License (includes OpenEXR code under the OpenEXR BSD licence) | OpenEXR reading and writing for vector displacement maps (Brush > Vector Displacement). Vendored in third_party/tinyexr; uses stb's zlib. |
| [Instant Meshes](https://github.com/wjakob/instant-meshes) | formulas only, nothing vendored | BSD 3-Clause License | QRemesh (Tool > Geometry): the field formulas in src/core/QRemesh.cpp (extrinsic 4-RoSy orientation / position compatibility, the middle point of two tangent planes, lattice rounding) follow its reference code. The rest of QRemesh is our own. |
| [Inter typeface](https://github.com/rsms/inter) | 4.1 | SIL Open Font License 1.1 | User interface font, embedded in the desktop app. Vendored in assets/fonts. |
+| [ICT-FaceKit](https://github.com/ICT-VGL/ICT-FaceKit) (ICT Face Model Light) | commit on master, 2020 | MIT License | The template head of Generate Facial Shapes (Tool > Facial Shapes): its neutral skin, mouth and eye sockets and its 53 ARKit-style expression shapes, converted by tools/face/build_ict_template.py into assets/face/ict-arkit.sfface (embedded). Not the separately licensed full ICT Face Model. |
| [libcurl](https://curl.se) | system library | curl License (MIT/X derivate) | HTTPS for optional AI features on Linux and macOS. Linked dynamically from the operating system; Windows uses the built-in WinHTTP instead. |
SculptForge does not include, bundle or redistribute any AI model. The optional AI features connect
@@ -588,3 +589,36 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
+
+---
+
+## ICT-FaceKit
+
+https://github.com/ICT-VGL/ICT-FaceKit — MIT License. The "ICT Face Model Light" (the repository's FaceXModel
+meshes) is released under this licence; SculptForge uses its neutral mesh and expression shapes as the template
+head for Generate Facial Shapes (assets/face/ict-arkit.sfface, see assets/face/README.md). Core contributors:
+Kalle Bladin, Owen Ingraham, Yajie Zhao, Pratusha Prasad, Xinglei Ren, Bipin Kishore, Marcel Ramos.
+
+```
+MIT License
+
+Copyright (c) 2020 USC Institute for Creative Technologies
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
diff --git a/addons/blender/sculptforge_bridge/__init__.py b/addons/blender/sculptforge_bridge/__init__.py
index 05ab42f4..5552a417 100644
--- a/addons/blender/sculptforge_bridge/__init__.py
+++ b/addons/blender/sculptforge_bridge/__init__.py
@@ -212,6 +212,32 @@ def update_object(obj, g):
return result
+def apply_shapes(obj, path):
+ """Shape keys from a SculptForge shapes file (exchange.read_shapes) on a received object: a Basis, then one
+ key per sculpt layer, named as in SculptForge (the facial shapes keep their ARKit names), at its weight."""
+ try:
+ nv, shapes = exchange.read_shapes(path)
+ except (OSError, ValueError):
+ return 0 # the mesh still arrives, without its shape keys
+ me = obj.data
+ if nv != len(me.vertices) or not shapes:
+ return 0
+ if me.shape_keys is None:
+ obj.shape_key_add(name="Basis", from_mix=False)
+ basis = np.empty(nv * 3, dtype=np.float64)
+ me.shape_keys.reference_key.data.foreach_get("co", basis)
+ basis = basis.reshape(-1, 3)
+ to_local = np.linalg.inv(np.array(obj.matrix_world, dtype=np.float64))[:3, :3]
+ for name, weight, idx, off in shapes:
+ key = me.shape_keys.key_blocks.get(name) or obj.shape_key_add(name=name, from_mix=False)
+ co = basis.copy()
+ co[idx] += off @ to_local.T # offsets are world-space vectors
+ key.data.foreach_set("co", np.ascontiguousarray(co, dtype=np.float32).ravel())
+ key.value = max(key.slider_min, min(key.slider_max, weight))
+ me.update()
+ return len(shapes)
+
+
def new_object(context, name, g):
me = bpy.data.meshes.new(name)
loops = set_geometry(me, g.positions, g.faces)
@@ -355,7 +381,8 @@ def receive(context):
meshes = []
for entry in entries:
try:
- meshes.append((entry.get("name") or "Object", exchange.read_goz(os.path.join(folder, entry["file"]))))
+ meshes.append((entry.get("name") or "Object", exchange.read_goz(os.path.join(folder, entry["file"])),
+ os.path.join(folder, entry["shapes"]) if entry.get("shapes") else None))
except (OSError, ValueError) as e:
return "ERROR", "Cannot read %s from SculptForge: %s" % (entry.get("name", "?"), e)
@@ -365,16 +392,21 @@ def receive(context):
counts = {"updated": 0, "rebuilt": 0, "new": 0}
disabled = 0
+ keys = 0
previous = context.mode
try:
- with _object_mode(context, [target(n) for n, _ in meshes]): # back to the previous mode afterwards
- for name, g in meshes:
+ with _object_mode(context, [target(n) for n, _, _ in meshes]): # back to the previous mode afterwards
+ for name, g, shapes in meshes:
obj = target(name)
if obj is None:
- new_object(context, name, g)
+ obj = new_object(context, name, g)
counts["new"] += 1
+ if shapes:
+ keys += apply_shapes(obj, shapes)
continue
counts[update_object(obj, g)] += 1
+ if shapes:
+ keys += apply_shapes(obj, shapes)
applied = obj.get(APPLIED_KEY)
if applied is not None: # those modifiers are in the mesh now
for m in obj.modifiers:
@@ -394,6 +426,8 @@ def receive(context):
message = "Received %d object%s from SculptForge (%s)" % (len(meshes), "" if len(meshes) == 1 else "s", ", ".join(parts))
if disabled:
message += "; turned off %d modifier%s applied when sending" % (disabled, "" if disabled == 1 else "s")
+ if keys:
+ message += "; %d shape key%s" % (keys, "" if keys == 1 else "s")
return "INFO", message
diff --git a/addons/blender/sculptforge_bridge/exchange.py b/addons/blender/sculptforge_bridge/exchange.py
index ed527ebb..4110e9e9 100644
--- a/addons/blender/sculptforge_bridge/exchange.py
+++ b/addons/blender/sculptforge_bridge/exchange.py
@@ -378,6 +378,39 @@ def read_goz(path):
return out
+def read_shapes(path):
+ """A SculptForge blend shapes file (an object's sculpt layers, e.g. the 52 ARKit facial shapes): a list of
+ (name, weight, indices, offsets) with offsets (N, 3) in Blender's axes, world space, and the vertex count.
+ The object's .GoZ then holds the base shape (every layer at zero)."""
+ with open(path, "rb") as f:
+ data = f.read()
+ if len(data) < 20 or data[:8] != b"SFSHAPES":
+ raise ValueError("Not a SculptForge shapes file: %s" % path)
+ version, nv, count = struct.unpack_from("<III", data, 8)
+ if version != 1:
+ raise ValueError("The shapes file is from a newer SculptForge; update the add-on")
+ pos = 20
+ shapes = []
+ for _ in range(count):
+ if pos + 4 > len(data):
+ raise ValueError("Truncated shapes file: %s" % path)
+ (n,) = struct.unpack_from("<I", data, pos)
+ name = data[pos + 4:pos + 4 + n].decode("utf-8", "replace")
+ pos += 4 + n
+ weight, k = struct.unpack_from("<fI", data, pos)
+ pos += 8
+ if k > nv or pos + 16 * k > len(data):
+ raise ValueError("Truncated shapes file: %s" % path)
+ idx = np.frombuffer(data, dtype="<u4", count=k, offset=pos).astype(np.int64)
+ pos += 4 * k
+ off = np.frombuffer(data, dtype="<f4", count=3 * k, offset=pos).reshape(-1, 3).astype(np.float64)
+ pos += 12 * k
+ if k and idx.max() >= nv:
+ raise ValueError("The shapes file has bad vertex indices: %s" % path)
+ shapes.append((name, float(weight), idx, off))
+ return nv, shapes
+
+
# --------------------------------------------------------------------------------------------------
# SculptForge: running? installed where? start it
# --------------------------------------------------------------------------------------------------
diff --git a/assets/face/README.md b/assets/face/README.md
new file mode 100644
index 00000000..8a7b027f
--- /dev/null
+++ b/assets/face/README.md
@@ -0,0 +1,19 @@
+# Face template
+
+`ict-arkit.sfface` is the template head Generate Facial Shapes (Tool > Facial Shapes, `face_shapes_generate`,
+src/core/Face.h) fits to a sculpt. It is embedded into the program at build time.
+
+| File | Source | Licence |
+|---|---|---|
+| `ict-arkit.sfface` | The "ICT Face Model Light" of [ICT-FaceKit](https://github.com/ICT-VGL/ICT-FaceKit) by the USC Institute for Creative Technologies Vision and Graphics Lab: `FaceXModel/generic_neutral_mesh.obj` (vertices 0-14061: face, head and neck, mouth socket, eye sockets) and the expression OBJs, converted by `tools/face/build_ict_template.py` | [MIT](https://github.com/ICT-VGL/ICT-FaceKit/blob/master/LICENSE), Copyright (c) 2020 USC Institute for Creative Technologies (full text in THIRD_PARTY_NOTICES.md) |
+
+What changed from ICT's data: the 52 shapes carry Apple ARKit's names (ICT's `_L` / `_R` become `Left` / `Right`,
+the character's own sides), ICT's separate `browInnerUp_L/_R` and `cheekPuff_L/_R` are summed into ARKit's single
+`browInnerUp` and `cheekPuff`, `cheekRaiser_L/_R` and `PupilDilate_L/_R` (not ARKit shapes) are left out, and
+`tongueOut`, which ICT doesn't have, is a quarter of `jawOpen` (a tongue SubTool gets the tongue's motion).
+Offsets under 0.02 mm are dropped and the rest quantised to 16 bits; the teeth are kept only as the lower jaw's
+rigid motion per shape. ICT's 100 identity (PCA) shapes are not used. The separately licensed full ICT Face Model
+is not used either.
+
+To rebuild: download ICT-FaceKit's `FaceXModel` folder, then
+`python3 tools/face/build_ict_template.py <ICT-FaceKit>/FaceXModel assets/face/ict-arkit.sfface`.
diff --git a/assets/face/ict-arkit.sfface b/assets/face/ict-arkit.sfface
new file mode 100644
index 00000000..21083b4d
Binary files /dev/null and b/assets/face/ict-arkit.sfface differ
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 883725ae..31180abd 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -9,6 +9,7 @@
#include "core/Decimate.h"
#include "core/Dyntopo.h"
#include "core/EnginePresets.h"
+#include "core/Face.h"
#include "core/ImageTo3D.h"
#include "core/Masking.h"
#include "core/Multires.h"
@@ -380,15 +381,18 @@ CommandRegistry::CommandRegistry() {
add({"export_glb",
"Export a game-ready binary glTF (.glb), one node and mesh per visible SubTool. Sculpt layers become "
- "morph targets (blend shapes). UVs are kept and SubTool textures are embedded.",
+ "morph targets (blend shapes). UVs are kept and SubTool textures are embedded. A baked face take "
+ "(face_take_bake) becomes an animation of the morph target weights.",
{{"path", T::String, "Output .glb path (UTF-8).", true}},
[](Document& doc, const Args& a) -> CommandResult {
std::string path = argString(a, "path");
std::string err;
const auto objects = visibleSubtoolObjects(doc);
if (objects.empty()) return {false, "Nothing visible to export"};
- if (!saveGlb(path, objects, doc.assetName(), err)) return {false, err};
- return {true, "Exported " + path + objectCountText(objects)};
+ MorphAnimation take;
+ const bool animated = bakedFaceAnimation(doc, take);
+ if (!saveGlb(path, objects, doc.assetName(), err, animated ? &take : nullptr)) return {false, err};
+ return {true, "Exported " + path + objectCountText(objects) + (animated ? " with the take '" + take.name + "'" : "")};
}});
add({"export_usd",
@@ -396,7 +400,8 @@ CommandRegistry::CommandRegistry() {
"SubTool. Sculpt layers become "
"UsdSkel blend shapes with their current weights; loaded Gaussian splats are included as a "
"ParticleField3DGaussianSplat prim. UVs are kept; a SubTool's texture becomes a UsdPreviewSurface texture "
- "(packed into .usdz, else a PNG beside the file).",
+ "(packed into .usdz, else a PNG beside the file). A baked face take (face_take_bake) becomes time samples "
+ "of the blend shape weights.",
{{"path", T::String, "Output .usda, .usd or .usdz path (UTF-8).", true},
{"splats", T::Bool, "Include the loaded Gaussian splats. Default true.", false}},
[](Document& doc, const Args& a) -> CommandResult {
@@ -404,9 +409,12 @@ CommandRegistry::CommandRegistry() {
std::string err;
const SplatCloud* splats = argBool(a, "splats", true) && !doc.splats.empty() ? &doc.splats : nullptr;
const auto objects = visibleSubtoolObjects(doc);
- if (!saveUsd(path, objects, splats, doc.assetName(), err)) return {false, err};
+ MorphAnimation take;
+ const bool animated = bakedFaceAnimation(doc, take);
+ if (!saveUsd(path, objects, splats, doc.assetName(), err, animated ? &take : nullptr)) return {false, err};
return {true, "Exported " + path + objectCountText(objects) +
- (splats ? " (mesh + " + std::to_string(splats->size()) + " splats)" : "")};
+ (splats ? " (mesh + " + std::to_string(splats->size()) + " splats)" : "") +
+ (animated ? " with the take '" + take.name + "'" : "")};
}});
add({"export_fbx",
@@ -783,6 +791,7 @@ CommandRegistry::CommandRegistry() {
registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
registerBlenderCommands(*this); // blender_send/receive (io/BlenderCommands.cpp)
registerBakeCommands(*this); // bake (core/Bake.cpp)
+ registerFaceCommands(*this); // face_shapes_generate, face_weights, ... (core/FaceCommands.cpp)
registerProjectCommands(*this); // keep last (core/Project.cpp)
}
diff --git a/src/core/Face.cpp b/src/core/Face.cpp
new file mode 100644
index 00000000..98c3118f
--- /dev/null
+++ b/src/core/Face.cpp
@@ -0,0 +1,1420 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Face.h"
+
+#include "core/Document.h"
+#include "core/Multires.h"
+#include "core/SurfaceQuery.h"
+#include "core/ThreadPool.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <mutex>
+#include <sstream>
+#include <unordered_map>
+
+namespace sf::assets {
+extern const unsigned char faceTemplateData[];
+extern const unsigned long long faceTemplateData_size;
+} // namespace sf::assets
+
+namespace sf {
+
+// ---------------------------------------------------------------------------
+// Names
+// ---------------------------------------------------------------------------
+
+const std::vector<std::string>& arkitBlendShapeNames() {
+ static const std::vector<std::string> names = {
+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight",
+ "cheekPuff", "cheekSquintLeft", "cheekSquintRight", "eyeBlinkLeft", "eyeBlinkRight",
+ "eyeLookDownLeft", "eyeLookDownRight", "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft",
+ "eyeLookOutRight", "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",
+ "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",
+ "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight", "mouthFrownLeft",
+ "mouthFrownRight", "mouthFunnel", "mouthLeft", "mouthLowerDownLeft", "mouthLowerDownRight",
+ "mouthPressLeft", "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower",
+ "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft", "mouthSmileRight",
+ "mouthStretchLeft", "mouthStretchRight", "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft",
+ "noseSneerRight", "tongueOut"};
+ return names;
+}
+
+int arkitBlendShapeIndex(std::string_view name) {
+ const auto& n = arkitBlendShapeNames();
+ for (size_t i = 0; i < n.size(); ++i)
+ if (n[i] == name) return int(i);
+ return -1;
+}
+
+std::string arkitMirrorName(std::string_view name) {
+ auto swapSuffix = [&](std::string_view from, std::string_view to) -> std::string {
+ return std::string(name.substr(0, name.size() - from.size())) + std::string(to);
+ };
+ if (name.ends_with("Left")) return swapSuffix("Left", "Right");
+ if (name.ends_with("Right")) return swapSuffix("Right", "Left");
+ return std::string(name);
+}
+
+// ---------------------------------------------------------------------------
+// Template
+// ---------------------------------------------------------------------------
+
+namespace {
+
+struct Reader {
+ const uint8_t* p;
+ const uint8_t* end;
+ bool ok = true;
+ template <class T> T get() {
+ T v{};
+ if (size_t(end - p) < sizeof(T)) {
+ ok = false;
+ return v;
+ }
+ std::memcpy(&v, p, sizeof(T)); // the file is little endian, like every platform SculptForge builds for
+ p += sizeof(T);
+ return v;
+ }
+};
+
+} // namespace
+
+bool parseFaceTemplate(const uint8_t* data, size_t size, FaceTemplate& out, std::string& error) {
+ Reader r{data, data + size};
+ if (size < 8 || std::memcmp(data, "SFFACE01", 8) != 0) {
+ error = "Not a SculptForge face template";
+ return false;
+ }
+ r.p += 8;
+ const uint32_t nv = r.get<uint32_t>(), nt = r.get<uint32_t>(), ns = r.get<uint32_t>();
+ FaceTemplate t;
+ t.faceEnd = r.get<uint32_t>();
+ t.skinEnd = r.get<uint32_t>();
+ t.mouthEnd = r.get<uint32_t>();
+ const uint32_t eyesEnd = r.get<uint32_t>();
+ if (!r.ok || nv == 0 || nv > 65536 || eyesEnd != nv || t.faceEnd > t.skinEnd || t.skinEnd > t.mouthEnd ||
+ t.mouthEnd > nv || ns > 256) {
+ error = "Bad face template header";
+ return false;
+ }
+ t.neutral.resize(nv);
+ for (auto& p : t.neutral) p = {r.get<float>(), r.get<float>(), r.get<float>()};
+ t.triangles.resize(nt);
+ for (auto& tri : t.triangles) {
+ tri = {r.get<uint16_t>(), r.get<uint16_t>(), r.get<uint16_t>()};
+ if (tri.x >= nv || tri.y >= nv || tri.z >= nv) r.ok = false;
+ }
+ t.lowerTeethCentroid = {r.get<float>(), r.get<float>(), r.get<float>()};
+ t.upperTeethY = r.get<float>();
+ for (uint32_t s = 0; s < ns && r.ok; ++s) {
+ FaceTemplate::Shape shape;
+ const uint8_t len = r.get<uint8_t>();
+ if (size_t(r.end - r.p) < len) {
+ r.ok = false;
+ break;
+ }
+ shape.name.assign(reinterpret_cast<const char*>(r.p), len);
+ r.p += len;
+ const float step = r.get<float>();
+ const float qx = r.get<float>(), qy = r.get<float>(), qz = r.get<float>(), qw = r.get<float>();
+ shape.jawRotation = glm::quat(qw, qx, qy, qz);
+ shape.jawTranslation = {r.get<float>(), r.get<float>(), r.get<float>()};
+ const uint32_t count = r.get<uint32_t>();
+ if (count > nv) {
+ r.ok = false;
+ break;
+ }
+ shape.index.resize(count);
+ for (auto& i : shape.index) {
+ i = r.get<uint16_t>();
+ if (i >= nv) r.ok = false;
+ }
+ shape.offset.resize(count);
+ for (auto& o : shape.offset) o = step * glm::vec3(float(r.get<int16_t>()), float(r.get<int16_t>()), float(r.get<int16_t>()));
+ t.shapes.push_back(std::move(shape));
+ }
+ if (!r.ok) {
+ error = "Truncated or corrupt face template";
+ return false;
+ }
+ out = std::move(t);
+ return true;
+}
+
+namespace {
+
+// The template with what the fit and the transfer need: adjacency weights (per vertex pair, the number of
+// triangles sharing the edge) as CSR, and the triangles around each vertex.
+struct TemplateData {
+ FaceTemplate t;
+ std::vector<uint32_t> rowStart, col; // neighbours
+ std::vector<float> weight;
+ std::vector<float> degree; // sum of the row's weights
+ std::vector<uint32_t> triStart, triList; // triangles around each vertex
+};
+
+const TemplateData& templateData() {
+ static const TemplateData data = [] {
+ TemplateData d;
+ std::string error;
+ if (!parseFaceTemplate(assets::faceTemplateData, size_t(assets::faceTemplateData_size), d.t, error)) return d;
+ const size_t nv = d.t.neutral.size();
+ std::vector<std::vector<std::pair<uint32_t, float>>> rows(nv);
+ std::vector<std::vector<uint32_t>> tris(nv);
+ auto add = [&](uint32_t i, uint32_t j) {
+ for (auto& [c, w] : rows[i])
+ if (c == j) {
+ w += 1.0f;
+ return;
+ }
+ rows[i].push_back({j, 1.0f});
+ };
+ for (uint32_t ti = 0; ti < d.t.triangles.size(); ++ti) {
+ const glm::uvec3 tri = d.t.triangles[ti];
+ for (int a = 0; a < 3; ++a) {
+ tris[tri[a]].push_back(ti);
+ for (int b = 0; b < 3; ++b)
+ if (a != b) add(tri[a], tri[b]);
+ }
+ }
+ d.rowStart.push_back(0);
+ d.triStart.push_back(0);
+ for (size_t i = 0; i < nv; ++i) {
+ std::sort(rows[i].begin(), rows[i].end());
+ float deg = 0.0f;
+ for (auto [c, w] : rows[i]) {
+ d.col.push_back(c);
+ d.weight.push_back(w);
+ deg += w;
+ }
+ d.degree.push_back(deg);
+ d.rowStart.push_back(uint32_t(d.col.size()));
+ d.triList.insert(d.triList.end(), tris[i].begin(), tris[i].end());
+ d.triStart.push_back(uint32_t(d.triList.size()));
+ }
+ return d;
+ }();
+ return data;
+}
+
+} // namespace
+
+const FaceTemplate& faceTemplate() { return templateData().t; }
+
+// ---------------------------------------------------------------------------
+// Landmarks
+// ---------------------------------------------------------------------------
+
+namespace {
+struct LandmarkInfo {
+ const char* key;
+ const char* label;
+ uint32_t vertex; // ICT-FaceKit vertex (its Multi-PIE 68 list: 36, 39, 42, 45, nose tip, 48, 54, 8)
+};
+constexpr LandmarkInfo kLandmarks[kFaceLandmarkCount] = {
+ {"eye_outer_right", "Right eye, outer corner", 1507}, {"eye_inner_right", "Right eye, inner corner", 1528},
+ {"eye_inner_left", "Left eye, inner corner", 3742}, {"eye_outer_left", "Left eye, outer corner", 3721},
+ {"nose_tip", "Nose tip", 4841}, {"mouth_right", "Mouth, right corner", 5708},
+ {"mouth_left", "Mouth, left corner", 6213}, {"chin", "Chin (front, lowest point)", 966},
+};
+} // namespace
+
+const char* faceLandmarkKey(int i) { return i >= 0 && i < kFaceLandmarkCount ? kLandmarks[i].key : ""; }
+const char* faceLandmarkLabel(int i) { return i >= 0 && i < kFaceLandmarkCount ? kLandmarks[i].label : ""; }
+uint32_t faceLandmarkVertex(int i) { return i >= 0 && i < kFaceLandmarkCount ? kLandmarks[i].vertex : 0; }
+
+int FaceLandmarks::count() const { return int(std::count(set.begin(), set.end(), true)); }
+
+Json FaceLandmarks::toJson() const {
+ Json j = Json::object();
+ for (int i = 0; i < kFaceLandmarkCount; ++i) {
+ if (!set[size_t(i)]) continue;
+ Json p = Json::array();
+ for (int k = 0; k < 3; ++k) p.push(double(position[size_t(i)][k]));
+ j.set(kLandmarks[i].key, std::move(p));
+ }
+ return j;
+}
+
+bool FaceLandmarks::fromJson(const Json& j, FaceLandmarks& out, std::string& error) {
+ FaceLandmarks l;
+ if (!j.isObject()) {
+ error = "Landmarks must be a JSON object like {\"nose_tip\":[0,1.6,0.1]}";
+ return false;
+ }
+ for (const auto& [key, value] : j.members()) {
+ int index = -1;
+ for (int i = 0; i < kFaceLandmarkCount; ++i)
+ if (key == kLandmarks[i].key) index = i;
+ if (index < 0) {
+ error = "Unknown landmark '" + key + "' (eye_outer_right, eye_inner_right, eye_inner_left, eye_outer_left, "
+ "nose_tip, mouth_right, mouth_left, chin)";
+ return false;
+ }
+ if (!value.isArray() || value.size() != 3 || !value[0].isNumber() || !value[1].isNumber() || !value[2].isNumber()) {
+ error = "Landmark '" + key + "' must be [x, y, z]";
+ return false;
+ }
+ l.position[size_t(index)] = {float(value[0].asNumber()), float(value[1].asNumber()), float(value[2].asNumber())};
+ l.set[size_t(index)] = true;
+ }
+ out = l;
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Small linear algebra
+// ---------------------------------------------------------------------------
+
+namespace {
+
+// Eigen decomposition of a symmetric 4x4 matrix (cyclic Jacobi): the eigenvector of the largest eigenvalue.
+glm::dvec4 largestEigenvector(double a[4][4]) {
+ double v[4][4] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
+ for (int sweep = 0; sweep < 50; ++sweep) {
+ double off = 0.0;
+ for (int p = 0; p < 4; ++p)
+ for (int q = p + 1; q < 4; ++q) off += a[p][q] * a[p][q];
+ if (off < 1e-30) break;
+ for (int p = 0; p < 4; ++p)
+ for (int q = p + 1; q < 4; ++q) {
+ if (std::abs(a[p][q]) < 1e-300) continue;
+ const double theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
+ const double t = (theta >= 0 ? 1.0 : -1.0) / (std::abs(theta) + std::sqrt(theta * theta + 1.0));
+ const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c;
+ for (int k = 0; k < 4; ++k) { // A = J^T A J
+ const double akp = a[k][p], akq = a[k][q];
+ a[k][p] = c * akp - s * akq;
+ a[k][q] = s * akp + c * akq;
+ }
+ for (int k = 0; k < 4; ++k) {
+ const double apk = a[p][k], aqk = a[q][k];
+ a[p][k] = c * apk - s * aqk;
+ a[q][k] = s * apk + c * aqk;
+ }
+ for (int k = 0; k < 4; ++k) {
+ const double vkp = v[k][p], vkq = v[k][q];
+ v[k][p] = c * vkp - s * vkq;
+ v[k][q] = s * vkp + c * vkq;
+ }
+ }
+ }
+ int best = 0;
+ for (int i = 1; i < 4; ++i)
+ if (a[i][i] > a[best][best]) best = i;
+ return {v[0][best], v[1][best], v[2][best], v[3][best]};
+}
+
+// Weighted least-squares similarity (or rigid, `withScale` false) taking src to dst (Horn's quaternion method).
+Similarity solveSimilarity(const std::vector<glm::vec3>& src, const std::vector<glm::vec3>& dst,
+ const std::vector<float>& w, bool withScale) {
+ Similarity s;
+ double wsum = 0.0;
+ glm::dvec3 cs(0.0), cd(0.0);
+ for (size_t i = 0; i < src.size(); ++i) {
+ wsum += w[i];
+ cs += double(w[i]) * glm::dvec3(src[i]);
+ cd += double(w[i]) * glm::dvec3(dst[i]);
+ }
+ if (wsum <= 0.0) return s;
+ cs /= wsum;
+ cd /= wsum;
+ double S[3][3] = {};
+ double ss = 0.0;
+ for (size_t i = 0; i < src.size(); ++i) {
+ const glm::dvec3 a = glm::dvec3(src[i]) - cs, b = glm::dvec3(dst[i]) - cd;
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c) S[r][c] += w[i] * a[r] * b[c];
+ ss += w[i] * glm::dot(a, a);
+ }
+ double N[4][4] = {
+ {S[0][0] + S[1][1] + S[2][2], S[1][2] - S[2][1], S[2][0] - S[0][2], S[0][1] - S[1][0]},
+ {S[1][2] - S[2][1], S[0][0] - S[1][1] - S[2][2], S[0][1] + S[1][0], S[2][0] + S[0][2]},
+ {S[2][0] - S[0][2], S[0][1] + S[1][0], -S[0][0] + S[1][1] - S[2][2], S[1][2] + S[2][1]},
+ {S[0][1] - S[1][0], S[2][0] + S[0][2], S[1][2] + S[2][1], -S[0][0] - S[1][1] + S[2][2]}};
+ const glm::dvec4 q = largestEigenvector(N); // (w, x, y, z)
+ const glm::dquat dq = glm::normalize(glm::dquat(q.x, q.y, q.z, q.w));
+ const glm::dmat3 R = glm::mat3_cast(dq);
+ double scale = 1.0;
+ if (withScale && ss > 1e-30) {
+ double num = 0.0;
+ for (size_t i = 0; i < src.size(); ++i)
+ num += w[i] * glm::dot(glm::dvec3(dst[i]) - cd, R * (glm::dvec3(src[i]) - cs));
+ scale = std::max(num / ss, 1e-9);
+ }
+ s.rotation = glm::mat3(R);
+ s.scale = float(scale);
+ s.translation = glm::vec3(cd - scale * (R * cs));
+ return s;
+}
+
+// Jacobi-preconditioned conjugate gradients on 3 right-hand sides at once (each converging on its own) for a
+// symmetric positive definite operator `apply(x, out)` with diagonal `diag`. `x` holds the start and receives the
+// solution. Serial and in a fixed order, so the result never depends on the thread count.
+template <class Apply>
+int solvePcg(const Apply& apply, const std::vector<double>& diag, const std::vector<glm::dvec3>& b,
+ std::vector<glm::dvec3>& x, double tolerance, int maxIterations) {
+ const size_t n = b.size();
+ std::vector<glm::dvec3> r(n), z(n), p(n), ap(n);
+ apply(x, ap);
+ glm::dvec3 bnorm(0.0), rz(0.0);
+ for (size_t i = 0; i < n; ++i) {
+ r[i] = b[i] - ap[i];
+ z[i] = r[i] / diag[i];
+ p[i] = z[i];
+ rz += r[i] * z[i];
+ bnorm += b[i] * b[i];
+ }
+ const glm::dvec3 limit = glm::max(bnorm, glm::dvec3(1e-30)) * (tolerance * tolerance);
+ int it = 0;
+ for (; it < maxIterations; ++it) {
+ glm::dvec3 rr(0.0);
+ for (size_t i = 0; i < n; ++i) rr += r[i] * r[i];
+ if (rr.x <= limit.x && rr.y <= limit.y && rr.z <= limit.z) break;
+ apply(p, ap);
+ glm::dvec3 pap(0.0);
+ for (size_t i = 0; i < n; ++i) pap += p[i] * ap[i];
+ glm::dvec3 alpha(0.0);
+ for (int k = 0; k < 3; ++k) alpha[k] = pap[k] > 1e-300 ? rz[k] / pap[k] : 0.0;
+ glm::dvec3 rzNew(0.0);
+ for (size_t i = 0; i < n; ++i) {
+ x[i] += alpha * p[i];
+ r[i] -= alpha * ap[i];
+ z[i] = r[i] / diag[i];
+ rzNew += r[i] * z[i];
+ }
+ glm::dvec3 beta(0.0);
+ for (int k = 0; k < 3; ++k) beta[k] = rz[k] > 1e-300 ? rzNew[k] / rz[k] : 0.0;
+ rz = rzNew;
+ for (size_t i = 0; i < n; ++i) p[i] = z[i] + beta * p[i];
+ }
+ return it;
+}
+
+std::vector<glm::vec3> vertexNormals(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris) {
+ std::vector<glm::vec3> n(pos.size(), glm::vec3(0.0f));
+ for (const auto& t : tris) {
+ const glm::vec3 f = glm::cross(pos[t.y] - pos[t.x], pos[t.z] - pos[t.x]);
+ n[t.x] += f;
+ n[t.y] += f;
+ n[t.z] += f;
+ }
+ for (auto& v : n) {
+ const float l = glm::length(v);
+ v = l > 1e-20f ? v / l : glm::vec3(0.0f);
+ }
+ return n;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// Fit
+// ---------------------------------------------------------------------------
+
+namespace {
+
+struct Correspondences {
+ std::vector<glm::vec3> target;
+ std::vector<float> weight; // 0 = none
+};
+
+// Closest points on the sculpt for template vertices [0, end) (every `stride`-th), accepted within `maxDist` and
+// when the sculpt faces the same way (dot of normals > minDot).
+void findCorrespondences(const TriangleBVH& sculpt, const std::vector<glm::vec3>& pos, const std::vector<glm::vec3>& nrm,
+ uint32_t end, uint32_t stride, float maxDist, float minDot, Correspondences& out) {
+ out.target.assign(pos.size(), glm::vec3(0.0f));
+ out.weight.assign(pos.size(), 0.0f);
+ poolFor(end, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ if (i % stride) continue;
+ SurfaceHit hit;
+ if (!sculpt.closestPoint(pos[i], maxDist, hit)) continue;
+ const glm::vec3 fn = sculpt.faceNormal(hit.prim);
+ if (glm::dot(fn, nrm[i]) < minDot) continue;
+ out.target[i] = hit.position;
+ out.weight[i] = 1.0f;
+ }
+ }, 512);
+}
+
+struct FitScore {
+ float rms = 0.0f; // template units (cm)
+ float coverage = 0.0f; // of the face vertices sampled
+};
+
+// Similarity ICP over the face vertices (every `stride`-th); returns the last iteration's score.
+FitScore similarityIcp(const TriangleBVH& sculpt, const FaceTemplate& t, const std::vector<glm::vec3>& templNormals,
+ const FaceLandmarks* landmarks, Similarity& align, int iterations, uint32_t stride) {
+ FitScore score;
+ std::vector<glm::vec3> pos(t.neutral.size()), nrm(t.neutral.size());
+ Correspondences c;
+ for (int it = 0; it < iterations; ++it) {
+ for (uint32_t i = 0; i < t.faceEnd; i += stride) {
+ pos[i] = align.apply(t.neutral[i]);
+ nrm[i] = align.rotation * templNormals[i];
+ }
+ const float maxDist = align.scale * glm::mix(4.0f, 1.0f, float(it) / float(std::max(iterations - 1, 1)));
+ findCorrespondences(sculpt, pos, nrm, t.faceEnd, stride, maxDist, 0.3f, c);
+ std::vector<glm::vec3> src, dst;
+ std::vector<float> w;
+ std::vector<float> dists;
+ for (uint32_t i = 0; i < t.faceEnd; i += stride)
+ if (c.weight[i] > 0.0f) dists.push_back(glm::distance(pos[i], c.target[i]));
+ size_t sampled = (t.faceEnd + stride - 1) / stride;
+ score.coverage = float(dists.size()) / float(std::max<size_t>(sampled, 1));
+ if (dists.size() < 30) {
+ score.rms = 1e9f;
+ return score;
+ }
+ // Trimmed: the closest 85% only.
+ std::vector<float> sorted = dists;
+ const size_t keep = std::max<size_t>(30, sorted.size() * 85 / 100);
+ std::nth_element(sorted.begin(), sorted.begin() + long(keep - 1), sorted.end());
+ const float cut = sorted[keep - 1];
+ double sq = 0.0;
+ size_t n = 0;
+ for (uint32_t i = 0; i < t.faceEnd; i += stride) {
+ if (c.weight[i] <= 0.0f) continue;
+ const float d = glm::distance(pos[i], c.target[i]);
+ if (d > cut) continue;
+ src.push_back(t.neutral[i]);
+ dst.push_back(c.target[i]);
+ w.push_back(1.0f);
+ sq += double(d) * d;
+ ++n;
+ }
+ score.rms = float(std::sqrt(sq / double(std::max<size_t>(n, 1)))) / align.scale;
+ if (landmarks) {
+ const float lw = float(n) * 0.04f; // all landmarks together weigh about a third of the surface
+ for (int l = 0; l < kFaceLandmarkCount; ++l)
+ if (landmarks->set[size_t(l)]) {
+ src.push_back(t.neutral[kLandmarks[l].vertex]);
+ dst.push_back(landmarks->position[size_t(l)]);
+ w.push_back(lw);
+ }
+ }
+ align = solveSimilarity(src, dst, w, true);
+ }
+ return score;
+}
+
+} // namespace
+
+bool fitFaceTemplate(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ const FaceLandmarks* landmarksIn, FaceFit& out, std::string& error) {
+ const TemplateData& td = templateData();
+ const FaceTemplate& t = td.t;
+ if (t.neutral.empty()) {
+ error = "The face template is missing from this build";
+ return false;
+ }
+ if (triangles.empty()) {
+ error = "The mesh is empty";
+ return false;
+ }
+ const FaceLandmarks* landmarks = landmarksIn && landmarksIn->count() >= 3 ? landmarksIn : nullptr;
+ if (landmarksIn && landmarksIn->count() > 0 && !landmarks) {
+ error = "Place at least 3 landmarks (or none, for the automatic fit)";
+ return false;
+ }
+ TriangleBVH sculpt;
+ sculpt.build(positions, triangles);
+ const std::vector<glm::vec3> templNormals = vertexNormals(t.neutral, t.triangles);
+
+ // --- 1. The similarity transform ---
+ Similarity align;
+ if (landmarks) {
+ std::vector<glm::vec3> src, dst;
+ std::vector<float> w;
+ for (int l = 0; l < kFaceLandmarkCount; ++l)
+ if (landmarks->set[size_t(l)]) {
+ src.push_back(t.neutral[kLandmarks[l].vertex]);
+ dst.push_back(landmarks->position[size_t(l)]);
+ w.push_back(1.0f);
+ }
+ align = solveSimilarity(src, dst, w, true);
+ similarityIcp(sculpt, t, templNormals, landmarks, align, 12, 3);
+ } else {
+ // Automatic: the head looks down +Z with Y up (SculptForge's front view). The nose tip is the most forward
+ // point near the middle, above the lower quarter; the scale comes from the nose tip to the top of the head.
+ AABB b;
+ for (const auto& tri : triangles)
+ for (int k = 0; k < 3; ++k) b.expand(positions[tri[k]]);
+ const glm::vec3 ext = b.extent();
+ const float cx = b.center().x;
+ int nose = -1;
+ for (const auto& tri : triangles)
+ for (int k = 0; k < 3; ++k) {
+ const glm::vec3& p = positions[tri[k]];
+ if (std::abs(p.x - cx) > 0.12f * ext.x || p.y < b.min.y + 0.25f * ext.y) continue;
+ if (nose < 0 || p.z > positions[size_t(nose)].z) nose = int(tri[k]);
+ }
+ if (nose < 0) {
+ error = "Couldn't find a nose: place landmarks";
+ return false;
+ }
+ const glm::vec3 noseTip = positions[size_t(nose)];
+ float templTop = -1e9f;
+ for (uint32_t i = 0; i < t.skinEnd; ++i) templTop = std::max(templTop, t.neutral[i].y);
+ const glm::vec3 templNose = t.neutral[kLandmarks[kNoseTip].vertex];
+ const float s0 = std::max(b.max.y - noseTip.y, 1e-6f) / (templTop - templNose.y);
+ // Hair, horns or a hat make the head look taller: try a few scales and keep the best fit.
+ float best = 1e30f;
+ for (float f : {0.6f, 0.75f, 0.9f, 1.0f}) {
+ Similarity s;
+ s.scale = s0 * f;
+ s.translation = noseTip - s.scale * templNose;
+ const FitScore score = similarityIcp(sculpt, t, templNormals, nullptr, s, 10, 4);
+ const float value = score.rms * (1.0f + 3.0f * (1.0f - score.coverage));
+ if (value < best) {
+ best = value;
+ align = s;
+ }
+ }
+ similarityIcp(sculpt, t, templNormals, nullptr, align, 10, 2);
+ }
+
+ // --- 2. Non-rigid ICP: displacement d of every template vertex, data term on the skin ---
+ const size_t nv = t.neutral.size();
+ std::vector<glm::vec3> start(nv), pos(nv);
+ for (size_t i = 0; i < nv; ++i) start[i] = align.apply(t.neutral[i]);
+ std::vector<glm::dvec3> d(nv, glm::dvec3(0.0));
+ Correspondences c;
+ const float s = align.scale;
+ struct Stage {
+ float alpha, maxDist;
+ };
+ // Stiffness from nearly rigid to loose; the search radius (template cm) shrinks with it.
+ const Stage stages[] = {{60.0f, 3.0f}, {25.0f, 2.5f}, {10.0f, 2.0f}, {5.0f, 1.5f},
+ {2.5f, 1.2f}, {1.2f, 1.0f}, {0.6f, 0.8f}, {0.35f, 0.7f}};
+ const double eps = 1e-6;
+ for (const Stage& stage : stages)
+ for (int inner = 0; inner < 2; ++inner) {
+ for (size_t i = 0; i < nv; ++i) pos[i] = start[i] + glm::vec3(d[i]);
+ const std::vector<glm::vec3> nrm = vertexNormals(pos, t.triangles);
+ findCorrespondences(sculpt, pos, nrm, t.skinEnd, 1, stage.maxDist * s, 0.5f, c);
+ std::vector<double> w(nv, 0.0), diag(nv);
+ std::vector<glm::dvec3> rhs(nv, glm::dvec3(0.0));
+ for (size_t i = 0; i < t.skinEnd; ++i)
+ if (c.weight[i] > 0.0f) {
+ w[i] = 1.0;
+ rhs[i] = glm::dvec3(c.target[i] - start[i]);
+ }
+ if (landmarks) {
+ const double lw = 20.0;
+ for (int l = 0; l < kFaceLandmarkCount; ++l)
+ if (landmarks->set[size_t(l)]) {
+ const uint32_t v = kLandmarks[l].vertex;
+ w[v] += lw;
+ rhs[v] += lw * glm::dvec3(landmarks->position[size_t(l)] - start[v]);
+ }
+ }
+ for (size_t i = 0; i < nv; ++i) {
+ rhs[i] += eps * d[i];
+ diag[i] = w[i] + double(stage.alpha) * td.degree[i] + eps;
+ }
+ const double alpha = stage.alpha;
+ auto apply = [&](const std::vector<glm::dvec3>& x, std::vector<glm::dvec3>& y) {
+ for (size_t i = 0; i < nv; ++i) {
+ glm::dvec3 acc = diag[i] * x[i];
+ for (uint32_t k = td.rowStart[i]; k < td.rowStart[i + 1]; ++k) acc -= alpha * td.weight[k] * x[td.col[k]];
+ y[i] = acc;
+ }
+ };
+ solvePcg(apply, diag, rhs, d, 1e-4, 400);
+ }
+ for (size_t i = 0; i < nv; ++i) pos[i] = start[i] + glm::vec3(d[i]);
+
+ // --- Quality: how close the face came, and how much of it found the sculpt ---
+ {
+ const std::vector<glm::vec3> nrm = vertexNormals(pos, t.triangles);
+ findCorrespondences(sculpt, pos, nrm, t.faceEnd, 1, 1.0f * s, 0.3f, c);
+ double sq = 0.0;
+ size_t n = 0;
+ for (uint32_t i = 0; i < t.faceEnd; ++i)
+ if (c.weight[i] > 0.0f) {
+ const double dd = glm::distance(pos[i], c.target[i]);
+ sq += dd * dd;
+ ++n;
+ }
+ out.rmsError = float(std::sqrt(sq / double(std::max<size_t>(n, 1))));
+ out.coverage = float(n) / float(std::max<uint32_t>(t.faceEnd, 1));
+ }
+ out.align = align;
+ out.positions = std::move(pos);
+ for (int l = 0; l < kFaceLandmarkCount; ++l) {
+ out.landmarks.position[size_t(l)] = out.positions[kLandmarks[l].vertex];
+ out.landmarks.set[size_t(l)] = true;
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Deformation transfer
+// ---------------------------------------------------------------------------
+
+namespace {
+
+glm::dmat3 triangleFrame(const glm::dvec3& a, const glm::dvec3& b, const glm::dvec3& c) {
+ const glm::dvec3 e1 = b - a, e2 = c - a, n = glm::cross(e1, e2);
+ const double len = glm::length(n);
+ return glm::dmat3(e1, e2, len > 1e-300 ? n / std::sqrt(len) : glm::dvec3(0.0));
+}
+
+} // namespace
+
+void transferFaceShapes(const FaceFit& fit, std::vector<std::vector<glm::vec3>>& offsets) {
+ const TemplateData& td = templateData();
+ const FaceTemplate& t = td.t;
+ const size_t nv = t.neutral.size(), ns = t.shapes.size();
+ offsets.assign(ns, std::vector<glm::vec3>(nv, glm::vec3(0.0f)));
+ if (fit.positions.size() != nv) return;
+ // The fitted template back in the template's frame (the similarity's rotation and scale undone).
+ std::vector<glm::dvec3> x(nv);
+ for (size_t i = 0; i < nv; ++i) x[i] = glm::dvec3(fit.align.inverse(fit.positions[i]));
+
+ poolFor(ns, [&](size_t sb, size_t se) {
+ for (size_t si = sb; si < se; ++si) {
+ const FaceTemplate::Shape& shape = t.shapes[si];
+ if (shape.index.empty()) continue;
+ std::vector<glm::dvec3> dense(nv, glm::dvec3(0.0));
+ std::vector<uint8_t> inRegion(nv, 0);
+ for (size_t k = 0; k < shape.index.size(); ++k) {
+ dense[shape.index[k]] = glm::dvec3(shape.offset[k]);
+ inRegion[shape.index[k]] = 1;
+ }
+ // The region solved for: the moved vertices and two rings around them; the rest stays put.
+ for (int ring = 0; ring < 2; ++ring) {
+ std::vector<uint8_t> grown = inRegion;
+ for (size_t i = 0; i < nv; ++i)
+ if (inRegion[i])
+ for (uint32_t k = td.rowStart[i]; k < td.rowStart[i + 1]; ++k) grown[td.col[k]] = 1;
+ inRegion.swap(grown);
+ }
+ std::vector<uint32_t> region, local(nv, ~0u);
+ for (uint32_t i = 0; i < nv; ++i)
+ if (inRegion[i]) {
+ local[i] = uint32_t(region.size());
+ region.push_back(i);
+ }
+ const size_t n = region.size();
+ // Right-hand side: per triangle, the source deformation gradient minus identity applied to the
+ // fitted template's edges.
+ std::vector<glm::dvec3> rhs(n, glm::dvec3(0.0)), u(n);
+ std::vector<uint8_t> triDone(t.triangles.size(), 0);
+ for (uint32_t i : region)
+ for (uint32_t k = td.triStart[i]; k < td.triStart[i + 1]; ++k) {
+ const uint32_t ti = td.triList[k];
+ if (triDone[ti]) continue;
+ triDone[ti] = 1;
+ const glm::uvec3 tri = t.triangles[ti];
+ const glm::dvec3 n0(t.neutral[tri.x]), n1(t.neutral[tri.y]), n2(t.neutral[tri.z]);
+ const glm::dmat3 vn = triangleFrame(n0, n1, n2);
+ const glm::dmat3 ve = triangleFrame(n0 + dense[tri.x], n1 + dense[tri.y], n2 + dense[tri.z]);
+ if (std::abs(glm::determinant(vn)) < 1e-18) continue;
+ const glm::dmat3 m = ve * glm::inverse(vn) - glm::dmat3(1.0);
+ for (int a = 0; a < 3; ++a) {
+ const uint32_t li = local[tri[a]];
+ if (li == ~0u) continue;
+ for (int bb = 0; bb < 3; ++bb)
+ if (a != bb) rhs[li] += m * (x[tri[a]] - x[tri[bb]]);
+ }
+ }
+ std::vector<double> diag(n);
+ for (size_t li = 0; li < n; ++li) {
+ diag[li] = td.degree[region[li]] + 1e-9;
+ u[li] = dense[region[li]]; // start from the template's own offsets
+ }
+ auto apply = [&](const std::vector<glm::dvec3>& xin, std::vector<glm::dvec3>& y) {
+ for (size_t li = 0; li < n; ++li) {
+ const uint32_t i = region[li];
+ glm::dvec3 acc = diag[li] * xin[li];
+ for (uint32_t k = td.rowStart[i]; k < td.rowStart[i + 1]; ++k) {
+ const uint32_t lj = local[td.col[k]];
+ if (lj != ~0u) acc -= double(td.weight[k]) * xin[lj];
+ }
+ y[li] = acc;
+ }
+ };
+ solvePcg(apply, diag, rhs, u, 1e-7, 3000);
+ for (size_t li = 0; li < n; ++li) offsets[si][region[li]] = fit.align.applyVector(glm::vec3(u[li]));
+ }
+ }, 1, 2);
+}
+
+// ---------------------------------------------------------------------------
+// Generate
+// ---------------------------------------------------------------------------
+
+namespace {
+
+std::string lower(std::string s) {
+ for (auto& ch : s) ch = char(std::tolower(static_cast<unsigned char>(ch)));
+ return s;
+}
+
+enum class PartKind { Skin, Eyes, Teeth, Tongue, Other };
+
+PartKind classifySubtool(const std::string& name) {
+ const std::string n = lower(name);
+ auto has = [&](const char* w) { return n.find(w) != std::string::npos; };
+ if (has("tongue")) return PartKind::Tongue;
+ if (has("teeth") || has("tooth") || has("gum") || has("jaw")) return PartKind::Teeth;
+ if (has("eye") && !has("lash") && !has("brow") && !has("lid")) return PartKind::Eyes;
+ return PartKind::Other;
+}
+
+// Where each vertex sits on the fitted template: its closest triangle, barycentric weights and a falloff weight
+// (1 near the template, 0 beyond `r1`).
+struct Binding {
+ std::vector<uint32_t> tri;
+ std::vector<glm::vec3> bary;
+ std::vector<float> weight;
+};
+
+Binding bindToTemplate(const std::vector<glm::vec3>& positions, const TriangleBVH& fitted, float r0, float r1) {
+ Binding b;
+ const size_t n = positions.size();
+ b.tri.assign(n, 0);
+ b.bary.assign(n, glm::vec3(0.0f));
+ b.weight.assign(n, 0.0f);
+ poolFor(n, [&](size_t lo, size_t hi) {
+ for (size_t v = lo; v < hi; ++v) {
+ SurfaceHit hit;
+ if (!fitted.closestPoint(positions[v], r1, hit)) continue;
+ b.tri[v] = hit.prim;
+ b.bary[v] = hit.bary;
+ b.weight[v] = hit.distance <= r0 ? 1.0f : std::clamp((r1 - hit.distance) / (r1 - r0), 0.0f, 1.0f);
+ const float w = b.weight[v];
+ b.weight[v] = w * w * (3.0f - 2.0f * w); // smoothstep
+ }
+ }, 4096);
+ return b;
+}
+
+std::vector<glm::vec3> boundOffsets(const Binding& b, const std::vector<glm::uvec3>& tris, const std::vector<glm::vec3>& off) {
+ std::vector<glm::vec3> out(b.weight.size(), glm::vec3(0.0f));
+ poolFor(out.size(), [&](size_t lo, size_t hi) {
+ for (size_t v = lo; v < hi; ++v) {
+ if (b.weight[v] <= 0.0f) continue;
+ const glm::uvec3 t = tris[b.tri[v]];
+ out[v] = b.weight[v] * (b.bary[v].x * off[t.x] + b.bary[v].y * off[t.y] + b.bary[v].z * off[t.z]);
+ }
+ }, 8192);
+ return out;
+}
+
+// The vertex nearest to each vertex's mirror image across X = 0, or ~0u when there is none within `tol`.
+std::vector<uint32_t> mirrorMap(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris, float tol) {
+ TriangleBVH bvh;
+ bvh.build(pos, tris);
+ std::vector<uint32_t> m(pos.size(), ~0u);
+ poolFor(pos.size(), [&](size_t lo, size_t hi) {
+ for (size_t v = lo; v < hi; ++v) {
+ const glm::vec3 q(-pos[v].x, pos[v].y, pos[v].z);
+ SurfaceHit hit;
+ if (!bvh.closestPoint(q, tol, hit)) continue;
+ const glm::uvec3 t = tris[hit.prim];
+ uint32_t best = t.x;
+ for (int k = 1; k < 3; ++k)
+ if (glm::distance(pos[t[k]], q) < glm::distance(pos[best], q)) best = t[k];
+ if (glm::distance(pos[best], q) <= tol) m[v] = best;
+ }
+ }, 4096);
+ return m;
+}
+
+void setNamedLayer(Mesh& m, const std::string& name, std::vector<glm::vec3> delta) {
+ for (auto& l : m.layers)
+ if (l.name == name) {
+ l.delta = std::move(delta);
+ l.weight = 0.0f;
+ return;
+ }
+ const int i = m.addLayer(name);
+ m.layers[size_t(i)].delta = std::move(delta);
+ m.layers[size_t(i)].weight = 0.0f;
+}
+
+bool nonZero(const std::vector<glm::vec3>& d) {
+ return std::any_of(d.begin(), d.end(), [](const glm::vec3& v) { return v != glm::vec3(0.0f); });
+}
+
+// The visible triangles of `m`.
+std::vector<glm::uvec3> visibleTriangles(const Mesh& m) {
+ std::vector<glm::uvec3> out;
+ out.reserve(m.triangleCount());
+ for (uint32_t t = 0; t < m.triangleCount(); ++t)
+ if (!m.triangleHidden(t)) out.push_back(m.triangles[t]);
+ return out;
+}
+
+// The subdivision level to make the shapes on: the lowest with at least kFaceMinVertices vertices (else the top).
+int faceLevel(const Mesh& m, int wanted) {
+ const int levels = subdivLevelCount(m);
+ if (levels == 0) return 0;
+ if (wanted >= 0) return std::min(wanted, levels - 1);
+ for (int l = 0; l < levels; ++l)
+ if (subdivLevelData(m, l).positions.size() >= kFaceMinVertices) return l;
+ return levels - 1;
+}
+
+// Rigid motions in the template frame, applied to sculpt-space points through the fit's similarity.
+glm::vec3 moveRigid(const Similarity& align, const glm::mat3& R, const glm::vec3& tr, const glm::vec3& shift, const glm::vec3& p) {
+ const glm::vec3 x = align.inverse(p);
+ return align.apply(R * (x - shift) + tr + shift);
+}
+
+// Undoable mesh replacement for SubTool `i` (the active one through Document::replaceMeshUndoable).
+void replaceSubtoolMesh(Document& doc, int i, Mesh m, const std::string& label) {
+ if (i == doc.activeSubtool) {
+ doc.replaceMeshUndoable(std::move(m), label);
+ return;
+ }
+ SubTool& s = doc.subtools[size_t(i)];
+ UndoRecord r;
+ r.label = label;
+ r.mesh = std::make_unique<Mesh>(std::move(s.mesh));
+ s.mesh = std::move(m);
+ s.mesh.topologyDirty = true;
+ s.bvhDirty = true;
+ s.undo.push(std::move(r));
+ doc.modified = true;
+}
+
+} // namespace
+
+bool generateFaceShapes(Document& doc, const FaceShapesOptions& options, FaceShapesReport& report, std::string& error) {
+ const TemplateData& td = templateData();
+ const FaceTemplate& t = td.t;
+ const auto& names = arkitBlendShapeNames();
+ if (t.shapes.size() != names.size()) {
+ error = "The face template is missing from this build";
+ return false;
+ }
+ if (doc.mesh.triangleCount() == 0) {
+ error = "The active SubTool is empty";
+ return false;
+ }
+ subdivCommit(doc.mesh);
+ Mesh m = doc.mesh;
+ const int originalLevel = subdivCurrentLevel(m);
+ const int level = faceLevel(m, options.level);
+ if (level != originalLevel && !subdivSetLevel(m, level, error)) return false;
+ report.level = level;
+
+ // --- Fit and transfer ---
+ const std::vector<glm::vec3> base = m.basePositions();
+ const std::vector<glm::uvec3> tris = visibleTriangles(m);
+ FaceFit& fit = report.fit;
+ if (!fitFaceTemplate(base, tris, options.landmarks.count() ? &options.landmarks : nullptr, fit, error)) return false;
+ if (fit.coverage < 0.35f) {
+ error = "Couldn't fit the face (only " + std::to_string(int(fit.coverage * 100.0f)) +
+ "% of the template found the sculpt): face the head down +Z (front view), Y up, or place landmarks";
+ return false;
+ }
+ std::vector<std::vector<glm::vec3>> offsets;
+ transferFaceShapes(fit, offsets);
+
+ // --- Bind the sculpt to the fitted template ---
+ TriangleBVH fitted;
+ fitted.build(fit.positions, t.triangles);
+ const float s = fit.align.scale;
+ const Binding bind = bindToTemplate(base, fitted, 0.6f * s, 2.0f * s);
+ std::vector<std::vector<glm::vec3>> deltas(names.size());
+ poolFor(names.size(), [&](size_t b, size_t e) {
+ for (size_t k = b; k < e; ++k) deltas[k] = boundOffsets(bind, t.triangles, offsets[k]);
+ }, 1, 2);
+
+ // --- Symmetry: mirror Left / Right pairs and make centre shapes symmetric ---
+ AABB box;
+ for (const auto& p : base) box.expand(p);
+ const float tol = 2e-3f * glm::length(box.extent());
+ bool symmetric = options.symmetry == 1;
+ std::vector<uint32_t> mirror;
+ if (options.symmetry != 0) {
+ mirror = mirrorMap(base, tris, tol);
+ size_t bound = 0, paired = 0;
+ for (size_t v = 0; v < base.size(); ++v)
+ if (bind.weight[v] > 0.0f) {
+ ++bound;
+ paired += mirror[v] != ~0u;
+ }
+ if (options.symmetry < 0) symmetric = bound > 0 && paired >= bound * 97 / 100;
+ }
+ if (symmetric) {
+ auto flip = [](const glm::vec3& d) { return glm::vec3(-d.x, d.y, d.z); };
+ std::vector<std::vector<glm::vec3>> sym(names.size());
+ for (size_t k = 0; k < names.size(); ++k) {
+ const int other = arkitBlendShapeIndex(arkitMirrorName(names[k]));
+ const auto& mine = deltas[k];
+ const auto& theirs = deltas[size_t(other)];
+ sym[k].resize(mine.size());
+ for (size_t v = 0; v < mine.size(); ++v)
+ sym[k][v] = mirror[v] == ~0u ? mine[v] : 0.5f * (mine[v] + flip(theirs[mirror[v]]));
+ }
+ deltas.swap(sym);
+ }
+ report.symmetric = symmetric;
+ // Offsets under 0.1 mm on a life-size head are dropped: they don't show, and live updates (face_weights) only
+ // visit the vertices a shape moves.
+ const float cutoff = 0.01f * s;
+ for (auto& d : deltas)
+ for (auto& v : d)
+ if (glm::length(v) < cutoff) v = glm::vec3(0.0f);
+
+ // --- Into the active SubTool's layers ---
+ for (size_t k = 0; k < names.size(); ++k) {
+ report.movedVertices = std::max(report.movedVertices,
+ size_t(std::count_if(deltas[k].begin(), deltas[k].end(),
+ [](const glm::vec3& v) { return v != glm::vec3(0.0f); })));
+ setNamedLayer(m, names[k], std::move(deltas[k]));
+ }
+ m.evaluateAll();
+ m.recomputeAllNormals();
+ if (level != originalLevel && !subdivSetLevel(m, originalLevel, error)) return false;
+ replaceSubtoolMesh(doc, doc.activeSubtool, std::move(m), "Generate Facial Shapes");
+
+ if (!options.subtools) return true;
+
+ // --- The other SubTools ---
+ const glm::vec3 mouthCenter = 0.5f * (fit.align.inverse(fit.landmarks.position[kMouthLeft]) +
+ fit.align.inverse(fit.landmarks.position[kMouthRight]));
+ const glm::vec3 templMouth = 0.5f * (t.neutral[kLandmarks[kMouthLeft].vertex] + t.neutral[kLandmarks[kMouthRight].vertex]);
+ const glm::vec3 shift = mouthCenter - templMouth; // where the sculpt's mouth sits relative to the template's
+ const float biteY = 0.5f * (t.upperTeethY + t.lowerTeethCentroid.y) + shift.y;
+ for (int i = 0; i < doc.subtoolCount(); ++i) {
+ if (i == doc.activeSubtool || !doc.subtools[size_t(i)].visible) continue;
+ const std::string& name = doc.subtools[size_t(i)].name;
+ const PartKind kind = classifySubtool(name);
+ subdivCommit(doc.subtoolMesh(i));
+ Mesh sm = doc.subtoolMesh(i);
+ if (sm.triangleCount() == 0) continue;
+ const int orig = subdivCurrentLevel(sm), lvl = faceLevel(sm, options.level);
+ if (lvl != orig && !subdivSetLevel(sm, lvl, error)) return false;
+ const std::vector<glm::vec3> pos = sm.basePositions();
+ std::vector<std::pair<std::string, std::vector<glm::vec3>>> made;
+ std::string what;
+ if (kind == PartKind::Eyes) {
+ // Each eye turns about its own centre: the vertices on the character's left (+X in the template
+ // frame) are the left eye.
+ AABB eyeBox[2];
+ for (const auto& p : pos) eyeBox[fit.align.inverse(p).x > 0.0f ? 1 : 0].expand(p);
+ const glm::mat3 R = fit.align.rotation;
+ auto gaze = [&](float yawDeg, float pitchDeg) {
+ glm::mat4 rot(1.0f);
+ rot = glm::rotate(rot, glm::radians(yawDeg), glm::vec3(0, 1, 0));
+ rot = glm::rotate(rot, glm::radians(pitchDeg), glm::vec3(1, 0, 0));
+ return R * glm::mat3(rot) * glm::transpose(R);
+ };
+ struct EyeShape {
+ const char* name;
+ int side; // 0 right, 1 left
+ float yaw, pitch;
+ };
+ // Looking out / in turns about Y, up / down about X (ARKit's eyes reach about 30 degrees sideways and
+ // 25 up or down).
+ const EyeShape eyeShapes[] = {
+ {"eyeLookDownLeft", 1, 0, 25}, {"eyeLookDownRight", 0, 0, 25}, {"eyeLookInLeft", 1, -30, 0},
+ {"eyeLookInRight", 0, 30, 0}, {"eyeLookOutLeft", 1, 30, 0}, {"eyeLookOutRight", 0, -30, 0},
+ {"eyeLookUpLeft", 1, 0, -25}, {"eyeLookUpRight", 0, 0, -25}};
+ for (const EyeShape& es : eyeShapes) {
+ if (!eyeBox[es.side].valid()) continue;
+ const glm::vec3 pivot = eyeBox[es.side].center();
+ const glm::mat3 rot = gaze(es.yaw, es.pitch);
+ std::vector<glm::vec3> d(pos.size(), glm::vec3(0.0f));
+ for (size_t v = 0; v < pos.size(); ++v)
+ if ((fit.align.inverse(pos[v]).x > 0.0f ? 1 : 0) == es.side) d[v] = pivot + rot * (pos[v] - pivot) - pos[v];
+ made.push_back({es.name, std::move(d)});
+ }
+ what = "eye rotations";
+ } else if (kind == PartKind::Teeth || kind == PartKind::Tongue) {
+ for (size_t k = 0; k < names.size(); ++k) {
+ const FaceTemplate::Shape& sh = t.shapes[k];
+ const glm::mat3 R = glm::mat3_cast(sh.jawRotation);
+ const bool jaw = sh.jawTranslation != glm::vec3(0.0f) || std::abs(sh.jawRotation.w) < 0.999999f;
+ const bool tongueOut = kind == PartKind::Tongue && names[k] == "tongueOut";
+ if (!jaw && !tongueOut) continue;
+ std::vector<glm::vec3> d(pos.size(), glm::vec3(0.0f));
+ for (size_t v = 0; v < pos.size(); ++v) {
+ const bool lowerJaw = kind == PartKind::Tongue || fit.align.inverse(pos[v]).y < biteY;
+ if (!lowerJaw) continue;
+ glm::vec3 p = moveRigid(fit.align, R, sh.jawTranslation, shift, pos[v]);
+ if (tongueOut) p += fit.align.applyVector(glm::vec3(0.0f, -0.3f, 2.2f)); // out past the lips
+ d[v] = p - pos[v];
+ }
+ made.push_back({names[k], std::move(d)});
+ }
+ what = kind == PartKind::Tongue ? "jaw and tongueOut" : "jaw (teeth below the bite)";
+ } else {
+ // Brows, lashes, a beard: follow the skin, if they sit on the face.
+ const Binding b = bindToTemplate(pos, fitted, 0.6f * s, 2.0f * s);
+ const size_t near = size_t(std::count_if(b.weight.begin(), b.weight.end(), [](float w) { return w > 0.5f; }));
+ if (near * 5 < pos.size()) continue; // not on the face
+ for (size_t k = 0; k < names.size(); ++k) {
+ std::vector<glm::vec3> d = boundOffsets(b, t.triangles, offsets[k]);
+ if (nonZero(d)) made.push_back({names[k], std::move(d)});
+ }
+ what = "follows the skin";
+ }
+ if (made.empty()) continue;
+ for (auto& [n, d] : made) setNamedLayer(sm, n, std::move(d));
+ sm.evaluateAll();
+ sm.recomputeAllNormals();
+ if (lvl != orig && !subdivSetLevel(sm, orig, error)) return false;
+ replaceSubtoolMesh(doc, i, std::move(sm), "Generate Facial Shapes");
+ report.subtools.push_back(name + ": " + what);
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Live weights
+// ---------------------------------------------------------------------------
+
+bool parseFaceWeights(const std::string& text, std::vector<std::pair<std::string, float>>& out, std::string& error) {
+ Json j;
+ if (!Json::parse(text, j, error)) {
+ error = "face_weights: not JSON (" + error + ")";
+ return false;
+ }
+ // The whole face message is fine too: {"type":"face","weights":{...}}.
+ const Json& w = j.isObject() && j["weights"].isObject() ? j["weights"] : j;
+ if (!w.isObject()) {
+ error = "face_weights: expected an object like {\"jawOpen\":0.3}";
+ return false;
+ }
+ out.clear();
+ for (const auto& [name, value] : w.members()) {
+ if (!value.isNumber()) {
+ error = "face_weights: '" + name + "' is not a number";
+ return false;
+ }
+ out.push_back({name, std::clamp(float(value.asNumber()), -1.0f, 2.0f)});
+ }
+ return true;
+}
+
+namespace {
+
+// The vertices each layer moves, found once per layer and kept while its offsets stay the same: keyed by the
+// offsets' address and checked against their size, the SubTool's undo revision (strokes into a layer push an
+// undo step) and a few sampled values.
+struct SupportEntry {
+ size_t size = 0;
+ uint64_t revision = 0, fingerprint = 0;
+ std::vector<uint32_t> verts;
+};
+
+uint64_t fingerprint(const std::vector<glm::vec3>& d) {
+ uint64_t h = 1469598103934665603ull ^ d.size();
+ const size_t step = std::max<size_t>(d.size() / 61, 1);
+ for (size_t i = 0; i < d.size(); i += step) {
+ uint32_t bits[3];
+ std::memcpy(bits, &d[i], sizeof bits);
+ for (uint32_t b : bits) h = (h ^ b) * 1099511628211ull;
+ }
+ return h;
+}
+
+std::mutex gSupportMutex;
+std::unordered_map<const void*, SupportEntry> gSupport;
+
+const std::vector<uint32_t>& layerSupport(const SculptLayer& l, uint64_t revision) {
+ const uint64_t fp = fingerprint(l.delta);
+ SupportEntry& e = gSupport[l.delta.data()];
+ if (e.size == l.delta.size() && e.revision == revision && e.fingerprint == fp && !e.verts.empty()) return e.verts;
+ e.size = l.delta.size();
+ e.revision = revision;
+ e.fingerprint = fp;
+ e.verts.clear();
+ for (uint32_t v = 0; v < l.delta.size(); ++v)
+ if (l.delta[v] != glm::vec3(0.0f)) e.verts.push_back(v);
+ if (e.verts.empty()) e.verts.push_back(~0u); // (marks "computed, empty")
+ return e.verts;
+}
+
+} // namespace
+
+FaceWeightsStats applyFaceWeights(Document& doc, const std::vector<std::pair<std::string, float>>& weights) {
+ FaceWeightsStats stats;
+ std::vector<uint8_t> matched(weights.size(), 0);
+ std::lock_guard lock(gSupportMutex);
+ if (gSupport.size() > 8192) gSupport.clear();
+ for (int si = 0; si < doc.subtoolCount(); ++si) {
+ Mesh& m = doc.subtoolMesh(si);
+ if (m.layers.empty() || m.base.size() != m.positions.size()) continue;
+ const uint64_t revision = si == doc.activeSubtool ? doc.undo.revision() : doc.subtools[size_t(si)].undo.revision();
+ std::vector<uint32_t> changed;
+ for (size_t w = 0; w < weights.size(); ++w)
+ for (size_t li = 0; li < m.layers.size(); ++li)
+ if (m.layers[li].name == weights[w].first) {
+ matched[w] = 1;
+ if (m.layers[li].weight != weights[w].second) {
+ m.layers[li].weight = weights[w].second;
+ changed.push_back(uint32_t(li));
+ }
+ }
+ if (changed.empty()) continue;
+ stats.layers += int(changed.size());
+ // The vertices the changed layers move, found and re-evaluated in blocks of the vertex index range, in
+ // parallel: each vertex from its base plus every layer with a weight, in layer order, walking each layer's
+ // own (sorted) vertex list. Those are the same sums as Mesh::evaluate (the layers left out would only add
+ // zeros), at the cost of the offsets that exist rather than vertices x layers.
+ std::vector<const std::vector<uint32_t>*> changedSupport;
+ for (uint32_t li : changed) changedSupport.push_back(&layerSupport(m.layers[li], revision));
+ std::vector<std::pair<const SculptLayer*, const std::vector<uint32_t>*>> live;
+ for (const auto& l : m.layers)
+ if (l.weight != 0.0f) live.push_back({&l, &layerSupport(l, revision)});
+ constexpr size_t kBlock = 16384;
+ const size_t nv = m.positions.size(), blocks = (nv + kBlock - 1) / kBlock;
+ static std::vector<uint8_t> mark; // (guarded by gSupportMutex; all zero between calls)
+ if (mark.size() < nv) mark.assign(nv, 0);
+ std::vector<std::vector<uint32_t>> blockVerts(blocks);
+ poolFor(blocks, [&](size_t bb, size_t be) {
+ for (size_t blk = bb; blk < be; ++blk) {
+ const uint32_t lo = uint32_t(blk * kBlock), hi = uint32_t(std::min(nv, (blk + 1) * kBlock));
+ for (const auto* support : changedSupport)
+ for (auto it = std::lower_bound(support->begin(), support->end(), lo); it != support->end() && *it < hi; ++it)
+ mark[*it] = 1;
+ std::vector<uint32_t>& vs = blockVerts[blk];
+ for (uint32_t v = lo; v < hi; ++v)
+ if (mark[v]) {
+ vs.push_back(v);
+ m.positions[v] = m.base[v];
+ }
+ if (vs.empty()) continue;
+ for (const auto& [l, support] : live) {
+ const float w = l->weight;
+ for (auto it = std::lower_bound(support->begin(), support->end(), lo); it != support->end() && *it < hi; ++it)
+ if (mark[*it]) m.positions[*it] += w * l->delta[*it];
+ }
+ for (uint32_t v : vs) mark[v] = 0;
+ }
+ }, 1, 2);
+ std::vector<uint32_t> verts;
+ for (const auto& vs : blockVerts) verts.insert(verts.end(), vs.begin(), vs.end());
+ if (verts.empty()) continue;
+ m.updateNormals(verts); // (also marks them, and their neighbours, for the GPU)
+ stats.vertices += verts.size();
+ if (si == doc.activeSubtool) doc.bvhDirty = true;
+ else doc.subtools[size_t(si)].bvhDirty = true;
+ }
+ for (size_t w = 0; w < weights.size(); ++w) {
+ if (matched[w]) ++stats.matched;
+ else stats.unknown.push_back(weights[w].first);
+ }
+ return stats;
+}
+
+// ---------------------------------------------------------------------------
+// Takes
+// ---------------------------------------------------------------------------
+
+bool parseFaceTake(const std::string& text, MorphAnimation& out, std::string& error) {
+ std::vector<Json> frames;
+ Json j;
+ std::string err;
+ if (Json::parse(text, j, err)) {
+ if (j.isArray()) frames = j.items();
+ else if (j.isObject() && j["frames"].isArray()) frames = j["frames"].items();
+ else if (j.isObject()) frames.push_back(j);
+ } else {
+ // JSON Lines: one face message per line.
+ std::istringstream in(text);
+ std::string line;
+ int n = 0;
+ while (std::getline(in, line)) {
+ ++n;
+ if (line.find_first_not_of(" \t\r") == std::string::npos) continue;
+ Json f;
+ if (!Json::parse(line, f, err)) {
+ error = "Take line " + std::to_string(n) + ": " + err;
+ return false;
+ }
+ frames.push_back(std::move(f));
+ }
+ }
+ const auto& names = arkitBlendShapeNames();
+ MorphAnimation a;
+ a.channels = names;
+ const double fps = j.isObject() && j["fps"].isNumber() ? j["fps"].asNumber() : 30.0;
+ double t0 = 0.0;
+ bool first = true;
+ for (size_t i = 0; i < frames.size(); ++i) {
+ const Json& f = frames[i];
+ if (!f.isObject()) continue;
+ if (f["type"].isString() && f["type"].asString() != "face") continue;
+ const double t = f["t"].isNumber() ? f["t"].asNumber() / 1000.0 : double(a.times.size()) / std::max(fps, 1.0);
+ if (first) t0 = t;
+ first = false;
+ const float time = float(t - t0);
+ if (!a.times.empty() && time <= a.times.back()) continue; // (out of order or duplicate)
+ std::vector<float> row(names.size(), 0.0f);
+ const Json& w = f["weights"];
+ if (w.isObject()) {
+ for (const auto& [name, value] : w.members()) {
+ const int k = arkitBlendShapeIndex(name);
+ if (k >= 0 && value.isNumber()) row[size_t(k)] = float(value.asNumber());
+ }
+ } else if (f["blendshapes"].isArray()) { // MediaPipe: [{"categoryName":..,"score":..}]
+ for (const Json& c : f["blendshapes"].items()) {
+ const int k = arkitBlendShapeIndex(c["categoryName"].asString());
+ if (k >= 0) row[size_t(k)] = float(c["score"].asNumber());
+ }
+ } else {
+ continue;
+ }
+ a.times.push_back(time);
+ a.values.insert(a.values.end(), row.begin(), row.end());
+ }
+ if (a.times.empty()) {
+ error = "The take has no face frames ({\"type\":\"face\",\"t\":ms,\"weights\":{...}})";
+ return false;
+ }
+ a.fps = float(fps);
+ out = std::move(a);
+ return true;
+}
+
+bool loadFaceTake(const std::string& path, MorphAnimation& out, std::string& error) {
+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::stringstream ss;
+ ss << f.rdbuf();
+ if (!parseFaceTake(ss.str(), out, error)) return false;
+ out.name = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().string();
+ return true;
+}
+
+void sampleMorphAnimation(const MorphAnimation& a, float time, std::vector<std::pair<std::string, float>>& out) {
+ out.clear();
+ if (a.empty()) return;
+ const size_t nc = a.channels.size();
+ size_t k = size_t(std::upper_bound(a.times.begin(), a.times.end(), time) - a.times.begin());
+ size_t k0 = k == 0 ? 0 : k - 1, k1 = std::min(k, a.times.size() - 1);
+ float f = 0.0f;
+ if (k1 != k0 && a.times[k1] > a.times[k0]) f = std::clamp((time - a.times[k0]) / (a.times[k1] - a.times[k0]), 0.0f, 1.0f);
+ for (size_t c = 0; c < nc; ++c) out.push_back({a.channels[c], glm::mix(a.value(k0, c), a.value(k1, c), f)});
+}
+
+MorphAnimation resampleMorphAnimation(const MorphAnimation& a, float fps) {
+ MorphAnimation r;
+ r.name = a.name;
+ r.channels = a.channels;
+ r.fps = fps;
+ if (a.empty() || fps <= 0.0f) return r;
+ const int frames = int(std::floor(a.duration() * fps + 1e-4f)) + 1;
+ std::vector<std::pair<std::string, float>> w;
+ for (int i = 0; i < frames; ++i) {
+ const float t = float(i) / fps;
+ sampleMorphAnimation(a, t, w);
+ r.times.push_back(t);
+ for (const auto& [n, v] : w) r.values.push_back(v);
+ }
+ return r;
+}
+
+void setBakedFaceAnimation(Document& doc, const MorphAnimation* a) {
+ if (!doc.projectSettings.isObject()) doc.projectSettings = Json::object();
+ if (!a || a->empty()) {
+ if (doc.projectSettings.has("face_animation")) {
+ Json copy = Json::object();
+ for (const auto& [k, v] : doc.projectSettings.members())
+ if (k != "face_animation") copy.set(k, v);
+ doc.projectSettings = std::move(copy);
+ doc.modified = true;
+ }
+ return;
+ }
+ Json j = Json::object();
+ j.set("name", a->name);
+ j.set("fps", double(a->fps));
+ Json ch = Json::array(), times = Json::array(), values = Json::array();
+ for (const auto& c : a->channels) ch.push(c);
+ for (float t : a->times) times.push(double(t));
+ for (float v : a->values) values.push(double(std::round(v * 10000.0f) / 10000.0f));
+ j.set("channels", std::move(ch));
+ j.set("times", std::move(times));
+ j.set("values", std::move(values));
+ doc.projectSettings.set("face_animation", std::move(j));
+ doc.modified = true;
+}
+
+bool bakedFaceAnimation(const Document& doc, MorphAnimation& out) {
+ if (!doc.projectSettings.isObject()) return false;
+ const Json& j = doc.projectSettings["face_animation"];
+ if (!j.isObject() || !j["channels"].isArray() || !j["times"].isArray() || !j["values"].isArray()) return false;
+ MorphAnimation a;
+ a.name = j["name"].isString() ? j["name"].asString() : "Take";
+ a.fps = float(j["fps"].asNumber(30.0));
+ for (const Json& c : j["channels"].items()) a.channels.push_back(c.asString());
+ for (const Json& t : j["times"].items()) a.times.push_back(float(t.asNumber()));
+ for (const Json& v : j["values"].items()) a.values.push_back(float(v.asNumber()));
+ if (a.empty() || a.values.size() != a.times.size() * a.channels.size()) return false;
+ out = std::move(a);
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Presets
+// ---------------------------------------------------------------------------
+
+const std::vector<FacePreset>& facePresets() {
+ static const std::vector<FacePreset> presets = {
+ {"Neutral", "Every facial shape at 0.", {}},
+ {"Smile", "Closed smile: mouth corners up, cheeks raised.",
+ {{"mouthSmileLeft", 0.8f}, {"mouthSmileRight", 0.8f}, {"cheekSquintLeft", 0.4f}, {"cheekSquintRight", 0.4f},
+ {"eyeSquintLeft", 0.2f}, {"eyeSquintRight", 0.2f}}},
+ {"Grin", "Big open smile.",
+ {{"mouthSmileLeft", 1.0f}, {"mouthSmileRight", 1.0f}, {"jawOpen", 0.25f}, {"mouthUpperUpLeft", 0.3f},
+ {"mouthUpperUpRight", 0.3f}, {"mouthLowerDownLeft", 0.3f}, {"mouthLowerDownRight", 0.3f},
+ {"cheekSquintLeft", 0.6f}, {"cheekSquintRight", 0.6f}, {"eyeSquintLeft", 0.3f}, {"eyeSquintRight", 0.3f}}},
+ {"Surprise", "Brows up, eyes wide, jaw dropped.",
+ {{"browInnerUp", 0.9f}, {"browOuterUpLeft", 0.8f}, {"browOuterUpRight", 0.8f}, {"eyeWideLeft", 0.8f},
+ {"eyeWideRight", 0.8f}, {"jawOpen", 0.45f}}},
+ {"Anger", "Brows down, nose sneer, lips pressed.",
+ {{"browDownLeft", 0.9f}, {"browDownRight", 0.9f}, {"eyeSquintLeft", 0.5f}, {"eyeSquintRight", 0.5f},
+ {"noseSneerLeft", 0.5f}, {"noseSneerRight", 0.5f}, {"mouthPressLeft", 0.4f}, {"mouthPressRight", 0.4f},
+ {"mouthFrownLeft", 0.3f}, {"mouthFrownRight", 0.3f}}},
+ {"Sad", "Inner brows up, mouth corners down.",
+ {{"browInnerUp", 0.7f}, {"mouthFrownLeft", 0.7f}, {"mouthFrownRight", 0.7f}, {"mouthShrugLower", 0.4f},
+ {"eyeLookDownLeft", 0.2f}, {"eyeLookDownRight", 0.2f}}},
+ {"Disgust", "Nose wrinkled, upper lip raised.",
+ {{"noseSneerLeft", 0.8f}, {"noseSneerRight", 0.8f}, {"mouthUpperUpLeft", 0.6f}, {"mouthUpperUpRight", 0.6f},
+ {"browDownLeft", 0.4f}, {"browDownRight", 0.4f}, {"cheekSquintLeft", 0.3f}, {"cheekSquintRight", 0.3f}}},
+ {"Fear", "Brows up and together, eyes wide, lips stretched.",
+ {{"browInnerUp", 0.8f}, {"browOuterUpLeft", 0.4f}, {"browOuterUpRight", 0.4f}, {"eyeWideLeft", 0.9f},
+ {"eyeWideRight", 0.9f}, {"mouthStretchLeft", 0.6f}, {"mouthStretchRight", 0.6f}, {"jawOpen", 0.15f}}},
+ {"Blink", "Both eyes closed.", {{"eyeBlinkLeft", 1.0f}, {"eyeBlinkRight", 1.0f}}},
+ {"Wink", "Left eye closed with a half smile.",
+ {{"eyeBlinkLeft", 1.0f}, {"cheekSquintLeft", 0.4f}, {"mouthSmileLeft", 0.4f}}},
+ {"Kiss", "Lips puckered.", {{"mouthPucker", 0.9f}, {"mouthFunnel", 0.2f}}},
+ {"Aah", "Open vowel.", {{"jawOpen", 0.6f}, {"mouthLowerDownLeft", 0.2f}, {"mouthLowerDownRight", 0.2f}}},
+ {"Ooh", "Rounded vowel.", {{"mouthFunnel", 0.7f}, {"mouthPucker", 0.4f}, {"jawOpen", 0.2f}}},
+ {"Puff", "Cheeks puffed.", {{"cheekPuff", 1.0f}, {"mouthPucker", 0.2f}}},
+ {"Look left", "Both eyes turned to the character's left.", {{"eyeLookOutLeft", 0.8f}, {"eyeLookInRight", 0.8f}}},
+ {"Tongue out", "Tongue out, jaw a little open.", {{"tongueOut", 1.0f}, {"jawOpen", 0.2f}}},
+ };
+ return presets;
+}
+
+const FacePreset* findFacePreset(std::string_view name) {
+ for (const auto& p : facePresets()) {
+ std::string a(p.name), b(name);
+ if (lower(a) == lower(b)) return &p;
+ }
+ return nullptr;
+}
+
+} // namespace sf
diff --git a/src/core/Face.h b/src/core/Face.h
new file mode 100644
index 00000000..5508d50b
--- /dev/null
+++ b/src/core/Face.h
@@ -0,0 +1,175 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Facial shapes: Generate Facial Shapes gives a sculpted head the 52 Apple ARKit blend shapes (eyeBlinkLeft,
+// jawOpen, mouthSmileRight, ...) as sculpt layers, and face_weights drives them live (the phone's face feed).
+//
+// How the shapes are made:
+// 1. A template head with the 52 shapes (assets/face/ict-arkit.sfface, built from the MIT-licensed ICT-FaceKit
+// by tools/face/build_ict_template.py; embedded in the binary).
+// 2. Fit: a similarity transform (from landmarks the artist placed, else from the nose tip and the head's
+// height, refined by ICP over the face) and then a non-rigid registration (non-rigid ICP: closest points on
+// the sculpt pull the template, a membrane energy on the displacement keeps it smooth, the stiffness relaxed
+// over the iterations) wrap the template around the sculpt.
+// 3. Transfer: each template shape is carried onto the fitted template by deformation transfer (Sumner and
+// Popovic 2004, solved per shape as a Poisson system over the vertices the shape moves), so the shapes follow
+// the sculpt's proportions instead of the template's.
+// 4. Bind: every sculpt vertex near the face takes the offsets of its closest point on the fitted template (with
+// a falloff), so the sculpt's own detail rides along. Symmetric sculpts get mirrored Left / Right pairs.
+// 5. SubTools: eyes (named "eye...") rotate for the eyeLook shapes, teeth and tongue ("teeth", "tooth", "gum",
+// "jaw", "tongue") follow the lower jaw's motion below the bite, and other SubTools on the face (brows,
+// lashes, beard) follow the skin.
+// Multires: the shapes are made at the lowest level with enough vertices for a face (kFaceMinVertices) and the
+// subdivision levels carry them up, so higher-level detail is kept.
+#pragma once
+
+#include "core/Json.h"
+#include "core/Mesh.h"
+#include "core/MorphAnimation.h"
+
+#include <glm/glm.hpp>
+#include <glm/gtc/quaternion.hpp>
+
+#include <array>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+struct Document;
+
+// The 52 ARKit blend shape names, exactly as Apple ARKit and MediaPipe's Face Landmarker spell them, in
+// alphabetical order (MediaPipe's order without _neutral, then tongueOut). Left / Right are the character's own.
+const std::vector<std::string>& arkitBlendShapeNames();
+int arkitBlendShapeIndex(std::string_view name); // -1 if not an ARKit name
+// The other side's shape (eyeBlinkLeft <-> eyeBlinkRight, jawLeft <-> jawRight); centre shapes give themselves.
+std::string arkitMirrorName(std::string_view name);
+
+// --- The template head (centimetres, Y up, looking down +Z; the character's left is +X) ---
+struct FaceTemplate {
+ std::vector<glm::vec3> neutral;
+ std::vector<glm::uvec3> triangles;
+ // Vertex ranges: [0, faceEnd) face, [faceEnd, skinEnd) head and neck, [skinEnd, mouthEnd) mouth socket,
+ // [mouthEnd, neutral.size()) eye sockets.
+ uint32_t faceEnd = 0, skinEnd = 0, mouthEnd = 0;
+ glm::vec3 lowerTeethCentroid{0.0f};
+ float upperTeethY = 0.0f;
+ struct Shape {
+ std::string name;
+ std::vector<uint32_t> index; // the vertices the shape moves
+ std::vector<glm::vec3> offset;
+ glm::quat jawRotation{1.0f, 0.0f, 0.0f, 0.0f}; // the lower teeth: x' = R x + t
+ glm::vec3 jawTranslation{0.0f};
+ };
+ std::vector<Shape> shapes; // in arkitBlendShapeNames() order
+};
+// The embedded template, parsed once (thread-safe).
+const FaceTemplate& faceTemplate();
+bool parseFaceTemplate(const uint8_t* data, size_t size, FaceTemplate& out, std::string& error);
+
+// --- Landmarks: points the artist can place on the sculpt to guide the fit ---
+enum FaceLandmark : int {
+ kEyeOuterRight, kEyeInnerRight, kEyeInnerLeft, kEyeOuterLeft, kNoseTip, kMouthRight, kMouthLeft, kChin,
+ kFaceLandmarkCount
+};
+const char* faceLandmarkKey(int i); // "eye_outer_right", ... (JSON keys)
+const char* faceLandmarkLabel(int i); // "Right eye, outer corner", ...
+uint32_t faceLandmarkVertex(int i); // the template vertex
+
+struct FaceLandmarks {
+ std::array<glm::vec3, kFaceLandmarkCount> position{};
+ std::array<bool, kFaceLandmarkCount> set{};
+ int count() const;
+ Json toJson() const;
+ // {"nose_tip":[x,y,z], ...}; unknown keys are an error.
+ static bool fromJson(const Json& j, FaceLandmarks& out, std::string& error);
+};
+
+// Uniform scale, rotation and translation (template -> sculpt).
+struct Similarity {
+ float scale = 1.0f;
+ glm::mat3 rotation{1.0f};
+ glm::vec3 translation{0.0f};
+ glm::vec3 apply(const glm::vec3& p) const { return scale * (rotation * p) + translation; }
+ glm::vec3 applyVector(const glm::vec3& v) const { return scale * (rotation * v); }
+ glm::vec3 inverse(const glm::vec3& p) const { return glm::transpose(rotation) * (p - translation) / scale; }
+};
+
+struct FaceFit {
+ Similarity align; // the rigid part of the fit
+ std::vector<glm::vec3> positions; // the template's vertices wrapped onto the sculpt (sculpt space)
+ FaceLandmarks landmarks; // the template's landmarks after the fit (sculpt space)
+ float rmsError = 0.0f; // face vertices that found the sculpt: RMS distance to it (sculpt units)
+ float coverage = 0.0f; // the fraction of face vertices that found the sculpt
+};
+
+// Fits the template to the visible triangles of `positions` / `triangles` (the sculpt with its layers at zero).
+// `landmarks` (optional, at least 3 set) start the fit and pull their template vertices all the way.
+bool fitFaceTemplate(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ const FaceLandmarks* landmarks, FaceFit& out, std::string& error);
+
+// Deformation transfer: the offsets (sculpt space, per template vertex) of every template shape on the fitted
+// template, in arkitBlendShapeNames() order. On the template itself this gives back its own shapes.
+void transferFaceShapes(const FaceFit& fit, std::vector<std::vector<glm::vec3>>& offsets);
+
+constexpr size_t kFaceMinVertices = 20000;
+
+struct FaceShapesOptions {
+ FaceLandmarks landmarks; // none set = automatic
+ int symmetry = -1; // -1 = when the sculpt is symmetric about X = 0, 0 = off, 1 = on
+ bool subtools = true; // eyes, teeth, tongue and SubTools on the face get the shapes too
+ int level = -1; // subdivision level to make them on (-1 = the lowest with kFaceMinVertices)
+};
+struct FaceShapesReport {
+ FaceFit fit;
+ int level = 0; // the subdivision level the shapes were made on
+ bool symmetric = false; // Left / Right were mirrored
+ size_t movedVertices = 0;
+ std::vector<std::string> subtools; // "Eyes: eye rotations", ...
+};
+// Gives the active SubTool (and, with options.subtools, the others) the 52 shapes as sculpt layers at weight 0,
+// replacing layers with those names; one undo step per SubTool (active one: "Generate Facial Shapes").
+bool generateFaceShapes(Document& doc, const FaceShapesOptions& options, FaceShapesReport& report, std::string& error);
+
+// --- Live weights (face_weights) ---
+// {"jawOpen":0.3, ...}: names and weights (clamped to -1..2). Error on bad JSON or non-number weights.
+bool parseFaceWeights(const std::string& json, std::vector<std::pair<std::string, float>>& out, std::string& error);
+struct FaceWeightsStats {
+ int layers = 0; // layers whose weight changed
+ size_t vertices = 0; // vertices re-evaluated (all SubTools)
+ int matched = 0; // names that matched a layer on some SubTool
+ std::vector<std::string> unknown; // names no SubTool has
+};
+// Sets the weights of the layers with these names on every SubTool. Only the vertices those layers move are
+// re-evaluated (positions, normals, dirty range for the GPU); no undo step, the document isn't marked modified.
+FaceWeightsStats applyFaceWeights(Document& doc, const std::vector<std::pair<std::string, float>>& weights);
+
+// --- Takes: recorded face feeds ---
+// A JSON array of face messages ({"type":"face","t":<ms>,"weights":{...},"head":[...]}), an object with such an
+// array in "frames", or JSON Lines of them. Channels: the 52 ARKit names; times in seconds from the first frame.
+bool parseFaceTake(const std::string& text, MorphAnimation& out, std::string& error);
+bool loadFaceTake(const std::string& path, MorphAnimation& out, std::string& error);
+// The weights at `time` (linear between keys, clamped at the ends).
+void sampleMorphAnimation(const MorphAnimation& a, float time, std::vector<std::pair<std::string, float>>& out);
+// Keys every 1/fps seconds.
+MorphAnimation resampleMorphAnimation(const MorphAnimation& a, float fps);
+// The baked take the exporters write (kept in the project, Document::projectSettings["face_animation"]).
+void setBakedFaceAnimation(Document& doc, const MorphAnimation* a);
+bool bakedFaceAnimation(const Document& doc, MorphAnimation& out);
+
+// --- Expression presets (Face test) ---
+struct FacePreset {
+ const char* name;
+ const char* help;
+ std::vector<std::pair<const char*, float>> weights; // the rest are 0
+};
+const std::vector<FacePreset>& facePresets();
+const FacePreset* findFacePreset(std::string_view name);
+
+// face_shapes_generate, face_landmarks_detect, face_weights, face_preset, face_take_bake, face_take_clear.
+void registerFaceCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/FaceCommands.cpp b/src/core/FaceCommands.cpp
new file mode 100644
index 00000000..0f2206e3
--- /dev/null
+++ b/src/core/FaceCommands.cpp
@@ -0,0 +1,160 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Commands.h"
+#include "core/Face.h"
+#include "core/Multires.h"
+
+#include <cmath>
+#include <cstdio>
+
+namespace sf {
+
+namespace {
+
+std::string percent(float f) {
+ char buf[32];
+ std::snprintf(buf, sizeof buf, "%.1f%%", double(f) * 100.0);
+ return buf;
+}
+
+// The fit error as a share of the head: the template head is about 34 cm tall.
+float headShare(const FaceFit& fit) { return fit.rmsError / (34.0f * fit.align.scale); }
+
+std::string presetNames() {
+ std::string s;
+ for (const auto& p : facePresets()) s += (s.empty() ? "" : ", ") + std::string(p.name);
+ return s;
+}
+
+} // namespace
+
+void registerFaceCommands(CommandRegistry& registry) {
+ using T = ParamSpec::Type;
+ registry.add({"face_shapes_generate",
+ "Generate Facial Shapes: gives the active SubTool (a sculpted humanoid head looking down +Z, Y up) "
+ "the 52 Apple ARKit blend shapes (eyeBlinkLeft, jawOpen, mouthSmileRight, ...) as sculpt layers at "
+ "weight 0, fitted to its proportions, ready to fix by sculpting into each layer and to export as "
+ "morph targets. Layers with those names are replaced (undo brings them back). Eyes, teeth and tongue "
+ "SubTools (by name) and SubTools on the face (brows, lashes) get the shapes they need.",
+ {{"landmarks", T::String,
+ "Optional JSON of points on the sculpt guiding the fit, e.g. {\"nose_tip\":[0,1.2,0.4],"
+ "\"chin\":[0,0.9,0.3]}: eye_outer_right, eye_inner_right, eye_inner_left, eye_outer_left, "
+ "nose_tip, mouth_right, mouth_left, chin (right / left are the character's). At least 3, or none "
+ "for the automatic fit.",
+ false},
+ {"symmetry", T::String,
+ "auto (default: mirror Left / Right when the sculpt is symmetric about X = 0), on or off.", false},
+ {"subtools", T::Bool, "Also give the shapes to eyes, teeth, tongue and SubTools on the face (default true).",
+ false},
+ {"level", T::Number,
+ "Subdivision level (1-based, as SDiv) to make the shapes on; default: the lowest with at least 20,000 "
+ "vertices. Higher levels carry them up with their detail.",
+ false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ FaceShapesOptions o;
+ std::string error;
+ const std::string lm = argString(a, "landmarks");
+ if (!lm.empty()) {
+ Json j;
+ if (!Json::parse(lm, j, error) || !FaceLandmarks::fromJson(j, o.landmarks, error))
+ return {false, "Landmarks: " + error};
+ }
+ const std::string sym = argString(a, "symmetry", "auto");
+ o.symmetry = sym == "on" || sym == "true" || sym == "1" ? 1 : sym == "off" || sym == "false" || sym == "0" ? 0 : -1;
+ o.subtools = argBool(a, "subtools", true);
+ if (a.count("level")) o.level = int(argNumber(a, "level", 1.0)) - 1;
+ FaceShapesReport r;
+ if (!generateFaceShapes(doc, o, r, error)) return {false, error};
+ std::string msg = "Generated 52 facial shapes on " + doc.activeSubtoolInfo().name;
+ if (subdivLevelCount(doc.mesh)) msg += " (made at SDiv " + std::to_string(r.level + 1) + ")";
+ msg += ": fit error " + percent(headShare(r.fit)) + " of the head, " + percent(r.fit.coverage) +
+ " of the template's face on the sculpt" + (r.symmetric ? ", Left/Right mirrored" : "");
+ for (const auto& s : r.subtools) msg += "; " + s;
+ return {true, msg};
+ }});
+
+ registry.add({"face_landmarks_detect",
+ "Finds the facial landmarks (eye and mouth corners, nose tip, chin) on the active SubTool by fitting "
+ "the template head automatically, and reports them as the JSON face_shapes_generate takes (to check "
+ "or correct before generating).",
+ {},
+ [](Document& doc, const Args&) -> CommandResult {
+ std::vector<glm::uvec3> tris;
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t)
+ if (!doc.mesh.triangleHidden(t)) tris.push_back(doc.mesh.triangles[t]);
+ FaceFit fit;
+ std::string error;
+ if (!fitFaceTemplate(doc.mesh.basePositions(), tris, nullptr, fit, error)) return {false, error};
+ return {true, fit.landmarks.toJson().dump() + " (fit error " + percent(headShare(fit)) +
+ " of the head, " + percent(fit.coverage) + " found the sculpt)"};
+ }});
+
+ registry.add({"face_weights",
+ "Live face: sets the weights of the named blend shapes (sculpt layers) on every SubTool, e.g. "
+ "json={\"jawOpen\":0.3,\"eyeBlinkLeft\":1}. Made for 30+ calls a second (the phone's face feed): no "
+ "undo step, only the vertices those shapes move are updated. Names not given keep their weight.",
+ {{"json", T::String, "JSON object of ARKit blend shape names and weights 0-1 (a whole face message works too).",
+ true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<std::pair<std::string, float>> w;
+ std::string error;
+ if (!parseFaceWeights(argString(a, "json"), w, error)) return {false, error};
+ const FaceWeightsStats s = applyFaceWeights(doc, w);
+ if (!w.empty() && s.matched == 0)
+ return {false, "No facial shapes to drive: run Generate Facial Shapes (face_shapes_generate) first"};
+ std::string msg = "Face weights: " + std::to_string(s.matched) + " shapes, " + std::to_string(s.layers) +
+ " changed (" + std::to_string(s.vertices) + " vertices)";
+ if (!s.unknown.empty()) msg += ", unknown: " + s.unknown.front() + (s.unknown.size() > 1 ? ", ..." : "");
+ return {true, msg};
+ }});
+
+ registry.add({"face_preset",
+ "Face test: shows an expression made of the ARKit shapes (sets all 52 weights; no undo step). "
+ "Presets: " + presetNames() + ".",
+ {{"name", T::String, "The preset, e.g. Smile.", true},
+ {"amount", T::Number, "How strongly, 0-1 (default 1).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const FacePreset* p = findFacePreset(argString(a, "name"));
+ if (!p) return {false, "Unknown face preset '" + argString(a, "name") + "' (" + presetNames() + ")"};
+ const float amount = float(argNumber(a, "amount", 1.0));
+ std::vector<std::pair<std::string, float>> w;
+ for (const auto& n : arkitBlendShapeNames()) {
+ float v = 0.0f;
+ for (const auto& [pn, pv] : p->weights)
+ if (n == pn) v = pv * amount;
+ w.push_back({n, v});
+ }
+ const FaceWeightsStats s = applyFaceWeights(doc, w);
+ if (s.matched == 0) return {false, "No facial shapes: run Generate Facial Shapes first"};
+ return {true, std::string("Face: ") + p->name};
+ }});
+
+ registry.add({"face_take_bake",
+ "Bakes a recorded face take (JSON frames from the phone link: {\"type\":\"face\",\"t\":ms,\"weights\":"
+ "{...}}) into keyframed blend-shape weights. GLB export writes them as a glTF animation and USD export "
+ "as time samples; the take is saved with the project.",
+ {{"path", T::String, "The take file (.json array, {\"frames\":[...]} or JSON Lines).", true},
+ {"fps", T::Number, "Keys per second (default 30).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ MorphAnimation take;
+ std::string error;
+ if (!loadFaceTake(argString(a, "path"), take, error)) return {false, error};
+ const float fps = float(std::clamp(argNumber(a, "fps", 30.0), 1.0, 240.0));
+ MorphAnimation baked = resampleMorphAnimation(take, fps);
+ setBakedFaceAnimation(doc, &baked);
+ char buf[96];
+ std::snprintf(buf, sizeof buf, "%.2f s, %zu keys at %g fps", double(baked.duration()), baked.times.size(),
+ double(fps));
+ return {true, "Baked take '" + baked.name + "' (" + buf + "): exports with GLB and USD"};
+ }});
+
+ registry.add({"face_take_clear", "Removes the baked face take (exports go back to a still pose).", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ MorphAnimation a;
+ if (!bakedFaceAnimation(doc, a)) return {true, "No baked take"};
+ setBakedFaceAnimation(doc, nullptr);
+ return {true, "Removed the baked take '" + a.name + "'"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/MorphAnimation.h b/src/core/MorphAnimation.h
new file mode 100644
index 00000000..9c6ac654
--- /dev/null
+++ b/src/core/MorphAnimation.h
@@ -0,0 +1,30 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Keyframed blend-shape weights (a baked face take, core/Face.h): exported as a glTF animation on the morph
+// target weights and as USD time samples on the SkelAnimation's blendShapeWeights.
+#pragma once
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct MorphAnimation {
+ std::string name = "Take";
+ std::vector<std::string> channels; // blend shape (sculpt layer) names
+ std::vector<float> times; // seconds from the start, increasing
+ std::vector<float> values; // times.size() rows of channels.size() weights
+ float fps = 30.0f; // the rate the keys were baked at (USD timeCodesPerSecond)
+
+ bool empty() const { return times.empty() || channels.empty(); }
+ float duration() const { return times.empty() ? 0.0f : times.back(); }
+ int channel(const std::string& n) const {
+ for (size_t i = 0; i < channels.size(); ++i)
+ if (channels[i] == n) return int(i);
+ return -1;
+ }
+ float value(size_t key, size_t ch) const { return values[key * channels.size() + ch]; }
+};
+
+} // namespace sf
diff --git a/src/io/BlenderBridge.cpp b/src/io/BlenderBridge.cpp
index 77ff3f93..ce6ee3eb 100644
--- a/src/io/BlenderBridge.cpp
+++ b/src/io/BlenderBridge.cpp
@@ -10,6 +10,7 @@
#include <chrono>
#include <cmath>
#include <cstdio>
+#include <cstring>
#include <cstdlib>
#include <filesystem>
#include <fstream>
@@ -141,6 +142,11 @@ bool parseBridgeManifest(const std::string& text, BridgeManifest& out, std::stri
error = "Bridge manifest names a bad file: \"" + b.file + "\"";
return false;
}
+ b.shapes = o["shapes"].asString();
+ if (!b.shapes.empty() && !plainFileName(b.shapes)) {
+ error = "Bridge manifest names a bad file: \"" + b.shapes + "\"";
+ return false;
+ }
const Json& mw = o["matrix_world"];
if (mw.isArray()) {
// Rows, as Blender prints a Matrix: matrix_world[row][column].
@@ -175,6 +181,7 @@ std::string writeBridgeManifest(const BridgeManifest& m) {
const BridgeObject& o = m.objects[i];
s += i ? ",\n {" : "\n {";
s += "\"name\": " + jsonQuote(o.name) + ", \"file\": " + jsonQuote(o.file);
+ if (!o.shapes.empty()) s += ", \"shapes\": " + jsonQuote(o.shapes);
if (o.hasMatrix) {
s += ", \"matrix_world\": [";
for (int r = 0; r < 4; ++r) {
@@ -199,6 +206,90 @@ bool readBridgeManifest(const std::string& path, BridgeManifest& out, std::strin
return parseBridgeManifest(text, out, error);
}
+bool writeBridgeShapes(const std::string& path, const Mesh& mesh, std::string& error) {
+ std::string data("SFSHAPES", 8);
+ auto u32 = [&](uint32_t v) { data.append(reinterpret_cast<const char*>(&v), 4); };
+ auto f32 = [&](float v) { data.append(reinterpret_cast<const char*>(&v), 4); };
+ u32(1);
+ u32(uint32_t(mesh.vertexCount()));
+ u32(uint32_t(mesh.layers.size()));
+ for (const SculptLayer& l : mesh.layers) {
+ u32(uint32_t(l.name.size()));
+ data += l.name;
+ f32(l.weight);
+ std::vector<uint32_t> idx;
+ for (uint32_t v = 0; v < l.delta.size(); ++v)
+ if (l.delta[v] != glm::vec3(0.0f)) idx.push_back(v);
+ u32(uint32_t(idx.size()));
+ for (uint32_t v : idx) u32(v);
+ for (uint32_t v : idx) {
+ const glm::dvec3 d = sculptForgeToBlender(glm::dvec3(l.delta[v])); // (linear: works for offsets)
+ f32(float(d.x));
+ f32(float(d.y));
+ f32(float(d.z));
+ }
+ }
+ if (!writeAtomically(utf8Path(path), data)) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+bool readBridgeShapes(const std::string& path, uint32_t& vertexCount, std::vector<BridgeShape>& out, std::string& error) {
+ std::string data;
+ if (!readFile(utf8Path(path), data)) {
+ error = "Cannot read " + path;
+ return false;
+ }
+ size_t pos = 8;
+ bool ok = data.size() >= 20 && data.compare(0, 8, "SFSHAPES") == 0;
+ auto u32 = [&]() {
+ uint32_t v = 0;
+ if (pos + 4 > data.size()) ok = false;
+ else std::memcpy(&v, data.data() + pos, 4);
+ pos += 4;
+ return v;
+ };
+ auto f32 = [&]() {
+ float v = 0.0f;
+ if (pos + 4 > data.size()) ok = false;
+ else std::memcpy(&v, data.data() + pos, 4);
+ pos += 4;
+ return v;
+ };
+ if (ok && u32() != 1) ok = false;
+ vertexCount = ok ? u32() : 0;
+ const uint32_t count = ok ? u32() : 0;
+ out.clear();
+ for (uint32_t s = 0; ok && s < count; ++s) {
+ BridgeShape shape;
+ const uint32_t len = u32();
+ if (!ok || pos + len > data.size()) {
+ ok = false;
+ break;
+ }
+ shape.name.assign(data, pos, len);
+ pos += len;
+ shape.weight = f32();
+ const uint32_t n = u32();
+ if (!ok || n > vertexCount || pos + size_t(n) * 16 > data.size()) {
+ ok = false;
+ break;
+ }
+ shape.index.resize(n);
+ for (auto& v : shape.index) {
+ v = u32();
+ if (v >= vertexCount) ok = false;
+ }
+ shape.offset.resize(n);
+ for (auto& o : shape.offset) o = {f32(), f32(), f32()};
+ out.push_back(std::move(shape));
+ }
+ if (!ok) error = path + " is not a valid SculptForge shapes file";
+ return ok;
+}
+
bool blenderReceive(const std::string& root, std::vector<MeshObject>& out, BridgeManifest* manifest,
std::string& message) {
if (root.empty()) {
@@ -286,7 +377,21 @@ bool blenderSend(const std::vector<MeshObjectRef>& objects, const std::string& r
GozWriteOptions o;
o.quads = objects[k].mesh->hasQuads(); // only kept quads: triangles of n-gons must stay triangles
std::string err;
- if (!saveGoz(pathUtf8(outbox / utf8Path(b.file)), *objects[k].mesh, name, err, o)) {
+ const Mesh& sent = *objects[k].mesh;
+ bool ok;
+ if (sent.layers.empty()) {
+ ok = saveGoz(pathUtf8(outbox / utf8Path(b.file)), sent, name, err, o);
+ } else {
+ // Sculpt layers go as shape keys: the .GoZ holds the base shape, the shapes file the offsets.
+ Mesh neutral = sent;
+ neutral.positions = sent.base;
+ neutral.layers.clear();
+ neutral.base.clear();
+ b.shapes = prefix + std::string(file, std::strlen(file) - 4) + ".shapes";
+ ok = saveGoz(pathUtf8(outbox / utf8Path(b.file)), neutral, name, err, o) &&
+ writeBridgeShapes(pathUtf8(outbox / utf8Path(b.shapes)), sent, err);
+ }
+ if (!ok) {
message = "Cannot send \"" + name + "\" to Blender: " + err;
return false;
}
diff --git a/src/io/BlenderBridge.h b/src/io/BlenderBridge.h
index 621da3b9..ab569350 100644
--- a/src/io/BlenderBridge.h
+++ b/src/io/BlenderBridge.h
@@ -31,6 +31,7 @@ struct BridgeObject {
std::string file; // .GoZ file name inside the manifest's folder
bool hasMatrix = false; // the mesh is in object space and `matrix` places it in the scene
glm::dmat4 matrix{1.0}; // Blender's matrix_world (Z-up, metres; glm column-major)
+ std::string shapes; // optional: blend shapes file (writeBridgeShapes) beside the .GoZ
};
struct BridgeManifest {
@@ -58,6 +59,19 @@ glm::dvec3 blenderToSculptForge(const glm::dvec3& p);
glm::dvec3 sculptForgeToBlender(const glm::dvec3& p);
glm::dmat4 blenderMatrixToSculptForge(const glm::dmat4& m);
+// Blend shapes (sculpt layers) for the add-on's shape keys, sent beside an object's .GoZ (which then holds the base
+// shape, every layer at zero). Little endian: "SFSHAPES", u32 version 1, u32 vertex count, u32 shape count, then per
+// shape u32 name length, the name (UTF-8), f32 weight, u32 count N, u32[N] vertex indices, f32[3N] offsets in
+// Blender's axes (Z up, metres, world space).
+struct BridgeShape {
+ std::string name;
+ float weight = 0.0f;
+ std::vector<uint32_t> index;
+ std::vector<glm::vec3> offset; // Blender axes
+};
+bool writeBridgeShapes(const std::string& path, const Mesh& mesh, std::string& error);
+bool readBridgeShapes(const std::string& path, uint32_t& vertexCount, std::vector<BridgeShape>& out, std::string& error);
+
// Loads what Blender sent (<root>/to_sculptforge): every object's .GoZ, moved by its matrix into place, named
// after its Blender object. `manifest` receives the manifest (for its revision).
bool blenderReceive(const std::string& root, std::vector<MeshObject>& out, BridgeManifest* manifest,
diff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cpp
index 5682db46..ec1465be 100644
--- a/src/io/GltfIO.cpp
+++ b/src/io/GltfIO.cpp
@@ -16,6 +16,7 @@
#include <unordered_map>
#include <array>
+#include <algorithm>
#include <cstring>
#include <filesystem>
#include <fstream>
@@ -96,7 +97,7 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,
}
bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects, const std::string& sceneName,
- std::string& error) {
+ std::string& error, const MorphAnimation* animation) {
if (objects.empty()) {
error = "Nothing to export";
return false;
@@ -136,6 +137,21 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
<< ",\"componentType\":5126,\"count\":" << v.size() << ",\"type\":\"VEC2\"}";
return accessorCount++;
};
+ auto addScalars = [&](const std::vector<float>& v, bool withMinMax) { // animation data (no buffer target)
+ size_t off = bin.append(v.data(), v.size() * sizeof(float));
+ views.push_back({off, v.size() * sizeof(float), 0});
+ accessors << (accessorCount ? "," : "") << "{\"bufferView\":" << views.size() - 1
+ << ",\"componentType\":5126,\"count\":" << v.size() << ",\"type\":\"SCALAR\"";
+ if (withMinMax && !v.empty()) {
+ std::ostringstream mm;
+ mm.precision(9);
+ mm << ",\"min\":[" << *std::min_element(v.begin(), v.end()) << "],\"max\":["
+ << *std::max_element(v.begin(), v.end()) << "]";
+ accessors << mm.str();
+ }
+ accessors << "}";
+ return accessorCount++;
+ };
// One node and one mesh per object, each with its own morph targets.
for (size_t oi = 0; oi < objects.size(); ++oi) {
@@ -234,6 +250,34 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
json << "}";
}
+ // The animation: one sampler per object with layers the animation names, keying all of its targets.
+ std::ostringstream samplers, channels;
+ int animated = 0;
+ if (animation && !animation->empty()) {
+ int input = -1;
+ for (size_t oi = 0; oi < objects.size(); ++oi) {
+ const Mesh& mesh = *objects[oi].mesh;
+ std::vector<int> channelOf;
+ bool any = false;
+ for (const auto& l : mesh.layers) {
+ channelOf.push_back(animation->channel(l.name));
+ any |= channelOf.back() >= 0;
+ }
+ if (!any) continue;
+ if (input < 0) input = addScalars(animation->times, true);
+ std::vector<float> out;
+ out.reserve(animation->times.size() * channelOf.size());
+ for (size_t k = 0; k < animation->times.size(); ++k)
+ for (int c : channelOf) out.push_back(c >= 0 ? animation->value(k, size_t(c)) : 0.0f);
+ const int output = addScalars(out, false);
+ samplers << (animated ? "," : "") << "{\"input\":" << input << ",\"output\":" << output
+ << ",\"interpolation\":\"LINEAR\"}";
+ channels << (animated ? "," : "") << "{\"sampler\":" << animated << ",\"target\":{\"node\":" << oi
+ << ",\"path\":\"weights\"}}";
+ ++animated;
+ }
+ }
+
std::ostringstream json;
json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"scene\":0,\"scenes\":[{";
if (objects.size() > 1) json << "\"name\":\"" << jsonEscape(sceneName) << "\",";
@@ -253,6 +297,9 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
for (int i = 0; i < textureCount; ++i) json << (i ? "," : "") << "{\"sampler\":0,\"source\":" << i << "}";
json << "],\"materials\":[" << materials.str() << "]";
}
+ if (animated)
+ json << ",\"animations\":[{\"name\":\"" << jsonEscape(animation->name) << "\",\"samplers\":[" << samplers.str()
+ << "],\"channels\":[" << channels.str() << "]}]";
json << "}";
return writeGlbFile(path, json.str(), bin.data, error);
diff --git a/src/io/GltfIO.h b/src/io/GltfIO.h
index 200067d9..df5a803e 100644
--- a/src/io/GltfIO.h
+++ b/src/io/GltfIO.h
@@ -3,6 +3,7 @@
#pragma once
#include "core/Mesh.h"
+#include "core/MorphAnimation.h"
#include "core/Splats.h"
#include "io/MeshObject.h"
@@ -18,9 +19,11 @@ namespace sf {
// (core/Texture.h) is embedded as a PNG: the primitive's baseColorTexture.
bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error);
// One node and mesh per object (SubTool), each with its own morph targets;
-// with several, the scene is called `sceneName`.
+// with several, the scene is called `sceneName`. `animation` (optional, e.g. a
+// baked face take) becomes a glTF animation on the morph target weights of
+// every object with layers of those names (other targets keyed at 0).
bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects, const std::string& sceneName,
- std::string& error);
+ std::string& error, const MorphAnimation* animation = nullptr);
// Reads .glb or .gltf (embedded/data-URI or external buffers). All triangle
// primitives in the default scene are merged with their node transforms
diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cpp
index e280689e..93c6e96b 100644
--- a/src/io/UsdIO.cpp
+++ b/src/io/UsdIO.cpp
@@ -112,7 +112,8 @@ void writeExtent(Writer& w, const AABB& b) {
}
// One mesh prim `prim` under the root (a SkelRoot holding the Mesh when it has blend shapes).
-void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& prim, const std::string& material) {
+void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& prim, const std::string& material,
+ const MorphAnimation* animation) {
const bool skinned = !mesh.layers.empty();
const std::string meshPath = skinned ? "/" + root + "/" + prim + "/Mesh" : "/" + root + "/" + prim;
// Unique, valid names for the blend shapes.
@@ -220,6 +221,31 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::
w.open("def SkelAnimation \"Weights\"");
w.array("uniform token[] blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });
w.array("float[] blendShapeWeights", mesh.layers, [&](const SculptLayer& l) { w.num(l.weight); });
+ if (animation && !animation->empty()) {
+ // Keys for the shapes the animation names (the rest at their current weight), at time codes in frames.
+ std::vector<int> channelOf;
+ bool any = false;
+ for (const auto& l : mesh.layers) {
+ channelOf.push_back(animation->channel(l.name));
+ any |= channelOf.back() >= 0;
+ }
+ if (any) {
+ w.line("float[] blendShapeWeights.timeSamples = {");
+ ++w.depth;
+ for (size_t k = 0; k < animation->times.size(); ++k) {
+ w.indent();
+ w.num(std::round(animation->times[k] * animation->fps * 1000.0f) / 1000.0f);
+ w.s += ": [";
+ for (size_t i = 0; i < channelOf.size(); ++i) {
+ if (i) w.s += ", ";
+ w.num(channelOf[i] >= 0 ? animation->value(k, size_t(channelOf[i])) : mesh.layers[i].weight);
+ }
+ w.s += "],\n";
+ }
+ --w.depth;
+ w.line("}");
+ }
+ }
w.close();
w.close();
w.close();
@@ -313,7 +339,7 @@ void writeTextureMaterial(Writer& w, const std::string& path, const std::string&
// `textures`: per mesh, the PNG asset path its material reads ("" = no texture).
std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vector<std::string>& textures,
- const SplatCloud* splats, const std::string& name) {
+ const SplatCloud* splats, const std::string& name, const MorphAnimation* animation) {
const std::string root = usdIdentifier(name.empty() ? "Sculpt" : name);
// Textured meshes bind a material of their own. Of the others, polypainted ones bind a material that
// reads their colours; with a mix, plain ones bind "Clay".
@@ -332,6 +358,22 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
w.line(" doc = \"Created with SculptForge\"");
w.line(" metersPerUnit = 1");
w.line(" upAxis = \"Y\"");
+ if (animation && !animation->empty()) {
+ w.indent();
+ w.s += " startTimeCode = 0\n";
+ w.indent();
+ w.s += " endTimeCode = ";
+ w.num(std::round(animation->duration() * animation->fps * 1000.0f) / 1000.0f);
+ w.s += "\n";
+ w.indent();
+ w.s += " timeCodesPerSecond = ";
+ w.num(animation->fps);
+ w.s += "\n";
+ w.indent();
+ w.s += " framesPerSecond = ";
+ w.num(animation->fps);
+ w.s += "\n";
+ }
w.line(")");
w.s += '\n';
w.line("def Xform " + quoted(root) + " (");
@@ -357,7 +399,7 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
textured.push_back({prim + "_Material", textures[i]});
material = "/" + root + "/Materials/" + textured.back().first;
}
- writeMesh(w, *m.mesh, root, prim, material);
+ writeMesh(w, *m.mesh, root, prim, material, animation);
w.s += '\n';
}
w.open("def Scope \"Materials\"");
@@ -985,7 +1027,7 @@ bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats
}
bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn, const SplatCloud* splats,
- const std::string& name, std::string& error) {
+ const std::string& name, std::string& error, const MorphAnimation* animation) {
std::vector<MeshObjectRef> meshes;
for (const auto& m : meshesIn)
if (m.mesh && m.mesh->triangleCount() > 0) meshes.push_back(m);
@@ -1007,7 +1049,7 @@ bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn
}
// Textures: PNGs inside a .usdz package, else beside the layer; asset paths are relative to the layer.
const std::vector<std::string> pngs = textureFileNames(path, meshes);
- const std::string text = buildUsda(meshes, pngs, hasSplats ? splats : nullptr, name);
+ const std::string text = buildUsda(meshes, pngs, hasSplats ? splats : nullptr, name, animation);
if (ext == ".usdz") {
std::string inner = usdIdentifier(name.empty() ? "Sculpt" : name) + ".usda";
std::vector<ZipEntry> entries = {{inner, std::vector<uint8_t>(text.begin(), text.end())}};
diff --git a/src/io/UsdIO.h b/src/io/UsdIO.h
index 92e8d069..fb7c6b68 100644
--- a/src/io/UsdIO.h
+++ b/src/io/UsdIO.h
@@ -18,6 +18,7 @@
#pragma once
#include "core/Mesh.h"
+#include "core/MorphAnimation.h"
#include "core/Splats.h"
#include "io/MeshObject.h"
@@ -30,9 +31,11 @@ bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats
std::string& error);
// One Mesh prim per object (SubTool) under the root Xform `name`, each with its
// own blend shapes: a single object is the prim "Sculpt" as above, several are
-// named after the objects (made valid and unique).
+// named after the objects (made valid and unique). `animation` (optional, e.g.
+// a baked face take) adds time samples to each SkelAnimation's
+// blendShapeWeights for the shapes it names, at its fps.
bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshes, const SplatCloud* splats,
- const std::string& name, std::string& error);
+ const std::string& name, std::string& error, const MorphAnimation* animation = nullptr);
// Fills whichever of `mesh` / `splats` the file contains (the other is left
// empty; every Mesh prim is merged). Fails if it contains neither.
diff --git a/tests/test_face.cpp b/tests/test_face.cpp
new file mode 100644
index 00000000..6b7fb64f
--- /dev/null
+++ b/tests/test_face.cpp
@@ -0,0 +1,664 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Facial shapes (core/Face.h): the ARKit names, the template, the fit (landmark error on a known head, with and
+// without landmarks, on a reshaped and re-topologised head), deformation transfer on the template itself
+// (near-identity), mirrored Left / Right pairs, SubTools (eyes, teeth), multires, face_weights (exact, no undo,
+// timing on a 500k head), takes, and export round trips that keep the morph targets, their names and the take.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Decimate.h"
+#include "core/Face.h"
+#include "core/Multires.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "core/ThreadPool.h"
+#include "io/BlenderBridge.h"
+#include "io/FbxIO.h"
+#include "io/GltfIO.h"
+#include "io/UsdIO.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <fstream>
+#include <sstream>
+
+using namespace sf;
+
+namespace {
+
+const CommandRegistry& registry() {
+ static CommandRegistry r;
+ return r;
+}
+
+CommandResult run(Document& d, const std::string& name, const Args& a = {}) {
+ CommandResult r = registry().execute(d, name, a);
+ if (!r.ok) std::printf(" (%s: %s)\n", name.c_str(), r.message.c_str());
+ return r;
+}
+
+// The template's skin (face, head and neck; no mouth or eye sockets) as a sculpt, in metres (the template is in
+// centimetres), optionally reshaped by `warp` (template cm -> sculpt units).
+template <class Warp>
+Mesh templateHead(Warp warp) {
+ const FaceTemplate& t = faceTemplate();
+ Mesh m;
+ for (uint32_t i = 0; i < t.skinEnd; ++i) m.positions.push_back(warp(t.neutral[i]));
+ for (const auto& tri : t.triangles)
+ if (tri.x < t.skinEnd && tri.y < t.skinEnd && tri.z < t.skinEnd) m.triangles.push_back(tri);
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ return m;
+}
+Mesh templateHead() {
+ return templateHead([](const glm::vec3& p) { return p * 0.01f; });
+}
+
+// A different person: wider face, longer jaw, bigger nose, smaller head, turned 8 degrees and moved; metres.
+glm::vec3 otherPerson(const glm::vec3& p) {
+ glm::vec3 q = p;
+ q.x *= 1.1f;
+ if (q.y < -2.0f) q.y = -2.0f + (q.y + 2.0f) * 1.12f; // longer lower face
+ const float nose = std::exp(-(q.x * q.x + (q.y + 0.5f) * (q.y + 0.5f)) / 4.0f); // around the nose
+ q.z += 0.6f * nose * std::max(q.z - 9.0f, 0.0f) / 4.0f;
+ const glm::mat4 r = glm::rotate(glm::mat4(1.0f), glm::radians(8.0f), glm::vec3(0, 1, 0));
+ return glm::vec3(r * glm::vec4(q * 0.0095f, 1.0f)) + glm::vec3(0.05f, 1.6f, -0.02f);
+}
+
+float maxLength(const std::vector<glm::vec3>& v) {
+ float m = 0.0f;
+ for (const auto& d : v) m = std::max(m, glm::length(d));
+ return m;
+}
+
+const SculptLayer* findLayer(const Mesh& m, const std::string& name) {
+ for (const auto& l : m.layers)
+ if (l.name == name) return &l;
+ return nullptr;
+}
+
+// The template's offsets of shape `name`, dense, scaled to `scale`.
+std::vector<glm::vec3> templateShape(const std::string& name, size_t count, float scale) {
+ const FaceTemplate& t = faceTemplate();
+ std::vector<glm::vec3> d(count, glm::vec3(0.0f));
+ const auto& s = t.shapes[size_t(arkitBlendShapeIndex(name))];
+ for (size_t k = 0; k < s.index.size(); ++k)
+ if (s.index[k] < count) d[s.index[k]] = s.offset[k] * scale;
+ return d;
+}
+
+} // namespace
+
+TEST(face_arkit_names_are_exact) {
+ // Apple ARKit's ARFaceAnchor.BlendShapeLocation names (MediaPipe uses the same, without tongueOut), typed out
+ // again here so a typo in the list can't hide.
+ const char* expected[] = {
+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight", "cheekPuff",
+ "cheekSquintLeft", "cheekSquintRight", "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",
+ "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight", "eyeLookUpLeft", "eyeLookUpRight",
+ "eyeSquintLeft", "eyeSquintRight", "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",
+ "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight", "mouthFrownLeft", "mouthFrownRight",
+ "mouthFunnel", "mouthLeft", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft", "mouthPressRight",
+ "mouthPucker", "mouthRight", "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper",
+ "mouthSmileLeft", "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight", "mouthUpperUpLeft",
+ "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight", "tongueOut"};
+ const auto& names = arkitBlendShapeNames();
+ CHECK(names.size() == 52);
+ CHECK(std::size(expected) == 52);
+ for (size_t i = 0; i < names.size() && i < std::size(expected); ++i) CHECK(names[i] == expected[i]);
+ CHECK(std::is_sorted(names.begin(), names.end()));
+ CHECK(arkitMirrorName("eyeBlinkLeft") == "eyeBlinkRight");
+ CHECK(arkitMirrorName("jawRight") == "jawLeft");
+ CHECK(arkitMirrorName("jawOpen") == "jawOpen");
+ for (const auto& n : names) CHECK(arkitBlendShapeIndex(arkitMirrorName(n)) >= 0);
+ // The template has exactly these shapes, each moving something, in this order.
+ const FaceTemplate& t = faceTemplate();
+ CHECK(t.shapes.size() == 52);
+ for (size_t i = 0; i < t.shapes.size() && i < names.size(); ++i) {
+ CHECK(t.shapes[i].name == names[i]);
+ CHECK(!t.shapes[i].index.empty());
+ }
+ CHECK(t.neutral.size() == 14062);
+ CHECK(t.skinEnd == 11248);
+}
+
+TEST(face_template_shapes_look_right) {
+ // Left is +X (the character's left), jawOpen drops the chin, blinks close the upper lid, the jaw shapes move
+ // the lower teeth.
+ const FaceTemplate& t = faceTemplate();
+ auto centroid = [&](const std::string& n) {
+ const auto& s = t.shapes[size_t(arkitBlendShapeIndex(n))];
+ glm::vec3 c(0.0f), d(0.0f);
+ float w = 0.0f;
+ for (size_t k = 0; k < s.index.size(); ++k) {
+ const float l = glm::length(s.offset[k]);
+ c += l * t.neutral[s.index[k]];
+ d += s.offset[k];
+ w += l;
+ }
+ return std::make_pair(c / w, d / float(s.index.size()));
+ };
+ CHECK(centroid("eyeBlinkLeft").first.x > 2.0f);
+ CHECK(centroid("eyeBlinkRight").first.x < -2.0f);
+ CHECK(centroid("eyeBlinkLeft").second.y < 0.0f);
+ CHECK(centroid("mouthSmileLeft").first.x > 1.0f);
+ CHECK(centroid("jawOpen").second.y < -0.2f);
+ CHECK(centroid("jawLeft").second.x > 0.05f); // towards the character's left
+ const auto& jaw = t.shapes[size_t(arkitBlendShapeIndex("jawOpen"))];
+ CHECK(std::abs(jaw.jawRotation.w) < 0.999f); // the lower teeth turn
+ const auto& blink = t.shapes[size_t(arkitBlendShapeIndex("eyeBlinkLeft"))];
+ CHECK(blink.jawTranslation == glm::vec3(0.0f));
+ // Landmarks sit where they should.
+ CHECK(t.neutral[faceLandmarkVertex(kEyeOuterLeft)].x > 3.0f);
+ CHECK(t.neutral[faceLandmarkVertex(kEyeOuterRight)].x < -3.0f);
+ CHECK(t.neutral[faceLandmarkVertex(kChin)].y < t.neutral[faceLandmarkVertex(kMouthLeft)].y);
+}
+
+TEST(face_transfer_on_the_template_is_near_identity) {
+ // Deformation transfer onto the template itself gives the template's shapes back.
+ const FaceTemplate& t = faceTemplate();
+ FaceFit fit;
+ fit.positions = t.neutral;
+ std::vector<std::vector<glm::vec3>> off;
+ transferFaceShapes(fit, off);
+ CHECK(off.size() == 52);
+ float worst = 0.0f;
+ for (size_t k = 0; k < off.size(); ++k) {
+ const auto ref = templateShape(t.shapes[k].name, t.neutral.size(), 1.0f);
+ float err = 0.0f;
+ for (size_t i = 0; i < ref.size(); ++i) err = std::max(err, glm::length(off[k][i] - ref[i]));
+ worst = std::max(worst, err / std::max(maxLength(ref), 1e-6f));
+ }
+ std::printf(" transfer on the template: worst error %.2e of the shape's peak\n", double(worst));
+ CHECK(worst < 1e-3f);
+
+ // Through a similarity (scaled to metres, turned, moved): the same shapes, scaled and turned.
+ fit.align.scale = 0.01f;
+ fit.align.rotation = glm::mat3(glm::rotate(glm::mat4(1.0f), 0.3f, glm::vec3(0, 1, 0)));
+ fit.align.translation = glm::vec3(1, 2, 3);
+ for (size_t i = 0; i < t.neutral.size(); ++i) fit.positions[i] = fit.align.apply(t.neutral[i]);
+ transferFaceShapes(fit, off);
+ const size_t jaw = size_t(arkitBlendShapeIndex("jawOpen"));
+ const auto ref = templateShape("jawOpen", t.neutral.size(), 1.0f);
+ float err = 0.0f;
+ for (size_t i = 0; i < ref.size(); ++i) err = std::max(err, glm::length(off[jaw][i] - fit.align.applyVector(ref[i])));
+ CHECK(err < 1e-3f * 0.01f * maxLength(ref));
+}
+
+TEST(face_fit_finds_the_landmarks_on_a_known_head) {
+ // The template head reshaped (another person), re-topologised (decimated to 60%) and moved: the automatic fit
+ // puts each landmark within 3% of the head's height of where it really is; given landmarks, within 1%.
+ const FaceTemplate& t = faceTemplate();
+ Mesh head = decimate(templateHead(otherPerson), templateHead(otherPerson).triangleCount() * 6 / 10);
+ const float height = 34.0f * 0.0095f;
+ FaceFit fit;
+ std::string error;
+ CHECK(fitFaceTemplate(head.positions, head.triangles, nullptr, fit, error));
+ float worst = 0.0f;
+ for (int l = 0; l < kFaceLandmarkCount; ++l) {
+ const glm::vec3 truth = otherPerson(t.neutral[faceLandmarkVertex(l)]);
+ worst = std::max(worst, glm::distance(fit.landmarks.position[size_t(l)], truth));
+ }
+ std::printf(" automatic fit: worst landmark %.2f%% of the head, rms %.2f%%, coverage %.0f%%\n",
+ double(worst / height * 100.0f), double(fit.rmsError / height * 100.0f), double(fit.coverage * 100.0f));
+ CHECK(worst < 0.03f * height);
+ CHECK(fit.rmsError < 0.01f * height);
+ CHECK(fit.coverage > 0.8f);
+
+ // With the landmarks placed (as the artist would click them, a little off): closer still.
+ FaceLandmarks lm;
+ for (int l = 0; l < kFaceLandmarkCount; ++l) {
+ lm.position[size_t(l)] = otherPerson(t.neutral[faceLandmarkVertex(l)]) + glm::vec3(0.0005f, -0.0003f, 0.0f);
+ lm.set[size_t(l)] = true;
+ }
+ FaceFit guided;
+ CHECK(fitFaceTemplate(head.positions, head.triangles, &lm, guided, error));
+ float worstGuided = 0.0f;
+ for (int l = 0; l < kFaceLandmarkCount; ++l)
+ worstGuided = std::max(worstGuided, glm::distance(guided.landmarks.position[size_t(l)],
+ otherPerson(t.neutral[faceLandmarkVertex(l)])));
+ std::printf(" guided fit: worst landmark %.2f%% of the head\n", double(worstGuided / height * 100.0f));
+ CHECK(worstGuided < 0.01f * height);
+
+ // Too few landmarks is an error, not a bad fit.
+ FaceLandmarks two;
+ two.set[kNoseTip] = two.set[kChin] = true;
+ CHECK(!fitFaceTemplate(head.positions, head.triangles, &two, guided, error));
+ // A sphere has no face: the fit runs but finds little of the template on it.
+ Mesh ball = makeIcosphere(4, 0.15f);
+ FaceFit none;
+ if (fitFaceTemplate(ball.positions, ball.triangles, nullptr, none, error)) CHECK(none.rmsError > 0.005f || none.coverage < 0.8f);
+}
+
+TEST(face_generate_on_the_template_matches_its_shapes) {
+ // End to end on the template's own head: the generated layers are the template's shapes (in metres).
+ Document doc = makeDoc(templateHead());
+ const size_t nv = doc.mesh.vertexCount();
+ const auto before = doc.mesh.positions;
+ const size_t undoDepth = doc.undo.undoCount();
+ CHECK(run(doc, "face_shapes_generate").ok);
+ CHECK(doc.mesh.layers.size() == 52);
+ CHECK(doc.undo.undoCount() == undoDepth + 1);
+ for (size_t k = 0; k < doc.mesh.layers.size(); ++k) {
+ CHECK(doc.mesh.layers[k].name == arkitBlendShapeNames()[k]);
+ CHECK(doc.mesh.layers[k].weight == 0.0f);
+ }
+ CHECK(doc.mesh.positions == before); // all at weight 0: the sculpt looks the same
+ for (const char* name : {"jawOpen", "eyeBlinkLeft", "mouthSmileRight", "browInnerUp"}) {
+ const auto ref = templateShape(name, nv, 0.01f);
+ const SculptLayer* l = findLayer(doc.mesh, name);
+ CHECK(l != nullptr);
+ if (!l) continue;
+ float err = 0.0f;
+ for (uint32_t i = 0; i < faceTemplate().faceEnd; ++i) err = std::max(err, glm::length(l->delta[i] - ref[i]));
+ std::printf(" %s on the template: max error %.1f%% of its peak\n", name, double(err / maxLength(ref) * 100.0f));
+ CHECK(err < 0.1f * maxLength(ref));
+ }
+ // Generating again replaces the 52 layers instead of adding more; other layers stay.
+ CHECK(run(doc, "layer_add", {{"name", std::string("Corrective")}}).ok);
+ CHECK(run(doc, "face_shapes_generate").ok);
+ CHECK(doc.mesh.layers.size() == 53);
+ CHECK(findLayer(doc.mesh, "Corrective") != nullptr);
+}
+
+TEST(face_symmetric_pairs_mirror) {
+ // The template head is symmetric about X = 0: Left and Right shapes are exact mirror images, and centre shapes
+ // are symmetric themselves, on a reshaped head too.
+ Document doc = makeDoc(templateHead([](const glm::vec3& p) {
+ glm::vec3 q = p * 0.0105f;
+ q.y *= 1.08f; // a longer face, still symmetric
+ return q;
+ }));
+ CHECK(run(doc, "face_shapes_generate").ok);
+ const Mesh& m = doc.mesh;
+ // Each vertex's mirror image.
+ std::vector<uint32_t> mirror(m.vertexCount(), ~0u);
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ const glm::vec3 q(-m.positions[v].x, m.positions[v].y, m.positions[v].z);
+ float best = 1e9f;
+ for (uint32_t u = 0; u < m.vertexCount(); ++u) {
+ const float d = glm::distance(m.positions[u], q);
+ if (d < best) best = d, mirror[v] = u;
+ }
+ if (best > 1e-5f) mirror[v] = ~0u;
+ if (v > 3000) break; // (a sample is enough, and keeps this quadratic search quick)
+ }
+ auto flip = [](const glm::vec3& d) { return glm::vec3(-d.x, d.y, d.z); };
+ float worstPair = 0.0f, worstCentre = 0.0f, peak = 0.0f;
+ for (const char* name : {"eyeBlinkLeft", "mouthSmileLeft", "browOuterUpLeft", "jawLeft"}) {
+ const SculptLayer* a = findLayer(m, name);
+ const SculptLayer* b = findLayer(m, arkitMirrorName(name));
+ CHECK(a && b);
+ if (!a || !b) continue;
+ peak = std::max(peak, maxLength(a->delta));
+ for (uint32_t v = 0; v <= 3000 && v < m.vertexCount(); ++v)
+ if (mirror[v] != ~0u) worstPair = std::max(worstPair, glm::length(a->delta[v] - flip(b->delta[mirror[v]])));
+ }
+ for (const char* name : {"jawOpen", "mouthPucker", "browInnerUp"}) {
+ const SculptLayer* a = findLayer(m, name);
+ for (uint32_t v = 0; a && v <= 3000 && v < m.vertexCount(); ++v)
+ if (mirror[v] != ~0u) worstCentre = std::max(worstCentre, glm::length(a->delta[v] - flip(a->delta[mirror[v]])));
+ }
+ std::printf(" mirror error: pairs %.2e, centre %.2e (peak %.2e)\n", double(worstPair), double(worstCentre), double(peak));
+ CHECK(worstPair < 1e-4f * peak);
+ CHECK(worstCentre < 1e-4f * peak);
+ // Symmetry off: still close (the template is symmetric) but not forced.
+ CHECK(run(doc, "face_shapes_generate", {{"symmetry", std::string("off")}}).ok);
+}
+
+TEST(face_subtools_eyes_and_teeth) {
+ // Eyes turn about their centres for eyeLook*, the lower teeth follow jawOpen and the upper teeth don't, and
+ // brows on the face follow the skin.
+ const FaceTemplate& t = faceTemplate();
+ Document doc = makeDoc(templateHead());
+ auto at = [&](const glm::vec3& cm) { return cm * 0.01f; };
+ // Eyeballs where the template's eyes are (between the corners, a little behind).
+ Mesh eyes;
+ for (int side = 0; side < 2; ++side) {
+ const glm::vec3 c = 0.5f * (t.neutral[faceLandmarkVertex(side ? kEyeOuterLeft : kEyeOuterRight)] +
+ t.neutral[faceLandmarkVertex(side ? kEyeInnerLeft : kEyeInnerRight)]) -
+ glm::vec3(0, 0, 1.0f);
+ Mesh ball = makeIcosphere(3, 0.012f);
+ const uint32_t first = uint32_t(eyes.positions.size());
+ for (auto& p : ball.positions) eyes.positions.push_back(p + at(c));
+ for (auto tri : ball.triangles) eyes.triangles.push_back(tri + glm::uvec3(first));
+ }
+ eyes.rebuildTopology();
+ eyes.recomputeAllNormals();
+ doc.addSubtool(eyes, "Eyes", false);
+ // Teeth: an upper and a lower row of little boxes behind the lips.
+ Mesh teeth;
+ for (int row = 0; row < 2; ++row) {
+ Mesh box = makeCube(1, 0.004f);
+ for (int k = -3; k <= 3; ++k) {
+ const glm::vec3 c = at(glm::vec3(float(k) * 0.6f, row ? t.upperTeethY : t.lowerTeethCentroid.y,
+ t.lowerTeethCentroid.z + 0.8f - 0.05f * float(k * k)));
+ const uint32_t first = uint32_t(teeth.positions.size());
+ for (auto& p : box.positions) teeth.positions.push_back(p + c);
+ for (auto tri : box.triangles) teeth.triangles.push_back(tri + glm::uvec3(first));
+ }
+ }
+ teeth.rebuildTopology();
+ teeth.recomputeAllNormals();
+ doc.addSubtool(teeth, "Teeth", false);
+ doc.addSubtool(makeIcosphere(2, 0.5f), "Far away ball", false);
+ for (auto& p : doc.subtools[3].mesh.positions) p += glm::vec3(3, 0, 0);
+ CHECK(run(doc, "face_shapes_generate").ok);
+
+ const Mesh& em = doc.subtools[1].mesh;
+ const SculptLayer* up = findLayer(em, "eyeLookUpLeft");
+ const SculptLayer* out = findLayer(em, "eyeLookOutLeft");
+ CHECK(up && out && em.layers.size() == 8);
+ if (up && out) {
+ // The front of the left eye (largest z among x > 0) goes up; the right eye doesn't move.
+ uint32_t front = 0, rightFront = 0;
+ for (uint32_t v = 0; v < em.vertexCount(); ++v) {
+ if (em.positions[v].x > 0 && em.positions[v].z > em.positions[front].z) front = v;
+ if (em.positions[v].x < 0 && (em.positions[rightFront].x >= 0 || em.positions[v].z > em.positions[rightFront].z))
+ rightFront = v;
+ }
+ CHECK(em.positions[front].x > 0.0f);
+ CHECK(up->delta[front].y > 0.003f);
+ CHECK(out->delta[front].x > 0.003f); // looking out = towards the character's left
+ CHECK(up->delta[rightFront] == glm::vec3(0.0f));
+ }
+ const Mesh& tm = doc.subtools[2].mesh;
+ const SculptLayer* jaw = findLayer(tm, "jawOpen");
+ CHECK(jaw != nullptr);
+ if (jaw) {
+ float lowerMove = 0.0f, upperMove = 0.0f;
+ for (uint32_t v = 0; v < tm.vertexCount(); ++v) {
+ const bool lowerRow = v < tm.vertexCount() / 2;
+ (lowerRow ? lowerMove : upperMove) = std::max(lowerRow ? lowerMove : upperMove, glm::length(jaw->delta[v]));
+ }
+ std::printf(" teeth on jawOpen: lower %.1f mm, upper %.1f mm\n", double(lowerMove * 1000), double(upperMove * 1000));
+ CHECK(lowerMove > 0.005f);
+ CHECK(upperMove == 0.0f);
+ }
+ CHECK(findLayer(tm, "eyeBlinkLeft") == nullptr); // teeth only get the jaw shapes
+ CHECK(doc.subtools[3].mesh.layers.empty()); // not on the face: left alone
+
+ // face_weights drives every SubTool: the eyes turn with eyeLookUpLeft.
+ const auto eyesBefore = doc.subtools[1].mesh.positions;
+ CHECK(run(doc, "face_weights", {{"json", std::string("{\"eyeLookUpLeft\":1,\"jawOpen\":0.5}")}}).ok);
+ CHECK(doc.subtools[1].mesh.positions != eyesBefore);
+}
+
+TEST(face_weights_fast_path_is_exact_and_not_undoable) {
+ Document doc = makeDoc(templateHead());
+ CHECK(run(doc, "face_shapes_generate").ok);
+ const size_t undoDepth = doc.undo.undoCount();
+ doc.markClean();
+ CHECK(run(doc, "face_weights", {{"json", std::string("{\"jawOpen\":0.7,\"eyeBlinkLeft\":1,\"mouthSmileRight\":0.4}")}}).ok);
+ CHECK(doc.undo.undoCount() == undoDepth);
+ CHECK(!doc.dirty());
+ CHECK(findLayer(doc.mesh, "jawOpen")->weight == 0.7f);
+ // The same positions and normals as a full evaluation.
+ Mesh full = doc.mesh;
+ full.evaluateAll();
+ full.recomputeAllNormals();
+ CHECK(full.positions == doc.mesh.positions);
+ float nerr = 0.0f;
+ for (size_t i = 0; i < full.normals.size(); ++i) nerr = std::max(nerr, glm::length(full.normals[i] - doc.mesh.normals[i]));
+ CHECK(nerr < 1e-5f);
+ // Only what moved is marked for the GPU (not the whole mesh).
+ doc.mesh.clearDirty();
+ CHECK(run(doc, "face_weights", {{"json", std::string("{\"eyeBlinkLeft\":0.5}")}}).ok);
+ size_t dirty = 0;
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) dirty += doc.mesh.vertexDirty(v);
+ CHECK(dirty > 0 && dirty < doc.mesh.vertexCount() / 3);
+ // Presets set all 52; unknown names are reported; bad JSON is an error.
+ CHECK(run(doc, "face_preset", {{"name", std::string("smile")}}).ok);
+ CHECK(findLayer(doc.mesh, "jawOpen")->weight == 0.0f);
+ CHECK(findLayer(doc.mesh, "mouthSmileLeft")->weight == 0.8f);
+ CHECK(registry().execute(doc, "face_weights", {{"json", std::string("{\"notAShape\":1,\"jawOpen\":0.1}")}}).message.find("notAShape") !=
+ std::string::npos);
+ CHECK(!registry().execute(doc, "face_weights", {{"json", std::string("{jawOpen:1")}}).ok);
+ CHECK(!registry().execute(doc, "face_preset", {{"name", std::string("Nope")}}).ok);
+ // Without shapes it says what to do.
+ Document plain = makeDoc(makeIcosphere(2));
+ CHECK(registry().execute(plain, "face_weights", {{"json", std::string("{\"jawOpen\":1}")}}).message.find("Generate") !=
+ std::string::npos);
+ // After a stroke into a layer (new undo revision) the next call sees the layer's new vertices.
+ SculptLayer& smile = doc.mesh.layers[size_t(arkitBlendShapeIndex("mouthSmileLeft"))];
+ smile.delta[0] = glm::vec3(0.01f, 0, 0); // vertex 0 wasn't moved by the smile before
+ UndoRecord rec;
+ rec.label = "Stroke";
+ doc.undo.push(std::move(rec));
+ CHECK(run(doc, "face_weights", {{"json", std::string("{\"mouthSmileLeft\":0.2}")}}).ok);
+ Mesh again = doc.mesh;
+ again.evaluateAll();
+ CHECK(again.positions == doc.mesh.positions);
+}
+
+TEST(face_weights_timing_on_a_500k_head) {
+ // A 720k-vertex head (the template skin divided three times) with the 52 shapes: a live frame that changes
+ // every weight costs a few milliseconds and touches only the face.
+ Mesh base = templateHead();
+ std::string error;
+ for (int i = 0; i < 2; ++i) CHECK(subdivDivide(base, true, error));
+ Mesh head = subdivLevelMesh(base, subdivCurrentLevel(base));
+ head.multires.reset();
+ Mesh big = head;
+ CHECK(subdivDivide(big, true, error));
+ head = subdivLevelMesh(big, 1);
+ head.multires.reset();
+ head.rebuildTopology();
+ head.recomputeAllNormals();
+ std::printf(" head: %zu vertices\n", head.vertexCount());
+ CHECK(head.vertexCount() > 500000);
+ Document doc = makeDoc(std::move(head));
+ auto t0 = std::chrono::steady_clock::now();
+ CHECK(run(doc, "face_shapes_generate").ok);
+ const double genMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
+ const auto& names = arkitBlendShapeNames();
+ double total = 0.0, worst = 0.0;
+ size_t verts = 0;
+ const int frames = 30;
+ for (int f = 0; f < frames; ++f) {
+ std::string json = "{";
+ for (size_t k = 0; k < names.size(); ++k) {
+ char buf[64];
+ std::snprintf(buf, sizeof buf, "%s\"%s\":%.3f", k ? "," : "", names[k].c_str(),
+ 0.5 + 0.5 * std::sin(0.3 * double(f) + double(k)));
+ json += buf;
+ }
+ json += "}";
+ doc.mesh.clearDirty();
+ const auto s = std::chrono::steady_clock::now();
+ CHECK(registry().execute(doc, "face_weights", {{"json", json}}).ok);
+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - s).count();
+ if (f > 0) { // the first call finds each layer's vertices
+ total += ms;
+ worst = std::max(worst, ms);
+ }
+ verts = 0;
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); v += 7) verts += doc.mesh.vertexDirty(v);
+ }
+ const double avg = total / (frames - 1);
+ std::printf(" generate %.0f ms; face_weights (all 52 changing): %.2f ms average, %.2f ms worst, ~%zu%% of the "
+ "vertices re-uploaded\n",
+ genMs, avg, worst, verts * 7 * 100 / doc.mesh.vertexCount());
+ CHECK(verts * 7 < doc.mesh.vertexCount()); // the face, not the whole head
+ if (std::getenv("SF_BENCH_LIMITS")) CHECK(avg < 15.0);
+ Mesh full = doc.mesh;
+ full.evaluateAll();
+ CHECK(full.positions == doc.mesh.positions);
+}
+
+TEST(face_generation_is_deterministic_with_threads) {
+ Mesh head = templateHead(otherPerson);
+ Document a = makeDoc(head), b = makeDoc(head);
+ ThreadPool::shared().setSerial(true);
+ CHECK(run(a, "face_shapes_generate").ok);
+ ThreadPool::shared().setSerial(false);
+ CHECK(run(b, "face_shapes_generate").ok);
+ CHECK(a.mesh.layers.size() == b.mesh.layers.size());
+ bool same = true;
+ for (size_t k = 0; k < a.mesh.layers.size() && k < b.mesh.layers.size(); ++k) same &= a.mesh.layers[k].delta == b.mesh.layers[k].delta;
+ CHECK(same);
+}
+
+TEST(face_shapes_on_subdivision_levels) {
+ // A head with 3 levels (11k, 45k, 180k vertices): the shapes are made on SDiv 2 (the lowest with 20k) and show
+ // at the top level, where the top level's own detail is kept at weight 0.
+ Document doc = makeDoc(templateHead());
+ std::string msg;
+ CHECK(divideUndoable(doc, true, msg));
+ CHECK(divideUndoable(doc, true, msg));
+ // Detail at the top: a bump on the forehead.
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v)
+ if (doc.mesh.positions[v].y > 0.08f && doc.mesh.positions[v].z > 0.05f) doc.mesh.positions[v].z += 0.002f;
+ doc.mesh.recomputeAllNormals();
+ const auto detailed = doc.mesh.positions;
+ const CommandResult r = run(doc, "face_shapes_generate");
+ CHECK(r.ok);
+ CHECK(r.message.find("SDiv 2") != std::string::npos);
+ CHECK(subdivCurrentLevel(doc.mesh) == 2);
+ CHECK(doc.mesh.layers.size() == 52);
+ float detailErr = 0.0f;
+ for (size_t v = 0; v < detailed.size(); ++v) detailErr = std::max(detailErr, glm::distance(detailed[v], doc.mesh.positions[v]));
+ CHECK(detailErr < 1e-5f);
+ const SculptLayer* jaw = findLayer(doc.mesh, "jawOpen");
+ CHECK(jaw && maxLength(jaw->delta) > 0.02f);
+ // Down to SDiv 1 and the layers are there too.
+ CHECK(setSubdivLevelUndoable(doc, 0, msg));
+ CHECK(doc.mesh.layers.size() == 52);
+}
+
+TEST(face_takes_parse_bake_and_export) {
+ // A take as the phone link records it: a JSON array of face messages (ms timestamps); also {"frames":[...]}
+ // and JSON Lines.
+ const std::string take =
+ "[{\"type\":\"face\",\"t\":1000,\"weights\":{\"jawOpen\":0,\"eyeBlinkLeft\":1},\"head\":[0,0,0,1]},"
+ "{\"type\":\"face\",\"t\":1100,\"weights\":{\"jawOpen\":0.5}},"
+ "{\"type\":\"hello\"},"
+ "{\"type\":\"face\",\"t\":1200,\"weights\":{\"jawOpen\":1,\"_neutral\":0.2}}]";
+ MorphAnimation a;
+ std::string error;
+ CHECK(parseFaceTake(take, a, error));
+ CHECK(a.times.size() == 3);
+ CHECK(a.channels.size() == 52);
+ CHECK(std::abs(a.times[2] - 0.2f) < 1e-6f);
+ CHECK(a.value(1, size_t(a.channel("jawOpen"))) == 0.5f);
+ CHECK(a.value(0, size_t(a.channel("eyeBlinkLeft"))) == 1.0f);
+ MorphAnimation b;
+ CHECK(parseFaceTake("{\"frames\":[{\"t\":0,\"weights\":{\"jawOpen\":1}},{\"t\":40,\"weights\":{}}]}", b, error));
+ CHECK(b.times.size() == 2);
+ CHECK(parseFaceTake("{\"type\":\"face\",\"t\":5,\"weights\":{\"jawOpen\":0.1}}\n{\"type\":\"face\",\"t\":38,\"weights\":{\"jawOpen\":0.2}}\n", b, error));
+ CHECK(b.times.size() == 2);
+ CHECK(!parseFaceTake("[]", b, error));
+ std::vector<std::pair<std::string, float>> w;
+ sampleMorphAnimation(a, 0.05f, w);
+ CHECK(std::abs(w[size_t(a.channel("jawOpen"))].second - 0.25f) < 1e-5f);
+ const MorphAnimation r = resampleMorphAnimation(a, 30.0f);
+ CHECK(r.times.size() == 7); // 0 .. 0.2 s at 30 fps
+
+ // Bake into a document with the shapes, export GLB and USD, read them back.
+ Document doc = makeDoc(templateHead());
+ CHECK(run(doc, "face_shapes_generate").ok);
+ const std::string takePath = tempPath("sf_face_take.json");
+ {
+ std::ofstream f(takePath, std::ios::binary);
+ f << take;
+ }
+ CHECK(run(doc, "face_take_bake", {{"path", takePath}, {"fps", 30.0}}).ok);
+ MorphAnimation baked;
+ CHECK(bakedFaceAnimation(doc, baked));
+ CHECK(baked.times.size() == 7);
+ // It survives saving the project.
+ const std::string proj = tempPath("sf_face_take.sfproj");
+ CHECK(run(doc, "save_project", {{"path", proj}}).ok);
+ Document loaded;
+ CHECK(run(loaded, "open_project", {{"path", proj}}).ok);
+ MorphAnimation back;
+ CHECK(bakedFaceAnimation(loaded, back));
+ CHECK(back.times.size() == 7 && back.channels == baked.channels);
+ CHECK(loaded.mesh.layers.size() == 52);
+
+ const std::string glb = tempPath("sf_face_take.glb");
+ CHECK(run(doc, "export_glb", {{"path", glb}}).ok);
+ std::ifstream gf(glb, std::ios::binary);
+ std::string bytes((std::istreambuf_iterator<char>(gf)), std::istreambuf_iterator<char>());
+ CHECK(bytes.find("\"animations\":[{\"name\":\"sf_face_take\"") != std::string::npos);
+ CHECK(bytes.find("\"path\":\"weights\"") != std::string::npos);
+ const std::string usda = tempPath("sf_face_take.usda");
+ CHECK(run(doc, "export_usd", {{"path", usda}}).ok);
+ std::ifstream uf(usda);
+ std::stringstream us;
+ us << uf.rdbuf();
+ CHECK(us.str().find("blendShapeWeights.timeSamples") != std::string::npos);
+ CHECK(us.str().find("timeCodesPerSecond = 30") != std::string::npos);
+ // Cleared: plain exports again.
+ CHECK(run(doc, "face_take_clear").ok);
+ CHECK(!bakedFaceAnimation(doc, back));
+}
+
+TEST(face_export_round_trips_keep_morph_targets_and_names) {
+ Document doc = makeDoc(templateHead());
+ CHECK(run(doc, "face_shapes_generate").ok);
+ const Mesh& m = doc.mesh;
+ auto sameShapes = [&](const Mesh& got, float tol, const char* what) {
+ CHECK(got.layers.size() == 52);
+ bool names = got.layers.size() == 52, deltas = true;
+ for (size_t k = 0; k < got.layers.size() && k < 52; ++k) {
+ names &= got.layers[k].name == arkitBlendShapeNames()[k];
+ deltas &= got.vertexCount() == m.vertexCount() &&
+ std::abs(maxLength(got.layers[k].delta) - maxLength(m.layers[k].delta)) <= tol;
+ }
+ if (!names || !deltas) std::printf(" %s: names %d, deltas %d\n", what, int(names), int(deltas));
+ CHECK(names);
+ CHECK(deltas);
+ };
+ std::string error;
+ const std::string glb = tempPath("sf_face_rt.glb");
+ CHECK(saveGlb(glb, m, "Head", error));
+ Mesh g;
+ CHECK(loadGltf(glb, g, error));
+ sameShapes(g, 1e-6f, "glb");
+ const std::string usda = tempPath("sf_face_rt.usda");
+ CHECK(saveUsd(usda, &m, nullptr, "Head", error));
+ Mesh u;
+ SplatCloud sc;
+ CHECK(loadUsd(usda, u, sc, error));
+ sameShapes(u, 1e-5f, "usd");
+ const std::string fbx = tempPath("sf_face_rt.fbx");
+ FbxExportOptions fo;
+ fo.scale = 100.0f; // (FBX is in centimetres; SculptForge reads it back in metres)
+ CHECK(saveFbx(fbx, "Head", {&m}, fo, error));
+ Mesh f;
+ CHECK(loadFbx(fbx, f, error));
+ sameShapes(f, 1e-5f, "fbx");
+
+ // The Blender bridge sends the layers as shape keys beside the .GoZ (base shape).
+ const std::string root = tempPath("sf_face_bridge");
+ std::filesystem::remove_all(root);
+ std::string message;
+ CHECK(blenderSend({{"Head", &m}}, root, message));
+ BridgeManifest man;
+ CHECK(readBridgeManifest(blenderOutbox(root) + "/manifest.json", man, error));
+ CHECK(man.objects.size() == 1 && !man.objects[0].shapes.empty());
+ if (!man.objects.empty() && !man.objects[0].shapes.empty()) {
+ uint32_t nv = 0;
+ std::vector<BridgeShape> shapes;
+ CHECK(readBridgeShapes(blenderOutbox(root) + "/" + man.objects[0].shapes, nv, shapes, error));
+ CHECK(nv == m.vertexCount());
+ CHECK(shapes.size() == 52);
+ for (size_t k = 0; k < shapes.size() && k < 52; ++k) CHECK(shapes[k].name == arkitBlendShapeNames()[k]);
+ // Blender's axes: SculptForge's -Z offset (jaw back) is Blender's +Y.
+ const auto& jaw = shapes[size_t(arkitBlendShapeIndex("jawOpen"))];
+ const SculptLayer* l = findLayer(m, "jawOpen");
+ if (!jaw.index.empty() && l) {
+ const glm::vec3 sf = l->delta[jaw.index[0]];
+ CHECK(std::abs(jaw.offset[0].x - sf.x) < 1e-6f && std::abs(jaw.offset[0].y + sf.z) < 1e-6f &&
+ std::abs(jaw.offset[0].z - sf.y) < 1e-6f);
+ }
+ }
+ std::filesystem::remove_all(root);
+}
diff --git a/tools/face/build_ict_template.py b/tools/face/build_ict_template.py
new file mode 100644
index 00000000..25b056ff
--- /dev/null
+++ b/tools/face/build_ict_template.py
@@ -0,0 +1,205 @@
+#!/usr/bin/env python3
+# SculptForge - open source digital sculpting
+# SPDX-License-Identifier: GPL-3.0-or-later
+"""Builds assets/face/ict-arkit.sfface, the template head SculptForge's Generate Facial Shapes fits to a sculpt.
+
+Source: ICT-FaceKit (USC Institute for Creative Technologies, MIT licence), the "ICT Face Model Light":
+https://github.com/ICT-VGL/ICT-FaceKit (FaceXModel/*.obj). Download that folder (about 150 MB of OBJs), then
+
+ python3 tools/face/build_ict_template.py <ICT-FaceKit>/FaceXModel assets/face/ict-arkit.sfface
+
+What is kept: the neutral mesh's skin (face, head and neck), mouth socket and eye sockets (vertices 0-14061), and
+for each of the 52 Apple ARKit blend shapes the offsets of those vertices, sparse and quantised to 16 bits. ICT's
+names are ARKit's with _L / _R for Left / Right (the character's own left, +X); its separate browInnerUp_L/_R and
+cheekPuff_L/_R are summed into ARKit's single browInnerUp and cheekPuff, cheekRaiser_L/_R and PupilDilate_L/_R are
+not ARKit shapes and are left out, and ICT has no tongueOut: the file's tongueOut opens the jaw a little (the
+tongue itself is a SubTool's job, see core/Face.cpp). The teeth aren't kept, only how the lower teeth move in each
+shape (a rigid transform fitted to ICT's lower teeth), which drives teeth SubTools. Units: centimetres, Y up, the
+face looking down +Z.
+
+File layout (little endian):
+ char[8] "SFFACE01"
+ u32 vertex count V, triangle count T, shape count S
+ u32[4] region ends: face, skin (face + head and neck), mouth socket, eye sockets (= V)
+ f32[3V] neutral positions
+ u16[3T] triangles (ICT's quads split along their first diagonal)
+ f32[3] lower teeth centroid, f32 upper teeth centroid y
+ S times: u8 name length, name (ASCII), f32 quantisation step, f32[4] lower jaw rotation (x, y, z, w),
+ f32[3] lower jaw translation (x' = R x + t), u32 count N, u16[N] vertex indices, i16[3N] offsets / step
+"""
+import math
+import os
+import struct
+import sys
+
+ARKIT = sorted([
+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight", "cheekPuff",
+ "cheekSquintLeft", "cheekSquintRight", "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",
+ "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight", "eyeLookUpLeft", "eyeLookUpRight",
+ "eyeSquintLeft", "eyeSquintRight", "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",
+ "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight", "mouthFrownLeft", "mouthFrownRight",
+ "mouthFunnel", "mouthLeft", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft", "mouthPressRight",
+ "mouthPucker", "mouthRight", "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper",
+ "mouthSmileLeft", "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight", "mouthUpperUpLeft",
+ "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight", "tongueOut"])
+assert len(ARKIT) == 52
+
+FACE_END, SKIN_END, MOUTH_END, EYES_END = 9409, 11248, 13294, 14062
+UPPER_TEETH = range(17039, 19247)
+LOWER_TEETH = range(19247, 21451)
+THRESHOLD = 0.002 # cm: offsets below 0.02 mm are dropped
+
+
+def load_obj(path, faces=False):
+ verts, polys = [], []
+ with open(path) as f:
+ for line in f:
+ if line.startswith("v "):
+ a = line.split()
+ verts.append((float(a[1]), float(a[2]), float(a[3])))
+ elif faces and line.startswith("f "):
+ polys.append([int(c.split("/")[0]) - 1 for c in line.split()[1:]])
+ return verts, polys
+
+
+def ict_sources(name):
+ """The ICT files whose offsets make up ARKit shape `name`, and a factor for each."""
+ if name == "browInnerUp":
+ return [("browInnerUp_L", 1.0), ("browInnerUp_R", 1.0)]
+ if name == "cheekPuff":
+ return [("cheekPuff_L", 1.0), ("cheekPuff_R", 1.0)]
+ if name == "tongueOut":
+ return [("jawOpen", 0.25)]
+ for side, suffix in (("Left", "_L"), ("Right", "_R")):
+ if name.endswith(side) and name not in ("jawLeft", "jawRight", "mouthLeft", "mouthRight"):
+ return [(name[: -len(side)] + suffix, 1.0)]
+ return [(name, 1.0)]
+
+
+def mat_to_quat(m):
+ tr = m[0][0] + m[1][1] + m[2][2]
+ if tr > 0:
+ s = math.sqrt(tr + 1.0) * 2
+ return ((m[2][1] - m[1][2]) / s, (m[0][2] - m[2][0]) / s, (m[1][0] - m[0][1]) / s, 0.25 * s)
+ if m[0][0] > m[1][1] and m[0][0] > m[2][2]:
+ s = math.sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]) * 2
+ return (0.25 * s, (m[0][1] + m[1][0]) / s, (m[0][2] + m[2][0]) / s, (m[2][1] - m[1][2]) / s)
+ if m[1][1] > m[2][2]:
+ s = math.sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]) * 2
+ return ((m[0][1] + m[1][0]) / s, 0.25 * s, (m[1][2] + m[2][1]) / s, (m[0][2] - m[2][0]) / s)
+ s = math.sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]) * 2
+ return ((m[0][2] + m[2][0]) / s, (m[1][2] + m[2][1]) / s, 0.25 * s, (m[1][0] - m[0][1]) / s)
+
+
+def quat_to_mat(q):
+ x, y, z, w = q
+ return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
+
+
+def rigid_fit(src, dst):
+ """Rotation (quaternion) and translation taking points src to dst in the least-squares sense: Horn's method
+ (the largest eigenvector of the 4x4 matrix N, found by power iteration on N + cI)."""
+ n = len(src)
+ cs = [sum(p[k] for p in src) / n for k in range(3)]
+ cd = [sum(p[k] for p in dst) / n for k in range(3)]
+ S = [[0.0] * 3 for _ in range(3)]
+ for p, q in zip(src, dst):
+ a = [p[k] - cs[k] for k in range(3)]
+ b = [q[k] - cd[k] for k in range(3)]
+ for i in range(3):
+ for j in range(3):
+ S[i][j] += a[i] * b[j]
+ Sxx, Sxy, Sxz = S[0]
+ Syx, Syy, Syz = S[1]
+ Szx, Szy, Szz = S[2]
+ N = [[Sxx + Syy + Szz, Syz - Szy, Szx - Sxz, Sxy - Syx],
+ [Syz - Szy, Sxx - Syy - Szz, Sxy + Syx, Szx + Sxz],
+ [Szx - Sxz, Sxy + Syx, -Sxx + Syy - Szz, Syz + Szy],
+ [Sxy - Syx, Szx + Sxz, Syz + Szy, -Sxx - Syy + Szz]]
+ c = sum(abs(N[i][j]) for i in range(4) for j in range(4)) + 1e-9
+ v = [1.0, 0.0, 0.0, 0.0]
+ for _ in range(2000):
+ w = [sum((N[i][j] + (c if i == j else 0.0)) * v[j] for j in range(4)) for i in range(4)]
+ norm = math.sqrt(sum(x * x for x in w))
+ w = [x / norm for x in w]
+ if sum(abs(a - b) for a, b in zip(w, v)) < 1e-14:
+ v = w
+ break
+ v = w
+ q = (v[1], v[2], v[3], v[0]) # (x, y, z, w)
+ if q[3] < 0:
+ q = tuple(-x for x in q)
+ R = quat_to_mat(q)
+ t = [cd[i] - sum(R[i][j] * cs[j] for j in range(3)) for i in range(3)]
+ return q, t
+
+
+def main():
+ if len(sys.argv) != 3:
+ print(__doc__)
+ sys.exit(2)
+ src, out = sys.argv[1], sys.argv[2]
+ neutral, polys = load_obj(os.path.join(src, "generic_neutral_mesh.obj"), faces=True)
+ V = EYES_END
+ tris = []
+ for p in polys:
+ if max(p) >= V:
+ continue
+ for k in range(1, len(p) - 1):
+ tris.append((p[0], p[k], p[k + 1]))
+ lower = [neutral[i] for i in LOWER_TEETH]
+ lower_centroid = [sum(p[k] for p in lower) / len(lower) for k in range(3)]
+ upper_y = sum(neutral[i][1] for i in UPPER_TEETH) / len(UPPER_TEETH)
+
+ cache = {}
+
+ def expression(name):
+ if name not in cache:
+ cache[name] = load_obj(os.path.join(src, name + ".obj"))[0]
+ return cache[name]
+
+ data = bytearray(b"SFFACE01")
+ data += struct.pack("<3I", V, len(tris), len(ARKIT))
+ data += struct.pack("<4I", FACE_END, SKIN_END, MOUTH_END, EYES_END)
+ for p in neutral[:V]:
+ data += struct.pack("<3f", *p)
+ for t in tris:
+ data += struct.pack("<3H", *t)
+ data += struct.pack("<4f", *lower_centroid, upper_y)
+ total = 0
+ for name in ARKIT:
+ offsets = [[0.0, 0.0, 0.0] for _ in range(V)]
+ moved = [list(p) for p in lower]
+ for file, factor in ict_sources(name):
+ e = expression(file)
+ for i in range(V):
+ for k in range(3):
+ offsets[i][k] += factor * (e[i][k] - neutral[i][k])
+ for j, i in enumerate(LOWER_TEETH):
+ for k in range(3):
+ moved[j][k] += factor * (e[i][k] - neutral[i][k])
+ idx = [i for i in range(V) if math.sqrt(sum(x * x for x in offsets[i])) > THRESHOLD]
+ peak = max((abs(x) for i in idx for x in offsets[i]), default=0.0)
+ step = peak / 32767.0 if peak > 0 else 1.0
+ q, t = rigid_fit(lower, moved)
+ R = quat_to_mat(q)
+ reach = max(math.dist([sum(R[i][j] * p[j] for j in range(3)) + t[i] for i in range(3)], p) for p in lower)
+ if reach < 0.01: # under 0.1 mm (ICT's blinks nudge a few teeth vertices): the jaw doesn't move
+ q, t = (0.0, 0.0, 0.0, 1.0), [0.0, 0.0, 0.0]
+ data += struct.pack("<B", len(name)) + name.encode("ascii")
+ data += struct.pack("<f4f3fI", step, *q, *t, len(idx))
+ data += struct.pack("<%dH" % len(idx), *idx)
+ for i in idx:
+ data += struct.pack("<3h", *(max(-32767, min(32767, round(x / step))) for x in offsets[i]))
+ total += len(idx)
+ print("%-20s %6d vertices, peak %.3f cm, jaw %s" % (name, len(idx), peak,
+ "moves" if q[3] != 1.0 or any(t) else "-"))
+ with open(out, "wb") as f:
+ f.write(data)
+ print("%s: %d bytes, %d vertices, %d triangles, %d offsets" % (out, len(data), V, len(tris), total))
+
+
+if __name__ == "__main__":
+ main()