载入中...
搜索中...
未找到
ContainerAdapters.cpp
浏览该文件的文档.
2#include "common/Json.h"
3
5
6#include <algorithm>
7#include <exception>
8#include <limits>
9#include <string_view>
10#include <unordered_set>
11#include <utility>
12#include <vector>
13
14namespace eve::building {
15namespace {
16
17[[nodiscard]] std::string quote(std::string_view value) {
18 return eve::json::quoteString(value, eve::json::StringEscapeStyle::UnicodeBackspaceFormFeed);
19}
20
21[[nodiscard]] const GarrisonMember* payloadMember(const eve::container::ContainerObject& object,
22 GarrisonMember& fallback) {
23 const auto* payload = dynamic_cast<const BuildingGarrisonContainerObject*>(object.payload.get());
24 if (payload != nullptr) {
25 if (payload->member.id != object.id.value() || payload->member.type != object.type ||
26 payload->member.tags != object.tags)
27 return nullptr;
28 return &payload->member;
29 }
30 if (!object.id.isValid() || object.type.empty()) return nullptr;
31 fallback.id = object.id.value();
32 fallback.type = object.type;
33 fallback.tags = object.tags;
34 return &fallback;
35}
36
37[[nodiscard]] bool sameLayout(const eve::container::ContainerSnapshot& lhs,
39 if (lhs.id != rhs.id || lhs.revision != rhs.revision || lhs.entries.size() != rhs.entries.size()) return false;
40 for (const auto& left : lhs.entries) {
41 const auto right = std::find_if(rhs.entries.begin(), rhs.entries.end(), [&](const auto& entry) {
42 return entry.membership.object == left.membership.object;
43 });
44 if (right == rhs.entries.end() || left.membership.slot != right->membership.slot ||
45 left.membership.generation != right->membership.generation || left.object.id != right->object.id ||
46 left.object.type != right->object.type || left.object.quantity != right->object.quantity ||
47 left.object.tags != right->object.tags)
48 return false;
49 }
50 return true;
51}
52
53[[nodiscard]] game_event::GameEvent makeEvent(const eve::container::ContainerId& container,
54 const eve::container::MembershipId& object,
57 std::string_view reason = {}) {
59 if (!schema) std::terminate();
60
61 game_event::GameEvent event;
62 event.eventId = eve::container::deterministicContainerEventId(container, object, kind, serial);
64 event.source = container.value();
65 event.subject = object.value();
66 event.schemaId = *schema;
67 event.schemaVersion = eve::SchemaVersion(1);
68 event.tick = tick;
69 event.payload = "{\"containerId\":" + quote(container.value()) + ",\"objectId\":" + quote(object.value()) +
70 ",\"slot\":" + std::to_string(slot.isValid() ? slot.value() : -1) + ",\"revision\":\"" +
71 std::to_string(revision.value()) + "\"";
72 if (!reason.empty()) event.payload += ",\"reason\":" + quote(reason);
73 event.payload += '}';
74 return event;
75}
76
77void notify(const eve::container::GameEventSink& sink, const eve::container::ContainerId& container,
80 std::string_view reason, bool& callbackFailed) noexcept {
81 if (!sink) return;
82 try {
83 const auto event = makeEvent(container, object, kind, slot, revision, serial, tick, reason);
84 sink(event);
85 } catch (...) {
86 callbackFailed = true;
87 }
88}
89
90[[nodiscard]] eve::Status appliedStatus(bool callbackFailed) {
91 if (!callbackFailed) return eve::Status::success(eve::StatusCode::Applied);
92 try {
93 std::vector<eve::Diagnostic> diagnostics;
94 diagnostics.emplace_back(eve::Diagnostic::warning(
95 eve::DiagnosticCode::CallbackFailure, "container membership committed but an event observer threw"));
96 return eve::Status(eve::StatusCode::Applied, std::move(diagnostics));
97 } catch (...) {
99 }
100}
101
102} // namespace
103
105public:
106 PreparedState(BuildingGarrisonContainerAdapter& owner, std::vector<GarrisonMember> staged,
107 eve::Revision expectedRevision, std::size_t expectedSize, eve::Revision revision)
108 : owner_(owner),
109 staged_(std::move(staged)),
110 expectedRevision_(expectedRevision),
111 expectedSize_(expectedSize),
112 revision_(revision) {}
113
114 void commit() noexcept override {
115 if (committed_) return;
116 auto* building = owner_.building();
117 if (building == nullptr || building->garrisonRevision != expectedRevision_ ||
118 building->garrison.size() != expectedSize_)
119 std::terminate();
120 building->garrison.swap(staged_);
121 building->garrisonRevision = revision_;
122 committed_ = true;
123 }
124
125 void rollback() noexcept override {
126 if (!committed_) staged_.clear();
127 }
128
129private:
131 std::vector<GarrisonMember> staged_;
132 eve::Revision expectedRevision_;
133 std::size_t expectedSize_ = 0;
134 eve::Revision revision_;
135 bool committed_ = false;
136};
137
139 PlacementWorld* world, int instanceId,
142 : descriptor_{std::move(id), capacity, eve::container::Ordering::Insertion, std::move(accepted)},
143 world_(world),
144 instanceId_(instanceId) {}
145
146const PlacedBuilding* BuildingGarrisonContainerAdapter::building() const noexcept {
147 if (world_ == nullptr || instanceId_ <= 0) return nullptr;
148 const auto& values = world_->buildings();
149 const auto it = values.find(instanceId_);
150 return it == values.end() ? nullptr : &it->second;
151}
152
153PlacedBuilding* BuildingGarrisonContainerAdapter::building() noexcept {
154 if (world_ == nullptr || instanceId_ <= 0) return nullptr;
155 auto& values = world_->buildings();
156 const auto it = values.find(instanceId_);
157 return it == values.end() ? nullptr : &it->second;
158}
159
161 const auto* value = building();
162 return value == nullptr ? eve::Revision::zero() : value->garrisonRevision;
163}
164
165std::uint64_t BuildingGarrisonContainerAdapter::nextEventSerial() noexcept {
166 if (eventSerial_ != std::numeric_limits<std::uint64_t>::max()) ++eventSerial_;
167 return eventSerial_;
168}
169
170eve::container::ContainerObject BuildingGarrisonContainerAdapter::describe(const GarrisonMember& member) {
173 object.type = member.type;
174 object.tags = member.tags;
175 object.quantity = 1;
176 auto payload = std::make_shared<BuildingGarrisonContainerObject>();
177 payload->member = member;
178 object.payload = std::move(payload);
179 return object;
180}
181
183 const auto* value = building();
184 if (!descriptor_.id.isValid() || value == nullptr)
186 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "building garrison adapter is stale or unbound"));
187 if (!descriptor_.capacity.isUnlimited() && value->garrison.size() > descriptor_.capacity.value())
189 eve::DiagnosticCode::InvariantViolation, "building garrison exceeds configured capacity"));
190 eve::container::ContainerSnapshot result{descriptor_.id, value->garrisonRevision, {}};
191 result.entries.reserve(value->garrison.size());
192 std::unordered_set<eve::container::MembershipId> identities;
193 for (std::size_t index = 0; index < value->garrison.size(); ++index) {
194 if (index > static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max()))
196 eve::DiagnosticCode::InvariantViolation, "building garrison has too many indexed memberships"));
197 const auto& member = value->garrison[index];
198 if (!eve::container::MembershipId::from(member.id) || member.type.empty() ||
201 eve::DiagnosticCode::Conflict, "building garrison contains invalid or duplicate member"));
202 const auto id = eve::container::MembershipId(member.id);
203 result.entries.push_back(
204 {{id, eve::container::SlotIndex(static_cast<std::int32_t>(index)), eve::Generation(1)}, describe(member)});
205 }
207}
208
210 const eve::container::ContainerObject& object, std::optional<eve::container::SlotIndex> destination,
211 std::optional<eve::container::MembershipId> ignoredObject) const {
212 const auto* value = building();
213 if (!descriptor_.id.isValid() || value == nullptr)
215 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "building garrison adapter is stale or unbound"));
216 if (!object.id.isValid() || object.type.empty() || object.quantity != 1u)
218 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "building garrison object facts are invalid"));
219 GarrisonMember fallback;
220 if (payloadMember(object, fallback) == nullptr)
222 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "building garrison payload is stale"));
223 for (const auto& member : value->garrison) {
224 if (member.id == object.id.value() && (!ignoredObject || *ignoredObject != object.id))
226 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "building garrison already contains member"));
227 }
228 const std::size_t effectiveSize =
229 value->garrison.size() -
230 ((ignoredObject && std::any_of(value->garrison.begin(), value->garrison.end(),
231 [&](const auto& member) { return member.id == ignoredObject->value(); }))
232 ? 1u
233 : 0u);
234 if (destination && (!destination->isValid() || static_cast<std::size_t>(destination->value()) > effectiveSize))
236 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "building garrison slot is out of range"));
237 auto accepted = descriptor_.filter.evaluate(object);
238 if (!accepted) return accepted;
239 if (!descriptor_.capacity.isUnlimited() && effectiveSize >= descriptor_.capacity.value())
241 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "building garrison capacity is full"));
243}
244
247 const auto* value = building();
248 if (!descriptor_.id.isValid() || value == nullptr)
250 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "building garrison adapter is stale or unbound"));
251 if (expected.id != descriptor_.id || candidate.id != descriptor_.id)
253 eve::DiagnosticCode::InvalidArgument, "building garrison prepare targets another container"));
254 auto current = snapshot();
255 if (!current)
257 if (!sameLayout(current.value(), expected))
259 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "building garrison expected snapshot is stale"));
260 const auto next = expected.revision.incremented();
261 if (!next || candidate.revision != *next)
263 eve::DiagnosticCode::InvariantViolation, "building garrison candidate revision is not the next revision"));
264 if (!descriptor_.capacity.isUnlimited() && candidate.entries.size() > descriptor_.capacity.value())
266 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "building garrison candidate exceeds capacity"));
267
268 std::vector<GarrisonMember> staged;
269 staged.reserve(candidate.entries.size());
270 std::unordered_set<eve::container::MembershipId> identities;
271 for (std::size_t index = 0; index < candidate.entries.size(); ++index) {
272 const auto& entry = candidate.entries[index];
273 if (!entry.membership.object.isValid() || !entry.membership.slot.isValid() ||
274 entry.membership.slot.value() != static_cast<std::int32_t>(index) || entry.membership.generation.isZero() ||
275 entry.object.id != entry.membership.object || entry.object.quantity != 1u ||
276 !identities.insert(entry.membership.object).second)
279 "building garrison candidate contains invalid membership"));
280 GarrisonMember fallback;
281 const auto* member = payloadMember(entry.object, fallback);
282 if (member == nullptr)
285 "building garrison candidate payload is stale"));
286 staged.push_back(*member);
287 }
288 std::unique_ptr<eve::container::IContainer::PreparedState> prepared =
289 std::make_unique<PreparedState>(*this, std::move(staged), expected.revision, expected.entries.size(), *next);
291}
292
294 std::string type,
295 std::vector<std::string> tags,
298 const auto serial = nextEventSerial();
299 const eve::container::MembershipId objectId(std::move(memberId));
300 auto current = snapshot();
301 if (!current) {
302 const auto status = current.status();
303 bool ignored = false;
304 const auto* diagnostic = status.primaryDiagnostic();
305 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Rejected,
307 diagnostic == nullptr ? "stale_container" : diagnostic->message(), ignored);
309 }
311 object.id = objectId;
312 object.type = type.empty() ? "building.garrison.member" : std::move(type);
313 object.tags = std::move(tags);
314 object.quantity = 1;
315 auto accepted = validateInsert(object, std::nullopt, std::nullopt);
316 if (!accepted) {
317 const auto status = accepted.status();
318 bool ignored = false;
319 const auto* diagnostic = status.primaryDiagnostic();
320 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Rejected,
322 diagnostic == nullptr ? "rejected" : diagnostic->message(), ignored);
324 }
325 auto candidate = current.value();
326 const auto next = candidate.revision.incremented();
327 if (!next) {
328 const auto status = eve::Status::failure(
329 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "building garrison revision exhausted"));
330 bool ignored = false;
331 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Rejected,
332 eve::container::SlotIndex::invalid(), candidate.revision, serial, tick, "revision_exhausted", ignored);
334 }
335 candidate.revision = *next;
336 candidate.entries.push_back(
337 {{objectId, eve::container::SlotIndex(static_cast<std::int32_t>(current.value().entries.size())),
338 eve::Generation(1)},
339 std::move(object)});
340 auto prepared = prepare(current.value(), candidate);
341 if (!prepared) {
342 const auto status = prepared.status();
343 bool ignored = false;
344 const auto* diagnostic = status.primaryDiagnostic();
345 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Rejected,
347 diagnostic == nullptr ? "prepare_failed" : diagnostic->message(), ignored);
349 }
350 auto staged = std::move(prepared).takeValue();
351 staged->commit();
352 bool callbackFailed = false;
353 const auto slot = candidate.entries.back().membership.slot;
354 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Accepted, slot, *next, serial, tick, {},
355 callbackFailed);
356 notify(sink, descriptor_.id, objectId, eve::container::ContainerEventKind::Enter, slot, *next, serial, tick, {},
357 callbackFailed);
358 return eve::Result<eve::container::MembershipId>::success(objectId, appliedStatus(callbackFailed));
359}
360
364 const auto serial = nextEventSerial();
365 auto current = snapshot();
367 if (current) {
368 for (const auto& entry : current.value().entries) {
369 if (entry.membership.object == memberId) {
370 slot = entry.membership.slot;
371 break;
372 }
373 }
374 }
375 if (!current || !slot.isValid()) {
377 eve::DiagnosticCode::NotFound, "building garrison member was not found"))
378 : current.status();
379 bool ignored = false;
380 const auto* diagnostic = status.primaryDiagnostic();
381 notify(sink, descriptor_.id, memberId, eve::container::ContainerEventKind::Rejected, slot, revision(), serial,
382 tick, diagnostic == nullptr ? "rejected" : diagnostic->message(), ignored);
384 }
385 auto candidate = current.value();
386 candidate.entries.erase(std::remove_if(candidate.entries.begin(), candidate.entries.end(),
387 [&](const auto& entry) { return entry.membership.object == memberId; }),
388 candidate.entries.end());
389 for (std::size_t index = 0; index < candidate.entries.size(); ++index)
390 candidate.entries[index].membership.slot = eve::container::SlotIndex(static_cast<std::int32_t>(index));
391 const auto next = candidate.revision.incremented();
392 if (!next) {
393 const auto status = eve::Status::failure(
394 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "building garrison revision exhausted"));
395 bool ignored = false;
396 notify(sink, descriptor_.id, memberId, eve::container::ContainerEventKind::Rejected, slot,
397 current.value().revision, serial, tick, "revision_exhausted", ignored);
399 }
400 candidate.revision = *next;
401 auto prepared = prepare(current.value(), candidate);
402 if (!prepared) {
403 const auto status = prepared.status();
404 bool ignored = false;
405 const auto* diagnostic = status.primaryDiagnostic();
406 notify(sink, descriptor_.id, memberId, eve::container::ContainerEventKind::Rejected, slot,
407 current.value().revision, serial, tick, diagnostic == nullptr ? "prepare_failed" : diagnostic->message(),
408 ignored);
410 }
411 auto staged = std::move(prepared).takeValue();
412 staged->commit();
413 bool callbackFailed = false;
414 notify(sink, descriptor_.id, memberId, eve::container::ContainerEventKind::Accepted, slot, *next, serial, tick, {},
415 callbackFailed);
416 notify(sink, descriptor_.id, memberId, eve::container::ContainerEventKind::Exit, slot, *next, serial, tick, {},
417 callbackFailed);
418 return eve::Result<eve::container::MembershipId>::success(memberId, appliedStatus(callbackFailed));
419}
420
421} // namespace eve::building
Value::Object payload
std::uint64_t revision
std::unordered_map< std::string, QuestRuntime > entries
int instanceId
std::uint32_t capacity
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
HexVec3 left
HexVec3 right
char quote
std::string id
Poco::JSON::Object::Ptr result
std::unordered_set< std::string > tags
std::shared_ptr< OceanGpuSpectrum > owner
uint64_t serial
Definition Plugins.cpp:26
std::set< std::string > values
std::set< std::string > identities
Object::Ptr value
std::string slot
std::string kind
double current
SimulationTick tick
Json object
float(ui::Theme::* member)[4]
uint32_t index
Building adapters for the common Container/Zone/Transfer protocol.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Diagnostic warning(DiagnosticCode code, std::string message, std::string path={})
Construct a warning diagnostic.
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:521
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
const Diagnostic * primaryDiagnostic() const noexcept
First diagnostic, or null when no diagnostic was supplied.
Definition Status.h:141
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
void rollback() noexcept override
Abandon an unpublished stage; the operation is non-throwing.
void commit() noexcept override
Publish the staged state; the operation is non-throwing.
PreparedState(BuildingGarrisonContainerAdapter &owner, std::vector< GarrisonMember > staged, eve::Revision expectedRevision, std::size_t expectedSize, eve::Revision revision)
Transactional adapter over one placed building's authoritative garrison.
eve::Result< eve::container::MembershipId > exit(eve::container::MembershipId memberId, eve::container::GameEventSink sink={}, eve::SimulationTick tick=eve::SimulationTick::zero())
Stage and publish removal of one member.
eve::Result< eve::container::ContainerSnapshot > snapshot() const override
Snapshot.
eve::Revision revision() const noexcept
Return the authoritative garrison revision, or zero when stale.
BuildingGarrisonContainerAdapter(eve::container::ContainerId id, PlacementWorld *world, int instanceId, eve::container::Capacity capacity=eve::container::Capacity::unlimited(), eve::container::AcceptedCondition accepted={})
Binds an adapter to a placed building.
eve::Result< std::unique_ptr< eve::container::IContainer::PreparedState > > prepare(const eve::container::ContainerSnapshot &expected, const eve::container::ContainerSnapshot &candidate) override
Prepare an exact replacement from expected to candidate.
eve::Result< void > validateInsert(const eve::container::ContainerObject &object, std::optional< eve::container::SlotIndex > destination, std::optional< eve::container::MembershipId > ignoredObject=std::nullopt) const override
Validate insert.
eve::Result< eve::container::MembershipId > enter(std::string memberId, std::string type="building.garrison.member", std::vector< std::string > tags={}, eve::container::GameEventSink sink={}, eve::SimulationTick tick=eve::SimulationTick::zero())
Stage and publish a new garrison member.
格子型建筑放置世界(脚本可直接操作)。
const std::unordered_map< int, PlacedBuilding > & buildings() const
Non-negative capacity measured in membership slots.
Definition Container.h:92
constexpr std::size_t value() const noexcept
Definition Container.h:99
constexpr bool isUnlimited() const noexcept
Definition Container.h:98
Strong identity of one runtime or persistent container.
Definition Container.h:44
bool isValid() const noexcept
Return whether this ID is usable by a transfer request.
Definition Container.h:58
const std::string & value() const noexcept
Return the owned stable spelling.
Definition Container.h:60
Extensible filter result used by container and zone acceptance rules.
Definition Container.h:139
Result< void > evaluate(const struct ContainerObject &object) const
Evaluate the filter; an empty filter accepts every object.
Definition Container.h:149
Detached state prepared for an atomic container replacement.
Definition Container.h:296
Strong identity of an object which can have one container membership.
Definition Container.h:68
static std::optional< MembershipId > from(std::string_view value)
Construct a valid membership ID, rejecting an empty value.
Definition Container.h:76
const std::string & value() const noexcept
Return the owned stable spelling.
Definition Container.h:84
Explicit slot number; it never implicitly converts to an integer.
Definition Container.h:117
static constexpr SlotIndex invalid() noexcept
Invalid.
Definition Container.h:124
constexpr std::int32_t value() const noexcept
Value.
Definition Container.h:128
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
建筑放置模块入口:定义 / 放置世界 / 鬼影 / 变更事件的脚本绑定点。 设计文档:docs/dev/建筑放置系统设计.md
Definition Building.cpp:10
constexpr std::string_view containerEventSchemaName
Canonical schema name for container lifecycle envelopes.
Definition Container.h:232
ContainerEventKind
Lifecycle outcome represented by every container-domain event.
Definition Container.h:205
const char * containerEventTypeName(ContainerEventKind kind) noexcept
Stable event type spelling shared by all container adapters.
Definition Container.h:221
std::function< void(const game_event::GameEvent &)> GameEventSink
Callback receiving a canonical game_event envelope.
Definition Container.h:245
EventId deterministicContainerEventId(const ContainerId &container, const MembershipId &object, ContainerEventKind kind, std::uint64_t serial) noexcept
Derives a deterministic event identity for an adapter lifecycle event.
Definition Container.h:257
std::string quoteString(std::string_view value, StringEscapeStyle style)
Encode an owning JSON string using the canonical serializer's escaping implementation.
Definition Json.cpp:576
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
detail::StrongUint64< detail::GenerationTag > Generation
Registry/object replacement generation used to reject stale handles.
Definition Generation.h:13
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
One persistent member of a placed building's logical garrison.
已放置的建筑实例。
Generic object facts used by filters and transfer diagnostics.
Definition Container.h:168
Lossless snapshot of one container at one revision.
Definition Container.h:190
std::vector< MembershipEntry > entries
Definition Container.h:193