载入中...
搜索中...
未找到
TacticsPersistence.cpp
浏览该文件的文档.
37 return Value(Value::Object{{"layer", Value(cell.layer)}, {"x", Value(cell.x)}, {"y", Value(cell.y)}});
40Value subjectValue(SubjectRef subject) { return Value(subject.isValid() ? subject.format() : std::string{}); }
54 Diagnostic::error(DiagnosticCode::ParseError, "missing required field", path + "." + std::string(name)));
124 for (const auto& [name, target] : {std::pair{"x", &result.x}, {"y", &result.y}, {"layer", &result.layer}}) {
132 Diagnostic::error(DiagnosticCode::ParseError, "cell coordinate is out of range", path + "." + name));
144 ecs::EntityHandle side{};
145 LogicalId definition;
199 for (const auto& candidate : window.candidates) candidates.push_back(candidateValue(candidate));
207 for (const auto& candidate : command.candidates) candidates.push_back(candidateValue(candidate));
246 streams.emplace(name, Value(Value::Object{{"rollIndex", Value(std::to_string(state.rollIndex))},
263 {"definition", Value(unit.identity()->definition.isValid() ? unit.identity()->definition.format()
278Result<int> intField(const Value::Object& value, std::string_view name, const std::string& path) {
286 Diagnostic::error(DiagnosticCode::ParseError, "integer is out of range", path + "." + std::string(name)));
325 from.value() < 0 || from.value() > static_cast<int>(BattlePhase::BattleEnd) || to.value() < 0 ||
335 if (!everyResultValid(sequence, tick, subjectRef, causation, correlation) || !type || type->empty() ||
352 Diagnostic::error(DiagnosticCode::ParseError, "invalid reactions object", "payload.reactions"));
358 Diagnostic::error(DiagnosticCode::ParseError, "incomplete reactions object", "payload.reactions"));
362 if (!maxDepth || maxDepth.value() == 0 || maxDepth.value() > static_cast<std::uint64_t>(SIZE_MAX) || !seen ||
393 if (!everyResultValid(trigger, depth) || trigger.value() == 0 || depth.value() != i + 1 || !candidates ||
428 DiagnosticCode::InvariantViolation, "reaction phase and stack disagree", "payload.reactions.stack"));
461Result<Battle::Commands> parseCommands(const Value& value, Revision snapshotRevision, CommandFieldPolicy policy) {
470 Diagnostic::error(DiagnosticCode::ParseError, "incomplete commands object", "payload.commands"));
506 const int highestKnownKind = policy.allowUseAbility ? static_cast<int>(BattleCommandKind::UseAbility)
543 if (!everyResultValid(sequence, expected, resulting, tick, delta, trigger, actor, cell) || !actionText ||
545 sequence.value() >= result.nextSequence || expected.value() == std::numeric_limits<std::uint64_t>::max() ||
573 DiagnosticCode::ParseError, "command payload exceeds the persisted size bound", path + ".payload"));
600 Diagnostic::error(DiagnosticCode::ParseError, "invalid command candidate identity", candidatePath));
607 case BattleCommandKind::Advance: return command.step.tick.isZero() || command.step.delta.nanoseconds() < 0;
635 DiagnosticCode::Conflict, "command log revision differs from snapshot revision", "payload.commands"));
642 DiagnosticCode::Conflict, "replay log does not start at the target revision", "payload.commands"));
646Result<Battle::Objectives> parseObjectives(Battle& battle, const BoardState& board, const Value& value,
651 Diagnostic::error(DiagnosticCode::ParseError, "objectives must be an array", "payload.objectives"));
677 if (!everyResultValid(idMember, beneficiaryMember, targetMember, roundMember, cellsMember, endsMember,
691 !ids.insert(id.value().format()).second || !sideSubjects.contains(beneficiary.value().format()) ||
714 (objective.spec.kind == ObjectiveKind::EliminateSide && !objective.spec.targetSide.isValid()) ||
720 if (std::adjacent_find(objective.spec.requiredCells.begin(), objective.spec.requiredCells.end()) !=
733 Diagnostic::error(DiagnosticCode::ParseError, "random streams must be an object", "payload.random"));
742 Diagnostic::error(DiagnosticCode::ParseError, "invalid random stream state", "payload.random." + name));
753 result.streams.emplace(name, Battle::RandomStreamState{parsedState.value(), parsedIndex.value()});
758Result<Candidate> parseCandidate(Battle& battle, const Value& payload, Revision snapshotRevision,
762 static const std::set<std::string> fields = {"activeUnit", "board", "commands", "cursor", "events",
782 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::ParseError, "invalid battle enum", {}));
783 if (status.value() < 0 || status.value() > static_cast<int>(BattleStatus::Ended) || phase.value() < 0 ||
786 Diagnostic::error(DiagnosticCode::UnknownVersion, "snapshot contains an unknown battle enum", {}));
792 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::ParseError, "invalid battle enum", {}));
801 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::ParseError, "invalid battle enum", {}));
809 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::ParseError, "missing turn state", {}));
813 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::ParseError, "invalid turn counters", {}));
837 Diagnostic::error(DiagnosticCode::ParseError, "invalid board topology", "payload.board.topology"));
841 Diagnostic::error(DiagnosticCode::ParseError, "board cells must be an array", "payload.board.cells"));
882 Diagnostic::error(DiagnosticCode::ParseError, "board edges must be an array", "payload.board.edges"));
996 Diagnostic::error(DiagnosticCode::ParseError, "invalid unit definition", path + ".definition"));
1016 Diagnostic::error(DiagnosticCode::InvariantViolation, "unit charge is negative", path + ".charge"));
1032 DiagnosticCode::InvariantViolation, "v1 tactics units must be placed exactly while alive", path));
1043 Diagnostic::error(DiagnosticCode::InvariantViolation, "unit facing is invalid", path + ".facing"));
1045 {found->second, restoredSide->second->identity()->self, definition, cell.value(), facing.value(),
1055 return Result<Candidate>::failure(Diagnostic::error(DiagnosticCode::Conflict, "active unit is absent", {}));
1061 Diagnostic::error(DiagnosticCode::InvariantViolation, "turn cursor is outside unit schedule", {}));
1071 Diagnostic::error(DiagnosticCode::ParseError, "round schedule must be an array", "payload.schedule"));
1086 const bool activationPhase = result.phase == BattlePhase::TurnStart || result.phase == BattlePhase::Acting ||
1090 DiagnosticCode::InvariantViolation, "turn cursor is outside the round schedule", "payload.cursor"));
1099 if (!everyResultValid(eventsMember, reactionsMember, commandsMember, objectivesMember, randomMember))
1101 Diagnostic::error(DiagnosticCode::ParseError, "snapshot is missing deterministic streams", {}));
1109 auto objectives = parseObjectives(battle, result.board, *objectivesMember.value(), snapshotRevision);
1134 if (command.kind == BattleCommandKind::RollRandom) ++randomCommandCounts[command.action.format()];
1139 DiagnosticCode::InvariantViolation, "random stream roll index differs from accepted command log",
1158 Diagnostic::error(DiagnosticCode::Conflict, "reaction candidate is absent from the target battle",
1178TacticsPersistence::PreparedRestore::PreparedRestore(std::unique_ptr<Impl> state) : state_(std::move(state)) {}
1181TacticsPersistence::PreparedRestore& TacticsPersistence::PreparedRestore::operator=(PreparedRestore&&) noexcept =
1184Result<SnapshotEnvelope> TacticsPersistence::snapshot(Battle& battle, const SnapshotHashProvider& hashProvider) {
1234 for (const auto& window : battle.reactions()->stack) reactionStack.push_back(windowValue(window));
1238 for (const auto& command : battle.commands()->values) commands.push_back(commandValue(command));
1240 for (const auto& objective : battle.objectives()->values) objectives.push_back(objectiveValue(objective));
1257 {"commands", Value(Value::Object{{"nextSequence", Value(std::to_string(battle.commands()->nextSequence))},
1259 {"events", Value(Value::Object{{"nextSequence", Value(std::to_string(battle.events()->nextSequence))},
1276 const auto version = battle.board()->value.topology() == BoardTopology::ExplicitGraph ? 7u : 6u;
1296Result<Battle::Commands> TacticsPersistence::parseCommandLog(const Value& value, Revision snapshotRevision) {
1318 Diagnostic::error(DiagnosticCode::InvalidArgument, "snapshot does not belong to tactics battle", {}));
1321 Diagnostic::error(DiagnosticCode::Conflict, "snapshot battle identity differs from target", {}));
1334 Diagnostic::error(DiagnosticCode::UnknownVersion, "unsupported tactics battle snapshot version", {}));
1337 auto candidate = parseCandidate(battle, source.payload, source.revision, source.schemaVersion);
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
std::vector< ecs::EntityHandle > schedule
The round's activation queue, resolved against the target battle.
Definition TacticsPersistence.cpp:170
bool abilityTargetFields
v6+: commands carry targetUnit and payload.
Definition TacticsPersistence.cpp:457
bool policyIdStrings
v3+: stable policy id string instead of the legacy numeric enum.
Definition TacticsPersistence.cpp:455
Versioned battle snapshots with transactional restore.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.cpp:21
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Definition StrongUint64.h:26
Battle short-root and authoritative owner of board and turn state.
Definition TacticsTypes.h:444
bool contains(Cell cell) const noexcept
Return whether the logical cell exists.
Definition TacticsTypes.cpp:23
Fully validated battle candidate awaiting a no-fail publication.
Definition TacticsPersistence.h:27
~PreparedRestore()
PreparedRestore(PreparedRestore &&) noexcept
Stateless codec for the authoritative state of one battle.
Definition TacticsPersistence.h:24
static Result< Battle::Commands > parseCommandLog(const Value &value, Revision snapshotRevision)
Parse a command log written by commandLogValue.
Definition TacticsPersistence.cpp:1296
static Result< void > restore(Battle &battle, const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Restore a verified compatible snapshot without partial mutation on failure.
Definition TacticsPersistence.cpp:1306
static Result< PreparedRestore > prepareRestore(Battle &battle, const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Verify and resolve a battle snapshot without changing live state. @thread Owning simulation thread; b...
Definition TacticsPersistence.cpp:1314
static void commitPrepared(PreparedRestore prepared) noexcept
Publish a previously prepared battle state without further fallible work.
Definition TacticsPersistence.cpp:1345
static Result< Value > commandLogValue(Battle &battle, Revision fromRevision)
Serialize the accepted command log after fromRevision in its persisted shape.
Definition TacticsPersistence.cpp:1282
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
Definition BuildingSnapshot.cpp:96
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
std::int32_t moveCost(const HexMap &map, HexCoordinates from, HexCoordinates to, HexDirection direction, const HexOccupancyQuery &occupied)
Cost of moving between two adjacent cells.
Definition HexSearch.cpp:131
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Definition Interaction.cpp:13
constexpr std::string_view kInitiativePolicyId
Stable id of the built-in per-unit initiative turn policy.
Definition TacticsTypes.h:66
@ Completed
constexpr std::string_view kSideAlternatingPolicyId
Stable id of the built-in side-alternating turn policy.
Definition TacticsTypes.h:64
BattleCommandKind
Accepted deterministic command kinds recorded for replay.
Definition TacticsTypes.h:356
@ RollRandom
@ AcceptReaction
@ DeclineReaction
@ OpenReaction
@ UseAbility
Declare a unit ability activation against a target cell.
@ DefeatUnit
@ OccupyCells
@ SurviveRounds
@ EliminateSide
@ Reaction
@ TurnStart
@ TurnEnd
@ BattleEnd
constexpr std::size_t kMaxAbilityPayloadBytes
Upper bound on the opaque ability payload a declaration may carry.
Definition TacticsTypes.h:353
@ Square4
@ Square8
@ ExplicitGraph
WidgetDesc window(std::string title, std::vector< WidgetDesc > children, std::string id)
Top-level window widget with a title bar.
Definition Widget.cpp:326
@ InvalidArgument
@ UnknownVersion
@ InvariantViolation
@ ParseError
@ StaleHandle
@ Conflict
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
@ Applied
@ Object
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Definition SchemaVersion.h:13
bool everyResultValid(const Results &... results) noexcept
True only when every argument Result succeeded, observing all of them.
Definition Result.h:618
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
detail::StrongUint64< detail::RevisionTag > Revision
Monotonic content/state revision used for optimistic-concurrency checks.
Definition Revision.h:13
Result< void > verifySnapshotEnvelope(const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Verify an envelope's content hash without modifying it.
Definition Snapshot.cpp:63
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Definition Container.h:602
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
One accepted replay command using only persistent identities and values.
Definition TacticsTypes.h:386
int roundReactionPoints
Definition TacticsTypes.h:290
int roundMovePoints
Definition TacticsTypes.h:289
int actionPoints
Definition TacticsTypes.h:285
int roundActionPoints
Definition TacticsTypes.h:288
int reactionPoints
Definition TacticsTypes.h:287
Revision revision
Definition TacticsPersistence.cpp:1171
SimulationTick tick
Definition TacticsPersistence.cpp:1172
Impl(Battle &target, Candidate &&state, Revision savedRevision, SimulationTick savedTick)
Definition TacticsPersistence.cpp:1174
Battle * battle
Definition TacticsPersistence.cpp:1169
Candidate candidate
Definition TacticsPersistence.cpp:1170