载入中...
搜索中...
未找到
EvpackVegetationScene.cpp
浏览该文件的文档.
2#include "common/ValueRead.h"
3
6
7#include <algorithm>
8#include <cmath>
9#include <cstdio>
10#include <glm/common.hpp>
11#include <glm/geometric.hpp>
12#include <limits>
13#include <new>
14#include <numeric>
15#include <set>
16
17namespace eve::asset_graphics {
18namespace {
19const Value& member(const Value::Object& object, std::string_view name) { return object.at(std::string(name)); }
20
21bool exact(const Value::Object& object, std::initializer_list<std::string_view> fields) {
22 if (object.size() != fields.size()) return false;
23 return std::all_of(fields.begin(), fields.end(), [&](auto name) { return object.contains(std::string(name)); });
24}
25
26bool numeric(const Value& value, float& result) {
27 auto parsed = eve::readFiniteFloatValue(value);
28 if (!parsed) return false;
29 result = parsed.value();
30 return true;
31}
32
33template <std::size_t N>
34bool values(const Value& value, std::array<float, N>& result) {
35 const auto* array = value.getIf<Value::Array>();
36 if (!array || array->size() != N) return false;
37 for (std::size_t index = 0; index < N; ++index)
38 if (!numeric((*array)[index], result[index])) return false;
39 return true;
40}
41
42bool validGuid(const Value& value, std::string& result) {
43 if (!value.isString()) return false;
44 result = value.asString();
45 return result.empty() ||
46 (result.size() == 32 && std::all_of(result.begin(), result.end(), [](unsigned char c) {
47 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
48 }));
49}
50
51bool unit(float value) { return value >= 0 && value <= 1; }
52bool nonnegative(float value) { return value >= 0 && std::isfinite(value); }
53bool whole(float value) { return std::trunc(value) == value; }
54
55bool finite(glm::vec2 value) { return std::isfinite(value.x) && std::isfinite(value.y); }
56bool finite(glm::vec4 value) {
57 return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z) && std::isfinite(value.w);
58}
59
60float remap(float value, float minimum, float maximum, float epsilon) {
61 value = std::clamp(value, .0001f, .9999f);
62 const float denominator = maximum - minimum + epsilon;
63 if (denominator == 0.f) return value >= maximum ? 1.f : 0.f;
64 return std::clamp((value - minimum) / denominator, 0.f, 1.f);
65}
66
67glm::vec3 rotate(const std::array<float, 4>& rotation, glm::vec3 value) {
68 const glm::vec3 xyz(rotation[0], rotation[1], rotation[2]);
69 const glm::vec3 t = 2.f * glm::cross(xyz, value);
70 return value + rotation[3] * t + glm::cross(xyz, t);
71}
72
73glm::vec3 inverseRotate(const std::array<float, 4>& rotation, glm::vec3 value) {
74 const std::array<float, 4> inverse{-rotation[0], -rotation[1], -rotation[2], rotation[3]};
75 return rotate(inverse, value);
76}
77
78glm::vec4 sampleMask(const graphics::VegetationMask& mask, glm::vec2 uv) {
79 if (mask.pixels.empty()) return glm::vec4(1.f);
80 const float x = std::clamp(uv.x * mask.width - .5f, 0.f, float(mask.width - 1));
81 const float y = std::clamp(uv.y * mask.height - .5f, 0.f, float(mask.height - 1));
82 const auto x0 = std::uint32_t(x), y0 = std::uint32_t(y);
83 const auto x1 = std::min(x0 + 1, mask.width - 1), y1 = std::min(y0 + 1, mask.height - 1);
84 return glm::mix(glm::mix(mask.pixels[std::size_t(y0) * mask.width + x0],
85 mask.pixels[std::size_t(y0) * mask.width + x1], x - float(x0)),
86 glm::mix(mask.pixels[std::size_t(y1) * mask.width + x0],
87 mask.pixels[std::size_t(y1) * mask.width + x1], x - float(x0)),
88 y - float(y0));
89}
90
91glm::vec4 seasonal(const VegetationSceneElement& element, float season) {
92 if (!element.seasonal) return glm::vec4(element.value[0], element.value[1], element.value[2], element.value[3]);
93 const float wrapped = season == 4.f ? 0.f : season;
94 const auto index = std::uint32_t(wrapped);
95 const float fraction = wrapped - float(index);
96 const float smooth = fraction * fraction * (3.f - 2.f * fraction);
97 const auto& a = element.seasons[index];
98 const auto& b = element.seasons[(index + 1) % 4];
99 return glm::mix(glm::vec4(a[0], a[1], a[2], a[3]), glm::vec4(b[0], b[1], b[2], b[3]), smooth);
100}
101
102float propertyScalar(const VegetationSceneElement& element, std::string_view name, float fallback) {
103 const auto found = std::find_if(element.properties.begin(), element.properties.end(),
104 [&](const auto& property) { return property.name == name; });
105 return found == element.properties.end() ? fallback : found->value;
106}
107
108glm::vec4 propertyVector(const VegetationSceneElement& element, std::string_view name, glm::vec4 fallback) {
109 const auto found = std::find_if(element.properties.begin(), element.properties.end(),
110 [&](const auto& property) { return property.name == name; });
111 if (found == element.properties.end()) return fallback;
112 return {found->vector[0], found->vector[1], found->vector[2], found->vector[3]};
113}
114} // namespace
115
117 const AssetRef& asset, const asset::EvpackCapabilities& capabilities, std::uint64_t maximumDecodedBytes) const {
118 auto payload = reader_.read(asset, "eve.vegetation-scene/1", capabilities, maximumDecodedBytes);
120 const asset::RuntimeAssetChunk* definition = nullptr;
121 for (const auto& chunk : payload.value().chunks) {
122 if (chunk.kind != asset::EvpackChunkKind::Definition) continue;
123 if (definition)
125 DiagnosticCode::Conflict, "duplicate scene definition", {}, {}, "asset.graphics.vegetation-scene"));
126 definition = &chunk;
127 }
128 if (!definition)
130 DiagnosticCode::NotFound, "scene definition is missing", {}, {}, "asset.graphics.vegetation-scene"));
132 limits.maximumBytes = maximumDecodedBytes;
133 auto decoded = asset::decodeRuntimeDefinition(definition->bytes, limits);
134 if (!decoded) return Result<LoadedVegetationScene>::failure(decoded.status());
135 const auto* root = decoded.value().getIf<Value::Object>();
136 if (!root || !exact(*root, {"schema", "schemaVersion", "sourceGuid", "control", "details", "motion", "volume", "elements"}) ||
137 !member(*root, "schema").isString() || member(*root, "schema").asString() != "eve.vegetation-scene" ||
138 !member(*root, "schemaVersion").isInt64() || member(*root, "schemaVersion").asInt() != 1 ||
139 !member(*root, "sourceGuid").isString())
141 "vegetation scene root is malformed", {}, {},
142 "asset.graphics.vegetation-scene"));
143 std::string sourceGuid;
144 if (!validGuid(member(*root, "sourceGuid"), sourceGuid) || sourceGuid.empty())
146 "vegetation scene source GUID is invalid", {},
147 {}, "asset.graphics.vegetation-scene"));
148
149 const auto* control = member(*root, "control").getIf<Value::Object>();
150 const auto* details = member(*root, "details").getIf<Value::Object>();
151 const auto* motion = member(*root, "motion").getIf<Value::Object>();
152 const auto* volume = member(*root, "volume").getIf<Value::Object>();
153 if (!control || !details || !motion || !volume ||
154 !exact(*control, {"values", "globalColor", "overlayColor", "overlayAlbedoGuid", "overlayNormalGuid",
155 "noiseTextureGuid"}) ||
156 !exact(*details, {"layers", "global", "colorMask", "overlayMask", "alphaThreshold", "perspective",
157 "motionHighlight", "bending", "flutter", "interactionAmplitude"}) ||
158 !exact(*motion, {"values", "direction", "noiseTextureGuid"}) ||
159 !exact(*volume, {"values", "colors", "extras", "motion", "vertex"}))
161 "vegetation scene sections are malformed", {},
162 {}, "asset.graphics.vegetation-scene"));
163
164 LoadedVegetationScene result{asset, std::move(sourceGuid), payload.value().variant, {}, {}, {}, {}, {}};
165 std::array<float, 17> controls{};
166 std::array<float, 8> motions{};
167 std::array<float, 4> volumes{};
168 std::array<float, 2> direction{};
169 if (!values(member(*control, "values"), controls) || !values(member(*control, "globalColor"), result.control.globalColor) ||
170 !values(member(*control, "overlayColor"), result.control.overlayColor) ||
171 !values(member(*motion, "values"), motions) || !values(member(*motion, "direction"), direction) ||
172 !values(member(*volume, "values"), volumes) ||
173 !validGuid(member(*control, "overlayAlbedoGuid"), result.control.overlayAlbedoGuid) ||
174 !validGuid(member(*control, "overlayNormalGuid"), result.control.overlayNormalGuid) ||
175 !validGuid(member(*control, "noiseTextureGuid"), result.control.noiseTextureGuid) ||
176 !validGuid(member(*motion, "noiseTextureGuid"), result.motion.noiseTextureGuid))
178 "vegetation scene values are malformed", {}, {},
179 "asset.graphics.vegetation-scene"));
180 auto& c = result.control;
181 c.season = controls[0]; c.globalAlpha = controls[1]; c.globalOverlay = controls[2];
182 c.globalWetness = controls[3]; c.globalEmissive = controls[4]; c.globalSubsurface = controls[5];
183 c.globalSize = controls[6]; c.overlaySmoothness = controls[7]; c.overlayNormalScale = controls[8];
184 c.overlaySubsurface = controls[9]; c.overlayScale = controls[10]; c.wetnessContrast = controls[11];
185 c.wetnessNormalScale = controls[12]; c.noiseTiling = controls[13]; c.proximityFade = controls[14];
186 c.distanceFadeBias = controls[15]; c.defaultConformHeight = controls[16];
187 auto& m = result.motion;
188 m.windPower = motions[0]; m.noiseTiling = motions[1]; m.bending = motions[2]; m.branch = motions[3];
189 m.flutter = motions[4]; m.speed = motions[5]; m.animatedTime = motions[6] >= .5f; m.fadeDistance = motions[7];
190 m.direction = direction;
191 if (!whole(volumes[1]) || !whole(volumes[2]))
193 "vegetation volume policy enum is not integral",
194 {}, {}, "asset.graphics.vegetation-scene"));
195 result.volume.renderScale = volumes[0]; result.volume.edgeFade = volumes[3];
196 result.volume.visibility = std::uint32_t(volumes[1]); result.volume.sorting = std::uint32_t(volumes[2]);
197 const std::array<std::string_view, 4> channelNames{"colors", "extras", "motion", "vertex"};
198 for (std::size_t index = 0; index < channelNames.size(); ++index) {
199 std::array<float, 3> channel{};
200 if (!values(member(*volume, channelNames[index]), channel))
202 "vegetation volume channel is malformed",
203 {}, {}, "asset.graphics.vegetation-scene"));
204 if (!whole(channel[0]) || !whole(channel[1]) || !whole(channel[2]) || channel[1] < 0 || channel[2] < 0)
206 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation volume channel integers are invalid", {},
207 {}, "asset.graphics.vegetation-scene"));
208 result.volume.channels[index] = {std::int32_t(channel[0]), std::uint32_t(channel[1]),
209 std::uint32_t(channel[2])};
210 }
211 if (c.season < 0 || c.season > 4 || !unit(c.globalAlpha) || !unit(c.globalOverlay) || !unit(c.globalWetness) ||
212 !nonnegative(c.globalEmissive) || !unit(c.globalSubsurface) || !unit(c.globalSize) ||
213 !unit(c.overlaySmoothness) || !unit(c.overlayNormalScale) || !unit(c.overlaySubsurface) || c.overlayScale <= 0 ||
214 !unit(c.wetnessContrast) || !unit(c.wetnessNormalScale) || c.noiseTiling <= 0 || !nonnegative(c.proximityFade) ||
215 !nonnegative(c.distanceFadeBias) || !unit(c.globalColor[3]) || !unit(c.overlayColor[3]) ||
216 !std::all_of(c.globalColor.begin(), c.globalColor.begin() + 3, nonnegative) ||
217 !std::all_of(c.overlayColor.begin(), c.overlayColor.begin() + 3, nonnegative) || !unit(m.windPower) ||
218 m.noiseTiling <= 0 || m.bending < 0 || m.bending > 2 || m.branch < 0 || m.branch > 2 ||
219 m.flutter < 0 || m.flutter > 2 || !nonnegative(m.speed) || !nonnegative(m.fadeDistance) ||
220 result.volume.renderScale <= 0 || !unit(result.volume.edgeFade) ||
221 (result.volume.visibility != 0 && result.volume.visibility != 10 && result.volume.visibility != 20) ||
222 (result.volume.sorting != 0 && result.volume.sorting != 10 && result.volume.sorting != 20) ||
223 std::abs(std::hypot(m.direction[0], m.direction[1]) - 1.f) > 1e-4f ||
224 !std::all_of(result.volume.channels.begin(), result.volume.channels.end(), [](const auto& channel) {
225 return (channel.renderMode == -1 || channel.renderMode == 10 || channel.renderMode == 20) &&
226 channel.width >= 32 && channel.height >= 32 && channel.width <= 16384 && channel.height <= 16384;
227 }))
229 "vegetation scene values are out of range", {},
230 {}, "asset.graphics.vegetation-scene"));
231
232 Value detailDocument = Value::object({{"schema", "eve.graphics.vegetation-details"}, {"version", 1},
233 {"layers", member(*details, "layers")}, {"global", member(*details, "global")},
234 {"colorMask", member(*details, "colorMask")}, {"overlayMask", member(*details, "overlayMask")},
235 {"alphaThreshold", member(*details, "alphaThreshold")}, {"perspective", member(*details, "perspective")},
236 {"motionHighlight", member(*details, "motionHighlight")}, {"bending", member(*details, "bending")},
237 {"flutter", member(*details, "flutter")}, {"interactionAmplitude", member(*details, "interactionAmplitude")}});
238 auto restored = graphics::restoreVegetationDetails(detailDocument);
239 if (!restored) return Result<LoadedVegetationScene>::failure(restored.status());
240 result.details = std::move(restored).takeValue();
241
242 const auto* elementValues = member(*root, "elements").getIf<Value::Array>();
243 if (!elementValues || elementValues->size() > 4096)
245 "vegetation scene element count is invalid", {},
246 {}, "asset.graphics.vegetation-scene"));
247 result.elements.reserve(elementValues->size());
248 const std::set<std::string> kinds{
249 "color-effect", "color-map", "color-noise", "color-tint", "extras-alpha", "extras-emissive",
250 "extras-overlay", "extras-wetness", "motion-advanced", "motion-interaction", "motion-wind-power",
251 "vertex-conform-model", "vertex-conform-simple", "vertex-conform-terrain", "vertex-height-offset",
252 "vertex-height", "vertex-orientation-model", "vertex-orientation-terrain", "vertex-size"};
253 for (const auto& encoded : *elementValues) {
254 const auto* element = encoded.getIf<Value::Object>();
255 if (!element || !exact(*element, {"sourceFileId", "shaderGuid", "kind", "channel", "properties", "enabled", "visibility", "position",
256 "rotation", "scale", "layers", "intensity", "value", "seasonal",
257 "seasons", "textureGuid", "textureAsset", "remap", "blendRgb", "blendAlpha", "directionMode",
258 "invertDirection", "volumeFade", "motionMode", "motionPower"}))
260 "vegetation scene element is malformed", {},
261 {}, "asset.graphics.vegetation-scene"));
262 VegetationSceneElement decodedElement;
263 const auto& sourceFileId = member(*element, "sourceFileId");
264 const auto& shaderGuid = member(*element, "shaderGuid");
265 const auto& kind = member(*element, "kind");
266 const auto& channel = member(*element, "channel");
267 const auto& enabled = member(*element, "enabled");
268 const auto& visibility = member(*element, "visibility");
269 const auto& layers = member(*element, "layers");
270 const auto& seasonal = member(*element, "seasonal");
271 const auto& blendRgb = member(*element, "blendRgb");
272 const auto& blendAlpha = member(*element, "blendAlpha");
273 const auto& directionMode = member(*element, "directionMode");
274 const auto& invertDirection = member(*element, "invertDirection");
275 const auto& volumeFade = member(*element, "volumeFade");
276 const auto& motionMode = member(*element, "motionMode");
277 if (!sourceFileId.isInt64() || sourceFileId.asInt() == 0 || !kind.isString() || !kinds.contains(kind.asString()) ||
278 !channel.isInt64() || !enabled.isBool() || !visibility.isInt64() || !layers.isInt64() ||
279 !seasonal.isBool() || !blendRgb.isInt64() || !blendAlpha.isInt64() || !directionMode.isInt64() || !invertDirection.isBool() ||
280 !volumeFade.isBool() || !motionMode.isInt64() || !validGuid(shaderGuid, decodedElement.shaderGuid) ||
281 decodedElement.shaderGuid.empty() ||
282 !values(member(*element, "position"), decodedElement.position) ||
283 !values(member(*element, "rotation"), decodedElement.rotation) ||
284 !values(member(*element, "scale"), decodedElement.scale) ||
285 !values(member(*element, "value"), decodedElement.value) ||
286 !values(member(*element, "remap"), decodedElement.remap) ||
287 !numeric(member(*element, "intensity"), decodedElement.intensity) ||
288 !numeric(member(*element, "motionPower"), decodedElement.motionPower) ||
289 !validGuid(member(*element, "textureGuid"), decodedElement.textureGuid) ||
290 !member(*element, "textureAsset").isString())
292 Diagnostic::error(DiagnosticCode::ParseError, "vegetation scene element values are malformed", {}, {},
293 "asset.graphics.vegetation-scene"));
294 decodedElement.textureAsset = member(*element, "textureAsset").asString();
295 if (!decodedElement.textureAsset.empty() && !AssetRef::parse(decodedElement.textureAsset))
297 Diagnostic::error(DiagnosticCode::ParseError, "vegetation scene element texture asset is invalid", {},
298 {}, "asset.graphics.vegetation-scene"));
299 const auto* propertyValues = member(*element, "properties").getIf<Value::Array>();
300 if (!propertyValues || propertyValues->size() > 256)
302 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene element property count is invalid",
303 {}, {}, "asset.graphics.vegetation-scene"));
304 decodedElement.properties.reserve(propertyValues->size());
305 std::set<std::string> propertyNames;
306 for (const auto& encodedProperty : *propertyValues) {
307 const auto* property = encodedProperty.getIf<Value::Object>();
308 VegetationSceneElementProperty decodedProperty;
309 if (!property || !exact(*property, {"name", "type", "textureGuid", "textureAsset", "vector", "value"}) ||
310 !member(*property, "name").isString() || member(*property, "name").asString().empty() ||
311 member(*property, "name").asString().size() > 128 || !member(*property, "type").isInt64() ||
312 member(*property, "type").asInt() < 0 || member(*property, "type").asInt() > 2 ||
313 !validGuid(member(*property, "textureGuid"), decodedProperty.textureGuid) ||
314 !member(*property, "textureAsset").isString() ||
315 !values(member(*property, "vector"), decodedProperty.vector) ||
316 !numeric(member(*property, "value"), decodedProperty.value) ||
317 !propertyNames.emplace(member(*property, "name").asString()).second)
319 Diagnostic::error(DiagnosticCode::ParseError, "vegetation scene element property is malformed", {},
320 {}, "asset.graphics.vegetation-scene"));
321 decodedProperty.name = member(*property, "name").asString();
322 decodedProperty.type = std::int32_t(member(*property, "type").asInt());
323 decodedProperty.textureAsset = member(*property, "textureAsset").asString();
324 if (!decodedProperty.textureAsset.empty() && !AssetRef::parse(decodedProperty.textureAsset))
326 DiagnosticCode::ParseError, "vegetation scene element property texture asset is invalid", {}, {},
327 "asset.graphics.vegetation-scene"));
328 decodedElement.properties.push_back(std::move(decodedProperty));
329 }
330 const auto* seasonValues = member(*element, "seasons").getIf<Value::Array>();
331 if (!seasonValues || seasonValues->size() != 4)
333 "vegetation scene seasons are malformed",
334 {}, {}, "asset.graphics.vegetation-scene"));
335 for (std::size_t index = 0; index < 4; ++index)
336 if (!values((*seasonValues)[index], decodedElement.seasons[index]))
338 Diagnostic::error(DiagnosticCode::ParseError, "vegetation scene season is malformed", {}, {},
339 "asset.graphics.vegetation-scene"));
340 const auto rawChannel = channel.asInt(), rawVisibility = visibility.asInt(), rawLayers = layers.asInt();
341 const auto rawBlendRgb = blendRgb.asInt(), rawBlendAlpha = blendAlpha.asInt();
342 const auto rawDirectionMode = directionMode.asInt(), rawMotionMode = motionMode.asInt();
343 if (rawChannel < 0 || rawChannel > 3 || rawVisibility < -1 || rawVisibility > 20 || rawLayers < 1 ||
344 rawLayers > 0x1ff || rawBlendRgb < 0 || rawBlendRgb > 2 || rawBlendAlpha < 0 || rawBlendAlpha > 1 ||
345 rawDirectionMode < 10 || rawDirectionMode > 40 ||
346 rawMotionMode < 13 || rawMotionMode > 15)
348 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene element integers are out of range",
349 {}, {}, "asset.graphics.vegetation-scene"));
350 decodedElement.sourceFileId = sourceFileId.asInt(); decodedElement.kind = kind.asString();
351 decodedElement.channel = std::uint32_t(rawChannel); decodedElement.enabled = enabled.asBool();
352 decodedElement.visibility = std::int32_t(rawVisibility); decodedElement.layers = std::uint16_t(rawLayers);
353 decodedElement.seasonal = seasonal.asBool(); decodedElement.blendRgb = std::int32_t(rawBlendRgb);
354 decodedElement.blendAlpha = std::int32_t(rawBlendAlpha);
355 decodedElement.directionMode = std::int32_t(directionMode.asInt());
356 decodedElement.invertDirection = invertDirection.asBool(); decodedElement.volumeFade = volumeFade.asBool();
357 decodedElement.motionMode = std::int32_t(motionMode.asInt());
358 const float rotationLength = std::sqrt(std::inner_product(decodedElement.rotation.begin(), decodedElement.rotation.end(),
359 decodedElement.rotation.begin(), 0.f));
360 const std::uint32_t expectedChannel = decodedElement.kind.starts_with("color-") ? 0u :
361 decodedElement.kind.starts_with("extras-") ? 1u : decodedElement.kind.starts_with("motion-") ? 2u : 3u;
362 if (decodedElement.channel > 3 || decodedElement.channel != expectedChannel ||
363 (decodedElement.visibility != -1 && decodedElement.visibility != 0 && decodedElement.visibility != 10 &&
364 decodedElement.visibility != 20) || decodedElement.layers == 0 || (decodedElement.layers & ~0x1ffu) ||
365 !unit(decodedElement.intensity) || !unit(decodedElement.motionPower) ||
366 std::abs(rotationLength - 1.f) > 1e-3f ||
367 std::any_of(decodedElement.scale.begin(), decodedElement.scale.end(), [](float value) { return value <= 0; }) ||
368 decodedElement.remap[0] > decodedElement.remap[1] || decodedElement.remap[2] > decodedElement.remap[3] ||
369 decodedElement.remap[4] > decodedElement.remap[5] ||
370 (decodedElement.blendRgb < 0 || decodedElement.blendRgb > 2) ||
371 (decodedElement.blendAlpha < 0 || decodedElement.blendAlpha > 1) ||
372 (decodedElement.directionMode != 10 && decodedElement.directionMode != 20 &&
373 decodedElement.directionMode != 30 && decodedElement.directionMode != 40) ||
374 (decodedElement.motionMode != 13 && decodedElement.motionMode != 15))
376 "vegetation scene element is out of range",
377 {}, {}, "asset.graphics.vegetation-scene"));
378 result.elements.push_back(std::move(decodedElement));
379 }
381}
382
384 const graphics::VegetationMotion& baseMotion,
385 const LoadedVegetationScene& scene) {
386 auto detailed = graphics::configureVegetationDetails(baseSurface, baseMotion, scene.details);
387 if (!detailed) return Result<VegetationSceneProjection>::failure(detailed.status());
388 VegetationSceneProjection result{std::move(detailed.value().surface), std::move(detailed.value().motion),
389 scene.volume, scene.control.season};
390 const auto& c = scene.control;
391 auto& s = result.surface;
392 s.vegetationColor.fieldColor = c.globalColor;
393 s.vegetationColor.overlay *= c.globalOverlay;
394 s.vegetationColor.wetness *= c.globalWetness;
395 s.vegetationColor.overlayColor = {c.overlayColor[0], c.overlayColor[1], c.overlayColor[2]};
396 s.vegetationColor.overlaySmoothness = c.overlaySmoothness;
397 s.vegetationColor.overlayNormalScale = c.overlayNormalScale;
398 s.vegetationColor.overlaySubsurface = c.overlaySubsurface;
399 s.vegetationColor.wetnessContrast = c.wetnessContrast;
400 s.vegetationColor.wetnessNormalScale = c.wetnessNormalScale;
401 s.vegetationAlpha.enabled = true;
402 s.vegetationAlpha.global *= c.globalAlpha;
403 s.vegetationAlpha.cameraFadeMin = (c.proximityFade + .01f) * .5f;
404 s.vegetationAlpha.cameraFadeMax = c.proximityFade + .01f;
405 if (s.vegetationEmission.enabled) s.vegetationEmission.global *= c.globalEmissive;
406 s.translucency.globalIntensity *= c.globalSubsurface;
407 s.vegetationVertex.globalSize *= c.globalSize;
408 s.vegetationVertex.distanceFadeBias *= c.distanceFadeBias + .01f;
409 auto& gpu = s.vegetationMotion;
410 gpu.fallback[2] = scene.motion.windPower;
411 gpu.globalDirection = scene.motion.direction;
412 gpu.globalBending *= scene.motion.bending;
413 gpu.globalBranch *= scene.motion.branch;
414 gpu.globalFlutter *= scene.motion.flutter;
415 gpu.noiseTiling *= scene.motion.noiseTiling;
416 gpu.fadeDistance = scene.motion.fadeDistance;
417 auto& cpu = result.motion;
418 cpu.globalBending *= scene.motion.bending;
419 cpu.globalBranch *= scene.motion.branch;
420 cpu.globalFlutter *= scene.motion.flutter;
421 cpu.noiseTiling *= scene.motion.noiseTiling;
422 cpu.fadeDistance = scene.motion.fadeDistance;
423 cpu.timeScale *= scene.motion.speed;
424 cpu.globalSize *= c.globalSize;
425 cpu.distanceFadeBias *= c.distanceFadeBias + .01f;
429}
430
432 const asset::EvpackResourceReader& reader, const LoadedVegetationScene& scene,
433 const asset::EvpackCapabilities& capabilities, std::uint64_t maximumDecodedBytes) {
434 try {
435 std::map<std::string, std::string> required;
436 auto admit = [&](const std::string& guid, const std::string& asset) -> Result<void> {
437 if (guid.empty()) return Result<void>::success();
438 if (asset.empty())
440 "vegetation element texture dependency is unavailable", guid,
441 {}, "asset.graphics.vegetation-scene"));
442 const auto [position, inserted] = required.emplace(guid, asset);
443 if (!inserted && position->second != asset)
445 "vegetation element texture GUID has conflicting assets",
446 guid, {}, "asset.graphics.vegetation-scene"));
447 return Result<void>::success();
448 };
449 for (const auto& element : scene.elements) {
450 auto admitted = admit(element.textureGuid, element.textureAsset);
451 if (!admitted) return Result<std::map<std::string, graphics::VegetationMask>>::failure(admitted.status());
452 for (const auto& property : element.properties) {
453 if (property.type != 0 || (property.name != "_MainTex" && property.name != "_NoiseTex")) continue;
454 admitted = admit(property.textureGuid, property.textureAsset);
455 if (!admitted) return Result<std::map<std::string, graphics::VegetationMask>>::failure(admitted.status());
456 }
457 }
458 std::map<std::string, graphics::VegetationMask> output;
459 std::uint64_t usedBytes = 0;
460 for (const auto& [guid, encodedAsset] : required) {
461 if (usedBytes >= maximumDecodedBytes)
463 DiagnosticCode::InvalidArgument, "vegetation element masks exceed aggregate decoded budget", {}, {},
464 "asset.graphics.vegetation-scene"));
465 auto image = AssetRef::parse(encodedAsset);
469 limits.maximumPixels = 4 * 1024 * 1024;
470 limits.maximumDecodedBytes = maximumDecodedBytes - usedBytes;
471 auto decoded = asset::decodeEvpackImage(reader, image.value(), capabilities, limits);
472 if (!decoded) return Result<std::map<std::string, graphics::VegetationMask>>::failure(decoded.status());
473 const std::uint64_t pixelCount = std::uint64_t(decoded.value().width) * decoded.value().height;
474 const std::uint64_t decodedBytes = decoded.value().pixels.size();
475 const std::uint64_t maskBytes = pixelCount * sizeof(glm::vec4);
476 if (decodedBytes > maximumDecodedBytes - usedBytes ||
477 maskBytes > maximumDecodedBytes - usedBytes - decodedBytes)
479 DiagnosticCode::InvalidArgument, "vegetation element masks exceed aggregate decoded budget", {}, {},
480 "asset.graphics.vegetation-scene"));
482 mask.width = decoded.value().width;
483 mask.height = decoded.value().height;
484 mask.pixels.resize(std::size_t(pixelCount));
485 for (std::size_t index = 0; index < mask.pixels.size(); ++index) {
486 const auto offset = index * 4;
487 mask.pixels[index] = {decoded.value().pixels[offset] / 255.f, decoded.value().pixels[offset + 1] / 255.f,
488 decoded.value().pixels[offset + 2] / 255.f,
489 decoded.value().pixels[offset + 3] / 255.f};
490 }
491 usedBytes += decodedBytes + maskBytes;
492 output.emplace(guid, std::move(mask));
493 }
495 } catch (const std::bad_alloc&) {
497 Diagnostic::error(DiagnosticCode::Failed, "vegetation element mask allocation failed", {}, {},
498 "asset.graphics.vegetation-scene"));
499 }
500}
501
504 if (!finite(input.localUv) || !finite(input.mainSample) || !finite(input.elementParams) ||
505 !finite(input.vertexColor) || !std::isfinite(input.worldPosition.x) || !std::isfinite(input.worldPosition.y) ||
506 !std::isfinite(input.worldPosition.z) || !std::isfinite(input.worldNormal.x) || !std::isfinite(input.worldNormal.y) ||
507 !std::isfinite(input.worldNormal.z) || !finite(input.velocityDirection) || !finite(input.noiseSample) ||
508 !std::isfinite(input.terrainHeight) ||
509 !unit(input.volumeFade) || !std::isfinite(input.season) || input.season < 0.f ||
510 input.season > 4.f || !unit(element.intensity) || element.blendRgb < 0 || element.blendRgb > 2 ||
511 element.blendAlpha < 0 || element.blendAlpha > 1)
513 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation element pixel inputs are invalid", {}, {},
514 "asset.graphics.vegetation-scene"));
515
517 output.blendRgb = element.blendRgb;
518 output.blendAlpha = element.blendAlpha;
520
521 const glm::vec3 remappedRgb(
522 remap(input.mainSample.r, element.remap[0], element.remap[1], 0.f),
523 remap(input.mainSample.g, element.remap[0], element.remap[1], 0.f),
524 remap(input.mainSample.b, element.remap[0], element.remap[1], 0.f));
525 const float remappedAlpha = remap(input.mainSample.a, element.remap[2], element.remap[3], .0001f);
526 const glm::vec2 centered = input.localUv * 2.f - 1.f;
527 const float radial = std::clamp(std::clamp(1.f - glm::length(centered), 0.f, 1.f), .0001f, .9999f);
528 const float falloff = remap(radial, element.remap[4], element.remap[5], .0001f);
529 const float volume = element.volumeFade ? input.volumeFade : 1.f;
530 const float alpha = element.intensity * remappedAlpha * input.elementParams.a * input.vertexColor.a * falloff * volume;
531 const glm::vec4 selected = seasonal(element, input.season);
532 const float scalar = selected.x * remappedRgb.x * input.elementParams.x * input.vertexColor.r;
533 const float alphaBlend = element.blendAlpha == 0 ? glm::mix(1.f, scalar, alpha) : scalar * alpha;
534
535 if (element.kind == "color-effect") {
536 output.value = {0.f, 0.f, 0.f, alphaBlend};
537 output.colorMask = 1;
539 output.alphaOperation = element.blendAlpha == 0 ? VegetationScenePixelBlend::Multiply
541 } else if (element.kind == "color-map") {
542 output.value = {selected.r * remappedRgb.r, selected.g * remappedRgb.g, selected.b * remappedRgb.b,
543 selected.a * alpha};
544 } else if (element.kind == "color-noise") {
545 const float minimum = propertyScalar(element, "_NoiseMinValue", 0.f);
546 const float maximum = propertyScalar(element, "_NoiseMaxValue", 1.f);
547 const float noise = maximum == minimum ? (input.noiseSample.r >= maximum ? 1.f : 0.f)
548 : std::clamp((input.noiseSample.r - minimum) / (maximum - minimum), 0.f, 1.f);
549 const glm::vec4 one = propertyVector(element, "_NoiseColorOne", glm::vec4(1.f));
550 const glm::vec4 two = propertyVector(element, "_NoiseColorTwo", glm::vec4(1.f));
551 const glm::vec4 color = glm::mix(one, two, noise);
552 output.value = {color.r, color.g, color.b, color.a * alpha * selected.a};
553 } else if (element.kind == "color-tint") {
554 output.value = {selected.r * remappedRgb.r * input.elementParams.r * input.vertexColor.r,
555 selected.g * remappedRgb.g * input.elementParams.g * input.vertexColor.g,
556 selected.b * remappedRgb.b * input.elementParams.b * input.vertexColor.b,
557 selected.a * alpha};
558 output.alphaOperation = VegetationScenePixelBlend::Add;
559 } else if (element.kind == "extras-alpha") {
560 output.value = {scalar, 0.f, 0.f, alphaBlend};
561 output.colorMask = 1;
563 output.alphaOperation = element.blendAlpha == 0 ? VegetationScenePixelBlend::Multiply
565 } else if (element.kind == "extras-emissive") {
566 output.value = {scalar, 0.f, 0.f, alpha};
567 output.colorMask = 8;
568 } else if (element.kind == "extras-overlay") {
569 output.value = {0.f, 0.f, scalar, alpha};
570 output.colorMask = 2;
571 } else if (element.kind == "extras-wetness") {
572 output.value = {0.f, scalar, 0.f, alpha};
573 output.colorMask = 4;
574 } else if (element.kind == "motion-wind-power") {
575 output.value = {0.f, 0.f, scalar, alpha};
576 output.colorMask = 2;
577 } else if (element.kind == "motion-advanced") {
578 const glm::vec3 forward3 = rotate(element.rotation, glm::vec3(0.f, 0.f, 1.f));
579 const glm::vec3 texture3 = rotate(
580 element.rotation, glm::vec3(remappedRgb.r * 2.f - 1.f, 0.f, remappedRgb.g * 2.f - 1.f));
581 glm::vec2 direction;
582 switch (element.directionMode) {
583 case 10: direction = {forward3.x, forward3.z}; break;
584 case 20: direction = {texture3.x, texture3.z}; break;
585 case 30: direction = glm::vec2(input.vertexColor) * 2.f - 1.f; break;
586 case 40: direction = input.velocityDirection; break;
587 default:
589 Diagnostic::error(DiagnosticCode::InvalidArgument, "TVE advanced motion direction mode is invalid",
590 {}, {}, "asset.graphics.vegetation-scene"));
591 }
592 if (element.invertDirection) direction = -direction;
593 const float noiseMinimum = propertyScalar(element, "_NoiseMinValue", 0.f);
594 const float noiseMaximum = propertyScalar(element, "_NoiseMaxValue", 1.f);
595 const float noiseDenominator = noiseMaximum - noiseMinimum;
596 glm::vec2 noise = noiseDenominator == 0.f
597 ? glm::step(glm::vec2(noiseMaximum), glm::vec2(input.noiseSample))
598 : glm::clamp((glm::vec2(input.noiseSample) - noiseMinimum) / noiseDenominator,
599 glm::vec2(0.f), glm::vec2(1.f));
600 const float noiseIntensity = propertyScalar(element, "_NoiseIntensityValue", 0.f);
601 const glm::vec2 encoded = glm::clamp(glm::mix(direction * .5f + .5f, noise, noiseIntensity),
602 glm::vec2(0.f), glm::vec2(1.f));
603 output.value = {encoded.x, encoded.y, element.motionPower,
604 element.intensity * remappedAlpha * input.elementParams.a * input.vertexColor.a * volume};
605 output.colorMask = std::uint8_t(element.motionMode);
606 output.alphaOperation = VegetationScenePixelBlend::Add;
607 } else if (element.kind == "vertex-size") {
608 output.value = {scalar, 0.f, 0.f, alphaBlend};
609 output.colorMask = 1;
611 output.alphaOperation = element.blendAlpha == 0 ? VegetationScenePixelBlend::Multiply
613 } else if (element.kind == "motion-interaction") {
614 const glm::vec3 localDirection(remappedRgb.r * 2.f - 1.f, 0.f, remappedRgb.g * 2.f - 1.f);
615 glm::vec3 worldDirection = rotate(element.rotation, localDirection);
616 if (element.invertDirection) worldDirection = -worldDirection;
617 output.value = {std::clamp(worldDirection.x * .5f + .5f, 0.f, 1.f),
618 std::clamp(worldDirection.z * .5f + .5f, 0.f, 1.f), element.motionPower,
619 element.intensity * remappedAlpha * input.elementParams.a * input.vertexColor.a * volume};
620 output.colorMask = std::uint8_t(element.motionMode);
621 output.alphaOperation = VegetationScenePixelBlend::Add;
622 } else if (element.kind == "vertex-conform-model") {
623 output.value = {0.f, 0.f, input.worldPosition.y + propertyScalar(element, "_HeightOffsetValue", 0.f),
624 element.intensity * volume};
625 output.colorMask = 2;
626 } else if (element.kind == "vertex-conform-simple") {
627 output.value = {0.f, 0.f, input.mainSample.r * propertyScalar(element, "_HeightValue", 1.f) +
628 propertyScalar(element, "_HeightOffsetValue", 0.f),
629 element.intensity * volume};
630 output.colorMask = 2;
631 } else if (element.kind == "vertex-conform-terrain") {
632 output.value = {0.f, 0.f, input.terrainHeight + propertyScalar(element, "_HeightOffsetValue", 0.f),
633 element.intensity * volume};
634 output.colorMask = 2;
635 } else if (element.kind == "vertex-height-offset") {
636 output.value = {0.f, 0.f, propertyScalar(element, "_HeightOffsetValue", 0.f) * remappedAlpha *
637 element.intensity * volume,
638 0.f};
639 output.colorMask = 2;
641 } else if (element.kind == "vertex-height") {
642 output.value = {0.f, 0.f, scalar * propertyScalar(element, "_HeightValue", 1.f) +
643 propertyScalar(element, "_HeightOffsetValue", 0.f),
644 alpha};
645 output.colorMask = 2;
646 } else if (element.kind == "vertex-orientation-model") {
647 const glm::vec3 normal = glm::length(input.worldNormal) > 0.f ? glm::normalize(input.worldNormal)
648 : glm::vec3(0.f, 1.f, 0.f);
649 output.value = {normal.x * .5f + .5f, normal.z * .5f + .5f, 0.f, element.intensity * volume};
650 output.colorMask = 12;
651 } else if (element.kind == "vertex-orientation-terrain") {
652 output.value = {input.mainSample.r, input.mainSample.b, 0.f, element.intensity * volume};
653 output.colorMask = 12;
654 } else {
656 Diagnostic::error(DiagnosticCode::Unsupported, "TVE Element pixel shader is not implemented", element.kind,
657 {}, "asset.graphics.vegetation-scene"));
658 }
659 if (!finite(output.value))
661 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation element pixel evaluation overflowed", {}, {},
662 "asset.graphics.vegetation-scene"));
664}
665
666glm::vec4 composeVegetationSceneElementPixel(glm::vec4 destination,
667 const VegetationSceneElementPixel& source) noexcept {
668 auto apply = [&](float dst, float src, VegetationScenePixelBlend operation) {
669 switch (operation) {
670 case VegetationScenePixelBlend::Alpha: return src * source.value.a + dst * (1.f - source.value.a);
671 case VegetationScenePixelBlend::Multiply: return src * dst;
672 case VegetationScenePixelBlend::Add: return src + dst;
673 case VegetationScenePixelBlend::Replace: return src;
674 }
675 return dst;
676 };
677 glm::vec4 result = destination;
678 if (source.colorMask & 8) result.r = apply(destination.r, source.value.r, source.rgbOperation);
679 if (source.colorMask & 4) result.g = apply(destination.g, source.value.g, source.rgbOperation);
680 if (source.colorMask & 2) result.b = apply(destination.b, source.value.b, source.rgbOperation);
681 if (source.colorMask & 1) result.a = apply(destination.a, source.value.a, source.alphaOperation);
682 return result;
683}
684
686 const LoadedVegetationScene& scene, const std::map<std::string, graphics::VegetationMask>& masks,
687 graphics::VegetationChannel channel, const graphics::VegetationChannelAtlas& base, std::uint8_t layer,
688 std::span<const glm::vec3> worldNormals, std::span<const float> terrainHeights,
689 std::span<const glm::vec4> noiseSamples) {
690 const std::uint64_t pixelCount64 = std::uint64_t(base.width) * base.height;
691 if (base.width == 0 || base.height == 0 || base.width > 2048 || base.height > 2048 ||
692 pixelCount64 > 4 * 1024 * 1024 || !std::isfinite(base.center.x) || !std::isfinite(base.center.y) ||
693 !std::isfinite(base.center.z) || !std::isfinite(base.extent.x) || !std::isfinite(base.extent.y) ||
694 !std::isfinite(base.extent.z) || base.extent.x <= 0.f || base.extent.y <= 0.f || base.extent.z <= 0.f ||
695 layer > 8)
697 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene channel geometry or layer is invalid",
698 {}, {}, "asset.graphics.vegetation-scene"));
699 const std::size_t pixelCount = std::size_t(pixelCount64);
700 if (base.pixels.size() != pixelCount ||
701 (!worldNormals.empty() && worldNormals.size() != pixelCount) ||
702 (!terrainHeights.empty() && terrainHeights.size() != pixelCount) ||
703 (!noiseSamples.empty() && noiseSamples.size() != pixelCount))
705 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene channel input sizes are inconsistent",
706 {}, {}, "asset.graphics.vegetation-scene"));
707 try {
709 const std::size_t channelIndex = static_cast<std::size_t>(channel);
710 const double stepX = 2.0 * base.extent.x / base.width;
711 const double stepZ = 2.0 * base.extent.z / base.height;
712 for (const auto& element : scene.elements) {
713 if (!element.enabled || element.channel != channelIndex || !(element.layers & (1u << layer))) continue;
714 const graphics::VegetationMask* mask = nullptr;
715 if (!element.textureGuid.empty()) {
716 const auto found = masks.find(element.textureGuid);
717 if (found == masks.end())
719 Diagnostic::error(DiagnosticCode::NotFound, "vegetation scene element mask is missing",
720 element.textureGuid, {}, "asset.graphics.vegetation-scene"));
721 mask = &found->second;
722 }
723 for (std::uint32_t y = 0; y < base.height; ++y) {
724 for (std::uint32_t x = 0; x < base.width; ++x) {
725 const std::size_t index = std::size_t(y) * base.width + x;
726 const glm::vec3 world(float(double(base.center.x) - base.extent.x + (x + .5) * stepX),
727 base.center.y,
728 float(double(base.center.z) - base.extent.z + (y + .5) * stepZ));
729 const glm::vec3 delta = world - glm::vec3(element.position[0], element.position[1], element.position[2]);
730 const glm::vec3 local = inverseRotate(element.rotation, delta) /
731 glm::vec3(element.scale[0], element.scale[1], element.scale[2]);
732 const glm::vec2 uv(local.x + .5f, local.z + .5f);
733 if (uv.x < 0.f || uv.x > 1.f || uv.y < 0.f || uv.y > 1.f) continue;
735 input.localUv = uv;
736 const bool flipped = element.kind == "motion-interaction" || element.kind == "motion-advanced" ||
737 element.kind == "vertex-conform-simple" ||
738 element.kind == "vertex-orientation-terrain" ||
739 element.kind == "vertex-height-offset";
740 input.mainSample = mask ? sampleMask(*mask, flipped ? glm::vec2(1.f) - uv : uv) : glm::vec4(1.f);
741 input.worldPosition = world;
742 if (!worldNormals.empty()) input.worldNormal = worldNormals[index];
743 if (!terrainHeights.empty()) input.terrainHeight = terrainHeights[index];
744 if (!noiseSamples.empty()) input.noiseSample = noiseSamples[index];
745 input.season = scene.control.season;
746 if (element.volumeFade) {
747 const glm::vec2 atlasUv((world.x - base.center.x) / (2.f * base.extent.x) + .5f,
748 (world.z - base.center.z) / (2.f * base.extent.z) + .5f);
749 const glm::vec2 edge = glm::abs(atlasUv * 2.002f - 1.001f);
750 if (scene.volume.edgeFade >= 1.f)
751 input.volumeFade = edge.x <= 1.f && edge.y <= 1.f ? 1.f : 0.f;
752 else {
753 const glm::vec2 faded = glm::clamp((edge - scene.volume.edgeFade) /
754 (1.f - scene.volume.edgeFade),
755 glm::vec2(0.f), glm::vec2(1.f));
756 input.volumeFade = 1.f - std::clamp(glm::dot(faded, faded), 0.f, 1.f);
757 }
758 }
762 }
763 }
764 }
766 } catch (const std::bad_alloc&) {
768 Diagnostic::error(DiagnosticCode::Failed, "vegetation scene channel allocation failed", {}, {},
769 "asset.graphics.vegetation-scene"));
770 }
771}
772
774 const LoadedVegetationScene& scene, const std::map<std::string, graphics::VegetationMask>& masks,
775 const graphics::VegetationAtlas& base, std::array<std::uint8_t, 4> layers,
776 std::span<const glm::vec3> worldNormals, std::span<const float> terrainHeights,
777 std::span<const glm::vec4> noiseSamples) {
779 output.width = base.width;
780 output.height = base.height;
781 output.center = base.center;
782 output.extent = base.extent;
783 for (std::size_t index = 0; index < 4; ++index) {
784 graphics::VegetationChannelAtlas channelBase{base.width, base.height, base.center, base.extent,
785 base.channels[index]};
786 auto baked = bakeVegetationSceneChannel(scene, masks, static_cast<graphics::VegetationChannel>(index),
787 channelBase, layers[index], worldNormals, terrainHeights, noiseSamples);
788 if (!baked) return Result<graphics::VegetationAtlas>::failure(baked.status());
789 output.channels[index] = std::move(baked).takeValue().pixels;
790 }
792}
793
796 const std::uint64_t pixelCount64 = std::uint64_t(tveAtlas.width) * tveAtlas.height;
797 if (tveAtlas.width == 0 || tveAtlas.height == 0 || tveAtlas.width > 2048 || tveAtlas.height > 2048 ||
798 pixelCount64 > 4 * 1024 * 1024 || !std::isfinite(tveAtlas.center.x) || !std::isfinite(tveAtlas.center.y) ||
799 !std::isfinite(tveAtlas.center.z) || !std::isfinite(tveAtlas.extent.x) ||
800 !std::isfinite(tveAtlas.extent.y) || !std::isfinite(tveAtlas.extent.z) || tveAtlas.extent.x <= 0.f ||
801 tveAtlas.extent.y <= 0.f || tveAtlas.extent.z <= 0.f)
803 Diagnostic::error(DiagnosticCode::InvalidArgument, "TVE vegetation channel geometry is invalid", {}, {},
804 "asset.graphics.vegetation-scene"));
805 const std::size_t pixelCount = std::size_t(pixelCount64);
806 if (tveAtlas.pixels.size() != pixelCount ||
807 std::any_of(tveAtlas.pixels.begin(), tveAtlas.pixels.end(), [](glm::vec4 value) { return !finite(value); }))
809 Diagnostic::error(DiagnosticCode::InvalidArgument, "TVE vegetation channel pixels are invalid", {}, {},
810 "asset.graphics.vegetation-scene"));
811 try {
812 graphics::VegetationChannelAtlas native = tveAtlas;
814 for (auto& motion : native.pixels) {
815 motion.x = motion.x * 2.f - 1.f;
816 motion.y = motion.y * 2.f - 1.f;
817 }
818 }
820 } catch (const std::bad_alloc&) {
822 Diagnostic::error(DiagnosticCode::Failed, "native vegetation channel allocation failed", {}, {},
823 "asset.graphics.vegetation-scene"));
824 }
825}
826
828 const graphics::VegetationAtlas& tveAtlas) {
830 native.width = tveAtlas.width;
831 native.height = tveAtlas.height;
832 native.center = tveAtlas.center;
833 native.extent = tveAtlas.extent;
834 for (std::size_t index = 0; index < 4; ++index) {
835 graphics::VegetationChannelAtlas source{tveAtlas.width, tveAtlas.height, tveAtlas.center, tveAtlas.extent,
836 tveAtlas.channels[index]};
838 if (!converted) return Result<graphics::VegetationAtlas>::failure(converted.status());
839 native.channels[index] = std::move(converted).takeValue().pixels;
840 }
841 return Result<graphics::VegetationAtlas>::success(std::move(native));
842}
843
845 graphics::IResourceFactory& factory, const graphics::PbrSurface& baseSurface,
846 const graphics::VegetationMotion& baseMotion, const LoadedVegetationScene& scene,
847 const std::map<std::string, graphics::VegetationMask>& masks, const VegetationSceneGpuBuild& build) {
848 if (build.sourceRevision == 0)
850 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene GPU revision must be nonzero", {}, {},
851 "asset.graphics.vegetation-scene"));
852 auto projected = projectVegetationScene(baseSurface, baseMotion, scene);
853 if (!projected) return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::failure(projected.status());
854 try {
855 std::array<std::array<graphics::VegetationChannelAtlas, 9>, 4> nativeChannels;
856 for (std::size_t channel = 0; channel < nativeChannels.size(); ++channel) {
857 const auto& input = build.channels[channel];
858 for (std::uint8_t layer = 0; layer < nativeChannels[channel].size(); ++layer) {
859 auto tve = bakeVegetationSceneChannel(scene, masks,
860 static_cast<graphics::VegetationChannel>(channel),
861 input.baseLayers[layer], layer, input.worldNormals,
862 input.terrainHeights, input.noiseSamples);
863 if (!tve) return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::failure(tve.status());
865 static_cast<graphics::VegetationChannel>(channel), tve.value());
866 if (!native) return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::failure(native.status());
867 nativeChannels[channel][layer] = std::move(native).takeValue();
868 }
869 }
870
871 auto runtime = std::unique_ptr<VegetationSceneGpuRuntime>(new VegetationSceneGpuRuntime(factory));
872 runtime->projection_ = std::move(projected).takeValue();
873 runtime->sourceRevision_ = build.sourceRevision;
874 auto uploaded = graphics::uploadVegetationGpuFieldSet(factory, nativeChannels[0], nativeChannels[1],
875 nativeChannels[2], nativeChannels[3],
876 build.sourceRevision);
877 if (!uploaded) return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::failure(uploaded.status());
878 runtime->fields_ = std::move(uploaded).takeValue();
879
881 const auto& motion = runtime->projection_.surface.vegetationMotion;
882 gpu.motionDirection = motion.globalDirection;
884 gpu.time = runtime->projection_.motion.time;
885 gpu.globalBending = motion.globalBending;
886 gpu.globalBranch = motion.globalBranch;
887 gpu.globalFlutter = motion.globalFlutter;
888 gpu.noiseTiling = motion.noiseTiling;
889 gpu.motionFadeDistance = motion.fadeDistance;
890 gpu.cameraFadeMin = runtime->projection_.surface.vegetationAlpha.cameraFadeMin;
891 gpu.cameraFadeMax = runtime->projection_.surface.vegetationAlpha.cameraFadeMax;
892 gpu.fadeNoiseTiling = runtime->projection_.surface.vegetationAlpha.noiseTiling;
893 auto bound = graphics::bindVegetationGpuFields(runtime->projection_.surface, runtime->fields_,
894 build.sourceRevision, gpu);
895 if (!bound) {
896 auto released = runtime->release();
897 if (!released)
899 Diagnostic::error(DiagnosticCode::Failed, "vegetation scene GPU binding rollback failed", {}, {},
900 "asset.graphics.vegetation-scene"));
901 return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::failure(bound.status());
902 }
903 return Result<std::unique_ptr<VegetationSceneGpuRuntime>>::success(std::move(runtime));
904 } catch (const std::bad_alloc&) {
906 Diagnostic::error(DiagnosticCode::Failed, "vegetation scene GPU runtime allocation failed", {}, {},
907 "asset.graphics.vegetation-scene"));
908 }
909}
910
912 std::uint64_t expectedRevision, const graphics::PbrSurface& baseSurface,
913 const graphics::VegetationMotion& baseMotion, const LoadedVegetationScene& scene,
914 const std::map<std::string, graphics::VegetationMask>& masks, const VegetationSceneGpuBuild& build) {
915 if (!factory_)
917 Diagnostic::error(DiagnosticCode::Conflict, "released vegetation scene runtime cannot be replaced", {}, {},
918 "asset.graphics.vegetation-scene"));
919 if (expectedRevision != sourceRevision_)
921 Diagnostic::error(DiagnosticCode::Conflict, "vegetation scene GPU revision changed before replacement", {},
922 {}, "asset.graphics.vegetation-scene"));
923 if (build.sourceRevision <= sourceRevision_)
925 Diagnostic::error(DiagnosticCode::InvalidArgument, "vegetation scene replacement revision must increase",
926 {}, {}, "asset.graphics.vegetation-scene"));
927
928 auto candidate = create(*factory_, baseSurface, baseMotion, scene, masks, build);
929 if (!candidate) return Result<VegetationSceneGpuPublication>::failure(candidate.status());
930 try {
931 retiredFields_.reserve(retiredFields_.size() + 1);
932 retiredFields_.push_back(std::move(fields_));
933 } catch (const std::bad_alloc&) {
935 Diagnostic::error(DiagnosticCode::Failed, "vegetation scene replacement retirement allocation failed", {},
936 {}, "asset.graphics.vegetation-scene"));
937 }
938
939 fields_ = std::move(candidate.value()->fields_);
940 std::swap(projection_, candidate.value()->projection_);
941 sourceRevision_ = build.sourceRevision;
942 candidate.value()->factory_ = nullptr;
943
944 for (auto current = retiredFields_.begin(); current != retiredFields_.end();) {
945 auto released = graphics::releaseVegetationGpuFieldSet(*factory_, *current);
946 if (released)
947 current = retiredFields_.erase(current);
948 else
949 ++current;
950 }
951 return Result<VegetationSceneGpuPublication>::success({sourceRevision_, retiredFields_.size()});
952}
953
955 auto released = release();
956 if (!released)
957 std::fprintf(stderr, "vegetation scene GPU release failed: %s\n", released.error()->message().c_str());
958}
959
961 if (!factory_) return Result<void>::success();
962 projection_.surface.vegetationExtras.texture = nullptr;
963 projection_.surface.vegetationColors.texture = nullptr;
964 projection_.surface.vegetationMotion.texture = nullptr;
965 projection_.surface.vegetationVertex.texture = nullptr;
966 auto released = graphics::releaseVegetationGpuFieldSet(*factory_, fields_);
967 Status firstFailure;
968 if (!released) firstFailure = released.status();
969 for (auto current = retiredFields_.begin(); current != retiredFields_.end();) {
971 if (retired)
972 current = retiredFields_.erase(current);
973 else {
974 if (firstFailure.isSuccess()) firstFailure = retired.status();
975 ++current;
976 }
977 }
978 if (firstFailure.isFailure()) return Result<void>::failure(firstFailure);
979 factory_ = nullptr;
980 return Result<void>::success();
981}
982} // namespace eve::asset_graphics
double y
double m[16]
double x
ActionParameterOperation operation
Value::Object payload
int root
Definition AnimSmr.cpp:119
std::string selected
std::string output
double volume
const std::string & s
int mask
float uv
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
Backend-neutral canonical EVIMG decoding.
Runtime decoding and projection of TVE scene-manager state.
EvpackChunkInput input
Definition Evpack.cpp:170
float maximum[3]
float minimum[3]
vk::UniqueImage image
float u
Definition Grass.cpp:233
std::int32_t c
std::string local
size_t offset
std::array< float, 4 > rotation
std::array< float, 3 > position
bool required
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
std::shared_ptr< OceanGpuSpectrum > gpu
std::vector< OceanHullVolume > volumes
bool finite
TileLayer * layer
std::weak_ptr< PrimitiveScene > scene
std::set< std::string > values
Object::Ptr value
float t
std::string build
std::unordered_map< std::uint32_t, std::uint32_t > remap
RoadLaneDirection direction
bool found
JSON-free versioned runtime metadata codec.
std::string_view source
std::string kind
double current
std::string element
TacticalUnit * unit
float size
Definition TreeMesh.cpp:158
float(ui::Theme::* member)[4]
const AssetImportLimits & limits
uint32_t index
float fraction
Stable asset identity backed by PersistentId.
Definition ResourceRef.h:53
static Result< AssetRef > parse(std::string_view text)
Parse an asset://<canonical UUID> reference.
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
bool isSuccess() const noexcept
Whether the operation completed without a failure outcome.
Definition Status.h:105
bool isFailure() const noexcept
Whether the operation has a failure outcome.
Definition Status.h:122
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
Immutable reader retaining an admitted pack by shared ownership.
Result< RuntimeAssetPayload > read(const AssetRef &asset, std::string_view expectedType, const EvpackCapabilities &capabilities, std::uint64_t maximumDecodedBytes) const
Resolve, type-check, variant-select and decode a canonical runtime asset.
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.
Owning GPU publication of one immutable TVE manager scene. The resource factory, mask map and scene a...
const graphics::VegetationMotion & motion() const noexcept
Borrow the projected CPU motion snapshot; valid for this runtime's lifetime.
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.
Result< VegetationSceneGpuPublication > replace(std::uint64_t expectedRevision, const graphics::PbrSurface &baseSurface, const graphics::VegetationMotion &baseMotion, const LoadedVegetationScene &scene, const std::map< std::string, graphics::VegetationMask > &masks, const VegetationSceneGpuBuild &build)
Atomically replace this runtime after validating its observed revision. A complete candidate is built...
Result< void > release()
Invalidate material borrows and release all fields; failed entries remain owned for retry.
Texture / mesh / shader / canvas creation and release.
Result< graphics::VegetationChannelAtlas > convertVegetationSceneChannelToNative(graphics::VegetationChannel channel, const graphics::VegetationChannelAtlas &tveAtlas)
Convert one fully composed TVE channel atlas to EVEngine conventions.
Result< graphics::VegetationChannelAtlas > bakeVegetationSceneChannel(const LoadedVegetationScene &scene, const std::map< std::string, graphics::VegetationMask > &masks, graphics::VegetationChannel channel, const graphics::VegetationChannelAtlas &base, std::uint8_t layer, std::span< const glm::vec3 > worldNormals, std::span< const float > terrainHeights, std::span< const glm::vec4 > noiseSamples)
Bake one TVE manager channel at its own resolution and world mapping.
Result< VegetationSceneElementPixel > evaluateVegetationSceneElementPixel(const VegetationSceneElement &element, const VegetationSceneElementPixelInput &input)
Evaluate one TVE Element fragment using caller-supplied texture, instance and particle inputs.
Result< VegetationSceneProjection > projectVegetationScene(const graphics::PbrSurface &baseSurface, const graphics::VegetationMotion &baseMotion, const LoadedVegetationScene &scene)
Project validated TVE manager controls onto one material/motion snapshot.
Result< graphics::VegetationAtlas > convertVegetationSceneAtlasToNative(const graphics::VegetationAtlas &tveAtlas)
Convert a fully composed TVE render-target atlas to EVEngine field channel conventions.
VegetationScenePixelBlend
Detached TVE render-target source value and independent hardware blend policy.
Result< graphics::VegetationAtlas > bakeVegetationSceneElements(const LoadedVegetationScene &scene, const std::map< std::string, graphics::VegetationMask > &masks, const graphics::VegetationAtlas &base, std::array< std::uint8_t, 4 > layers, std::span< const glm::vec3 > worldNormals, std::span< const float > terrainHeights, std::span< const glm::vec4 > noiseSamples)
Rasterize the ordered TVE Element list over an owning four-channel atlas candidate.
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.
glm::vec4 composeVegetationSceneElementPixel(glm::vec4 destination, const VegetationSceneElementPixel &source) noexcept
Apply one evaluated source pixel to a destination with TVE's separate blend factors and ColorMask.
bool validGuid(std::string_view value)
Valid guid.
Result< Value > decodeRuntimeDefinition(std::span< const std::uint8_t > bytes, const RuntimeDefinitionLimits &limits)
Decode a bounded EVDEF\0\1 metadata tree without a JSON parser.
Result< DecodedEvpackImage > decodeEvpackImage(const EvpackResourceReader &reader, const AssetRef &image, const EvpackCapabilities &capabilities, const EvpackImageDecodeLimits &limits)
Decode and validate canonical eve.image/3 data with eve.image/2 compatibility.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Result< VegetationDetailSettings > restoreVegetationDetails(const Value &document)
Decode one exact Global Details document transactionally.
Result< void > releaseVegetationGpuFieldSet(IResourceFactory &factory, VegetationGpuFieldSet &set)
Release every texture still present in a detached field set. Successful entries are nulled....
VegetationChannel
Independent vegetation field channels; values use linear color and world units.
Result< VegetationGpuFieldSet > uploadVegetationGpuFieldSet(IResourceFactory &factory, const VegetationField &field, glm::vec3 center, glm::vec3 extent, uint32_t width, uint32_t height, bool snapToTexel)
Bake and upload all four nine-layer projections as one publication. Earlier uploads are released if a...
Result< void > validatePbrSurface(const PbrSurface &s)
Validate finite material factors and sampler enums without changing the input.
Result< void > bindVegetationGpuFields(PbrSurface &surface, const VegetationField &field, const VegetationExtrasGpuAtlas &extras, const VegetationColorsGpuAtlas &colors, const VegetationMotionGpuAtlas &motion, const VegetationVertexGpuAtlas &vertex, const VegetationGpuRuntime &runtime)
Atomically bind four coherent GPU projections to an owning PBR parameter snapshot.
Result< VegetationDetailRuntime > configureVegetationDetails(const PbrSurface &baseSurface, const VegetationMotion &baseMotion, const VegetationDetailSettings &s)
Validate and project TVE Global Details into native PBR and motion snapshots.
SocketDirection rotate(SocketDirection direction, int degrees)
Result< float > readFiniteFloatValue(const Value &value)
Convert an Integer or Double to a finite Float after validating its source range.
Definition Value.cpp:81
bool enabled
Actual runtime device capabilities used for variant selection.
Definition Evpack.h:92
Bounds applied before allocating decoded image bytes.
One decoded runtime chunk with its admitted semantic metadata.
Structural and allocation limits for untrusted EVDEF metadata.
Fully validated, detached scene-manager candidate with no archive or GPU borrows.
Explicit per-draw inputs consumed by one TVE Element fragment evaluation.
Detached TVE render-target source value and independent hardware blend policy.
One normalized Unity TVEElement definition awaiting texture realization.
One normalized Unity TVEElement definition awaiting texture realization.
std::vector< VegetationSceneElementProperty > properties
std::array< std::array< float, 4 >, 4 > seasons
Explicit detached inputs for publishing all nine TVE scene-manager field layers.
Detached PBR and CPU-motion snapshot ready for atomic material publication.
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
Definition PbrSurface.h:240
PbrVegetationMotion vegetationMotion
Definition PbrSurface.h:281
PbrVegetationExtras vegetationExtras
Definition PbrSurface.h:278
PbrVegetationVertex vegetationVertex
Definition PbrSurface.h:280
PbrVegetationColors vegetationColors
Definition PbrSurface.h:279
Four owning arrays in row-major X/Z order at texel centers.
std::array< std::vector< glm::vec4 >, 4 > channels
One owning vegetation channel in row-major X/Z order at texel centers. Channel atlases may use indepe...
Runtime-owned global inputs shared by one coherent vegetation field binding. Time is explicit for det...
Owning linear RGBA mask, sampled bilinearly with clamped addressing.
Source-equivalent plant motion parameters with explicit time and texture inputs. All data is owned....
glm::vec4 color