#include "AutoRig.h" #include "UniRigPredictor.h" #include "MeshSegmenter.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { // A template joint literal: name, parent index, normalised x/y/z in // [0,1]^3 (y = up), and whether the refinement step recentres it. struct TJ { const char* name; int parent; double x, y, z; bool recenter; }; // --- Skeleton templates ----------------------------------------------------- // // Positions are in a normalised unit box: x in [0,1] left→right, y in // [0,1] down→up, z in [0,1] back→front. The mesh's actual up axis is // remapped from +Y at fit time via Options::upAxis. 0.5 is centre. // Humanoid (≈ Mixamo-lite): pelvis → spine → chest → neck → head, plus // symmetric shoulder/arm and hip/leg chains. Limb tips keep their // proportional position (recenter=false) so they reach to the silhouette. const TJ kHumanoid[] = { {"Hips", -1, 0.50, 0.52, 0.50, true}, {"Spine", 0, 0.50, 0.62, 0.50, true}, {"Chest", 1, 0.50, 0.72, 0.50, true}, {"Neck", 2, 0.50, 0.84, 0.50, true}, {"Head", 3, 0.50, 0.92, 0.50, true}, // Left arm (model's left = +x). {"LeftShoulder", 2, 0.60, 0.78, 0.50, true}, {"LeftArm", 5, 0.70, 0.78, 0.50, false}, {"LeftForeArm", 6, 0.82, 0.78, 0.50, false}, {"LeftHand", 7, 0.93, 0.78, 0.50, false}, // Right arm (-x). {"RightShoulder",2, 0.40, 0.78, 0.50, true}, {"RightArm", 9, 0.30, 0.78, 0.50, false}, {"RightForeArm",10, 0.18, 0.78, 0.50, false}, {"RightHand", 11, 0.07, 0.78, 0.50, false}, // Left leg. {"LeftUpLeg", 0, 0.58, 0.50, 0.50, true}, {"LeftLeg", 13, 0.58, 0.27, 0.50, false}, {"LeftFoot", 14, 0.58, 0.04, 0.55, false}, // Right leg. {"RightUpLeg", 0, 0.42, 0.50, 0.50, true}, {"RightLeg", 16, 0.42, 0.27, 0.50, false}, {"RightFoot", 17, 0.42, 0.04, 0.55, false}, }; // Biped: spine + 2 legs + short arm stubs (simpler/cheaper than humanoid). const TJ kBiped[] = { {"Hips", -1, 0.50, 0.52, 0.50, true}, {"Spine", 0, 0.50, 0.68, 0.50, true}, {"Head", 1, 0.50, 0.90, 0.50, true}, {"LeftArm", 1, 0.68, 0.74, 0.50, false}, {"RightArm", 1, 0.32, 0.74, 0.50, false}, {"LeftUpLeg", 0, 0.58, 0.50, 0.50, true}, {"LeftFoot", 5, 0.58, 0.04, 0.55, false}, {"RightUpLeg", 0, 0.42, 0.50, 0.50, true}, {"RightFoot", 7, 0.42, 0.04, 0.55, false}, }; // Quadruped: a horizontal spine (front→back along +z), 4 legs, head, tail. // Body lies low; "up" is still +y. Front of the body = high z. const TJ kQuadruped[] = { {"SpineFront", -1, 0.50, 0.55, 0.70, true}, {"SpineMid", 0, 0.50, 0.55, 0.50, true}, {"SpineBack", 1, 0.50, 0.55, 0.30, true}, {"Neck", 0, 0.50, 0.62, 0.82, true}, {"Head", 3, 0.50, 0.66, 0.95, true}, {"Tail", 2, 0.50, 0.55, 0.08, false}, // Legs are THREE segments (upper / lower / foot), matching the canonical // creature skeleton. A two-bone leg cannot receive a template clip: the // clip's lower-leg rotation has nowhere to go and the foot bone absorbs // the whole knee-to-hoof rotation. Measured on Cow|Run, whose upper leg // swings 128 deg with a further 93 deg at the knee, that tore the mesh // into flat shards; a walk (44 deg upper) survived, which is why this only // showed up on the faster gaits. // Front legs (high z). {"FrontLeftUpLeg", 0, 0.62, 0.45, 0.72, true}, {"FrontLeftLowLeg", 6, 0.62, 0.24, 0.72, false}, {"FrontLeftFoot", 7, 0.62, 0.04, 0.72, false}, {"FrontRightUpLeg", 0, 0.38, 0.45, 0.72, true}, {"FrontRightLowLeg", 9, 0.38, 0.24, 0.72, false}, {"FrontRightFoot", 10, 0.38, 0.04, 0.72, false}, // Back legs (low z). {"BackLeftUpLeg", 2, 0.62, 0.45, 0.30, true}, {"BackLeftLowLeg", 12, 0.62, 0.24, 0.30, false}, {"BackLeftFoot", 13, 0.62, 0.04, 0.30, false}, {"BackRightUpLeg", 2, 0.38, 0.45, 0.30, true}, {"BackRightLowLeg", 15, 0.38, 0.24, 0.30, false}, {"BackRightFoot", 16, 0.38, 0.04, 0.30, false}, }; // #1013 Vehicle: chassis root, front/rear axle, four wheels. Template z is the // LENGTH (front = high z), x the width, y up; wheels sit low. No slab // recentring (it would drag the wheels onto the centre line) — fitVehicle() // snaps them to the real lowest OCCUPIED SPACE per quadrant instead (voxel // cells, so tessellation density and degenerate vertex piles cannot bias it). const TJ kVehicle[] = { {"Chassis", -1, 0.50, 0.35, 0.50, false}, {"FrontAxle", 0, 0.50, 0.15, 0.78, false}, {"RearAxle", 0, 0.50, 0.15, 0.22, false}, {"FrontLeftWheel", 1, 0.85, 0.12, 0.78, false}, {"FrontRightWheel", 1, 0.15, 0.12, 0.78, false}, {"RearLeftWheel", 2, 0.85, 0.12, 0.22, false}, {"RearRightWheel", 2, 0.15, 0.12, 0.22, false}, }; // Generic fallback: a 3-joint vertical spine. Always succeeds. const TJ kGeneric[] = { {"Root", -1, 0.50, 0.05, 0.50, true}, {"Spine", 0, 0.50, 0.50, 0.50, true}, {"Top", 1, 0.50, 0.95, 0.50, true}, }; std::vector toJoints(const TJ* arr, size_t n) { std::vector out; out.reserve(n); for (size_t i = 0; i < n; ++i) { AutoRig::Joint j; j.name = QString::fromUtf8(arr[i].name); j.parent = arr[i].parent; j.pos = {arr[i].x, arr[i].y, arr[i].z}; j.recenter = arr[i].recenter; out.push_back(std::move(j)); } return out; } } // namespace // Out-of-line so the {} default args on the static methods resolve to a // constructor call (not class-definition-time aggregate init). The member // initializers in the header supply the actual default values. AutoRig::Options::Options() = default; std::vector AutoRig::templateJoints(Template tmpl) { switch (tmpl) { case Template::Humanoid: return toJoints(kHumanoid, std::size(kHumanoid)); case Template::Biped: return toJoints(kBiped, std::size(kBiped)); case Template::Quadruped: return toJoints(kQuadruped, std::size(kQuadruped)); case Template::Generic: return toJoints(kGeneric, std::size(kGeneric)); case Template::Vehicle: return toJoints(kVehicle, std::size(kVehicle)); } return toJoints(kGeneric, std::size(kGeneric)); } std::vector AutoRig::fitVehicle(const float* verts, int vertexCount, const Options& opts) { // Start from the box-mapped template so every joint has a sane default. std::vector placed = fitTemplate(templateJoints(Template::Vehicle), verts, vertexCount, opts, nullptr); if (!verts || vertexCount <= 0) return placed; double mn[3] = { 1e300, 1e300, 1e300}; double mx[3] = {-1e300, -1e300, -1e300}; for (int i = 0; i < vertexCount; ++i) for (int a = 0; a < 3; ++a) { const double v = verts[3*i + a]; mn[a] = std::min(mn[a], v); mx[a] = std::max(mx[a], v); } const int up = std::clamp(opts.upAxis, 0, 2); const int a0 = (up == 0) ? 1 : 0; const int a1 = (up == 2) ? 1 : 2; // The car's length is the longer in-plane extent; "front" = its high end. const int L = (mx[a0] - mn[a0] >= mx[a1] - mn[a1]) ? a0 : a1; const int S = (L == a0) ? a1 : a0; const double cL = 0.5 * (mn[L] + mx[L]); const double cS = 0.5 * (mn[S] + mx[S]); // Everything below works on OCCUPIED SPACE, not on vertices: the cloud is // deduplicated into voxel cells (96 per axis over the AABB) and each cell // counts once. A vertex-weighted centroid is at the mercy of tessellation // — the Buick carries ~9,800 vertices collapsed onto ONE point at the // origin (a degenerate primitive), which dragged its rear wheel onto the // centre line no matter how the height band was chosen. constexpr int kGrid = 96; std::vector> cells; { double ext[3]; for (int a = 0; a < 3; ++a) ext[a] = std::max(1e-9, mx[a] - mn[a]); std::vector keys; keys.reserve(static_cast(vertexCount)); for (int i = 0; i < vertexCount; ++i) { std::uint32_t key = 0; for (int a = 0; a < 3; ++a) { const int c = std::clamp(static_cast((verts[3*i + a] - mn[a]) / ext[a] * kGrid), 0, kGrid - 1); key = key * kGrid + static_cast(c); } keys.push_back(key); } std::sort(keys.begin(), keys.end()); keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); cells.reserve(keys.size()); for (std::uint32_t key : keys) { std::array centre{}; for (int a = 2; a >= 0; --a) { centre[a] = mn[a] + (static_cast(key % kGrid) + 0.5) / kGrid * ext[a]; key /= kGrid; } cells.push_back(centre); } } // Ground = the bottom of the LARGEST height-contiguous mass of occupied // cells, not the AABB bottom: a detached shadow plane / dropped interior // part floating below the body (the Buick has one) is separated from it // by an empty vertical gap, so it forms its own smaller run of height bins // and is treated as junk. Anything touching the body counts as body. const double extUp = std::max(1e-9, mx[up] - mn[up]); double ground = mn[up]; { constexpr int kBins = 40; std::array hist{}; for (const auto& c : cells) { const int bin = static_cast((c[up] - mn[up]) / extUp * kBins); hist[std::clamp(bin, 0, kBins - 1)]++; } long long bestMass = -1; for (int bnum = 0; bnum < kBins; ) { if (hist[bnum] == 0) { ++bnum; continue; } const int runStart = bnum; long long mass = 0; while (bnum < kBins && hist[bnum] > 0) mass += hist[bnum++]; if (mass > bestMass) { bestMass = mass; ground = mn[up] + (extUp / kBins) * runStart; } } } const double lowCut = ground + 0.30 * std::max(1e-9, mx[up] - ground); const double junkCut = ground - 0.01 * extUp; // below the body's ground: junk // Quadrant centroids of the low band's cells: index = (front?2:0) | // (left?1:0), left = the −S side (the character convention the labeller uses). double sum[4][3] = {{0,0,0},{0,0,0},{0,0,0},{0,0,0}}; long long cnt[4] = {0,0,0,0}; for (const auto& v : cells) { if (v[up] > lowCut || v[up] < junkCut) continue; const int q = (v[L] > cL ? 2 : 0) | (v[S] < cS ? 1 : 0); for (int a = 0; a < 3; ++a) sum[q][a] += v[a]; ++cnt[q]; } auto wheelIdx = [&](const char* name) { for (size_t i = 0; i < placed.size(); ++i) if (placed[i].name == QLatin1String(name)) return static_cast(i); return -1; }; const struct { const char* name; int q; } wheels[] = { {"FrontLeftWheel", 3}, {"FrontRightWheel", 2}, {"RearLeftWheel", 1}, {"RearRightWheel", 0} }; for (const auto& w : wheels) { const int j = wheelIdx(w.name); if (j < 0 || cnt[w.q] == 0) continue; for (int a = 0; a < 3; ++a) placed[j].pos[a] = sum[w.q][a] / static_cast(cnt[w.q]); } auto mid = [&](const char* a, const char* b, const char* axle) { const int i = wheelIdx(a), k = wheelIdx(b), x = wheelIdx(axle); if (i < 0 || k < 0 || x < 0) return; for (int c2 = 0; c2 < 3; ++c2) placed[x].pos[c2] = 0.5 * (placed[i].pos[c2] + placed[k].pos[c2]); }; mid("FrontLeftWheel", "FrontRightWheel", "FrontAxle"); mid("RearLeftWheel", "RearRightWheel", "RearAxle"); if (const int ch = wheelIdx("Chassis"); ch >= 0) { placed[ch].pos[S] = cS; placed[ch].pos[L] = cL; placed[ch].pos[up] = ground + 0.35 * (mx[up] - ground); } return placed; } namespace { bool finiteVertex(const float* verts, int i) { return std::isfinite(verts[3 * i]) && std::isfinite(verts[3 * i + 1]) && std::isfinite(verts[3 * i + 2]); } // Mean depth of the occupied (side, depth) cells of the vertices whose height // lies in [lo, hi], and the largest depth extent of ONE foot: the band is split // at the middle of the side axis, so a long stride (feet far apart in depth) // is not mistaken for one deep slab. False when the band is empty. struct BandStats { double mean = 0, extent = 0; }; bool bandDepthMean(const float* verts, int n, int up, int side, int depth, double lo, double hi, double sideMin, double sideExt, double depthMin, double depthExt, BandStats* out) { constexpr int kCells = 96; std::vector used(static_cast(kCells) * kCells, 0); double sum = 0; double lowest[2] = {1e300, 1e300}, highest[2] = {-1e300, -1e300}; long long count = 0; for (int i = 0; i < n; ++i) { if (!finiteVertex(verts, i)) continue; const double h = verts[3 * i + up]; if (h < lo || h > hi) continue; const int cs = std::clamp(int((verts[3 * i + side] - sideMin) / sideExt * (kCells - 1)), 0, kCells - 1); const int cd = std::clamp(int((verts[3 * i + depth] - depthMin) / depthExt * (kCells - 1)), 0, kCells - 1); uint8_t& u = used[static_cast(cs) * kCells + static_cast(cd)]; if (u) continue; u = 1; const double d = depthMin + (cd + 0.5) / kCells * depthExt; const int half = cs < kCells / 2 ? 0 : 1; sum += d; lowest[half] = std::min(lowest[half], d); highest[half] = std::max(highest[half], d); ++count; } if (count == 0) return false; out->mean = sum / static_cast(count); out->extent = 0; for (int h = 0; h < 2; ++h) if (highest[h] >= lowest[h]) out->extent = std::max(out->extent, highest[h] - lowest[h]); return true; } } // namespace int AutoRig::facingFromFeet(const float* verts, int n, int upAxis, int depthAxis) { if (!verts || n <= 0 || upAxis < 0 || upAxis > 2 || depthAxis < 0 || depthAxis > 2 || upAxis == depthAxis) return 0; const int up = upAxis, depth = depthAxis; const int side = 3 - up - depth; // the third axis, 0..2 double mn[3] = {1e300, 1e300, 1e300}, mx[3] = {-1e300, -1e300, -1e300}; for (int i = 0; i < n; ++i) { if (!finiteVertex(verts, i)) continue; // a NaN would poison the bounds for (int a = 0; a < 3; ++a) { mn[a] = std::min(mn[a], double(verts[3 * i + a])); mx[a] = std::max(mx[a], double(verts[3 * i + a])); } } const double H = mx[up] - mn[up]; if (!(H > 0) || !std::isfinite(H)) return 0; const double sideExt = std::max(1e-9, mx[side] - mn[side]); const double depthExt = std::max(1e-9, mx[depth] - mn[depth]); BandStats toes, ankles; // toes: the lowest 3 % of the height; ankles: 7..13 % (above the foot, // below the knee for every humanoid proportion measured) if (!bandDepthMean(verts, n, up, side, depth, mn[up], mn[up] + 0.03 * H, mn[side], sideExt, mn[depth], depthExt, &toes) || !bandDepthMean(verts, n, up, side, depth, mn[up] + 0.07 * H, mn[up] + 0.13 * H, mn[side], sideExt, mn[depth], depthExt, &ankles)) return 0; // A foot is short (~15 % of the height). A bottom band whose ONE side is // much deeper than that is a base or pedestal, whose shape says nothing // about the facing (each side is measured alone, so a stride is not one). if (toes.extent > 0.35 * H) return 0; const double delta = toes.mean - ankles.mean; if (std::fabs(delta) < 0.01 * H) return 0; return delta > 0 ? 1 : -1; } std::vector AutoRig::fitTemplate(const std::vector& tmpl, const float* verts, int vertexCount, const Options& opts, int* outRecentered) { std::vector placed = tmpl; if (outRecentered) *outRecentered = 0; if (!verts || vertexCount <= 0 || tmpl.empty()) return placed; // 1. AABB of the vertex cloud. double mn[3] = { 1e300, 1e300, 1e300}; double mx[3] = {-1e300, -1e300, -1e300}; for (int i = 0; i < vertexCount; ++i) { for (int a = 0; a < 3; ++a) { const double v = verts[3 * i + a]; mn[a] = std::min(mn[a], v); mx[a] = std::max(mx[a], v); } } double ext[3]; for (int a = 0; a < 3; ++a) ext[a] = std::max(1e-9, mx[a] - mn[a]); const int up = std::clamp(opts.upAxis, 0, 2); // The two in-plane axes (everything that isn't "up"). const int p0 = (up == 0) ? 1 : 0; const int p1 = (up == 2) ? 1 : 2; // The template's y coordinate is "up"; its x,z are the in-plane axes. // Map template axis -> world axis so the box orients to the mesh's up. auto tmplAxisToWorld = [&](int tAxis) { // tAxis: 0=template-x, 1=template-y(up), 2=template-z if (tAxis == 1) return up; return (tAxis == 0) ? p0 : p1; }; // 1b. Which way does the creature FACE? The template is authored with the // front at HIGH template-z, but a generated mesh can face either way, // and rigging it backwards produces a creature that walks, runs and // jumps in reverse (reported on an AI-generated horse whose head sat // at z = -0.176 while the template put the head at +z). // // The head is the tall, NARROW end: a quadruped's head and neck rise // well above the back line, while the rump is broad and lower. So // compare the mean length-coordinate of the tallest slice against the // body centre; if it sits at the LOW end, the mesh faces backwards and // the template's length axis is flipped. // // Only applies to body plans whose template has a front/back axis; // fitVehicle does its own front detection. bool flipLength = false; // An UPRIGHT template (arms + legs: humanoid, biped) faces +template-z, // i.e. +p1, and its "Left" bones sit at +x. The head-height test below is // meaningless for a standing character (the head is centred in depth), // so the template kept facing +p1 even on characters that face -p1 — // TRELLIS.2 generations face -Z — and every Left/Right name came out // mirrored: name-keyed retargets (Kimodo, QtMesh T2M) then played clips // turned around, walking backwards. Read the facing from the feet. const bool upright = std::any_of(tmpl.begin(), tmpl.end(), [](const Joint& j) { return j.name == QLatin1String("LeftArm"); }); if (upright) { flipLength = facingFromFeet(verts, vertexCount, up, p1) < 0; } else if (vertexCount > 0) { // Work on OCCUPIED SPACE, not vertex counts: a percentile over // vertices lets TESSELLATION decide which end reads as tall, so a // sparsely-modelled head beside a densely-modelled back could put the // cutoff at back height and leave the creature rigged backwards. The // same reason fitVehicle deduplicates into cells (#1013). // // Bin the length axis into cells, record the HIGHEST point in each, // and compare the mean length-coordinate of the top cells against all // occupied cells. Every occupied cell counts once regardless of how // many vertices landed in it. constexpr int kBins = 64; std::array cellTop{}; std::array cellUsed{}; cellTop.fill(-std::numeric_limits::max()); cellUsed.fill(false); for (int i = 0; i < vertexCount; ++i) { const double L = static_cast(verts[3 * i + p1]); int b = static_cast((L - mn[p1]) / ext[p1] * (kBins - 1)); b = std::clamp(b, 0, kBins - 1); const double h = static_cast(verts[3 * i + up]); if (!cellUsed[static_cast(b)] || h > cellTop[static_cast(b)]) { cellTop[static_cast(b)] = h; cellUsed[static_cast(b)] = true; } } std::vector> cells; // (height, length) for (int b = 0; b < kBins; ++b) if (cellUsed[static_cast(b)]) cells.emplace_back(cellTop[static_cast(b)], mn[p1] + (static_cast(b) + 0.5) / kBins * ext[p1]); if (cells.size() >= 4) { std::vector hs; hs.reserve(cells.size()); for (const auto& c : cells) hs.push_back(c.first); std::sort(hs.begin(), hs.end()); const double hiCut = hs[static_cast(0.80 * (hs.size() - 1))]; double sumTall = 0, sumAll = 0; long long nTall = 0; for (const auto& c : cells) { sumAll += c.second; if (c.first >= hiCut) { sumTall += c.second; ++nTall; } } if (nTall > 0) { const double tallMean = sumTall / static_cast(nTall); const double bodyMean = sumAll / static_cast(cells.size()); // A clear margin only; a near-tie means the shape carries no // reliable head signal and the template's own convention // stands. if (tallMean < bodyMean - 0.05 * ext[p1]) flipLength = true; } } } // 2. Map each joint's normalised position into the AABB. for (auto& j : placed) { std::array world = {0, 0, 0}; for (int tAxis = 0; tAxis < 3; ++tAxis) { const int w = tmplAxisToWorld(tAxis); double t = j.pos[tAxis]; // Reversing the facing is a 180 deg turn about UP, so BOTH // in-plane axes mirror. Flipping only the length axis would keep // "Left" bones on the same side coordinate -- which for a // creature facing the other way is its anatomical RIGHT, so every // left/right label (and any clip that distinguishes them) comes // out swapped. if (flipLength && (w == p1 || w == p0)) t = 1.0 - t; world[w] = mn[w] + t * ext[w]; } j.pos = world; } // 3. Recentre flagged joints toward the mesh's in-plane mass at their // up-height (pulls the spine onto the medial line, lands limb roots // inside the silhouette). const double slab = std::clamp(opts.slabFraction, 1e-3, 0.5) * ext[up]; int recentered = 0; for (auto& j : placed) { if (!j.recenter) continue; const double y = j.pos[up]; double sum0 = 0, sum1 = 0; long long n = 0; for (int i = 0; i < vertexCount; ++i) { if (std::abs(static_cast(verts[3 * i + up]) - y) > slab) continue; sum0 += verts[3 * i + p0]; sum1 += verts[3 * i + p1]; ++n; } if (n > 0) { // Blend toward the slab centroid (0.75) but keep a little of the // template's lateral intent so symmetric joints don't all collapse // onto the exact centre line. const double c0 = sum0 / static_cast(n); const double c1 = sum1 / static_cast(n); const double kBlend = 0.75; j.pos[p0] = kBlend * c0 + (1.0 - kBlend) * j.pos[p0]; j.pos[p1] = kBlend * c1 + (1.0 - kBlend) * j.pos[p1]; ++recentered; } } if (outRecentered) *outRecentered = recentered; return placed; } QString AutoRig::markerLabel(MarkerId id) { switch (id) { case MarkerId::Chin: return QStringLiteral("Chin"); case MarkerId::LeftShoulder: return QStringLiteral("Left shoulder"); case MarkerId::RightShoulder: return QStringLiteral("Right shoulder"); case MarkerId::LeftWrist: return QStringLiteral("Left wrist"); case MarkerId::RightWrist: return QStringLiteral("Right wrist"); case MarkerId::LeftUpLeg: return QStringLiteral("Left hip"); case MarkerId::RightUpLeg: return QStringLiteral("Right hip"); case MarkerId::LeftKnee: return QStringLiteral("Left knee"); case MarkerId::RightKnee: return QStringLiteral("Right knee"); case MarkerId::Hips: return QStringLiteral("Hips"); case MarkerId::Count: break; } return QStringLiteral("?"); } std::vector AutoRig::humanoidMarkerOrder() { // Order = top-down, then limbs: chin, both shoulders, both wrists, both // hips (thigh roots), both knees, pelvis. Shoulders precede wrists, and the // hip sockets precede knees, so each limb chain has its attach point placed // before its tip. Pelvis (Hips) last so it can carry any unmarked thigh // roots along without overriding ones the user pinned. return { MarkerId::Chin, MarkerId::LeftShoulder, MarkerId::RightShoulder, MarkerId::LeftWrist, MarkerId::RightWrist, MarkerId::LeftUpLeg, MarkerId::RightUpLeg, MarkerId::LeftKnee, MarkerId::RightKnee, MarkerId::Hips }; } namespace { // Find a placed joint by name; returns nullptr if absent. AutoRig::Joint* findJoint(std::vector& js, const char* name) { for (auto& j : js) if (j.name == QLatin1String(name)) return &j; return nullptr; } // Place `mid` between `a` and `b` at parameter t (0=a, 1=b). std::array lerp3(const std::array& a, const std::array& b, double t) { return { a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t }; } // Lay an N-joint limb chain straight along anchor→marker. `names` is the // chain in parent→child order; the FIRST joint (the anchor — e.g. the // shoulder) keeps its template position, the LAST goes to the marker, and // every joint in between is distributed evenly by index (a straight rest-pose // limb). Distributing ALL the intermediate joints — not just one midpoint — // is what makes the whole limb reach toward the marker; anchoring only the // tip + a single mid leaves the upper segment tucked at its template position. // Any named joint that's missing is skipped (the rest still lay out from the // surviving anchor/tip). void layChain(std::vector& js, std::initializer_list names, const std::array& tipMarker) { if (names.size() < 2) return; AutoRig::Joint* anchor = findJoint(js, *names.begin()); if (!anchor) return; const auto a = anchor->pos; // copy: stays put, drives the lerp const int last = static_cast(names.size()) - 1; int i = 0; for (const char* n : names) { if (i > 0) { // i==0 is the anchor; leave it if (auto* j = findJoint(js, n)) j->pos = lerp3(a, tipMarker, static_cast(i) / last); } ++i; } } // Find a placed joint's position by name; returns `fallback` if absent. std::array jointPosOr(const std::vector& js, const char* name, const std::array& fallback) { for (const auto& j : js) if (j.name == QLatin1String(name)) return j.pos; return fallback; } std::array add3(const std::array& a, const std::array& b) { return { a[0]+b[0], a[1]+b[1], a[2]+b[2] }; } std::array sub3(const std::array& a, const std::array& b) { return { a[0]-b[0], a[1]-b[1], a[2]-b[2] }; } } // namespace std::vector AutoRig::fitTemplateWithMarkers( const std::vector& tmpl, const float* verts, int vertexCount, const std::vector& markers, const Options& opts, int* outRecentered, int* outMarkersApplied) { // Proportional baseline — gives sensible default joint positions AND the // template relationships (segment vectors, lateral offsets) we use to // INFER unmarked joints from marked ones, so a partial marker set produces // a coherent skeleton (no shoulder-above-head etc.) instead of mixing // marked anchors with stranded template joints. std::vector placed = fitTemplate(tmpl, verts, vertexCount, opts, outRecentered); if (outMarkersApplied) *outMarkersApplied = 0; auto get = [&](MarkerId id) -> const Marker* { for (const auto& m : markers) if (m.id == id && m.set) return &m; return nullptr; }; // No markers placed → the proportional fit is the answer, untouched (keeps // the "empty marker set ≡ fitTemplate" contract; nothing to infer from). bool anySet = false; for (const auto& m : markers) if (m.set) { anySet = true; break; } if (!anySet) return placed; int applied = 0; // Mesh AABB (mesh-local space, same coords the fit works in) — used to // CLAMP inferred joints to the model's extent so an extrapolated limb // (e.g. up-leg set but knee skipped) can't shoot a foot below the mesh. std::array mn = { 1e30, 1e30, 1e30}; std::array mx = {-1e30, -1e30, -1e30}; for (int i = 0; i < vertexCount; ++i) { for (int a = 0; a < 3; ++a) { const double v = verts[3 * i + a]; mn[a] = std::min(mn[a], v); mx[a] = std::max(mx[a], v); } } // ---- Template reference positions (the proportional fit) ------------- const auto tHips = jointPosOr(placed, "Hips", {0,0,0}); const auto tHead = jointPosOr(placed, "Head", tHips); const auto tLSh = jointPosOr(placed, "LeftShoulder", tHips); const auto tRSh = jointPosOr(placed, "RightShoulder", tHips); const auto tLHand = jointPosOr(placed, "LeftHand", tLSh); const auto tRHand = jointPosOr(placed, "RightHand", tRSh); const auto tLUp = jointPosOr(placed, "LeftUpLeg", tHips); const auto tRUp = jointPosOr(placed, "RightUpLeg", tHips); const auto tLKnee = jointPosOr(placed, "LeftLeg", tLUp); const auto tRKnee = jointPosOr(placed, "RightLeg", tRUp); // Reflect a point across the body's sagittal plane (the plane through Hips // perpendicular to the side axis). Used to mirror a marked left limb onto // an unmarked right one (and vice-versa). The side axis is whichever of the // two non-up axes the template shoulders are most separated along. const int up = std::clamp(opts.upAxis, 0, 2); int sideAxis = (up == 0) ? 1 : 0; // first non-up axis { const int a1 = (up == 0) ? 1 : 0; const int a2 = (up == 2) ? 1 : 2; if (std::abs(tLSh[a2] - tRSh[a2]) > std::abs(tLSh[a1] - tRSh[a1])) sideAxis = a2; } auto mirror = [&](std::array p, const std::array& center) { p[sideAxis] = center[sideAxis] - (p[sideAxis] - center[sideAxis]); return p; }; // ---- Resolve anchor positions (marked → inferred → template) --------- // Each `resolve` records whether a USER marker drove it (for applied count). const Marker* mHead = get(MarkerId::Chin); const Marker* mHips = get(MarkerId::Hips); const Marker* mLSh = get(MarkerId::LeftShoulder); const Marker* mRSh = get(MarkerId::RightShoulder); const Marker* mLWr = get(MarkerId::LeftWrist); const Marker* mRWr = get(MarkerId::RightWrist); const Marker* mLUp = get(MarkerId::LeftUpLeg); const Marker* mRUp = get(MarkerId::RightUpLeg); const Marker* mLKn = get(MarkerId::LeftKnee); const Marker* mRKn = get(MarkerId::RightKnee); for (const Marker* m : {mHead,mHips,mLSh,mRSh,mLWr,mRWr,mLUp,mRUp,mLKn,mRKn}) if (m) ++applied; // HIPS: marked → else from the up-legs (midpoint, lifted by the template // socket→pelvis rise) → else template. std::array pHips = tHips; if (mHips) pHips = mHips->pos; else if (mLUp && mRUp) { pHips = { 0.5*(mLUp->pos[0]+mRUp->pos[0]), 0.5*(mLUp->pos[1]+mRUp->pos[1]), 0.5*(mLUp->pos[2]+mRUp->pos[2]) }; const auto lift = sub3(tHips, { 0.5*(tLUp[0]+tRUp[0]), 0.5*(tLUp[1]+tRUp[1]), 0.5*(tLUp[2]+tRUp[2]) }); pHips = add3(pHips, lift); } // HEAD (chin): marked → else template lifted to keep the marked-hips offset. std::array pHead = mHead ? mHead->pos : add3(pHips, sub3(tHead, tHips)); // UP-LEGS: marked → else mirror the other marked one across the pelvis → // else pelvis + template socket offset. std::array pLUp, pRUp; pLUp = mLUp ? mLUp->pos : (mRUp ? mirror(mRUp->pos, pHips) : add3(pHips, sub3(tLUp, tHips))); pRUp = mRUp ? mRUp->pos : (mLUp ? mirror(mLUp->pos, pHips) : add3(pHips, sub3(tRUp, tHips))); // SHOULDERS: marked → else mirror the other → else from the spine: place at // the template's shoulder-height fraction along the live Hips→Head line, // plus the template lateral offset (so chin+hips imply the shoulders). auto shoulderFromSpine = [&](const std::array& tSh) { const double denomUp = (tHead[up] - tHips[up]); const double f = std::abs(denomUp) > 1e-9 ? (tSh[up] - tHips[up]) / denomUp : 0.78; std::array p = lerp3(pHips, pHead, std::clamp(f, 0.0, 1.0)); // lateral / depth offset of the template shoulder from the spine line const std::array tSpineAtSh = lerp3(tHips, tHead, std::clamp(f,0.0,1.0)); const auto off = sub3(tSh, tSpineAtSh); return add3(p, off); }; std::array pLSh, pRSh; pLSh = mLSh ? mLSh->pos : (mRSh ? mirror(mRSh->pos, pHead) : shoulderFromSpine(tLSh)); pRSh = mRSh ? mRSh->pos : (mLSh ? mirror(mLSh->pos, pHead) : shoulderFromSpine(tRSh)); // HANDS (wrist): marked → else shoulder + template arm vector (so a marked // shoulder with a skipped wrist still lays a full arm reaching out). std::array pLHand, pRHand; pLHand = mLWr ? mLWr->pos : add3(pLSh, sub3(tLHand, tLSh)); pRHand = mRWr ? mRWr->pos : add3(pRSh, sub3(tRHand, tRSh)); // KNEES + FEET: resolve both, clamped to the mesh's lower extent so an // inferred leg never punches through the bottom of the model. // * knee marked → knee at the marker, foot extrapolated below // (knee + thigh→knee), then clamped to the floor. // * knee unmarked → drop the foot to the mesh FLOOR (mn[up]) straight // below the up-leg, and put the knee halfway between the // up-leg and that foot. (Template thigh-vector // extrapolation is what shot feet past the mesh limit; // anchoring the foot to the floor fixes that.) const double floorUp = mn[up]; auto resolveLeg = [&](const std::array& upPos, const std::array& tKnee, const std::array& tUp, const Marker* kneeMk, std::array& knee, std::array& foot) { if (kneeMk) { knee = kneeMk->pos; foot = add3(knee, sub3(knee, upPos)); // continue below the knee } else { // Foot straight below the up-leg, sitting on the mesh floor. foot = upPos; foot[up] = floorUp; knee = { 0.5*(upPos[0]+foot[0]), 0.5*(upPos[1]+foot[1]), 0.5*(upPos[2]+foot[2]) }; // Nudge the knee slightly forward (template thigh→knee in-plane // direction) so it isn't a perfectly straight, lockable line. const auto tIn = sub3(tKnee, tUp); for (int a = 0; a < 3; ++a) if (a != up) knee[a] += tIn[a] * 0.25; } // Never let the foot go below the mesh floor (clamp the up coord). if (foot[up] < floorUp) foot[up] = floorUp; // Keep the knee strictly between the up-leg and the foot in up-coord. const double lo = std::min(upPos[up], foot[up]); const double hi = std::max(upPos[up], foot[up]); knee[up] = std::clamp(knee[up], lo, hi); }; std::array pLKnee, pLFoot, pRKnee, pRFoot; resolveLeg(pLUp, tLKnee, tLUp, mLKn, pLKnee, pLFoot); resolveLeg(pRUp, tRKnee, tRUp, mRKn, pRKnee, pRFoot); // ---- Write the resolved anchors back, then lay the dependent chains -- auto setJoint = [&](const char* name, const std::array& p) { if (auto* j = findJoint(placed, name)) j->pos = p; }; setJoint("Hips", pHips); setJoint("Head", pHead); setJoint("LeftShoulder", pLSh); setJoint("RightShoulder", pRSh); setJoint("LeftUpLeg", pLUp); setJoint("RightUpLeg", pRUp); // Spine: distribute Spine/Chest/Neck evenly between Hips and Head. { static const char* kSpine[] = { "Spine", "Chest", "Neck" }; const int last = static_cast(std::size(kSpine)) + 1; // +Head for (int i = 0; i < static_cast(std::size(kSpine)); ++i) setJoint(kSpine[i], lerp3(pHips, pHead, static_cast(i + 1) / last)); } // Arms: lay the full chain shoulder→arm→forearm→hand toward the resolved hand. layChain(placed, {"LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand"}, pLHand); layChain(placed, {"RightShoulder", "RightArm", "RightForeArm", "RightHand"}, pRHand); // Legs: write the resolved (and floor-clamped) knee + foot anchors. setJoint("LeftLeg", pLKnee); setJoint("LeftFoot", pLFoot); setJoint("RightLeg", pRKnee); setJoint("RightFoot", pRFoot); if (outMarkersApplied) *outMarkersApplied = applied; return placed; } namespace { // Tightly read POSITION floats out of a VertexData (same idiom as // SkinWeights::extractPositions). Appends to `out`. bool appendPositions(Ogre::VertexData* vd, std::vector& out) { if (!vd) return false; const auto* posElem = vd->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); if (!posElem) return false; auto vbuf = vd->vertexBufferBinding->getBuffer(posElem->getSource()); if (!vbuf || vd->vertexCount == 0) return false; const size_t base0 = out.size(); out.resize(base0 + static_cast(vd->vertexCount) * 3); const size_t stride = vbuf->getVertexSize(); auto* base = static_cast( vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); if (!base) { // Lock can fail (write-only buffer with no shadow copy, etc.). Shrink // back to the pre-grow size so the unread slots don't inflate vcount. out.resize(base0); return false; } for (size_t i = 0; i < vd->vertexCount; ++i) { float* p = nullptr; posElem->baseVertexPointerToElement(base + i * stride, &p); out[base0 + 3 * i + 0] = p[0]; out[base0 + 3 * i + 1] = p[1]; out[base0 + 3 * i + 2] = p[2]; } vbuf->unlock(); return true; } // Append a submesh's triangle indices (offset by `vertexBase`, the running // shared/per-submesh vertex offset) so RigNet sees one combined index buffer // over the same vertex order appendPositions produced. Only used for the // RigNet path. Returns the number of vertices this submesh contributed (to // advance vertexBase). Shared-vertex submeshes are still emitted but reference // the shared block at offset 0. int appendIndices(Ogre::SubMesh* sub, Ogre::Mesh* mesh, uint32_t sharedBase, uint32_t ownBase, std::vector& out) { if (!sub || !sub->indexData || !sub->indexData->indexBuffer) return 0; Ogre::IndexData* id = sub->indexData; const uint32_t base = sub->useSharedVertices ? sharedBase : ownBase; auto ibuf = id->indexBuffer; const bool is32 = ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT; auto* p = static_cast(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); if (!p) return 0; const auto* i32 = reinterpret_cast(p); const auto* i16 = reinterpret_cast(p); const size_t n = id->indexCount; out.reserve(out.size() + n); for (size_t k = 0; k + 2 < n; k += 3) { out.push_back(base + (is32 ? i32[k] : i16[k])); out.push_back(base + (is32 ? i32[k+1] : i16[k+1])); out.push_back(base + (is32 ? i32[k+2] : i16[k+2])); } ibuf->unlock(); return 0; } } // namespace bool AutoRig::gatherGeometry(Ogre::Entity* entity, std::vector& outVerts, std::vector& outIndices) { outVerts.clear(); outIndices.clear(); if (!entity || !entity->getMesh()) return false; Ogre::MeshPtr mesh = entity->getMesh(); const uint32_t sharedBase = 0; uint32_t ownBase = 0; if (mesh->sharedVertexData) { appendPositions(mesh->sharedVertexData, outVerts); ownBase = static_cast(mesh->sharedVertexData->vertexCount); } std::vector ownOffset(mesh->getNumSubMeshes(), 0); for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) { Ogre::SubMesh* sub = mesh->getSubMesh(si); if (sub && !sub->useSharedVertices && sub->vertexData) { ownOffset[si] = ownBase; appendPositions(sub->vertexData, outVerts); ownBase += static_cast(sub->vertexData->vertexCount); } } for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) appendIndices(mesh->getSubMesh(si), mesh.get(), sharedBase, ownOffset[si], outIndices); return !outVerts.empty(); } std::vector AutoRig::rigPriorPartLabels(Ogre::Entity* entity, int vertexCount, int* outResolved) { if (outResolved) *outResolved = 0; if (!entity || !entity->getMesh() || vertexCount <= 0) return {}; Ogre::MeshPtr mesh = entity->getMesh(); Ogre::SkeletonPtr skel = (mesh->hasSkeleton()) ? mesh->getSkeleton() : Ogre::SkeletonPtr(); if (!skel) return {}; // Per-vertex dominant bone (by weight), in gatherGeometry's vertex order: // shared vertex data first (base 0), then each submesh's own data at its // running offset. (Identical accounting to gatherGeometry above.) std::vector bestW(vertexCount, -1.0f); std::vector boneOf(vertexCount, -1); auto consider = [&](unsigned int gv, unsigned short boneIdx, float w) { if (gv < static_cast(vertexCount) && w > bestW[gv]) { bestW[gv] = w; boneOf[gv] = boneIdx; } }; uint32_t base = 0; if (mesh->sharedVertexData) { for (const auto& kv : mesh->getBoneAssignments()) consider(kv.second.vertexIndex, kv.second.boneIndex, kv.second.weight); base = static_cast(mesh->sharedVertexData->vertexCount); } for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) { Ogre::SubMesh* sub = mesh->getSubMesh(si); if (!sub || sub->useSharedVertices || !sub->vertexData) continue; for (const auto& kv : sub->getBoneAssignments()) consider(base + kv.second.vertexIndex, kv.second.boneIndex, kv.second.weight); base += static_cast(sub->vertexData->vertexCount); } // Per-bone part, WITH ANCESTOR INHERITANCE: a bone whose own name doesn't map // to a body region (e.g. an unnamed UniRig finger "joint_37", or a "_twist" // helper) inherits the part of its nearest NAMED ancestor — a finger under // LeftHand→LeftArm becomes LeftArm. Without this, finger/extra bones (a third // of a UniRig rig's joints) stayed Unknown and dragged the rig-prior resolve // rate below the 70% gate, so Select-by-Part fell back to the model even on a // perfectly good skinned rig. Cached per bone-index. const int numBones = static_cast(skel->getNumBones()); std::vector bonePart(numBones, -2); // -2 = not computed, -1 = none, ≥0 = Part std::function partOfBone = [&](int bi) -> int { if (bi < 0 || bi >= numBones) return -1; if (bonePart[bi] != -2) return bonePart[bi]; Ogre::Bone* b = skel->getBone(static_cast(bi)); const auto part = MeshSegmenter::partForBoneName( QString::fromStdString(b->getName())); if (part != MeshSegmenter::Part::Unknown) { bonePart[bi] = static_cast(part); } else if (b->getParent()) { bonePart[bi] = partOfBone( static_cast(static_cast(b->getParent())->getHandle())); } else { bonePart[bi] = -1; } return bonePart[bi]; }; std::vector labels(vertexCount, static_cast(MeshSegmenter::Part::Unknown)); int resolved = 0; for (int v = 0; v < vertexCount; ++v) { if (boneOf[v] < 0) continue; const int part = partOfBone(boneOf[v]); if (part >= 0) { labels[v] = part; ++resolved; } else { labels[v] = -1; // had a bone, but no body-region ancestor } } if (outResolved) *outResolved = resolved; return labels; } UniRigPredictor::Labeling AutoRig::uniRigLabelingForTemplate(Template tmpl) { switch (tmpl) { case Template::Humanoid: return UniRigPredictor::Labeling::Auto; case Template::Biped: return UniRigPredictor::Labeling::Humanoid; default: return UniRigPredictor::Labeling::Generic; } } std::vector AutoRig::predictUniRig( const std::vector& verts, const std::vector& indices, int upAxis, const std::function& progress, QString* outError, Template tmpl, QString* outLabeling) { std::vector out; const int vcount = static_cast(verts.size() / 3); if (vcount < 4) { if (outError) *outError = QStringLiteral("mesh has too few vertices"); return out; } if (!UniRigPredictor::isAvailable()) { if (outError) *outError = QStringLiteral("UniRig needs an ONNX-enabled build"); return out; } const QString enc = UniRigPredictor::ensureModelBlocking(); // may download (worker thread) if (enc.isEmpty()) { if (outError) *outError = QStringLiteral("UniRig model unavailable (offline or not yet hosted)"); return out; } UniRigPredictor::Options rnOpts; rnOpts.upAxis = upAxis; // #1013: --skeleton doubles as the category hint for UniRig. // humanoid → Auto (humanoid names only if the geometry reads as one) // biped → Humanoid forced ("I know it is bipedal" — e.g. a cartoon // rat whose arm chains the plausibility check rejects) // quadruped / generic → neutral names outright. rnOpts.labeling = uniRigLabelingForTemplate(tmpl); const auto rn = UniRigPredictor::predict( verts.data(), vcount, indices.empty() ? nullptr : indices.data(), static_cast(indices.size()), UniRigPredictor::encoderModelPath(), UniRigPredictor::decoderModelPath(), UniRigPredictor::embedModelPath(), rnOpts, progress); if (!rn.ok || rn.joints.size() < 2) { if (outError) *outError = rn.error.isEmpty() ? QStringLiteral("UniRig prediction returned no usable skeleton") : rn.error; return out; } if (outLabeling) *outLabeling = rn.labeling; out.reserve(rn.joints.size()); for (const auto& j : rn.joints) { Joint pj; pj.name = j.name; pj.parent = j.parent; pj.pos = j.pos; pj.recenter = false; out.push_back(std::move(pj)); } return out; } AutoRig::Report AutoRig::rigEntity(Ogre::Entity* entity, const Options& opts) { return rigEntityWithMarkers(entity, /*markers=*/{}, opts); } AutoRig::Report AutoRig::rigEntityWithMarkers(Ogre::Entity* entity, const std::vector& markers, const Options& opts) { Report report; report.templateName = templateToString(opts.tmpl); if (!entity || !entity->getMesh()) { report.error = QStringLiteral("no mesh to rig"); return report; } Ogre::MeshPtr mesh = entity->getMesh(); report.meshName = QString::fromStdString(mesh->getName()); if (mesh->hasSkeleton()) { report.error = QStringLiteral( "mesh already has a skeleton — auto-rig only applies to unrigged " "(static) meshes"); return report; } // Gather all vertex positions (shared + per-submesh). The vertex order is // shared-block first, then each non-shared submesh — appendIndices uses the // same offsets so the RigNet index buffer matches. std::vector verts; const uint32_t sharedBase = 0; uint32_t ownBase = 0; if (mesh->sharedVertexData) { appendPositions(mesh->sharedVertexData, verts); ownBase = static_cast(mesh->sharedVertexData->vertexCount); } // Per-submesh vertex offsets, captured before we know whether RigNet needs // them (cheap). offsets[si] = first vertex index of submesh si's own block. std::vector ownOffset(mesh->getNumSubMeshes(), 0); for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) { Ogre::SubMesh* sub = mesh->getSubMesh(si); if (sub && !sub->useSharedVertices && sub->vertexData) { ownOffset[si] = ownBase; appendPositions(sub->vertexData, verts); ownBase += static_cast(sub->vertexData->vertexCount); } } const int vcount = static_cast(verts.size() / 3); if (vcount == 0) { report.error = QStringLiteral("mesh has no readable vertex positions"); return report; } report.verticesSampled = vcount; const std::vector tmpl = templateJoints(opts.tmpl); int recentered = 0, markersApplied = 0; std::vector placed; report.algorithmUsed = Algorithm::Pinocchio; // updated to UniRig on success // --- UniRig (#408): ML skeleton prediction, with graceful fallback ------ // Markers are a Pinocchio/template concept, so UniRig only runs for the // plain (marker-less) rig; a marker-driven call always uses the template. bool mlUsed = false; if (opts.algorithm == Algorithm::UniRig && markers.empty()) { QString reason; if (!opts.prePredictedJoints.empty()) { // GUI worker path: inference already ran off-thread; just adopt the // joints (skip the slow ONNX predict here — we're on the main thread // building the Ogre skeleton). placed = opts.prePredictedJoints; for (auto& j : placed) j.recenter = false; report.algorithmUsed = Algorithm::UniRig; report.jointLabeling = opts.prePredictedLabeling; mlUsed = true; } else if (opts.tmpl == Template::Vehicle) { // #1013: UniRig returns creature-shaped graphs for vehicles (a // humanoid lying along the body on a fused low-poly car); the // geometric vehicle template is the better answer, so the hint // wins outright and says so. reason = QStringLiteral("vehicle template: UniRig produces creature-shaped skeletons " "for vehicles, so the geometric chassis/axle/wheel rig is used"); } else if (!UniRigPredictor::isAvailable()) { reason = QStringLiteral("UniRig needs an ONNX-enabled build"); } else { // ensureModelBlocking() returns the encoder path only when BOTH the // encoder and decoder models are present (it downloads the missing // one on first use); empty == unavailable/offline/not-yet-hosted. const QString encModel = UniRigPredictor::ensureModelBlocking(); if (encModel.isEmpty()) { reason = QStringLiteral("UniRig model unavailable (offline or not yet hosted)"); } else { // Build the combined index buffer over the appendPositions order. std::vector indices; for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) appendIndices(mesh->getSubMesh(si), mesh.get(), sharedBase, ownOffset[si], indices); UniRigPredictor::Options rnOpts; rnOpts.upAxis = opts.upAxis; // #1013: --skeleton doubles as the category hint (see predictUniRig). rnOpts.labeling = uniRigLabelingForTemplate(opts.tmpl); const auto rn = UniRigPredictor::predict( verts.data(), vcount, indices.empty() ? nullptr : indices.data(), static_cast(indices.size()), UniRigPredictor::encoderModelPath(), UniRigPredictor::decoderModelPath(), UniRigPredictor::embedModelPath(), rnOpts); if (rn.ok && rn.joints.size() >= 2) { placed.reserve(rn.joints.size()); for (const auto& j : rn.joints) { Joint pj; pj.name = j.name; pj.parent = j.parent; pj.pos = j.pos; pj.recenter = false; placed.push_back(std::move(pj)); } report.algorithmUsed = Algorithm::UniRig; report.jointLabeling = rn.labeling; mlUsed = true; } else { reason = rn.error.isEmpty() ? QStringLiteral("UniRig prediction returned no usable skeleton") : rn.error; } } } if (!mlUsed) report.fallbackReason = QStringLiteral("%1 — used the native template rig instead.").arg(reason); } // --- Pinocchio / template fit (default, and the UniRig fallback) -------- if (!mlUsed) { if (opts.tmpl == Template::Vehicle) placed = fitVehicle(verts.data(), vcount, opts); // markers are a humanoid concept else placed = markers.empty() ? fitTemplate(tmpl, verts.data(), vcount, opts, &recentered) : fitTemplateWithMarkers(tmpl, verts.data(), vcount, markers, opts, &recentered, &markersApplied); } report.jointsRecentered = recentered; report.markersApplied = markersApplied; // Build the Ogre skeleton. Bone POSITIONS are parent-relative in Ogre, // so each child's setPosition is its world pos minus its parent's world // pos. createBone(name, handle) — handle == index. auto& skelMgr = Ogre::SkeletonManager::getSingleton(); const std::string skelName = mesh->getName() + "_autorig"; if (skelMgr.resourceExists(skelName)) skelMgr.remove(skelName); Ogre::SkeletonPtr skel; try { skel = skelMgr.create( skelName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); std::vector bones(placed.size(), nullptr); for (size_t i = 0; i < placed.size(); ++i) bones[i] = skel->createBone(placed[i].name.toStdString(), static_cast(i)); for (size_t i = 0; i < placed.size(); ++i) { const Joint& j = placed[i]; Ogre::Vector3 local( static_cast(j.pos[0]), static_cast(j.pos[1]), static_cast(j.pos[2])); if (j.parent >= 0 && static_cast(j.parent) < placed.size()) { bones[j.parent]->addChild(bones[i]); const Joint& pj = placed[j.parent]; local -= Ogre::Vector3( static_cast(pj.pos[0]), static_cast(pj.pos[1]), static_cast(pj.pos[2])); } bones[i]->setPosition(local); bones[i]->setOrientation(Ogre::Quaternion::IDENTITY); } skel->setBindingPose(); // Bind the skeleton to the mesh, then force the entity to // re-initialise so it acquires a SkeletonInstance. Without the // _initialise(true), the already-created Ogre::Entity keeps // hasSkeleton()==false and BOTH exporters (FBXExporter and the // Assimp glTF/FBX path gate on entity->hasSkeleton()) would drop // the new rig — the skeleton would exist on the mesh but never // reach the wire. (Same refresh EditableMesh / EditModeController // do after mutating an entity's mesh.) mesh->_notifySkeleton(skel); // Placeholder rigid bind: weight every vertex 1.0 to the root bone. // A skeletal entity with NO blend data is unrenderable — Ogre's // per-frame software blend asserts ("You must supply position, blend // indices and blend weights") and the viewport dies until real skin // weights arrive (which is minutes away when the ML skinner runs // async, or never if the user rigs without skinning). The real // SkinWeights pass replaces these assignments wholesale. { Ogre::VertexBoneAssignment vba; vba.boneIndex = 0; // root bone (handle == joint index) vba.weight = 1.0f; if (mesh->sharedVertexData) { mesh->clearBoneAssignments(); const size_t n = mesh->sharedVertexData->vertexCount; for (size_t v = 0; v < n; ++v) { vba.vertexIndex = static_cast(v); mesh->addBoneAssignment(vba); } mesh->_compileBoneAssignments(); } for (unsigned short s = 0; s < mesh->getNumSubMeshes(); ++s) { Ogre::SubMesh* sm = mesh->getSubMesh(s); if (sm->useSharedVertices || !sm->vertexData) continue; sm->clearBoneAssignments(); const size_t n = sm->vertexData->vertexCount; for (size_t v = 0; v < n; ++v) { vba.vertexIndex = static_cast(v); sm->addBoneAssignment(vba); } sm->_compileBoneAssignments(); } } entity->_initialise(true); report.skeletonName = QString::fromStdString(skelName); report.boneCount = static_cast(placed.size()); report.applied = true; } catch (const Ogre::Exception& e) { report.error = QStringLiteral("Ogre error building skeleton: %1") .arg(QString::fromStdString(e.getFullDescription())); // Detach the half-built skeleton from the mesh BEFORE removing the // resource. _notifySkeleton(skel) ran before entity->_initialise; if // the latter threw, the mesh still references the skeleton, so // mesh->hasSkeleton() would stay true — a later rigEntity() would bail // with "mesh already has a skeleton" and exporters could pick up the // half-built rig. Reset it to a clean static mesh. mesh->_notifySkeleton(Ogre::SkeletonPtr()); if (skel && skelMgr.resourceExists(skelName)) skelMgr.remove(skelName); report.applied = false; } return report; } bool AutoRig::unrigEntity(Ogre::Entity* entity) { if (!entity || !entity->getMesh()) return false; Ogre::MeshPtr mesh = entity->getMesh(); if (!mesh->hasSkeleton()) return false; // Remember the skeleton resource name so we can free it after detaching. const std::string skelName = mesh->getSkeletonName(); // Strip the BLEND_INDICES/BLEND_WEIGHTS vertex elements that the skin step // (`_compileBoneAssignments`) added. CRUCIAL for undo when the rig was // committed with skinning: clearing the bone-assignment LIST is not enough // — Ogre's `_compileBoneAssignments` only *removes* the blend elements // inside `compileBoneAssignments`, which it skips entirely when the list is // empty (maxBones == 0). So a plain clear leaves the vertex declaration // advertising blend elements while the entity has no skeleton, and the next // `_initialise`/render dereferences a null SkeletonInstance → crash. We // mirror Ogre's own removal block (unset the buffer, drop both elements). auto stripBlend = [](Ogre::VertexData* vd) { if (!vd) return; Ogre::VertexDeclaration* decl = vd->vertexDeclaration; Ogre::VertexBufferBinding* bind = vd->vertexBufferBinding; const Ogre::VertexElement* e = decl->findElementBySemantic(Ogre::VES_BLEND_INDICES); if (!e) return; bind->unsetBinding(e->getSource()); decl->removeElement(Ogre::VES_BLEND_INDICES); decl->removeElement(Ogre::VES_BLEND_WEIGHTS); }; // Drop every bone assignment (shared + per-submesh) so the mesh carries no // stale weights once it's static again, then strip the blend elements. mesh->clearBoneAssignments(); stripBlend(mesh->sharedVertexData); for (unsigned short si = 0; si < mesh->getNumSubMeshes(); ++si) { if (Ogre::SubMesh* sub = mesh->getSubMesh(si)) { sub->clearBoneAssignments(); if (!sub->useSharedVertices) stripBlend(sub->vertexData); } } // Detach the skeleton and force the entity back to its static form (mirror // of the rig path's _notifySkeleton + _initialise(true)). mesh->_notifySkeleton(Ogre::SkeletonPtr()); entity->_initialise(true); auto& skelMgr = Ogre::SkeletonManager::getSingleton(); if (!skelName.empty() && skelMgr.resourceExists(skelName)) skelMgr.remove(skelName); return true; } QString AutoRig::templateToString(Template t) { switch (t) { case Template::Humanoid: return QStringLiteral("humanoid"); case Template::Biped: return QStringLiteral("biped"); case Template::Quadruped: return QStringLiteral("quadruped"); case Template::Generic: return QStringLiteral("generic"); case Template::Vehicle: return QStringLiteral("vehicle"); } return QStringLiteral("generic"); } AutoRig::Template AutoRig::templateFromString(const QString& s) { const QString l = s.trimmed().toLower(); if (l == "humanoid") return Template::Humanoid; if (l == "biped") return Template::Biped; if (l == "quadruped" || l == "quad") return Template::Quadruped; if (l == "generic") return Template::Generic; if (l == "vehicle" || l == "car") return Template::Vehicle; return Template::Humanoid; // default } QString AutoRig::algorithmToString(Algorithm a) { switch (a) { case Algorithm::Pinocchio: return QStringLiteral("pinocchio"); case Algorithm::UniRig: return QStringLiteral("unirig"); } return QStringLiteral("pinocchio"); } AutoRig::Algorithm AutoRig::algorithmFromString(const QString& s) { const QString l = s.trimmed().toLower(); if (l == "unirig" || l == "rignet") // "rignet" kept as a deprecated alias return Algorithm::UniRig; // Everything else ("pinocchio" / "native" / "template" / unknown) maps to // the offline-reliable native backend. return Algorithm::Pinocchio; } QJsonObject AutoRig::reportToJson(const Report& r) { QJsonObject o; o["applied"] = r.applied; o["meshName"] = r.meshName; o["skeletonName"] = r.skeletonName; o["template"] = r.templateName; o["algorithm"] = algorithmToString(r.algorithmUsed); o["boneCount"] = r.boneCount; o["verticesSampled"] = r.verticesSampled; o["jointsRecentered"] = r.jointsRecentered; if (!r.fallbackReason.isEmpty()) o["fallbackReason"] = r.fallbackReason; if (!r.jointLabeling.isEmpty()) o["jointLabeling"] = r.jointLabeling; // #1013 if (!r.error.isEmpty()) o["error"] = r.error; return o; } QString AutoRig::reportToText(const Report& r) { if (!r.applied) return QStringLiteral("Auto-rig failed: %1\n") .arg(r.error.isEmpty() ? QStringLiteral("unknown error") : r.error); QString s = QStringLiteral( "Auto-rigged %1 with the '%2' template (%3 backend).\n" " bones: %4\n vertices sampled: %5\n joints recentered: %6\n") .arg(r.meshName, r.templateName, algorithmToString(r.algorithmUsed)) .arg(r.boneCount).arg(r.verticesSampled).arg(r.jointsRecentered); if (!r.fallbackReason.isEmpty()) s += QStringLiteral(" note: %1\n").arg(r.fallbackReason); return s; }