载入中...
搜索中...
未找到
ProcgenPrefabSceneSink.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstdio>
5#include <glm/gtc/matrix_transform.hpp>
6#include <glm/gtc/type_ptr.hpp>
7#include <limits>
8#include <map>
9#include <unordered_map>
10#include <unordered_set>
13#include "common/Assert.h"
15
16namespace eve::asset_graphics {
17namespace {
18struct BusyScope {
19 bool& busy;
20 explicit BusyScope(bool& value) : busy(value) { busy = true; }
21 ~BusyScope() { busy = false; }
22};
23std::array<float, 16> instanceMatrix(const ProcgenInstanceDesc& value) {
24 auto matrix = glm::translate(glm::mat4(1.f), glm::vec3(value.x, value.y, value.z));
25 matrix = glm::rotate(matrix, glm::radians(value.yaw), glm::vec3(0.f, 1.f, 0.f));
26 matrix = glm::rotate(matrix, glm::radians(value.pitch), glm::vec3(1.f, 0.f, 0.f));
27 matrix = glm::rotate(matrix, glm::radians(value.roll), glm::vec3(0.f, 0.f, 1.f));
28 matrix = glm::scale(matrix, glm::vec3(value.scaleX, value.scaleY, value.scaleZ));
29 std::array<float, 16> output;
30 std::copy(glm::value_ptr(matrix), glm::value_ptr(matrix) + 16, output.begin());
31 return output;
32}
33} // namespace
37 struct Batch {
38 uint64_t revision = 0;
39 std::vector<ProcgenInstanceDesc> source;
40 std::vector<std::unique_ptr<StaticPrefabRenderInstance>> renderers;
41 std::size_t parts = 0;
42 };
43 using Batches = std::map<std::string, Batch>;
44 struct Version {
45 std::shared_ptr<EvpackStaticPrefab> prefab;
46 std::unique_ptr<StaticPrefabResourcePin> pin;
47 };
48 using VersionKey = std::pair<PersistentId, PersistentId>;
49 std::map<VersionKey, Version> assets;
51 std::vector<Batches::node_type> retired;
52 bool busy = false, closed = false;
53 bool available() const { return !busy && !closed; }
54 Result<void> validateRevision(const std::string& id) const {
55 const auto found = active.find(id);
56 if (found != active.end() && scene.batchRevision(id) != found->second.revision)
58 "Scene changed outside the prefab renderer projection", id));
59 return Result<void>::success();
60 }
61 static void visibility(StaticPrefabRenderInstance& instance, bool visible) {
62 for (std::size_t i = 0; i < instance.rendererCount(); ++i) {
63 auto renderer = instance.renderer(i);
64 if (renderer.ok()) renderer.value()->setVisible(visible);
65 }
66 }
67 static void visibility(Batch& batch, bool visible) {
68 for (auto& instance : batch.renderers) visibility(*instance, visible);
69 }
71 for (const auto& [id, batch] : candidates)
72 for (const auto& instance : batch.renderers)
73 for (std::size_t i = 0; i < instance->rendererCount(); ++i) {
74 auto renderer = instance->renderer(i);
75 if (!renderer.ok()) return Result<void>::failure(renderer.status());
76 }
77 return Result<void>::success();
78 }
79 Result<Batches> prepare(const std::vector<ProcgenBatchSnapshot>& snapshots) {
80 using Output = Result<Batches>;
81 if (snapshots.empty() || snapshots.size() > 64 || retired.size() + snapshots.size() > 64)
83 "prefab batch/retirement budget requires collectRetired"));
85 std::size_t parts = 0, instances = 0;
86 for (const auto& [id, batch] : active) {
87 parts += batch.parts;
88 instances += batch.source.size();
89 }
90 for (const auto& node : retired) {
91 parts += node.mapped().parts;
92 instances += node.mapped().source.size();
93 }
94 for (const auto& snapshot : snapshots) {
95 if (snapshot.batchId.empty() || !snapshot.targetRevision ||
96 scene.batchRevision(snapshot.batchId) >= snapshot.targetRevision ||
97 candidates.contains(snapshot.batchId))
98 return Output::failure(Diagnostic::error(DiagnosticCode::Conflict, "invalid or stale prefab snapshot"));
99 auto revision = validateRevision(snapshot.batchId);
100 if (!revision.ok()) return Output::failure(revision.status());
101 if (instances > 65536 || snapshot.instances.size() > 65536 - instances)
102 return Output::failure(
103 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab instance budget exceeded"));
104 instances += snapshot.instances.size();
105 auto& batch = candidates[snapshot.batchId];
106 batch.revision = snapshot.targetRevision;
107 batch.source = snapshot.instances;
108 std::unordered_set<std::string> ids;
109 std::unordered_set<uint64_t> pointIds;
110 for (const auto& value : snapshot.instances) {
111 if (value.id.empty() || !value.sourcePointId || !ids.insert(value.id).second ||
112 !pointIds.insert(value.sourcePointId).second)
113 return Output::failure(
114 Diagnostic::error(DiagnosticCode::Conflict, "prefab identities must be unique"));
115 for (float scalar : {value.x, value.y, value.z, value.yaw, value.pitch, value.roll, value.scaleX,
116 value.scaleY, value.scaleZ})
117 if (!std::isfinite(scalar))
118 return Output::failure(
119 Diagnostic::error(DiagnosticCode::InvalidArgument, "nonfinite prefab pose"));
120 if (!value.assetBinding) continue;
121 const auto& binding = *value.assetBinding;
122 if (binding.buildId.isNil() || value.asset != binding.asset.format())
123 return Output::failure(
124 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid typed prefab binding"));
125 const auto prefab = assets.find({binding.asset.id(), binding.buildId});
126 if (prefab == assets.end()) {
127 const auto firstVersion = assets.lower_bound({binding.asset.id(), PersistentId{}});
128 const auto code = firstVersion == assets.end() || firstVersion->first.first != binding.asset.id()
131 return Output::failure(
132 Diagnostic::error(code, "prefab asset/build version is not admitted", value.asset));
133 }
134 const auto count = prefab->second.prefab->drawCount();
135 if (parts > 65536 || count > 65536 - parts)
136 return Output::failure(
137 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab renderer budget exceeded"));
138 parts += count;
139 batch.parts += count;
140 auto preparation =
141 EvpackStaticPrefab::prepareScene(prefab->second.prefab, graphics, value.assetBinding->rootPose);
142 if (!preparation.ok()) return Output::failure(preparation.status());
143 auto instance =
144 StaticPrefabRenderInstance::create(std::move(preparation).takeValue(), instanceMatrix(value));
145 if (!instance.ok()) return Output::failure(instance.status());
146 visibility(*instance.value(), false);
147 batch.renderers.push_back(std::move(instance).takeValue());
148 }
149 }
150 std::size_t added = 0;
151 for (const auto& [id, batch] : candidates)
152 if (!active.contains(id)) ++added;
153 if (active.size() + added > 64)
154 return Output::failure(
155 Diagnostic::error(DiagnosticCode::PreconditionViolation, "active prefab batch budget exceeded"));
156 return Output::success(std::move(candidates));
157 }
159 while (!candidates.empty()) {
160 auto node = candidates.extract(candidates.begin());
161 const auto old = active.find(node.key());
162 if (old != active.end()) {
163 visibility(old->second, false);
164 retired.push_back(active.extract(old));
165 }
166 visibility(node.mapped(), true);
167 auto inserted = active.insert(std::move(node));
168 EV_ASSERT(inserted.inserted, "prepared prefab batch key must be absent at commit");
169 }
170 }
171};
175 auto result = release();
176 if (!result.ok()) std::fprintf(stderr, "prefab batch cleanup failed: %s\n", result.status().describe().c_str());
177}
178Result<void> ProcgenPrefabSceneSink::admit(std::shared_ptr<EvpackStaticPrefab> prefab) {
179 if (!impl_->available() || !prefab || !prefab->drawCount() || prefab->sourceBuildId().isNil())
181 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab admission requires live owners"));
182 const Impl::VersionKey key{prefab->sourceAsset().id(), prefab->sourceBuildId()};
183 if (impl_->assets.contains(key) || impl_->assets.size() >= 4096)
185 Diagnostic::error(DiagnosticCode::Conflict, "duplicate or oversized prefab catalogue"));
187 if (!pin.ok()) return Result<void>::failure(pin.status());
188 impl_->assets.emplace(key, Impl::Version{std::move(prefab), std::move(pin).takeValue()});
189 return Result<void>::success();
190}
191Result<uint64_t> ProcgenPrefabSceneSink::replaceBatchesCoordinated(const std::vector<ProcgenBatchSnapshot>& snapshots,
192 const std::function<Result<void>()>& owner) {
193 if (!impl_->available() || !owner)
195 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab publication is closed or reentered"));
196 BusyScope busy(impl_->busy);
197 auto candidate = impl_->prepare(snapshots);
198 if (!candidate.ok()) return Result<uint64_t>::failure(candidate.status());
199 impl_->retired.reserve(impl_->retired.size() + snapshots.size());
200 return impl_->scene.replaceBatchesCoordinated(snapshots, [&] {
201 auto valid = impl_->validateCandidates(candidate.value());
202 if (!valid.ok()) return valid;
203 auto committed = owner();
204 if (!committed.ok()) return committed;
205 impl_->commit(candidate.value());
206 return Result<void>::success();
207 });
208}
209Result<uint64_t> ProcgenPrefabSceneSink::replaceBatches(const std::vector<ProcgenBatchSnapshot>& snapshots) {
210 return replaceBatchesCoordinated(snapshots, [] { return Result<void>::success(); });
211}
213 const std::vector<ProcgenInstanceDesc>& instances) {
214 auto result = replaceBatches({{id, revision, instances}});
215 if (!result.ok()) return result;
216 return Result<uint64_t>::success(revision, result.status());
217}
218bool ProcgenPrefabSceneSink::applyBatch(const std::string& id, const std::vector<ProcgenInstanceDesc>& instances) {
219 if (!impl_->available() || instances.size() > 65536 || batchRevision(id) == std::numeric_limits<uint64_t>::max())
220 return false;
221 auto target = instances;
222 std::unordered_set<uint64_t> used;
223 std::unordered_map<std::string, uint64_t> previous;
224 if (const auto found = impl_->active.find(id); found != impl_->active.end())
225 for (const auto& value : found->second.source) previous.emplace(value.id, value.sourcePointId);
226 for (const auto& value : target)
227 if (value.sourcePointId) used.insert(value.sourcePointId);
228 uint64_t next = 1;
229 for (auto& value : target) {
230 if (value.sourcePointId) continue;
231 const auto old = previous.find(value.id);
232 if (old != previous.end() && used.insert(old->second).second)
233 value.sourcePointId = old->second;
234 else {
235 while (used.contains(next)) ++next;
236 value.sourcePointId = next;
237 used.insert(next);
238 }
239 }
240 auto result = replaceBatch(id, batchRevision(id) + 1, target);
241 return result.ok();
242}
244 if (!impl_->available())
246 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab delta is reentered or closed"));
247 for (std::size_t count : {delta.added.size(), delta.updated.size(), delta.removedPointIds.size(),
248 delta.removed.size(), delta.targetPointOrder.size(), delta.targetOrder.size()})
249 if (count > 65536)
251 "prefab delta collection exceeds its work budget"));
252 const auto found = impl_->active.find(id);
253 if (found == impl_->active.end())
255 Diagnostic::error(DiagnosticCode::NotFound, "prefab delta requires a committed snapshot"));
256 auto revision = impl_->validateRevision(id);
257 if (!revision.ok()) return Result<uint64_t>::failure(revision.status());
258 auto target = buildProcgenInstanceDeltaSnapshot(found->second.source, found->second.revision, delta);
259 if (!target.ok()) return Result<uint64_t>::failure(target.status());
260 return replaceBatch(id, delta.targetRevision, target.value());
261}
263 const std::function<Result<void>()>& owner) {
264 if (!impl_->available() || !owner || ids.empty() || ids.size() > 64 || impl_->retired.size() + ids.size() > 64)
266 DiagnosticCode::PreconditionViolation, "prefab removal requires live owners and retirement capacity"));
267 BusyScope busy(impl_->busy);
268 for (const auto& id : ids) {
269 auto revision = impl_->validateRevision(id);
270 if (!revision.ok()) return Result<uint64_t>::failure(revision.status());
271 }
272 impl_->retired.reserve(impl_->retired.size() + ids.size());
273 return impl_->scene.removeBatchesCoordinated(ids, [&] {
274 auto committed = owner();
275 if (!committed.ok()) return committed;
276 for (const auto& id : ids) {
277 const auto old = impl_->active.find(id);
278 if (old == impl_->active.end()) continue;
279 Impl::visibility(old->second, false);
280 impl_->retired.push_back(impl_->active.extract(old));
281 }
282 return Result<void>::success();
283 });
284}
286 return removeBatchesCoordinated(ids, [] { return Result<void>::success(); });
287}
288bool ProcgenPrefabSceneSink::removeBatch(const std::string& id) {
289 auto result = removeBatches({id});
290 return result.ok();
291}
293 if (impl_->busy)
295 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab cleanup cannot reenter publication"));
296 for (auto& node : impl_->retired)
297 for (auto& instance : node.mapped().renderers) {
298 auto result = instance->release();
299 if (!result.ok()) return result;
300 }
301 impl_->retired.clear();
302 return Result<void>::success();
303}
305 if (impl_->closed) return Result<void>::success();
306 if (impl_->busy)
308 Diagnostic::error(DiagnosticCode::PreconditionViolation, "prefab release cannot reenter publication"));
309 auto collected = collectRetired();
310 if (!collected.ok()) return collected;
311 if (!impl_->active.empty()) {
312 std::vector<std::string> ids;
313 for (const auto& [id, batch] : impl_->active) ids.push_back(id);
314 auto removed = removeBatches(ids);
315 if (!removed.ok()) return Result<void>::failure(removed.status());
316 }
317 collected = collectRetired();
318 if (!collected.ok()) return collected;
319 impl_->assets.clear();
320 impl_->closed = true;
321 return Result<void>::success();
322}
323std::size_t ProcgenPrefabSceneSink::rendererCount(const std::string& id) const noexcept {
324 const auto found = impl_->active.find(id);
325 return found == impl_->active.end() ? 0 : found->second.parts;
326}
327std::size_t ProcgenPrefabSceneSink::pendingRetirements() const noexcept { return impl_->retired.size(); }
328uint64_t ProcgenPrefabSceneSink::batchRevision(const std::string& id) const { return impl_->scene.batchRevision(id); }
329int ProcgenPrefabSceneSink::instanceCount(const std::string& id) const { return impl_->scene.instanceCount(id); }
330int ProcgenPrefabSceneSink::lastCreatedCount(const std::string& id) const { return impl_->scene.lastCreatedCount(id); }
331int ProcgenPrefabSceneSink::lastReusedCount(const std::string& id) const { return impl_->scene.lastReusedCount(id); }
332int ProcgenPrefabSceneSink::lastRemovedCount(const std::string& id) const { return impl_->scene.lastRemovedCount(id); }
333} // namespace eve::asset_graphics
LogicalId target
std::vector< eve::artifact::PartView > parts
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
std::string prefab
std::string output
std::uint64_t revision
bool committed
SQObjectPtr key
Definition ECS.cpp:155
DiagnosticCode code
std::string id
Poco::JSON::Object::Ptr result
uint64_t used
Snapshot snapshot
bool valid
std::shared_ptr< OceanGpuSpectrum > owner
std::shared_ptr< OceanRenderer > renderer
std::shared_ptr< const OceanSprayFrame > previous
eve::action::ActionVfxBinding binding
std::weak_ptr< PrimitiveScene > scene
bool & busy
Object::Ptr value
const RoadNode * node
bool found
glm::dmat4 matrix
int removed
Graphics * graphics
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
int count
bool visible
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Optional scene consumer for procedural instance batches.
virtual uint64_t batchRevision(const std::string &batchId) const =0
Current committed revision of a batch, or zero when it is absent.
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
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Result< std::unique_ptr< PreparedStaticPrefabScene > > prepareScene(const std::shared_ptr< EvpackStaticPrefab > &owner, graphics::Graphics &graphics, PrefabRootPose rootPose=PrefabRootPose::Authored)
Prepare complete scene-renderer materials and local transforms while pinning loaded prefab resources.
static Result< std::unique_ptr< StaticPrefabResourcePin > > pinResources(const std::shared_ptr< EvpackStaticPrefab > &owner)
Retain loaded resources for an admitted version without creating renderer/material inputs.
Result< void > collectRetired()
Release retired, already hidden renderers without changing committed batches.
Result< void > admit(std::shared_ptr< EvpackStaticPrefab > prefab)
Admit and pin one immutable asset/build version; historical versions remain available for undo/restor...
Result< uint64_t > applyDelta(const std::string &, const ProcgenInstanceDelta &) override
Apply one prevalidated identity delta atomically to an existing batch.
std::size_t pendingRetirements() const noexcept
Number of retired batch resource sets awaiting collectRetired, bounded to 64.
Result< uint64_t > replaceBatches(const std::vector< ProcgenBatchSnapshot > &) override
Atomically replace several batches from complete snapshots.
Result< void > release()
Remove all owned batches through Scene coordination, collect resources and close the decorator.
Result< uint64_t > removeBatches(const std::vector< std::string > &) override
Atomically remove several published batches.
Result< uint64_t > replaceBatch(const std::string &, uint64_t, const std::vector< ProcgenInstanceDesc > &) override
Atomically replace a batch with a complete stable-identity snapshot at an explicit revision.
std::size_t rendererCount(const std::string &batchId) const noexcept
Number of active renderer parts in a batch; metadata-only anchors contribute zero.
int lastRemovedCount(const std::string &) const override
Instances removed by the batch's latest successful apply or removal.
int instanceCount(const std::string &) const override
Number of currently published instances in a batch.
Result< uint64_t > removeBatchesCoordinated(const std::vector< std::string > &, const std::function< Result< void >()> &) override
Remove several batches while coordinating one external authoritative commit.
bool applyBatch(const std::string &, const std::vector< ProcgenInstanceDesc > &) override
Compatibility projection assigning absent PointIds by stable instance id before canonical replacement...
ProcgenPrefabSceneSink(graphics::Graphics &graphics, IProcgenSceneSink &scene)
Bind borrowed rendering and Scene owners; does not install a global capability or publish anything.
~ProcgenPrefabSceneSink() override
Attempt checked release before teardown and report failures; explicit release permits retry.
bool removeBatch(const std::string &) override
Compatibility wrapper over checked coordinated removal. @cost Same Scene staging and renderer retirem...
uint64_t batchRevision(const std::string &) const override
Current committed revision of a batch, or zero when it is absent.
int lastReusedCount(const std::string &) const override
Stable-id instances reused by the batch's latest successful apply.
Result< uint64_t > replaceBatchesCoordinated(const std::vector< ProcgenBatchSnapshot > &, const std::function< Result< void >()> &) override
Replace complete batches while committing one prepared external resource owner.
int lastCreatedCount(const std::string &) const override
Instances newly created by the batch's latest successful apply.
Own renderer entities and their prepared prefab resources, without owning a Scene node....
std::size_t rendererCount() const noexcept
Return the number of owned renderer handles; externally deleted entries remain counted until release.
Result< graphics::Renderable3D * > renderer(std::size_t index) const
Resolve a renderer for synchronous Scene linking or diagnostics.
static Result< std::unique_ptr< StaticPrefabRenderInstance > > create(std::unique_ptr< PreparedStaticPrefabScene > preparation, const std::array< float, 16 > &world)
Consume preparation and publish all renderer parts after validating composed transforms.
Id128 public API.
Definition Identity.h:111
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
Result< std::vector< ProcgenInstanceDesc > > buildProcgenInstanceDeltaSnapshot(const std::vector< ProcgenInstanceDesc > &current, uint64_t currentRevision, const ProcgenInstanceDelta &delta)
Build an owning target snapshot from one exact revision and identity delta; does not publish state.
Identity-based, revision-checked mutation of one procedural scene batch.
std::vector< uint64_t > removedPointIds
Stable source PointIds removed from the target batch.
std::vector< std::string > targetOrder
Compatibility target order addressed directly by Scene instance id.
std::vector< ProcgenInstanceDesc > updated
std::vector< std::string > removed
Compatibility removals addressed directly by Scene instance id.
std::vector< uint64_t > targetPointOrder
Exact target order addressed by stable source PointId.
std::vector< ProcgenInstanceDesc > added
std::vector< std::unique_ptr< StaticPrefabRenderInstance > > renderers
Result< void > validateCandidates(const Batches &candidates) const
std::pair< PersistentId, PersistentId > VersionKey
Result< void > validateRevision(const std::string &id) const
static void visibility(Batch &batch, bool visible)
static void visibility(StaticPrefabRenderInstance &instance, bool visible)
Result< Batches > prepare(const std::vector< ProcgenBatchSnapshot > &snapshots)