载入中...
搜索中...
未找到
AnimationMotionBindings.cpp
浏览该文件的文档.
1#include <array>
2#include <cstdint>
3#include <functional>
4#include <simplesquirrel/simplesquirrel.hpp>
5#include <stdexcept>
6#include <string>
7#include <vector>
8
16#include "filesystem/FileData.h"
18
19namespace eve::animation {
20namespace {
21
22constexpr const char* kSource = "animation.bindings";
23
24
25} // namespace
26
27// A provider read hands over a freshly allocated FileData that this call owns.
29
30void exposeMotionMatcherBindings(ssq::Table& table) {
31 const script::BindContext bind{table.getHandle(), kSource};
34 auto db = table.addClass<MotionDatabase>(
35 "MotionDatabase", std::function<MotionDatabase*()>([]() -> MotionDatabase* { return nullptr; }), true);
36 db.addFunc("addFeatureBone", &MotionDatabase::addFeatureBone);
37 db.addFunc("addFeatureBoneByName", &MotionDatabase::addFeatureBoneByName);
38 db.addFunc("setRootBone", &MotionDatabase::setRootBone);
39 db.addFunc("getRootBone", &MotionDatabase::getRootBone);
40 db.addFunc("setRootBoneByName", &MotionDatabase::setRootBoneByName);
41 db.addFunc("addClip", &MotionDatabase::addClip);
42 db.addFunc("getClipCount", &MotionDatabase::getClipCount);
43 db.addFunc("bake", &MotionDatabase::bake);
44 db.addFunc("isBaked", &MotionDatabase::isBaked);
45 db.addFunc("getFrameCount", &MotionDatabase::getFrameCount);
46 db.addFunc("getFeatureSize", &MotionDatabase::getFeatureSize);
47 db.addFunc("getFrameTime", &MotionDatabase::getFrameTime);
48 db.addFunc("getFrameClipIndex", &MotionDatabase::getFrameClipIndex);
49 db.addFunc("getFeatureBoneCount", &MotionDatabase::getFeatureBoneCount);
50 db.addFunc("getFeatureBone", &MotionDatabase::getFeatureBone);
51 db.addFunc("setLocomotionFeatures", [bind](MotionDatabase* self, int left, int right, int pelvis) {
52 return script::projectResult(bind.vm(), self->setLocomotionFeatures(left, right, pelvis));
53 });
54 db.addFunc("hasLocomotionFeatures", &MotionDatabase::hasLocomotionFeatures);
55 db.addFunc("hasFeatureLayout", &MotionDatabase::hasFeatureLayout);
56 db.addFunc("loadFeatureCurves", [bind](MotionDatabase* self, std::string path, ssq::Array sources) {
57 try {
58 if (sources.size() != static_cast<std::size_t>(self->getClipCount()))
59 throw std::runtime_error("one curve source per database clip is required");
60 std::vector<std::string> names;
61 names.reserve(sources.size());
62 for (std::size_t i = 0; i < sources.size(); ++i) names.push_back(sources.get<std::string>(i));
63 auto* fs = eve::ModuleManager::getInstance<eve::filesystem::Filesystem>("Filesystem");
64 if (!fs) throw std::runtime_error("filesystem unavailable");
65 auto* raw = fs->read(std::move(path));
66 if (!raw) throw std::runtime_error("feature curve file unavailable");
67 Owned<eve::filesystem::FileData> data(raw);
69 bind.vm(),
70 self->setFeatureCurves({static_cast<const std::byte*>(data->getData()), data->getSize()}, names));
71 } catch (const std::exception& error) {
72 return bind.failInvalid(error.what());
73 }
74 });
75 db.addFunc("setFeatureLayout", [bind](MotionDatabase* self, int rate, ssq::Array entries, float lengthScale) {
76 try {
77 if (entries.size() == 0 || entries.size() > 256)
78 throw std::runtime_error("feature layout requires 1..256 channels");
81 layout.normalizationLengthScale = lengthScale;
82 for (std::size_t i = 0; i < entries.size(); ++i) {
83 auto item = entries.get<ssq::Array>(i);
84 if (item.size() != 12 && item.size() != 13)
85 throw std::runtime_error("feature channel requires twelve fields plus an optional curve name");
87 const auto kind = item.get<std::string>(0), source = item.get<std::string>(1),
88 query = item.get<std::string>(2);
89 if (kind == "position")
91 else if (kind == "velocity")
93 else if (kind == "heading")
95 else if (kind == "curve")
97 else
98 throw std::runtime_error("unsupported feature operation");
99 if (source == "pose")
101 else if (source == "trajectory")
103 else
104 throw std::runtime_error("unsupported feature source");
105 if (query == "USE_CHARACTER_POSE")
107 else if (query == "USE_CONTINUING_POSE")
109 else
110 throw std::runtime_error("unsupported feature query policy");
111 c.bone = item.get<int>(3);
112 c.origin = item.get<int>(4);
113 const int axes = item.get<int>(5);
114 if (axes < 1 || axes > 7) throw std::runtime_error("feature axes must be a nonempty XYZ mask");
115 c.axes = static_cast<std::uint8_t>(axes);
116 c.headingAxis = item.get<int>(6);
117 c.sampleTime = item.get<float>(7);
118 c.weight = item.get<float>(8);
119 c.characterSpaceVelocity = item.get<bool>(9);
120 c.normalizeVelocity = item.get<bool>(10);
121 c.normalizationGroup = item.get<std::string>(11);
122 if (item.size() == 13) c.curve = item.get<std::string>(12);
123 layout.channels.push_back(std::move(c));
124 }
125 return script::projectResult(bind.vm(), self->setFeatureLayout(layout));
126 } catch (const std::exception& error) {
127 return bind.failInvalid(error.what());
128 }
129 });
130 db.addFunc("setFeatureNormalizationRanges", [bind](MotionDatabase* self, ssq::Array entries) {
131 try {
132 if (entries.size() > 100000) throw std::runtime_error("too many normalization ranges");
133 std::vector<MotionNormalizationRange> ranges;
134 for (std::size_t i = 0; i < entries.size(); ++i) {
135 auto item = entries.get<ssq::Array>(i);
136 if (item.size() != 3) throw std::runtime_error("normalization range requires clip,start,end");
137 ranges.push_back({item.get<int>(0), item.get<float>(1), item.get<float>(2)});
138 }
139 return script::projectResult(bind.vm(), self->setFeatureNormalizationRanges(ranges),
140 [](int count) { return Value(count); });
141 } catch (const std::exception& error) {
142 return bind.failInvalid(error.what());
143 }
144 });
145 auto mm = table.addClass<MotionMatcher>(
146 "MotionMatcher", std::function<MotionMatcher*()>([]() -> MotionMatcher* { return nullptr; }), true);
147 mm.addFunc("setDesiredVelocity", &MotionMatcher::setDesiredVelocity);
148 mm.addFunc("getDesiredVelocityX", &MotionMatcher::getDesiredVelocityX);
149 mm.addFunc("getDesiredVelocityZ", &MotionMatcher::getDesiredVelocityZ);
150 mm.addFunc("setDesiredYaw", &MotionMatcher::setDesiredYaw);
151 mm.addFunc("getDesiredYaw", &MotionMatcher::getDesiredYaw);
152 mm.addFunc("setSearchInterval", &MotionMatcher::setSearchInterval);
153 mm.addFunc("getSearchInterval", &MotionMatcher::getSearchInterval);
154 mm.addFunc("setBlendTime", &MotionMatcher::setBlendTime);
155 mm.addFunc("getBlendTime", &MotionMatcher::getBlendTime);
156 mm.addFunc("setPlayRateRange", [bind](MotionMatcher* self, float minimum, float maximum) {
157 return script::projectResult(bind.vm(), self->setPlayRateRange(minimum, maximum));
158 });
159 mm.addFunc("getPlayRateMinimum", &MotionMatcher::getPlayRateMinimum);
160 mm.addFunc("getPlayRateMaximum", &MotionMatcher::getPlayRateMaximum);
161 mm.addFunc("getPlayRate", &MotionMatcher::getPlayRate);
162 mm.addFunc("setTrajectoryWeight", &MotionMatcher::setTrajectoryWeight);
163 mm.addFunc("getTrajectoryWeight", &MotionMatcher::getTrajectoryWeight);
164 mm.addFunc("setPoseWeight", &MotionMatcher::setPoseWeight);
165 mm.addFunc("getPoseWeight", &MotionMatcher::getPoseWeight);
166 mm.addFunc("setVelocityWeight", &MotionMatcher::setVelocityWeight);
167 mm.addFunc("getVelocityWeight", &MotionMatcher::getVelocityWeight);
168 mm.addFunc("setIgnoreRadius", &MotionMatcher::setIgnoreRadius);
169 mm.addFunc("getIgnoreRadius", &MotionMatcher::getIgnoreRadius);
170 mm.addFunc("setPoseReselectHistory", [bind](MotionMatcher* self, float seconds) {
171 return script::projectResult(bind.vm(), self->setPoseReselectHistory(seconds));
172 });
173 mm.addFunc("getPoseReselectHistory", &MotionMatcher::getPoseReselectHistory);
174 mm.addFunc("getMatchedFrame", &MotionMatcher::getMatchedFrame);
175 mm.addFunc("getMatchedClipIndex", &MotionMatcher::getMatchedClipIndex);
176 mm.addFunc("getMatchedTime", &MotionMatcher::getMatchedTime);
177 mm.addFunc("getLastSearchCost", &MotionMatcher::getLastSearchCost);
178 mm.addFunc("getPose", &MotionMatcher::getPose);
179 mm.addFunc("search", &MotionMatcher::search);
180 mm.addFunc("update", &MotionMatcher::update);
181 mm.addFunc("setFeatureQuery", [bind](MotionMatcher* self, AnimPose* current, AnimPose* previous, float dt,
182 ssq::Array entries, ssq::Array curveEntries) {
183 try {
184 if (!current || !previous || entries.size() > 256)
185 throw std::runtime_error("feature query requires two poses and bounded trajectory samples");
186 std::vector<MotionFeatureTrajectorySample> samples;
187 for (std::size_t i = 0; i < entries.size(); ++i) {
188 auto item = entries.get<ssq::Array>(i);
189 if (item.size() != 8) throw std::runtime_error("feature sample requires time,x,y,z,vx,vy,vz,yaw");
190 samples.push_back({item.get<float>(0), item.get<float>(1), item.get<float>(2), item.get<float>(3),
191 item.get<float>(4), item.get<float>(5), item.get<float>(6), item.get<float>(7)});
192 }
193 if (curveEntries.size() > 256) throw std::runtime_error("curve query requires bounded samples");
194 std::vector<MotionFeatureCurveSample> curves;
195 for (std::size_t i = 0; i < curveEntries.size(); ++i) {
196 auto item = curveEntries.get<ssq::Array>(i);
197 if (item.size() != 3) throw std::runtime_error("curve sample requires name,time,value");
198 curves.push_back({item.get<std::string>(0), item.get<float>(1), item.get<float>(2)});
199 }
200 return script::projectResult(bind.vm(), self->setFeatureQuery(*current, *previous, dt, samples, curves));
201 } catch (const std::exception& error) {
202 return bind.failInvalid(error.what());
203 }
204 });
205 mm.addFunc("setLocomotionQuery", [bind](MotionMatcher* self, AnimPose* current, AnimPose* previous, float dt,
206 ssq::Array entries) {
207 try {
208 if (!current || !previous || entries.size() != 5)
209 throw std::runtime_error("locomotion query requires two poses and five trajectory samples");
210 std::array<MotionLocomotionSample, 5> samples;
211 for (std::size_t i = 0; i < 5; ++i) {
212 auto item = entries.get<ssq::Array>(i);
213 if (item.size() != 7) throw std::runtime_error("locomotion sample requires x,y,z,vx,vy,vz,yaw");
214 samples[i] = {item.get<float>(0), item.get<float>(1), item.get<float>(2), item.get<float>(3),
215 item.get<float>(4), item.get<float>(5), item.get<float>(6)};
216 }
217 return script::projectResult(bind.vm(), self->setLocomotionQuery(*current, *previous, dt, samples));
218 } catch (const std::exception& error) {
219 return bind.failInvalid(error.what());
220 }
221 });
222 mm.addFunc("setCandidateRanges", [bind](MotionMatcher* self, ssq::Array entries) {
223 try {
224 if (entries.size() > 100000) throw std::runtime_error("too many candidate ranges");
225 std::vector<MotionSearchRange> ranges;
226 for (std::size_t i = 0; i < entries.size(); ++i) {
227 auto item = entries.get<ssq::Array>(i);
228 if (item.size() != 9)
229 throw std::runtime_error(
230 "candidate range requires "
231 "clip,start,end,bias,disableReselection,transitionBlocks,continuingBias,costOverrides,"
232 "continuingCostOverrides");
233 MotionSearchRange range{item.get<int>(0), item.get<float>(1), item.get<float>(2), item.get<float>(3),
234 item.get<bool>(4)};
235 auto blocks = item.get<ssq::Array>(5);
236 if (blocks.size() > 100000) throw std::runtime_error("too many transition blocks");
237 for (std::size_t j = 0; j < blocks.size(); ++j) {
238 auto block = blocks.get<ssq::Array>(j);
239 if (block.size() != 2) throw std::runtime_error("transition block requires start,end");
240 range.transitionBlocks.push_back({block.get<float>(0), block.get<float>(1)});
241 }
242 range.continuingCostBias = item.get<float>(6);
243 for (std::size_t field : {std::size_t{7}, std::size_t{8}}) {
244 auto values = item.get<ssq::Array>(field);
245 if (values.size() > 100000) throw std::runtime_error("too many cost override intervals");
246 auto& destination = field == 7 ? range.costOverrides : range.continuingCostOverrides;
247 for (std::size_t j = 0; j < values.size(); ++j) {
248 auto value = values.get<ssq::Array>(j);
249 if (value.size() != 3) throw std::runtime_error("cost override requires start,end,bias");
250 destination.push_back({value.get<float>(0), value.get<float>(1), value.get<float>(2)});
251 }
252 }
253 ranges.push_back(std::move(range));
254 }
255 return script::projectResult(bind.vm(), self->setCandidateRanges(ranges),
256 [](int count) { return Value(count); });
257 } catch (const std::exception& error) {
258 return bind.failInvalid(error.what());
259 }
260 });
261 mm.addFunc("setQueryPose", [](MotionMatcher* self, AnimPose* pose) {
262 if (!pose) throw std::runtime_error("query pose is required");
263 auto configured = self->setQueryPose(*pose);
264 if (!configured) throw std::runtime_error(configured.status().describe());
265 });
266 mm.addFunc("setTrajectory", [bind](MotionMatcher* self, ssq::Array entries) {
267 try {
268 if (entries.size() != 3) throw std::runtime_error("trajectory requires three samples");
269 std::array<MotionTrajectorySample, 3> samples;
270 for (std::size_t i = 0; i < 3; ++i) {
271 auto item = entries.get<ssq::Array>(i);
272 if (item.size() != 3) throw std::runtime_error("trajectory sample requires x,z,yaw");
273 samples[i] = {item.get<float>(0), item.get<float>(1), item.get<float>(2)};
274 }
275 return script::projectResult(bind.vm(), self->setTrajectory(samples));
276 } catch (const std::exception& error) {
277 return bind.failInvalid(error.what());
278 }
279 });
280}
281} // namespace eve::animation
eve::EntitySpatialPose pose
std::unordered_map< std::string, QuestRuntime > entries
double raw
std::string layout
float maximum[3]
float minimum[3]
HexVec3 left
HexVec3 right
std::int32_t c
Range range
double dt
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
std::array< std::array< double, 3 >, 3 > axes
std::string_view source
std::string kind
double current
Per-translation-unit VM + diagnostic-source helper for Squirrel bindings.
int count
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
Baked motion-matching feature database from one or more AnimClips. Feature layout per frame: [0....
void setRootBoneByName(const std::string &name)
Sets the root bone by name.
eve::Result< int > setFeatureNormalizationRanges(std::span< const MotionNormalizationRange > ranges)
Atomically select weighted source ranges used to normalize a variable feature layout.
bool hasFeatureLayout() const
Whether this database uses an explicitly configured variable layout.
void addFeatureBone(int boneIndex)
Include bone world position in pose features (by index).
float getFrameTime(int frameIndex) const
Returns the frame time.
bool isBaked() const
True when baked.
int getFeatureBoneCount() const
Returns the feature bone count.
eve::Result< void > setFeatureLayout(const MotionFeatureLayout &layout)
Atomically configure an owning variable feature layout before bake.
int getFeatureSize() const
Returns the feature size.
int getRootBone() const
Returns the root bone.
void addFeatureBoneByName(const std::string &name)
Adds feature bone by name.
void bake()
Bake all clips into searchable frames. Call after addClip / feature bones.
bool hasLocomotionFeatures() const
Whether this database uses the 30-dimensional locomotion layout.
int getFeatureBone(int index) const
Returns the feature bone.
eve::Result< void > setFeatureCurves(std::span< const std::byte > bytes, std::span< const std::string > sources)
Atomically copy scalar source curves for the configured layout.
eve::Result< void > setLocomotionFeatures(int leftFoot, int rightFoot, int pelvis)
Configure the locomotion layout before baking or creating matchers.
int getFrameCount() const
Returns the frame count.
void setRootBone(int boneIndex)
Bone used for trajectory / velocity features (default 0). Mixamo clips typically want hips (mixamorig...
void addClip(AnimClip *clip)
Adds clip.
int getFrameClipIndex(int frameIndex) const
Returns the frame clip index.
int getClipCount() const
Returns the clip count.
Runtime motion matching player: builds a query feature from current pose + desired trajectory,...
void search()
Force an immediate search (also called periodically from update).
void update(float dt)
Legacy seconds facade; explicitly forwards to advance().
void setBlendTime(float seconds)
Sets the blend time.
float getMatchedTime() const
Returns the matched time.
void setDesiredYaw(float yaw)
Desired facing yaw (radians, Y-up).
int getMatchedFrame() const
Returns the matched frame.
float getDesiredVelocityX() const
Returns the desired velocity x.
void setDesiredVelocity(float x, float z)
Desired planar velocity in character/world XZ (units/sec).
void setVelocityWeight(float w)
Sets the velocity weight.
void setPoseWeight(float w)
Sets the pose weight.
void setTrajectoryWeight(float w)
Sets the trajectory weight.
AnimPose * getPose()
Returns the pose.
float getSearchInterval() const
Returns the search interval.
void setIgnoreRadius(int frames)
Keep continuous playback within this frame radius of the live playhead, including loop seams.
float getDesiredYaw() const
Returns the desired yaw.
float getVelocityWeight() const
Returns the velocity weight.
int getIgnoreRadius() const
Returns the ignore radius.
float getBlendTime() const
Returns the blend time.
int getMatchedClipIndex() const
Returns the matched clip index.
float getPlayRateMaximum() const
Returns the play rate maximum.
float getLastSearchCost() const
Returns the last search cost.
float getPoseWeight() const
Returns the pose weight.
void setSearchInterval(float seconds)
Sets the search interval.
float getTrajectoryWeight() const
Returns the trajectory weight.
float getDesiredVelocityZ() const
Returns the desired velocity z.
float getPlayRate() const
Returns the play rate.
Value get(const char *key) const
Returns the value.
Definition Json.cpp:337
Pins the active VM and a stable diagnostic source for one expose() TU.
void exposeAnimInertializerBindings(ssq::Table &table)
Register the owning AnimInertializer Squirrel surface.
void exposeOrientationWarpingBindings(ssq::Table &table)
Register the owning OrientationWarping Squirrel surface.
void exposeMotionMatcherBindings(ssq::Table &table)
Register the synchronous MotionMatcher Squirrel surface.
std::unique_ptr< T > Owned
C++ owning storage used by an object factory.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Owning configuration for one ordered motion feature channel.
Owning ordered feature layout; copied atomically by a database.
Owning candidate interval in seconds in a database clip; endpoints inclusive.
std::vector< MotionTransitionBlock > transitionBlocks
Owned transition blocks, unioned across all ranges of this clip; continuation remains eligible.