载入中...
搜索中...
未找到
ActionTimeline.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cmath>
5#include <set>
6#include <tuple>
7#include <utility>
8
9namespace eve::action {
10namespace {
11
12template <class T>
13Result<T> invalid(std::string message, std::string path) {
14 return Result<T>::failure(
16}
17
18const Value* field(const Value& value, std::string_view name) { return value.find(std::string(name)); }
19
20Result<std::string> stringField(const Value& value, std::string_view name, std::string path) {
21 const Value* member = field(value, name);
22 if (!member || !member->isString())
24 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected string field", std::move(path)));
25 return Result<std::string>::success(member->asString());
26}
27
28Result<std::int64_t> intField(const Value& value, std::string_view name, std::string path) {
29 const Value* member = field(value, name);
30 if (!member || !member->isInt64())
32 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected integer field", std::move(path)));
34}
35
36Result<bool> boolField(const Value& value, std::string_view name, std::string path) {
37 const Value* member = field(value, name);
38 if (!member || !member->isBool())
40 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected boolean field", std::move(path)));
41 return Result<bool>::success(member->asBool());
42}
43
44Result<LogicalId> logicalIdField(const Value& value, std::string_view name, std::string path) {
45 auto text = stringField(value, name, path);
46 if (!text) return Result<LogicalId>::failure(text.status());
47 auto parsed = LogicalId::parse(text.value());
48 if (!parsed)
50 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected namespace:name logical id", path));
51 return Result<LogicalId>::success(std::move(*parsed));
52}
53
54Value payloadValue(const Value::Object& payload) { return Value(payload); }
55
56Result<Value::Object> payloadField(const Value& value, std::string path) {
57 const Value* payload = field(value, "payload");
58 if (!payload || !payload->isObject())
60 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected object payload", std::move(path)));
62}
63
64Value encodeNotify(const ActionNotify& notify) {
66 object["id"] = notify.id.format();
67 object["type"] = notify.type.format();
68 object["timeNs"] = notify.time.nanoseconds();
69 object["payload"] = payloadValue(notify.payload);
70 object["enabled"] = notify.enabled;
71 return Value(std::move(object));
72}
73
74Value encodeState(const ActionNotifyState& state) {
76 object["id"] = state.id.format();
77 object["type"] = state.type.format();
78 object["startNs"] = state.start.nanoseconds();
79 object["endNs"] = state.end.nanoseconds();
80 object["payload"] = payloadValue(state.payload);
81 object["enabled"] = state.enabled;
82 return Value(std::move(object));
83}
84
85Value encodeAnimationSection(const ActionAnimationSection& section) {
87 object["id"] = section.id.format();
88 object["animationUri"] = section.animationUri;
89 object["startNs"] = section.start.nanoseconds();
90 object["endNs"] = section.end.nanoseconds();
91 object["blendInNs"] = section.blendIn.nanoseconds();
92 object["blendOutNs"] = section.blendOut.nanoseconds();
93 object["sourceStartNs"] = section.sourceStart.nanoseconds();
94 object["sourceEndNs"] = section.sourceEnd.nanoseconds();
95 object["blendInCurve"] = std::string(actionBlendCurveName(section.blendInCurve));
96 object["blendOutCurve"] = std::string(actionBlendCurveName(section.blendOutCurve));
97 return Value(std::move(object));
98}
99
100Result<ActionAnimationSection> decodeAnimationSection(const Value& value, const std::string& path,
101 std::int64_t schemaVersion) {
102 if (!value.isObject())
104 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected animation section object", path));
105 auto id = logicalIdField(value, "id", path + ".id");
107 auto uri = stringField(value, "animationUri", path + ".animationUri");
108 if (!uri) return Result<ActionAnimationSection>::failure(uri.status());
109 auto start = intField(value, "startNs", path + ".startNs");
111 auto end = intField(value, "endNs", path + ".endNs");
112 if (!end) return Result<ActionAnimationSection>::failure(end.status());
113 auto blend = intField(value, "blendInNs", path + ".blendInNs");
115 ActionAnimationSection section{std::move(id).takeValue(), std::move(uri).takeValue(),
118 if (schemaVersion >= 3) {
119 auto sourceStart = intField(value, "sourceStartNs", path + ".sourceStartNs");
120 if (!sourceStart) return Result<ActionAnimationSection>::failure(sourceStart.status());
121 auto sourceEnd = intField(value, "sourceEndNs", path + ".sourceEndNs");
122 if (!sourceEnd) return Result<ActionAnimationSection>::failure(sourceEnd.status());
123 section.sourceStart = Duration::fromNanoseconds(sourceStart.value());
124 section.sourceEnd = Duration::fromNanoseconds(sourceEnd.value());
125 if (schemaVersion < 5) {
126 auto blendCurve = stringField(value, "blendCurve", path + ".blendCurve");
127 if (!blendCurve) return Result<ActionAnimationSection>::failure(blendCurve.status());
128 auto parsedCurve = actionBlendCurveFromName(blendCurve.value());
129 if (!parsedCurve)
130 return invalid<ActionAnimationSection>("unknown animation blend curve", path + ".blendCurve");
131 section.blendInCurve = *parsedCurve;
132 section.blendOut = Duration::zero();
133 section.blendOutCurve = ActionBlendCurve::EaseInOut;
134 } else {
135 auto blendOut = intField(value, "blendOutNs", path + ".blendOutNs");
136 auto blendInCurve = stringField(value, "blendInCurve", path + ".blendInCurve");
137 auto blendOutCurve = stringField(value, "blendOutCurve", path + ".blendOutCurve");
138 if (!blendOut) return Result<ActionAnimationSection>::failure(blendOut.status());
139 if (!blendInCurve) return Result<ActionAnimationSection>::failure(blendInCurve.status());
140 if (!blendOutCurve) return Result<ActionAnimationSection>::failure(blendOutCurve.status());
141 auto parsedIn = actionBlendCurveFromName(blendInCurve.value());
142 auto parsedOut = actionBlendCurveFromName(blendOutCurve.value());
143 if (!parsedIn)
144 return invalid<ActionAnimationSection>("unknown animation blend-in curve", path + ".blendInCurve");
145 if (!parsedOut)
146 return invalid<ActionAnimationSection>("unknown animation blend-out curve", path + ".blendOutCurve");
147 section.blendOut = Duration::fromNanoseconds(blendOut.value());
148 section.blendInCurve = *parsedIn;
149 section.blendOutCurve = *parsedOut;
150 }
151 }
152 return Result<ActionAnimationSection>::success(std::move(section));
153}
154
155Result<ActionNotify> decodeNotify(const Value& value, const std::string& path, std::int64_t schemaVersion) {
156 if (!value.isObject())
158 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected notify object", path));
159 auto id = logicalIdField(value, "id", path + ".id");
160 if (!id) return Result<ActionNotify>::failure(id.status());
161 auto type = logicalIdField(value, "type", path + ".type");
162 if (!type) return Result<ActionNotify>::failure(type.status());
163 auto time = intField(value, "timeNs", path + ".timeNs");
164 if (!time) return Result<ActionNotify>::failure(time.status());
165 auto payload = payloadField(value, path + ".payload");
166 if (!payload) return Result<ActionNotify>::failure(payload.status());
167 bool enabled = true;
168 if (schemaVersion >= 4) {
169 auto decodedEnabled = boolField(value, "enabled", path + ".enabled");
170 if (!decodedEnabled) return Result<ActionNotify>::failure(decodedEnabled.status());
171 enabled = decodedEnabled.value();
172 }
173 return Result<ActionNotify>::success(ActionNotify{std::move(id).takeValue(), std::move(type).takeValue(),
175 std::move(payload).takeValue(), enabled});
176}
177
178Result<ActionNotifyState> decodeState(const Value& value, const std::string& path, std::int64_t schemaVersion) {
179 if (!value.isObject())
181 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected notify-state object", path));
182 auto id = logicalIdField(value, "id", path + ".id");
183 if (!id) return Result<ActionNotifyState>::failure(id.status());
184 auto type = logicalIdField(value, "type", path + ".type");
185 if (!type) return Result<ActionNotifyState>::failure(type.status());
186 auto start = intField(value, "startNs", path + ".startNs");
187 if (!start) return Result<ActionNotifyState>::failure(start.status());
188 auto end = intField(value, "endNs", path + ".endNs");
189 if (!end) return Result<ActionNotifyState>::failure(end.status());
190 auto payload = payloadField(value, path + ".payload");
192 bool enabled = true;
193 if (schemaVersion >= 4) {
194 auto decodedEnabled = boolField(value, "enabled", path + ".enabled");
195 if (!decodedEnabled) return Result<ActionNotifyState>::failure(decodedEnabled.status());
196 enabled = decodedEnabled.value();
197 }
198 return Result<ActionNotifyState>::success(ActionNotifyState{
199 std::move(id).takeValue(), std::move(type).takeValue(), Duration::fromNanoseconds(start.value()),
200 Duration::fromNanoseconds(end.value()), std::move(payload).takeValue(), enabled});
201}
202
203bool inWindow(Duration value, Duration previous, Duration current, bool includePrevious) {
204 return includePrevious ? value >= previous && value <= current : value > previous && value <= current;
205}
206
207} // namespace
208
209std::string_view actionBlendCurveName(ActionBlendCurve curve) noexcept {
210 switch (curve) {
211 case ActionBlendCurve::Linear: return "linear";
212 case ActionBlendCurve::EaseIn: return "ease-in";
213 case ActionBlendCurve::EaseOut: return "ease-out";
214 case ActionBlendCurve::EaseInOut: return "ease-in-out";
215 case ActionBlendCurve::SmoothStep: return "smooth-step";
216 }
217 return "ease-in-out";
218}
219
220std::optional<ActionBlendCurve> actionBlendCurveFromName(std::string_view name) noexcept {
221 if (name == "linear") return ActionBlendCurve::Linear;
222 if (name == "ease-in") return ActionBlendCurve::EaseIn;
223 if (name == "ease-out") return ActionBlendCurve::EaseOut;
224 if (name == "ease-in-out") return ActionBlendCurve::EaseInOut;
225 if (name == "smooth-step") return ActionBlendCurve::SmoothStep;
226 return std::nullopt;
227}
228
229double evaluateActionBlendCurve(ActionBlendCurve curve, double normalized) noexcept {
230 const double t = std::clamp(normalized, 0.0, 1.0);
231 switch (curve) {
232 case ActionBlendCurve::Linear: return t;
233 case ActionBlendCurve::EaseIn: return t * t;
234 case ActionBlendCurve::EaseOut: return 1.0 - (1.0 - t) * (1.0 - t);
235 case ActionBlendCurve::EaseInOut: return t * t * (3.0 - 2.0 * t);
236 case ActionBlendCurve::SmoothStep: return t * t * (3.0 - 2.0 * t);
237 }
238 return t;
239}
240
241std::string_view actionTrackKindName(ActionTrackKind kind) noexcept {
242 switch (kind) {
243 case ActionTrackKind::Animation: return "animation";
244 case ActionTrackKind::Gameplay: return "gameplay";
245 case ActionTrackKind::Effect: return "effect";
246 case ActionTrackKind::Audio: return "audio";
247 case ActionTrackKind::Camera: return "camera";
248 case ActionTrackKind::Movement: return "movement";
249 case ActionTrackKind::Tag: return "tag";
250 case ActionTrackKind::Custom: return "custom";
251 }
252 return "custom";
253}
254
263
267 Diagnostic::error(DiagnosticCode::InvalidArgument, "unsupported action timeline schema version", "schemaVersion"));
269 Diagnostic::error(DiagnosticCode::InvalidArgument, "action timeline requires a valid action id", "actionId"));
271 Diagnostic::error(DiagnosticCode::InvalidArgument, "timeline duration must be non-negative", "durationNs"));
272 if (!std::isfinite(montage.basePlayRate) || montage.basePlayRate <= 0.0)
274 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage base play rate must be positive and finite", "montage.basePlayRate"));
278 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage blend durations must be non-negative", "montage"));
279 for (std::size_t index = 0; index < splitTimestamps.size(); ++index) {
283 Diagnostic::error(DiagnosticCode::InvalidArgument, "physical section splits must be strictly ordered inside the timeline", "splitTimestampsNs[" + std::to_string(index) + "]"));
284 }
285
286 std::set<std::string> ids;
287 for (std::size_t index = 0; index < animationSections.size(); ++index) {
288 const auto& section = animationSections[index];
289 const std::string path = "animationSections[" + std::to_string(index) + "]";
290 if (!section.id.isValid()) return Result<void>::failure(
291 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation section id is invalid", path + ".id"));
292 if (!ids.insert(section.id.format()).second) return Result<void>::failure(
293 Diagnostic::error(DiagnosticCode::InvalidArgument, "timeline item ids must be unique", path + ".id"));
294 if (section.animationUri.empty()) return Result<void>::failure(
295 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation section requires a URI", path + ".animationUri"));
296 if (section.start < Duration::zero() || section.end <= section.start || section.end > duration)
298 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation section range is invalid", path));
299 const auto sectionDuration = section.end.nanoseconds() - section.start.nanoseconds();
300 if (section.blendIn < Duration::zero() || section.blendIn.nanoseconds() > sectionDuration)
302 DiagnosticCode::InvalidArgument, "animation section blend-in is outside its range",
303 path + ".blendInNs"));
304 if (section.blendOut < Duration::zero() || section.blendOut.nanoseconds() > sectionDuration)
306 DiagnosticCode::InvalidArgument, "animation section blend-out is outside its range",
307 path + ".blendOutNs"));
308 if (section.sourceStart < Duration::zero() || section.sourceEnd < Duration::zero() ||
309 (!section.sourceEnd.isZero() && section.sourceEnd <= section.sourceStart))
311 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation section source trim is invalid", path + ".sourceStartNs"));
312 if (index > 0) {
313 const auto& previous = animationSections[index - 1];
314 if (previous.start > section.start)
316 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation sections must be sorted by start time", path + ".startNs"));
317 if (previous.end > section.start) return Result<void>::failure(
318 Diagnostic::error(DiagnosticCode::InvalidArgument, "animation sections must not overlap", path + ".startNs"));
319 }
320 }
321 for (std::size_t trackIndex = 0; trackIndex < tracks.size(); ++trackIndex) {
322 const auto& track = tracks[trackIndex];
323 const std::string path = "tracks[" + std::to_string(trackIndex) + "]";
324 if (!track.id.isValid()) return Result<void>::failure(
325 Diagnostic::error(DiagnosticCode::InvalidArgument, "track id is invalid", path + ".id"));
326 if (!ids.insert(track.id.format()).second) return Result<void>::failure(
327 Diagnostic::error(DiagnosticCode::InvalidArgument, "timeline item ids must be unique", path + ".id"));
328 for (std::size_t index = 0; index < track.notifies.size(); ++index) {
329 const auto& notify = track.notifies[index];
330 const std::string itemPath = path + ".notifies[" + std::to_string(index) + "]";
331 if (!notify.id.isValid() || !notify.type.isValid()) return Result<void>::failure(
332 Diagnostic::error(DiagnosticCode::InvalidArgument, "notify ids are invalid", itemPath));
333 if (!ids.insert(notify.id.format()).second)
335 Diagnostic::error(DiagnosticCode::InvalidArgument, "timeline item ids must be unique", itemPath + ".id"));
336 if (notify.time < Duration::zero() || notify.time > duration)
338 Diagnostic::error(DiagnosticCode::InvalidArgument, "notify time is outside the timeline", itemPath + ".timeNs"));
339 if (index > 0 && track.notifies[index - 1].time > notify.time)
341 Diagnostic::error(DiagnosticCode::InvalidArgument, "notifies must be sorted by time", itemPath + ".timeNs"));
342 }
343 for (std::size_t index = 0; index < track.states.size(); ++index) {
344 const auto& state = track.states[index];
345 const std::string itemPath = path + ".states[" + std::to_string(index) + "]";
346 if (!state.id.isValid() || !state.type.isValid()) return Result<void>::failure(
347 Diagnostic::error(DiagnosticCode::InvalidArgument, "notify-state ids are invalid", itemPath));
348 if (!ids.insert(state.id.format()).second)
350 Diagnostic::error(DiagnosticCode::InvalidArgument, "timeline item ids must be unique", itemPath + ".id"));
351 if (state.start < Duration::zero() || state.end <= state.start || state.end > duration)
353 Diagnostic::error(DiagnosticCode::InvalidArgument, "notify-state range is invalid", itemPath));
354 if (index > 0 && track.states[index - 1].start > state.start)
356 Diagnostic::error(DiagnosticCode::InvalidArgument, "notify states must be sorted by start time", itemPath + ".startNs"));
357 }
358 }
359 return Result<void>::success();
360}
361
363 bool includePrevious) const {
364 auto valid = validate();
365 if (!valid) return Result<std::vector<ActionTimelineEvent>>::failure(valid.status());
366 if (previous < Duration::zero() || current < previous || current > duration)
368 Diagnostic::error(DiagnosticCode::InvalidArgument, "sample range is outside the timeline", "sample"));
369
370 std::vector<ActionTimelineEvent> out;
371 for (const auto& track : tracks) {
372 if (track.muted) continue;
373 for (const auto& notify : track.notifies) {
374 if (!notify.enabled) continue;
375 if (inWindow(notify.time, previous, current, includePrevious))
376 out.push_back(
377 {ActionTimelineEventKind::Notify, track.id, notify.id, notify.type, notify.time, notify.payload});
378 }
379 for (const auto& state : track.states) {
380 if (!state.enabled) continue;
381 if (inWindow(state.start, previous, current, includePrevious))
382 out.push_back(
383 {ActionTimelineEventKind::StateEnter, track.id, state.id, state.type, state.start, state.payload});
384 if (inWindow(state.end, previous, current, includePrevious))
385 out.push_back(
386 {ActionTimelineEventKind::StateExit, track.id, state.id, state.type, state.end, state.payload});
387 }
388 }
389 std::stable_sort(out.begin(), out.end(), [](const auto& left, const auto& right) {
390 if (left.time != right.time) return left.time < right.time;
391 if (left.trackId != right.trackId) return left.trackId.format() < right.trackId.format();
392 if (left.itemId != right.itemId) return left.itemId.format() < right.itemId.format();
393 return static_cast<std::uint8_t>(left.kind) < static_cast<std::uint8_t>(right.kind);
394 });
395 return Result<std::vector<ActionTimelineEvent>>::success(std::move(out));
396}
397
398Result<std::vector<ActionActiveBlock>> ActionTimeline::activeBlocks(Duration time) const {
399 auto valid = validate();
400 if (!valid) return Result<std::vector<ActionActiveBlock>>::failure(valid.status());
401 if (time < Duration::zero() || time > duration)
403 Diagnostic::error(DiagnosticCode::InvalidArgument, "active-block sample is outside the timeline", "time"));
404
405 std::vector<ActionActiveBlock> out;
406 for (const auto& track : tracks) {
407 if (track.muted) continue;
408 for (const auto& state : track.states) {
409 if (!state.enabled) continue;
410 if (time < state.start || time >= state.end) continue;
411 out.push_back({track.id,
412 state.id,
413 state.type,
414 Duration::fromNanoseconds(time.nanoseconds() - state.start.nanoseconds()),
415 Duration::fromNanoseconds(state.end.nanoseconds() - state.start.nanoseconds()),
416 state.payload});
417 }
418 }
419 std::stable_sort(out.begin(), out.end(), [](const auto& left, const auto& right) {
420 if (left.trackId != right.trackId) return left.trackId.format() < right.trackId.format();
421 return left.itemId.format() < right.itemId.format();
422 });
423 return Result<std::vector<ActionActiveBlock>>::success(std::move(out));
424}
425
426Result<Value> ActionTimeline::toValue() const {
427 auto valid = validate();
428 if (!valid) return Result<Value>::failure(valid.status());
429 Value::Array encodedTracks;
430 Value::Array encodedSections;
431 Value::Array encodedSplits;
432 encodedSections.reserve(animationSections.size());
433 for (const auto& section : animationSections) encodedSections.push_back(encodeAnimationSection(section));
434 encodedSplits.reserve(splitTimestamps.size());
435 for (const Duration split : splitTimestamps) encodedSplits.emplace_back(split.nanoseconds());
436 encodedTracks.reserve(tracks.size());
437 for (const auto& track : tracks) {
438 Value::Array notifies;
439 Value::Array states;
440 for (const auto& notify : track.notifies) notifies.push_back(encodeNotify(notify));
441 for (const auto& state : track.states) states.push_back(encodeState(state));
443 object["id"] = track.id.format();
444 object["label"] = track.label;
445 object["kind"] = std::string(actionTrackKindName(track.kind));
446 object["muted"] = track.muted;
447 object["locked"] = track.locked;
448 object["notifies"] = Value(std::move(notifies));
449 object["states"] = Value(std::move(states));
450 encodedTracks.emplace_back(std::move(object));
451 }
453 root["schema"] = std::string(kActionTimelineSchemaId);
454 root["schemaVersion"] = static_cast<std::int64_t>(schemaVersion.value());
455 root["actionId"] = actionId.format();
456 root["durationNs"] = duration.nanoseconds();
457 root["animationUri"] = animationSections.empty() ? animationUri : animationSections.front().animationUri;
458 root["animationSections"] = Value(std::move(encodedSections));
459 root["splitTimestampsNs"] = Value(std::move(encodedSplits));
460 root["montage"] = Value::Object{{"basePlayRate", montage.basePlayRate},
461 {"looping", montage.looping},
462 {"footIk", montage.footIk},
463 {"animationLayer", static_cast<std::int64_t>(montage.animationLayer)},
464 {"defaultBlendInNs", montage.defaultBlendIn.nanoseconds()},
465 {"defaultBlendOutNs", montage.defaultBlendOut.nanoseconds()},
466 {"blendOutOffsetNs", montage.blendOutOffset.nanoseconds()},
467 {"rootMotionHorizontal", montage.rootMotionHorizontal},
468 {"rootMotionVertical", montage.rootMotionVertical},
469 {"rootMotionRotation", montage.rootMotionRotation}};
470 root["tracks"] = Value(std::move(encodedTracks));
471 root["metadata"] = Value(metadata);
472 return Result<Value>::success(Value(std::move(root)));
473}
474
475Result<ActionTimeline> ActionTimeline::fromValue(const Value& value) {
476 if (!value.isObject())
478 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected action timeline object", "timeline"));
479 auto schema = stringField(value, "schema", "schema");
480 if (!schema) return Result<ActionTimeline>::failure(schema.status());
481 if (schema.value() != kActionTimelineSchemaId)
483 Diagnostic::error(DiagnosticCode::InvalidArgument, "unexpected action timeline schema", "schema"));
484 auto version = intField(value, "schemaVersion", "schemaVersion");
485 if (!version) return Result<ActionTimeline>::failure(version.status());
486 auto actionId = logicalIdField(value, "actionId", "actionId");
487 if (!actionId) return Result<ActionTimeline>::failure(actionId.status());
488 auto duration = intField(value, "durationNs", "durationNs");
490 auto animationUri = stringField(value, "animationUri", "animationUri");
491 if (!animationUri) return Result<ActionTimeline>::failure(animationUri.status());
492 const Value* tracksValue = field(value, "tracks");
493 const Value* metadataValue = field(value, "metadata");
494 if (!tracksValue || !tracksValue->isArray())
496 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected tracks array", "tracks"));
497 if (!metadataValue || !metadataValue->isObject())
499 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected metadata object", "metadata"));
500
501 ActionTimeline candidate;
502 if (version.value() < 1 || version.value() > static_cast<std::int64_t>(kActionTimelineSchemaVersion))
504 DiagnosticCode::InvalidArgument, "unsupported action timeline schema version", "schemaVersion"));
506 candidate.actionId = std::move(actionId).takeValue();
507 candidate.duration = Duration::fromNanoseconds(duration.value());
508 candidate.animationUri = std::move(animationUri).takeValue();
509 candidate.metadata = *metadataValue->getIf<Value::Object>();
510 if (version.value() == 1) {
511 if (!candidate.animationUri.empty() && !candidate.duration.isZero()) {
512 candidate.animationSections.push_back({*LogicalId::fromParts("animation-section", "legacy"),
513 candidate.animationUri, Duration::zero(), candidate.duration,
514 Duration::zero()});
515 }
516 } else {
517 const Value* sectionsValue = field(value, "animationSections");
518 if (!sectionsValue || !sectionsValue->isArray())
520 DiagnosticCode::InvalidArgument, "expected animationSections array", "animationSections"));
521 const auto& sections = *sectionsValue->getIf<Value::Array>();
522 for (std::size_t index = 0; index < sections.size(); ++index) {
523 auto decoded = decodeAnimationSection(sections[index], "animationSections[" + std::to_string(index) + "]",
524 version.value());
525 if (!decoded) return Result<ActionTimeline>::failure(decoded.status());
526 candidate.animationSections.push_back(std::move(decoded).takeValue());
527 }
528 if (!candidate.animationSections.empty())
529 candidate.animationUri = candidate.animationSections.front().animationUri;
530 if (version.value() >= 3) {
531 const Value* splitsValue = field(value, "splitTimestampsNs");
532 if (!splitsValue || !splitsValue->isArray())
534 DiagnosticCode::InvalidArgument, "expected splitTimestampsNs array", "splitTimestampsNs"));
535 const auto& splits = *splitsValue->getIf<Value::Array>();
536 for (std::size_t index = 0; index < splits.size(); ++index) {
537 if (!splits[index].isInt64())
539 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected physical section timestamp",
540 "splitTimestampsNs[" + std::to_string(index) + "]"));
541 candidate.splitTimestamps.push_back(Duration::fromNanoseconds(splits[index].asInt()));
542 }
543 const Value* montageValue = field(value, "montage");
544 if (!montageValue || !montageValue->isObject())
546 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected montage settings object", "montage"));
547 const Value* basePlayRate = field(*montageValue, "basePlayRate");
548 auto looping = boolField(*montageValue, "looping", "montage.looping");
549 auto footIk = boolField(*montageValue, "footIk", "montage.footIk");
550 auto layer = intField(*montageValue, "animationLayer", "montage.animationLayer");
551 auto blendIn = intField(*montageValue, "defaultBlendInNs", "montage.defaultBlendInNs");
552 auto blendOut = intField(*montageValue, "defaultBlendOutNs", "montage.defaultBlendOutNs");
553 auto blendOutOffset = intField(*montageValue, "blendOutOffsetNs", "montage.blendOutOffsetNs");
554 auto rootHorizontal = boolField(*montageValue, "rootMotionHorizontal", "montage.rootMotionHorizontal");
555 auto rootVertical = boolField(*montageValue, "rootMotionVertical", "montage.rootMotionVertical");
556 auto rootRotation = boolField(*montageValue, "rootMotionRotation", "montage.rootMotionRotation");
557 if (!basePlayRate || (!basePlayRate->isDouble() && !basePlayRate->isInt64()) || !looping || !footIk ||
558 !layer || !blendIn || !blendOut || !blendOutOffset || !rootHorizontal || !rootVertical ||
559 !rootRotation || layer.value() < 0)
561 Diagnostic::error(DiagnosticCode::InvalidArgument, "montage settings are invalid", "montage"));
562 candidate.montage.basePlayRate =
563 basePlayRate->isDouble() ? basePlayRate->asDouble() : static_cast<double>(basePlayRate->asInt());
564 candidate.montage.looping = looping.value();
565 candidate.montage.footIk = footIk.value();
566 candidate.montage.animationLayer = static_cast<std::uint32_t>(layer.value());
567 candidate.montage.defaultBlendIn = Duration::fromNanoseconds(blendIn.value());
568 candidate.montage.defaultBlendOut = Duration::fromNanoseconds(blendOut.value());
569 candidate.montage.blendOutOffset = Duration::fromNanoseconds(blendOutOffset.value());
570 candidate.montage.rootMotionHorizontal = rootHorizontal.value();
571 candidate.montage.rootMotionVertical = rootVertical.value();
572 candidate.montage.rootMotionRotation = rootRotation.value();
573 if (version.value() == 4) {
574 for (auto& section : candidate.animationSections)
575 section.blendOut = candidate.montage.defaultBlendOut;
576 }
577 }
578 }
579 const auto& tracks = *tracksValue->getIf<Value::Array>();
580 for (std::size_t trackIndex = 0; trackIndex < tracks.size(); ++trackIndex) {
581 const Value& trackValue = tracks[trackIndex];
582 const std::string path = "tracks[" + std::to_string(trackIndex) + "]";
583 if (!trackValue.isObject())
585 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected track object", path));
586 auto id = logicalIdField(trackValue, "id", path + ".id");
587 auto label = stringField(trackValue, "label", path + ".label");
588 auto kindText = stringField(trackValue, "kind", path + ".kind");
589 auto muted = boolField(trackValue, "muted", path + ".muted");
590 auto locked = boolField(trackValue, "locked", path + ".locked");
591 if (!id) return Result<ActionTimeline>::failure(id.status());
592 if (!label) return Result<ActionTimeline>::failure(label.status());
593 if (!kindText) return Result<ActionTimeline>::failure(kindText.status());
594 if (!muted) return Result<ActionTimeline>::failure(muted.status());
595 if (!locked) return Result<ActionTimeline>::failure(locked.status());
596 auto kind = parseActionTrackKind(kindText.value());
597 if (!kind) return Result<ActionTimeline>::failure(kind.status());
598 const Value* notifies = field(trackValue, "notifies");
599 const Value* states = field(trackValue, "states");
600 if (!notifies || !notifies->isArray())
602 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected notifies array", path + ".notifies"));
603 if (!states || !states->isArray())
605 Diagnostic::error(DiagnosticCode::InvalidArgument, "expected states array", path + ".states"));
606 ActionTrack track;
607 track.id = std::move(id).takeValue();
608 track.label = std::move(label).takeValue();
609 track.kind = std::move(kind).takeValue();
610 track.muted = muted.value();
611 track.locked = locked.value();
612 const auto& notifyValues = *notifies->getIf<Value::Array>();
613 for (std::size_t index = 0; index < notifyValues.size(); ++index) {
614 auto decoded = decodeNotify(notifyValues[index], path + ".notifies[" + std::to_string(index) + "]",
615 version.value());
616 if (!decoded) return Result<ActionTimeline>::failure(decoded.status());
617 track.notifies.push_back(std::move(decoded).takeValue());
618 }
619 const auto& stateValues = *states->getIf<Value::Array>();
620 for (std::size_t index = 0; index < stateValues.size(); ++index) {
621 auto decoded = decodeState(stateValues[index], path + ".states[" + std::to_string(index) + "]",
622 version.value());
623 if (!decoded) return Result<ActionTimeline>::failure(decoded.status());
624 track.states.push_back(std::move(decoded).takeValue());
625 }
626 candidate.tracks.push_back(std::move(track));
627 }
628 auto valid = candidate.validate();
629 if (!valid) return Result<ActionTimeline>::failure(valid.status());
630 return Result<ActionTimeline>::success(std::move(candidate));
631}
632
633Result<std::pair<Duration, Duration>> ActionTimeline::sectionRange(std::size_t index) const {
634 if (index >= sectionCount())
636 DiagnosticCode::InvalidArgument, "physical section index is outside the timeline", "index"));
637 const Duration start = index == 0 ? Duration::zero() : splitTimestamps[index - 1];
638 const Duration end = index < splitTimestamps.size() ? splitTimestamps[index] : duration;
640}
641
642} // namespace eve::action
Value::Object payload
bool locked
Duration start
Versioned, deterministic authoring timeline for gameplay actions.
float duration
int root
Definition AnimSmr.cpp:119
std::string name
Definition ECS.cpp:154
std::string message
wgpu::PopErrorScopeStatus status
HexVec3 left
HexVec3 right
float blend
std::vector< Track > tracks
std::string label
bool valid
std::shared_ptr< const OceanSprayFrame > previous
TileLayer * layer
std::string path
Definition PlayHost.cpp:111
std::string uri
Object::Ptr value
float t
std::string text
ScriptStructure out
size_t end
std::string kind
double current
Heightmap curve
Json object
float(ui::Theme::* member)[4]
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
constexpr bool isZero() const noexcept
Whether this duration is exactly zero.
Definition Time.h:75
static std::optional< LogicalId > fromParts(std::string_view namespaceName, std::string_view name)
Builds a logical ID from separate namespace and name components.
Definition Identity.cpp:49
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
bool isValid() const noexcept
Returns whether this value contains a valid namespace and name.
Definition Identity.h:436
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
bool isInt64() const noexcept
Return true when this value is an Int64.
Definition Value.h:102
std::map< std::string, Value > Object
Definition Value.h:34
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
double asDouble() const
Return the Double payload; the caller must have checked the kind.
Definition Value.cpp:195
std::int64_t asInt() const
Return the Int64 payload; the caller must have checked the kind.
Definition Value.cpp:189
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
bool isObject() const noexcept
Return true when this value is an object.
Definition Value.h:110
bool isDouble() const noexcept
Return true when this value is a Double.
Definition Value.h:104
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
std::string_view actionTrackKindName(ActionTrackKind kind) noexcept
Stable lowercase protocol spelling for a track kind.
std::optional< ActionBlendCurve > actionBlendCurveFromName(std::string_view name) noexcept
Parse a persisted montage cross-fade curve name.
constexpr std::uint64_t kActionTimelineSchemaVersion
Current action timeline schema version.
constexpr std::string_view kActionTimelineSchemaId
Canonical schema identifier for persisted action timelines.
Result< ActionTrackKind > parseActionTrackKind(std::string_view text)
Parse a stable track kind spelling.
std::string_view actionBlendCurveName(ActionBlendCurve curve) noexcept
Stable persisted name for a montage cross-fade curve.
ActionTrackKind
Semantic lane kind; hosts choose presentation without changing data.
ActionBlendCurve
Built-in deterministic cross-fade curve evaluated without asset callbacks.
double evaluateActionBlendCurve(ActionBlendCurve curve, double normalized) noexcept
Evaluate a deterministic built-in blend curve for a normalized input.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Status invalid(const char *message)
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
bool enabled
Canonical action timeline asset shared by runtime and editor.
ActionMontageSettings montage
Result< std::vector< ActionTimelineEvent > > sample(Duration previous, Duration current, bool includePrevious=false) const
Sample all boundaries in (previous,current] in stable order.
Result< void > validate() const
Validate ids, ranges, uniqueness and deterministic ordering.
std::vector< ActionAnimationSection > animationSections
std::string animationUri
Compatibility-only single-clip projection; v2 runtime uses animationSections.
std::vector< ActionTrack > tracks
std::vector< Duration > splitTimestamps
Sorted objective split timestamps forming N+1 physical sections.
Ordered semantic lane in one action timeline.
std::vector< ActionNotifyState > states
std::vector< ActionNotify > notifies