载入中...
搜索中...
未找到
VegetationSceneInstance.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cctype>
4#include <cmath>
5#include <limits>
6#include <new>
7#include <numeric>
8#include <set>
9#include <string_view>
11
12// VegetationSceneInstance.cpp
13namespace eve::asset_graphics {
14namespace {
15std::string folded(std::string value) {
16 for (char& character : value) character = static_cast<char>(std::tolower(static_cast<unsigned char>(character)));
17 return value;
18}
19} // namespace
20
22 const AssetRef& sceneTemplate, const asset::EvpackCapabilities& capabilities) const {
23 auto scene = asset_scene::EvpackSceneTemplateLoader(reader_).load(sceneTemplate, capabilities);
25 if (scene.value().sourceGuid.empty())
27 DiagnosticCode::Unsupported, "legacy Scene Template has no source GUID for manager association",
28 sceneTemplate.format(), {}, "asset.graphics.vegetation-scene-instance"));
29 auto candidates = reader_.listAssets("eve.vegetation-scene/1", capabilities, 4096);
31 std::optional<LoadedVegetationScene> match;
32 const auto expected = folded(scene.value().sourceGuid);
33 for (const auto& candidate : candidates.value()) {
34 auto manager = EvpackVegetationSceneLoader(reader_).load(candidate, capabilities);
35 if (!manager) return Result<VegetationSceneAssociation>::failure(manager.status());
36 if (folded(manager.value().sourceGuid) != expected) continue;
37 if (match)
39 Diagnostic::error(DiagnosticCode::Conflict, "Scene Template matches multiple vegetation managers",
40 sceneTemplate.format(), {}, "asset.graphics.vegetation-scene-instance"));
41 match.emplace(std::move(manager).takeValue());
42 }
43 if (!match)
45 Diagnostic::error(DiagnosticCode::NotFound, "Scene Template has no vegetation manager",
46 sceneTemplate.format(), {}, "asset.graphics.vegetation-scene-instance"));
47 auto masks = loadVegetationSceneElementMasks(reader_, *match, capabilities);
48 if (!masks) return Result<VegetationSceneAssociation>::failure(masks.status());
50 {std::move(scene).takeValue(), std::move(*match), std::move(masks).takeValue()});
51}
52
54 const asset::EvpackResourceReader& reader, graphics::IResourceFactory& factory, const AssetRef& sceneTemplate,
55 const asset::EvpackCapabilities& capabilities, graphics::PbrSurface baseSurface,
56 graphics::VegetationMotion baseMotion, const VegetationSceneGpuBuild& build, std::uint64_t owner) {
57 auto association = VegetationSceneAssociationLoader(reader).load(sceneTemplate, capabilities);
58 if (!association) return Result<std::unique_ptr<VegetationSceneInstance>>::failure(association.status());
59 auto runtime = VegetationSceneGpuRuntime::create(factory, baseSurface, baseMotion, association.value().manager,
60 association.value().masks, build);
61 if (!runtime) return Result<std::unique_ptr<VegetationSceneInstance>>::failure(runtime.status());
62 auto live = VegetationSceneLiveElements::create(association.value().manager, owner);
63 if (!live) return Result<std::unique_ptr<VegetationSceneInstance>>::failure(live.status());
64 try {
65 auto result = std::unique_ptr<VegetationSceneInstance>(new VegetationSceneInstance(
66 std::move(association).takeValue(), std::move(baseSurface), std::move(baseMotion),
67 std::move(runtime).takeValue(), std::move(live).takeValue()));
69 } catch (const std::bad_alloc&) {
71 Diagnostic::error(DiagnosticCode::Failed, "vegetation scene instance allocation failed", {}, {},
72 "asset.graphics.vegetation-scene-instance"));
73 }
74}
75
77 std::uint64_t expectedRevision, const VegetationSceneElement& element, const VegetationSceneGpuBuild& build) {
78 return liveElements_->registerElement(expectedRevision, runtime_->sourceRevision(), element, *runtime_,
79 baseSurface_, baseMotion_, association_.masks, build);
80}
81
83 std::uint64_t expectedRevision, VegetationSceneElementHandle handle, const VegetationSceneGpuBuild& build) {
84 return liveElements_->withdrawElement(expectedRevision, runtime_->sourceRevision(), handle, *runtime_, baseSurface_,
85 baseMotion_, association_.masks, build);
86}
87
88} // namespace eve::asset_graphics
89
90// VegetationSceneLiveElements.cpp
91namespace eve::asset_graphics {
92namespace {
93bool finite(float value) { return std::isfinite(value); }
94
95bool validGuid(std::string_view value, bool allowEmpty) {
96 return (allowEmpty && value.empty()) ||
97 (value.size() == 32 && std::all_of(value.begin(), value.end(),
98 [](unsigned char character) { return std::isxdigit(character) != 0; }));
99}
100
101bool validElement(const VegetationSceneElement& element) {
102 static const std::set<std::string> kinds{"color-effect",
103 "color-map",
104 "color-noise",
105 "color-tint",
106 "extras-alpha",
107 "extras-emissive",
108 "extras-overlay",
109 "extras-wetness",
110 "motion-advanced",
111 "motion-interaction",
112 "motion-wind-power",
113 "vertex-conform-model",
114 "vertex-conform-simple",
115 "vertex-conform-terrain",
116 "vertex-height-offset",
117 "vertex-height",
118 "vertex-orientation-model",
119 "vertex-orientation-terrain",
120 "vertex-size"};
121 const std::uint32_t expectedChannel = element.kind.starts_with("color-") ? 0u
122 : element.kind.starts_with("extras-") ? 1u
123 : element.kind.starts_with("motion-") ? 2u
124 : 3u;
125 const float rotationLength =
126 std::sqrt(std::inner_product(element.rotation.begin(), element.rotation.end(), element.rotation.begin(), 0.f));
127 std::set<std::string> propertyNames;
128 const auto finiteValues = [](const auto& values) {
129 return std::all_of(values.begin(), values.end(), [](float value) { return finite(value); });
130 };
131 if (element.sourceFileId == 0 || !validGuid(element.shaderGuid, false) || !validGuid(element.textureGuid, true) ||
132 !kinds.contains(element.kind) || element.channel != expectedChannel ||
133 (element.visibility != -1 && element.visibility != 0 && element.visibility != 10 && element.visibility != 20) ||
134 element.layers == 0 || (element.layers & ~0x1ffu) || !finite(element.intensity) || element.intensity < 0.f ||
135 element.intensity > 1.f || !finite(element.motionPower) || element.motionPower < 0.f ||
136 element.motionPower > 1.f || !finiteValues(element.position) || !finiteValues(element.rotation) ||
137 !finiteValues(element.scale) || !finiteValues(element.value) || !finiteValues(element.remap) ||
138 !finiteValues(element.seasons[0]) || !finiteValues(element.seasons[1]) || !finiteValues(element.seasons[2]) ||
139 !finiteValues(element.seasons[3]) || std::abs(rotationLength - 1.f) > 1e-3f ||
140 std::any_of(element.scale.begin(), element.scale.end(), [](float value) { return value <= 0.f; }) ||
141 element.remap[0] > element.remap[1] || element.remap[2] > element.remap[3] ||
142 element.remap[4] > element.remap[5] || element.blendRgb < 0 || element.blendRgb > 2 || element.blendAlpha < 0 ||
143 element.blendAlpha > 1 ||
144 (element.directionMode != 10 && element.directionMode != 20 && element.directionMode != 30 &&
145 element.directionMode != 40) ||
146 (element.motionMode != 13 && element.motionMode != 15) || element.properties.size() > 256 ||
147 (!element.textureAsset.empty() && !AssetRef::parse(element.textureAsset)))
148 return false;
149 for (const auto& property : element.properties) {
150 if (property.name.empty() || property.name.size() > 128 || property.type < 0 || property.type > 2 ||
151 !validGuid(property.textureGuid, true) || !finiteValues(property.vector) || !finite(property.value) ||
152 (!property.textureAsset.empty() && !AssetRef::parse(property.textureAsset)) ||
153 !propertyNames.emplace(property.name).second)
154 return false;
155 }
156 return true;
157}
158} // namespace
159
161 LoadedVegetationScene baseScene, std::uint64_t owner) {
162 if (owner == 0 || baseScene.elements.size() > 4096)
164 DiagnosticCode::InvalidArgument, "vegetation live-element registry identity or scene is invalid", {}, {},
165 "asset.graphics.vegetation-live-elements"));
166 if (std::any_of(baseScene.elements.begin(), baseScene.elements.end(),
167 [](const auto& element) { return !validElement(element); }))
169 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation live-element base scene is invalid", {}, {},
170 "asset.graphics.vegetation-live-elements"));
171 try {
173 std::unique_ptr<VegetationSceneLiveElements>(new VegetationSceneLiveElements(std::move(baseScene), owner)));
174 } catch (const std::bad_alloc&) {
176 Diagnostic::error(DiagnosticCode::Failed, "vegetation live-element registry allocation failed", {}, {},
177 "asset.graphics.vegetation-live-elements"));
178 }
179}
180
182 try {
183 LoadedVegetationScene result = baseScene_;
184 result.elements.reserve(baseScene_.elements.size() + slots_.size());
185 for (const auto& slot : slots_)
186 if (slot.element) result.elements.push_back(*slot.element);
188 } catch (const std::bad_alloc&) {
190 Diagnostic::error(DiagnosticCode::Failed, "vegetation live-element snapshot allocation failed", {}, {},
191 "asset.graphics.vegetation-live-elements"));
192 }
193}
194
196 std::uint64_t expectedRevision, std::uint64_t expectedGpuRevision, const VegetationSceneElement& element,
197 VegetationSceneGpuRuntime& runtime, const graphics::PbrSurface& baseSurface,
198 const graphics::VegetationMotion& baseMotion, const std::map<std::string, graphics::VegetationMask>& masks,
200 if (expectedRevision != revision_ || expectedGpuRevision != runtime.sourceRevision())
202 Diagnostic::error(DiagnosticCode::Conflict, "vegetation live-element state changed before registration", {},
203 {}, "asset.graphics.vegetation-live-elements"));
204 if (revision_ == std::numeric_limits<std::uint64_t>::max() || !validElement(element))
206 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation live Element is invalid", {}, {},
207 "asset.graphics.vegetation-live-elements"));
208 std::size_t slotIndex = 0;
209 while (slotIndex < slots_.size() && (slots_[slotIndex].element || slots_[slotIndex].retired)) ++slotIndex;
210 const auto activeCount =
211 std::count_if(slots_.begin(), slots_.end(), [](const Slot& slot) { return slot.element.has_value(); });
212 if (baseScene_.elements.size() + std::size_t(activeCount) + 1 > 4096)
214 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation live-element capacity exceeded", {}, {},
215 "asset.graphics.vegetation-live-elements"));
216 auto candidate = snapshot();
217 if (!candidate) return Result<VegetationSceneElementPublication>::failure(candidate.status());
218 try {
219 candidate.value().elements.push_back(element);
220 if (slotIndex == slots_.size()) slots_.reserve(slots_.size() + 1);
221 } catch (const std::bad_alloc&) {
223 Diagnostic::error(DiagnosticCode::Failed, "vegetation live-element registration allocation failed", {}, {},
224 "asset.graphics.vegetation-live-elements"));
225 }
226 auto published = runtime.replace(expectedGpuRevision, baseSurface, baseMotion, candidate.value(), masks, build);
227 if (!published) return Result<VegetationSceneElementPublication>::failure(published.status());
228 if (slotIndex == slots_.size()) slots_.push_back({});
229 auto& slot = slots_[slotIndex];
230 slot.element.emplace(std::move(candidate.value().elements.back()));
231 ++revision_;
233 {{owner_, static_cast<VegetationSceneElementHandle::index_type>(slotIndex), slot.generation},
234 revision_,
235 published.value()});
236}
237
239 std::uint64_t expectedRevision, std::uint64_t expectedGpuRevision, VegetationSceneElementHandle handle,
240 VegetationSceneGpuRuntime& runtime, const graphics::PbrSurface& baseSurface,
241 const graphics::VegetationMotion& baseMotion, const std::map<std::string, graphics::VegetationMask>& masks,
243 if (expectedRevision != revision_ || expectedGpuRevision != runtime.sourceRevision())
245 Diagnostic::error(DiagnosticCode::Conflict, "vegetation live-element state changed before withdrawal", {},
246 {}, "asset.graphics.vegetation-live-elements"));
247 if (!handle.isValid() || handle.owner() != owner_ || handle.index() >= slots_.size())
249 Diagnostic::error(DiagnosticCode::NotFound, "vegetation live Element handle is foreign or missing", {}, {},
250 "asset.graphics.vegetation-live-elements"));
251 auto& slot = slots_[handle.index()];
252 if (!slot.element || slot.generation != handle.generation())
254 Diagnostic::error(DiagnosticCode::NotFound, "vegetation live Element handle is stale or withdrawn", {}, {},
255 "asset.graphics.vegetation-live-elements"));
256 if (revision_ == std::numeric_limits<std::uint64_t>::max())
258 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation live-element revision is exhausted", {}, {},
259 "asset.graphics.vegetation-live-elements"));
260 auto candidate = snapshot();
261 if (!candidate) return Result<VegetationSceneElementPublication>::failure(candidate.status());
262 const std::size_t dynamicOffset = baseScene_.elements.size();
263 std::size_t activeBefore = 0;
264 for (std::size_t index = 0; index < handle.index(); ++index)
265 if (slots_[index].element) ++activeBefore;
266 candidate.value().elements.erase(candidate.value().elements.begin() + dynamicOffset + activeBefore);
267 auto published = runtime.replace(expectedGpuRevision, baseSurface, baseMotion, candidate.value(), masks, build);
268 if (!published) return Result<VegetationSceneElementPublication>::failure(published.status());
269 slot.element.reset();
271 if (next)
272 slot.generation = *next;
273 else
274 slot.retired = true;
275 ++revision_;
276 return Result<VegetationSceneElementPublication>::success({handle, revision_, published.value()});
277}
278
279} // namespace eve::asset_graphics
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
float u
Definition Grass.cpp:233
std::map< std::string, PropertyRule > properties
Poco::JSON::Object::Ptr result
std::shared_ptr< OceanGpuSpectrum > owner
bool finite
std::weak_ptr< PrimitiveScene > scene
PrimitiveHandle handle
std::set< std::string > values
Object::Ptr value
std::string build
std::string slot
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
std::string element
uint32_t index
Automatic Scene Template to TVE manager runtime association.
Transactional runtime registration of TVE Element volumes.
Stable asset identity backed by PersistentId.
Definition ResourceRef.h:53
static Result< AssetRef > parse(std::string_view text)
Parse an asset://<canonical UUID> reference.
std::string format() const
Return canonical asset://<uuid> text.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
constexpr std::optional< RuntimeHandle > nextGeneration() const noexcept
Returns this slot at its next generation.
Immutable reader retaining an admitted pack by shared ownership.
Result< std::vector< AssetRef > > listAssets(std::string_view expectedType, const EvpackCapabilities &capabilities, std::uint32_t maximumAssets=1 '000 '000) const
List stable assets providing an exact type/version for the selected runtime variant.
Strict capability-aware decoder for eve.vegetation-scene/1.
Result< LoadedVegetationScene > load(const AssetRef &asset, const asset::EvpackCapabilities &capabilities, std::uint64_t maximumDecodedBytes=1024 *1024) const
Decode and validate one complete scene state without mutating runtime objects.
Resolve a Scene Template to exactly one manager asset in the same admitted EVPACK.
Result< VegetationSceneAssociation > load(const AssetRef &sceneTemplate, const asset::EvpackCapabilities &capabilities) const
Load the template, find the unique manager with the same Unity source GUID, and decode all Element ma...
Instance-qualified handle for one dynamically registered TVE Element volume.
Owning GPU publication of one immutable TVE manager scene. The resource factory, mask map and scene a...
static Result< std::unique_ptr< VegetationSceneGpuRuntime > > create(graphics::IResourceFactory &factory, const graphics::PbrSurface &baseSurface, const graphics::VegetationMotion &baseMotion, const LoadedVegetationScene &scene, const std::map< std::string, graphics::VegetationMask > &masks, const VegetationSceneGpuBuild &build)
Bake, convert, upload and bind all field layers as one atomic candidate.
Owning executable instance coupling one Scene Template, its manager fields and live Element registry....
Result< VegetationSceneElementPublication > withdrawElement(std::uint64_t expectedRevision, VegetationSceneElementHandle handle, const VegetationSceneGpuBuild &build)
Withdraw one live Element and republish this associated instance atomically.
static Result< std::unique_ptr< VegetationSceneInstance > > create(const asset::EvpackResourceReader &reader, graphics::IResourceFactory &factory, const AssetRef &sceneTemplate, const asset::EvpackCapabilities &capabilities, graphics::PbrSurface baseSurface, graphics::VegetationMotion baseMotion, const VegetationSceneGpuBuild &build, std::uint64_t owner)
Resolve and publish the manager automatically from a Scene Template asset.
Result< VegetationSceneElementPublication > registerElement(std::uint64_t expectedRevision, const VegetationSceneElement &element, const VegetationSceneGpuBuild &build)
Register one live Element and republish this associated instance atomically.
Owning registry that atomically couples dynamic Element state to a scene GPU runtime....
Result< LoadedVegetationScene > snapshot() const
Detached scene containing imported Elements followed by live slots in stable index order.
static Result< std::unique_ptr< VegetationSceneLiveElements > > create(LoadedVegetationScene baseScene, std::uint64_t owner)
Create a registry from one validated imported scene.
Result< VegetationSceneElementPublication > registerElement(std::uint64_t expectedRevision, std::uint64_t expectedGpuRevision, const VegetationSceneElement &element, VegetationSceneGpuRuntime &runtime, const graphics::PbrSurface &baseSurface, const graphics::VegetationMotion &baseMotion, const std::map< std::string, graphics::VegetationMask > &masks, const VegetationSceneGpuBuild &build)
Register and publish one Element as an atomic registry/GPU transaction.
Result< VegetationSceneElementPublication > withdrawElement(std::uint64_t expectedRevision, std::uint64_t expectedGpuRevision, VegetationSceneElementHandle handle, VegetationSceneGpuRuntime &runtime, const graphics::PbrSurface &baseSurface, const graphics::VegetationMotion &baseMotion, const std::map< std::string, graphics::VegetationMask > &masks, const VegetationSceneGpuBuild &build)
Withdraw and publish one live Element as an atomic registry/GPU transaction. Foreign,...
Capability-aware scene-template/3 decoder with explicit scene-template/2 compatibility.
Result< LoadedSceneTemplate > load(const AssetRef &sceneTemplate, const asset::EvpackCapabilities &capabilities, const SceneTemplateLoadLimits &limits={}) const
Validate identities, hierarchy and finite TRS values before building a tree.
Texture / mesh / shader / canvas creation and release.
Result< std::map< std::string, graphics::VegetationMask > > loadVegetationSceneElementMasks(const asset::EvpackResourceReader &reader, const LoadedVegetationScene &scene, const asset::EvpackCapabilities &capabilities, std::uint64_t maximumDecodedBytes)
Decode every runtime texture used by admitted TVE Element shaders into owning linear masks.
bool validGuid(std::string_view value)
Valid guid.
Actual runtime device capabilities used for variant selection.
Definition Evpack.h:92
Fully validated, detached scene-manager candidate with no archive or GPU borrows.
std::vector< VegetationSceneElement > elements
std::map< std::string, graphics::VegetationMask > masks
One normalized Unity TVEElement definition awaiting texture realization.
Explicit detached inputs for publishing all nine TVE scene-manager field layers.
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
Definition PbrSurface.h:240
Source-equivalent plant motion parameters with explicit time and texture inputs. All data is owned....