File size: 6,834 Bytes
a84fca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""Build ../animation/: one flat folder, one file per distinct motion.

Files are named `<Species>-<Action>.fbx`, so the species travels with the file
rather than living in a directory: `Cat-Walk.fbx`, `Trex-Big_Roar_Step.fbx`.
The action never contains a hyphen, so `name.split("-", 1)` recovers both parts.

Every file here holds exactly one animation take, so a clip is a motion and
nothing else.

Starts from the names `normalize.py` recorded in `clips.csv` and drops two
kinds of redundancy:

1. `ALL.fbx`, the combined take that repeats every clip in its group, and
   `TPOSE.fbx`, the rest pose. Both are recognised by name, not by amplitude:
   most T-poses are perfectly flat and are dropped earlier as static, but one
   (`Tukan`) drifts by a degree or two and would otherwise pass for a clip. A
   threshold cannot separate the two — a genuine `Die_Loop` or `Sleep_Loop`
   moves no more than that drifting T-pose does — but the name settles it, since
   `TPOSE` is a reserved marker in `normalize.py` and never names a motion.
2. Clips that are the same motion exported twice. The source ships some groups
   in two batches — `Gazelle-Run.fbx` alongside a bare `run.fbx`, `PolarBearB-Idle.fbx`
   alongside `B idle 1.fbx` — and the second batch is often mislabelled
   (`die.fbx` actually holds the Fall motion). Candidates are found by comparing
   each animation curve's value range, then confirmed frame by frame, because
   the range test alone pairs up distinct motions that happen to span the same
   extents.

Which twin survives is decided in three steps. The shorter clip wins, since the
longer one carries a static tail. On a tie the clip from the group's primary
batch wins — the batch whose filenames carry the species prefix — because the
second batch is the one that abbreviates and, in several groups, mislabels. On
a tie there too the lower ordinal wins, so a group keeps `Attack_1` rather than
`Attack_2`.

Nothing here is re-exported. Every clip is a hardlink straight into
`Truebone_Z-OO/`, byte for byte, so the set costs almost no extra disk and no
clip carries a rig that a round trip through an editor has altered. A source file holding more than
one take is reported rather than repaired, and a take that exists only inside a
group's combined file stays there — `Lynx/Idle4` is the one such case.
"""
import csv, os, re, shutil, sys
HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPTS = os.path.dirname(HERE)
ROOT = os.path.dirname(SCRIPTS)
sys.path[:0] = [HERE, os.path.join(SCRIPTS, "probes")]
from fbx_fingerprint import probe as fingerprint
from fbx_takes import probe as takes
from fbx_curves import same_motion
from normalize import infer_aliases, norm_species, _base_species, _alnum, RESERVED
from fbx_stacks import takes_with_motion

DST = os.path.join(ROOT, "animation")


def secondary_batch(rows):
    """The clip names whose source filename does not carry the species prefix.

    Groups shipped in two batches name them differently: `Gazelle-HeadPoke.fbx`
    against a bare `atk 1.fbx`, `POLARBEARB-Idle.fbx` against `B idle 1.fbx`.
    The prefixed batch is the primary one — the other abbreviates and, in
    several groups, mislabels. Used only to break ties between exact duplicates.
    """
    alias = infer_aliases(rows)
    out = set()
    for r in rows:
        if not r.get("normalized_name"):
            continue
        sp = norm_species(r["group"])
        stem = _alnum(os.path.splitext(os.path.basename(r["file"]))[0])
        cands = [_alnum(sp), _alnum(_base_species(sp))]
        a = alias.get((sp, r["format"]))
        if a:
            cands.append(a)
        if not any(c and stem.startswith(c) for c in cands):
            out.add(r["normalized_name"])
    return out


def main():
    rows = list(csv.DictReader(open(os.path.join(ROOT, "clips.csv"))))
    os.makedirs(DST, exist_ok=True)
    kept = []
    for r in sorted(rows, key=lambda r: r["file"]):
        name = r.get("normalized_name")
        if not name:
            continue
        if os.path.splitext(name)[0].split("-", 1)[1] in RESERVED:
            continue
        t = os.path.join(DST, name)
        if not os.path.exists(t):
            try: os.link(os.path.join(ROOT, r["file"]), t)
            except OSError: shutil.copy2(os.path.join(ROOT, r["file"]), t)
        kept.append(t)
    print("linked %d clips (%s excluded)" % (len(kept), ", ".join(sorted(RESERVED))))

    groups = {}
    for p in kept:
        r = fingerprint(p)
        mv = tuple(sorted((a, b) for a, b in r["ranges"] if b - a > 1e-6))
        if mv:
            species = os.path.basename(p).split("-", 1)[0]
            groups.setdefault((species, mv), []).append(p)

    second = secondary_batch(rows)

    def rank(p):
        action = os.path.splitext(os.path.basename(p))[0].split("-", 1)[1]
        m = re.search(r"_(\d+)$", action)
        return (takes(p)["total_sec"], os.path.basename(p) in second,
                int(m.group(1)) if m else 1, action, os.path.getsize(p))

    removed = 0
    for files in groups.values():
        if len(files) < 2:
            continue
        files.sort(key=rank)
        keep = files[0]
        for other in files[1:]:
            ok, _ = same_motion(keep, other)
            if ok:
                os.remove(other); removed += 1
                print("  duplicate of %s: removed %s"
                      % (os.path.relpath(keep, ROOT), os.path.relpath(other, ROOT)))
    print("removed %d duplicates -> %d files" % (removed, len(kept) - removed))

    # One action per clip is a property of the source, not something imposed here.
    # Reported, never repaired: rewriting a file would mean re-exporting it, and a
    # round trip through an editor rebuilds the rest pose from the first frame and
    # quietly moves the root bones.
    #
    # Counting stacks is not the same as counting actions. Four files pair the real
    # motion with an empty `Take 001` left behind by a C4D export — a stack with no
    # curves under it at all — so what matters is how many stacks carry animation.
    multi, shells = [], []
    for f in sorted(os.listdir(DST)):
        p = os.path.join(DST, f)
        n_stacks = takes(p)["num_takes"]
        n_real = takes_with_motion(p)
        if n_real > 1:
            multi.append((f, n_real))
        elif n_stacks > n_real:
            shells.append((f, n_stacks - n_real))
    if multi:
        print("WARNING: %d clip(s) carry more than one action:" % len(multi))
        for f, n in multi:
            print("   %-34s %d actions" % (f, n))
    else:
        print("every clip holds exactly one action")
    if shells:
        print("(%d also carry an empty leftover stack: %s)"
              % (len(shells), ", ".join(f for f, _ in shells)))


if __name__ == "__main__":
    main()