载入中...
搜索中...
未找到
VegetationPresetConversion.cpp
浏览该文件的文档.
1#include <algorithm>
2
3#include <cmath>
4#include <iomanip>
5#include <new>
6#include <sstream>
7#include <utility>
9
10// VegetationPresetConversion.cpp
11namespace eve::asset_import {
12namespace {
13Result<void> applyOutputPlan(VegetationConversionResult& result) {
14 const auto value = [&](const char* domain) -> const std::string* {
15 const auto found = result.candidate.outputDirectives.find(domain);
16 return found == result.candidate.outputDirectives.end() || found->second.size() != 1 ? nullptr
17 : &found->second.front();
18 };
19 const auto invalid = [](std::string message) {
21 "asset.import.vegetation-preset.conversion"));
22 };
23 if (result.candidate.outputDirectives.contains("OutputMeshes")) {
24 const auto* mode = value("OutputMeshes");
25 if (!mode) return invalid("OutputMeshes requires one mode");
26 if (*mode == "OFF" || *mode == "NONE")
28 else if (*mode == "DEFAULT")
30 else if (*mode == "CUSTOM")
32 else
33 return invalid("unsupported OutputMeshes mode");
34 }
35 if (result.candidate.outputDirectives.contains("OutputMaterials")) {
36 const auto* mode = value("OutputMaterials");
37 if (!mode) return invalid("OutputMaterials requires one mode");
38 if (*mode == "OFF" || *mode == "NONE")
40 else if (*mode == "DEFAULT")
42 else
43 return invalid("unsupported OutputMaterials mode");
44 }
45 if (result.candidate.outputDirectives.contains("OutputTextures")) {
46 const auto* mode = value("OutputTextures");
47 if (!mode) return invalid("OutputTextures requires one mode");
48 if (*mode == "SAVE_TEXTURES_AS_PNG")
50 else if (*mode == "SAVE_TEXTURES_AS_TGA")
52 else if (*mode == "SAVE_TEXTURES_AS_EXR")
54 else if (*mode == "SAVE_TEXTURES_AS_ASSET")
56 else
57 return invalid("unsupported OutputTextures mode");
58 }
59 if (result.candidate.outputDirectives.contains("OutputTransforms")) {
60 const auto* mode = value("OutputTransforms");
61 if (!mode) return invalid("OutputTransforms requires one mode");
62 if (*mode == "KEEP_ORIGINAL_TRANSFORMS" || *mode == "USE_ORIGINAL_TRANSFORMS")
64 else if (*mode == "TRANSFORM_TO_WORLD_SPACE")
66 else
67 return invalid("unsupported OutputTransforms mode");
68 }
69 return Result<void>::success();
70}
71
72Result<void> transformToWorld(asset::CanonicalMeshData& mesh, const std::array<float, 16>& point,
73 const std::array<float, 9>& direction) {
74 for (const float value : point)
75 if (!std::isfinite(value))
77 "source-to-world point matrix contains nonfinite values", {},
78 {}, "asset.import.vegetation-preset.conversion"));
79 for (const float value : direction)
80 if (!std::isfinite(value))
82 "source-to-world direction matrix contains nonfinite values",
83 {}, {}, "asset.import.vegetation-preset.conversion"));
84 const float determinant = direction[0] * (direction[4] * direction[8] - direction[7] * direction[5]) -
85 direction[3] * (direction[1] * direction[8] - direction[7] * direction[2]) +
86 direction[6] * (direction[1] * direction[5] - direction[4] * direction[2]);
87 const auto dot = [&](unsigned a, unsigned b) {
88 return direction[a] * direction[b] + direction[a + 1] * direction[b + 1] + direction[a + 2] * direction[b + 2];
89 };
90 if (std::abs(determinant - 1.f) > 1e-4f || std::abs(dot(0, 0) - 1.f) > 1e-4f || std::abs(dot(3, 3) - 1.f) > 1e-4f ||
91 std::abs(dot(6, 6) - 1.f) > 1e-4f || std::abs(dot(0, 3)) > 1e-4f || std::abs(dot(0, 6)) > 1e-4f ||
92 std::abs(dot(3, 6)) > 1e-4f)
94 "source-to-world direction matrix is not a proper rotation", {},
95 {}, "asset.import.vegetation-preset.conversion"));
96 const auto transformDirection = [&](float& x, float& y, float& z) {
97 const float ox = direction[0] * x + direction[3] * y + direction[6] * z;
98 const float oy = direction[1] * x + direction[4] * y + direction[7] * z;
99 const float oz = direction[2] * x + direction[5] * y + direction[8] * z;
100 const float length = std::sqrt(ox * ox + oy * oy + oz * oz);
101 if (length < 1e-8f) return false;
102 x = ox / length;
103 y = oy / length;
104 z = oz / length;
105 return true;
106 };
107 for (std::size_t i = 0; i < mesh.positions.size(); i += 3) {
108 const float x = mesh.positions[i], y = mesh.positions[i + 1], z = mesh.positions[i + 2];
109 mesh.positions[i] = point[0] * x + point[4] * y + point[8] * z + point[12];
110 mesh.positions[i + 1] = point[1] * x + point[5] * y + point[9] * z + point[13];
111 mesh.positions[i + 2] = point[2] * x + point[6] * y + point[10] * z + point[14];
112 if (!transformDirection(mesh.normals[i], mesh.normals[i + 1], mesh.normals[i + 2]))
114 "world transform produced a zero mesh normal", {}, {},
115 "asset.import.vegetation-preset.conversion"));
116 }
117 if (auto tangent = mesh.attributes.find("TANGENT"); tangent != mesh.attributes.end()) {
118 if (tangent->second.components != 4 || tangent->second.values.size() / 4 != mesh.positions.size() / 3)
120 "world transform tangent stream is malformed", {}, {},
121 "asset.import.vegetation-preset.conversion"));
122 for (std::size_t i = 0; i < tangent->second.values.size(); i += 4)
123 if (!transformDirection(tangent->second.values[i], tangent->second.values[i + 1],
124 tangent->second.values[i + 2]))
126 "world transform produced a zero mesh tangent", {}, {},
127 "asset.import.vegetation-preset.conversion"));
128 }
129 return Result<void>::success();
130}
131} // namespace
132
134 VegetationConversionCandidate source, const std::vector<VegetationPresetCommand>& commands,
135 std::optional<asset::CanonicalMeshData> mesh, const std::map<std::string, VegetationPresetImage>& textures,
136 float variationSeed, const std::optional<std::array<float, 16>>& sourceToWorld,
137 const std::optional<std::array<float, 9>>& sourceDirectionToWorld) {
138 try {
139 auto applied = applyVegetationPreset(std::move(source), commands);
142 result.candidate = std::move(applied).takeValue();
143 auto outputPlan = applyOutputPlan(result);
144 if (!outputPlan) return Result<VegetationConversionResult>::failure(outputPlan.status());
145 if (mesh && result.meshOutput != VegetationMeshOutputMode::Off &&
147 if (sourceToWorld.has_value() != sourceDirectionToWorld.has_value())
149 DiagnosticCode::InvalidArgument, "world conversion requires both point and direction matrices", {},
150 {}, "asset.import.vegetation-preset.conversion"));
151 if (sourceToWorld) {
152 auto transformed = transformToWorld(*mesh, *sourceToWorld, *sourceDirectionToWorld);
153 if (!transformed) return Result<VegetationConversionResult>::failure(transformed.status());
154 }
155 }
156 if (mesh && result.meshOutput != VegetationMeshOutputMode::Off) {
157 auto converted = executeVegetationMeshRules(result.candidate, std::move(*mesh), textures, variationSeed);
158 if (!converted) return Result<VegetationConversionResult>::failure(converted.status());
159 result.mesh = std::move(converted).takeValue();
160 const auto count = result.mesh->positions.size() / 3;
161 float radius = 0, minimumY = result.mesh->positions[1], maximumY = minimumY;
162 for (std::size_t i = 0; i < count; ++i) {
163 radius = std::max(radius, std::max(std::abs(result.mesh->positions[i * 3]),
164 std::abs(result.mesh->positions[i * 3 + 2])));
165 minimumY = std::min(minimumY, result.mesh->positions[i * 3 + 1]);
166 maximumY = std::max(maximumY, result.mesh->positions[i * 3 + 1]);
167 }
168 if (auto bounds = result.candidate.meshRules.find("SetBounds");
169 bounds != result.candidate.meshRules.end()) {
170 if (bounds->second.size() != 2 || bounds->second[0] != "GET_BOUNDS_PROCEDURAL")
172 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported vegetation bounds rule", {}, {},
173 "asset.import.vegetation-preset.conversion"));
174 const auto& option = bounds->second[1];
175 const float expand = option == "0" ? 1.2f
176 : option == "1" ? 1.4f
177 : option == "2" ? 1.6f
178 : option == "3" ? 2.f
179 : 0.f;
180 if (expand == 0)
182 Diagnostic::error(DiagnosticCode::ParseError, "invalid vegetation bounds option", {}, {},
183 "asset.import.vegetation-preset.conversion"));
184 result.meshBoundsMinimum = std::array{-radius * expand, minimumY, -radius * expand};
185 result.meshBoundsMaximum = std::array{radius * expand, maximumY * 1.25f, radius * expand};
186 }
187 if (auto readable = result.candidate.meshRules.find("SetReadWrite");
188 readable != result.candidate.meshRules.end()) {
189 if (readable->second.size() != 1 || (readable->second[0] != "MARK_MESHES_AS_READABLE" &&
190 readable->second[0] != "MARK_MESHES_AS_NON_READABLE"))
192 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported vegetation mesh readability rule",
193 {}, {}, "asset.import.vegetation-preset.conversion"));
194 result.meshCpuReadable = readable->second[0] == "MARK_MESHES_AS_READABLE";
195 }
196 } else if (!mesh && !result.candidate.meshRules.empty() && result.meshOutput != VegetationMeshOutputMode::Off) {
198 Diagnostic::error(DiagnosticCode::NotFound, "vegetation preset requires a source mesh", {}, {},
199 "asset.import.vegetation-preset.conversion"));
200 }
201 if (result.materialOutput != VegetationMaterialOutputMode::Off) {
202 auto packed = result.mesh ? executeVegetationTexturePacks(result.candidate, textures, *result.mesh)
203 : executeVegetationTexturePacks(result.candidate, textures);
204 if (!packed) return Result<VegetationConversionResult>::failure(packed.status());
205 result.textures = std::move(packed).takeValue();
206 }
208 } catch (const std::bad_alloc&) {
210 Diagnostic::error(DiagnosticCode::Failed, "vegetation conversion allocation failed", {}, {},
211 "asset.import.vegetation-preset.conversion"));
212 }
213}
214
216 if (request.sourcePath.empty() || request.shaderName.empty() || request.materialName.empty() ||
217 request.rootPreset.empty())
220 "Unity vegetation conversion requires source, shader, material, and root preset names",
221 request.sourcePath, {}, "asset.import.vegetation-preset.conversion"));
222 try {
223 auto source = decodeUnityVegetationConversionCandidate(request.materialYaml, request.sourcePath,
224 request.maximumMaterialBytes);
226 auto context = makeVegetationPresetContext(source.value(), request.shaderName, request.materialName,
227 request.shaderPipeline, request.outputOptions);
228 auto commands = evaluateVegetationPreset(request.presetDefinitions, request.rootPreset, context);
230 return executeVegetationConversion(std::move(source).takeValue(), commands.value(), request.mesh,
231 request.textures, request.variationSeed, request.sourceToWorld,
232 request.sourceDirectionToWorld);
233 } catch (const std::bad_alloc&) {
235 Diagnostic::error(DiagnosticCode::Failed, "Unity vegetation transaction allocation failed",
236 request.sourcePath, {}, "asset.import.vegetation-preset.conversion"));
237 }
238}
239} // namespace eve::asset_import
240
241// VegetationPresetMaterial.cpp
242namespace eve::asset_import {
243namespace {
244Result<std::string> shaderGuid(std::string_view shader) {
245 if (shader == "7befaa6f41d00a6478d5f4af21d66518" ||
246 shader == "BOXOPHOBIC/The Vegetation Engine/Geometry/Plant Standard Lit")
247 return Result<std::string>::success("7befaa6f41d00a6478d5f4af21d66518");
248 if (shader == "a933075b367f9b24981408633f72ff34" ||
249 shader == "BOXOPHOBIC/The Vegetation Engine/Geometry/Plant Subsurface Lit")
250 return Result<std::string>::success("a933075b367f9b24981408633f72ff34");
251 if (shader == "6e6307b56f9201d40ad738f21cf03495" ||
252 shader == "BOXOPHOBIC/The Vegetation Engine/Geometry/Prop Standard Lit")
253 return Result<std::string>::success("6e6307b56f9201d40ad738f21cf03495");
254 if (shader == "d9a724745053dee46bf301b216cdd348" ||
255 shader == "BOXOPHOBIC/The Vegetation Engine/Geometry/Prop Subsurface Lit")
256 return Result<std::string>::success("d9a724745053dee46bf301b216cdd348");
258 "vegetation output shader is not an admitted TVE 12.6 target",
259 {}, {}, "asset.import.vegetation-preset.material"));
260}
261
262bool propertyName(std::string_view value) {
263 return !value.empty() && value.size() <= 127 && std::all_of(value.begin(), value.end(), [](unsigned char c) {
264 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
265 });
266}
267
268bool finite(const std::array<double, 4>& value) {
269 return std::all_of(value.begin(), value.end(), [](double component) { return std::isfinite(component); });
270}
271
272bool guid(std::string_view value) {
273 return value.size() == 32 && std::all_of(value.begin(), value.end(), [](unsigned char c) {
274 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
275 });
276}
277} // namespace
278
280 const VegetationConversionCandidate& candidate, std::uint64_t maximumBytes) {
281 try {
282 auto shader = shaderGuid(candidate.materialShader);
283 if (!shader) return Result<std::vector<std::uint8_t>>::failure(shader.status());
284 std::map<std::string, std::array<double, 4>> vectors = candidate.materialVectors;
285 for (const auto& [name, value] : candidate.materialColors) {
286 if (const auto found = vectors.find(name); found != vectors.end() && found->second != value)
287 return Result<std::vector<std::uint8_t>>::failure(
288 Diagnostic::error(DiagnosticCode::Conflict, "material vector and color values conflict", name, {},
289 "asset.import.vegetation-preset.material"));
290 vectors[name] = value;
291 }
292 for (const auto& [name, value] : candidate.materialFloats)
293 if (!propertyName(name) || !std::isfinite(value))
294 return Result<std::vector<std::uint8_t>>::failure(
295 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid vegetation material float", name, {},
296 "asset.import.vegetation-preset.material"));
297 for (const auto& [name, value] : vectors)
298 if (!propertyName(name) || !finite(value))
299 return Result<std::vector<std::uint8_t>>::failure(
300 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid vegetation material vector", name, {},
301 "asset.import.vegetation-preset.material"));
302 for (const auto& [name, value] : candidate.materialTextures)
303 if (!propertyName(name) || !guid(value))
304 return Result<std::vector<std::uint8_t>>::failure(Diagnostic::error(
305 DiagnosticCode::InvalidArgument, "vegetation material texture requires a lowercase Unity GUID",
306 name, {}, "asset.import.vegetation-preset.material"));
307
308 std::ostringstream text;
309 text << std::setprecision(17);
310 text << "%YAML 1.1\n--- !u!21 &2100000\nMaterial:\n"
311 << " m_Shader: {fileID: 4800000, guid: " << shader.value() << ", type: 3}\n"
312 << " m_ValidKeywords:\n";
313 for (const auto& keyword : candidate.materialKeywords) text << " - " << keyword << '\n';
314 text << " m_EnableInstancingVariants: " << (candidate.materialInstancing ? 1 : 0) << '\n'
315 << " m_SavedProperties:\n serializedVersion: 3\n m_TexEnvs:\n";
316 for (const auto& [name, texture] : candidate.materialTextures) {
317 const auto transform = candidate.materialTextureTransforms.contains(name)
318 ? candidate.materialTextureTransforms.at(name)
319 : std::array<double, 4>{1, 1, 0, 0};
320 if (!finite(transform))
321 return Result<std::vector<std::uint8_t>>::failure(
322 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid vegetation texture transform", name, {},
323 "asset.import.vegetation-preset.material"));
324 text << " - " << name << ":\n"
325 << " m_Texture: {fileID: 2800000, guid: " << texture << ", type: 3}\n"
326 << " m_Scale: {x: " << transform[0] << ", y: " << transform[1] << "}\n"
327 << " m_Offset: {x: " << transform[2] << ", y: " << transform[3] << "}\n";
328 }
329 text << " m_Ints: []\n m_Floats:\n";
330 for (const auto& [name, value] : candidate.materialFloats) text << " - " << name << ": " << value << '\n';
331 text << " m_Colors:\n";
332 for (const auto& [name, value] : vectors)
333 text << " - " << name << ": {r: " << value[0] << ", g: " << value[1] << ", b: " << value[2]
334 << ", a: " << value[3] << "}\n";
335 const auto encoded = text.str();
336 if (encoded.size() > maximumBytes)
337 return Result<std::vector<std::uint8_t>>::failure(
338 Diagnostic::error(DiagnosticCode::InvalidArgument, "encoded vegetation material exceeds byte budget",
339 {}, {}, "asset.import.vegetation-preset.material"));
340 return Result<std::vector<std::uint8_t>>::success({encoded.begin(), encoded.end()});
341 } catch (const std::bad_alloc&) {
342 return Result<std::vector<std::uint8_t>>::failure(
343 Diagnostic::error(DiagnosticCode::Failed, "vegetation material encoding allocation failed", {}, {},
344 "asset.import.vegetation-preset.material"));
345 }
346}
347} // namespace eve::asset_import
double z
double y
double x
bool applied
std::string name
Definition ECS.cpp:154
std::string message
const GltfImportRequest & request
std::int32_t c
float length
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanMeshSettings mesh
bool finite
std::string error
Definition Package.cpp:174
Texture * texture
Object::Ptr value
std::string domain
Shader * shader
RoadLaneDirection direction
bool found
std::string text
std::string_view source
int count
double oy
double ox
std::vector< VegetationPresetCommand > commands
const VegetationPresetContext & context
glm::vec3 point
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
EVENGINE_API_PLATFORM Result< std::vector< std::uint8_t > > encodeUnityVegetationConversionMaterial(const VegetationConversionCandidate &candidate, std::uint64_t maximumBytes=16ull *1024ull *1024ull)
Encode an applied vegetation candidate as a detached Unity text Material for the canonical TVE import...
EVENGINE_API_PLATFORM Result< VegetationConversionCandidate > applyVegetationPreset(VegetationConversionCandidate source, const std::vector< VegetationPresetCommand > &commands)
Type-check and atomically apply an evaluated TVE command sequence.
EVENGINE_API_PLATFORM Result< VegetationConversionResult > executeUnityVegetationConversion(const UnityVegetationConversionRequest &request)
Decode a Unity Material, evaluate one TVE preset graph, and execute every output atomically.
EVENGINE_API_PLATFORM Result< asset::CanonicalMeshData > executeVegetationMeshRules(const VegetationConversionCandidate &candidate, asset::CanonicalMeshData source, float variationSeed=1.f)
Execute preset mask and coordinate rules into canonical TVE authoring streams.
Result< VegetationConversionCandidate > decodeUnityVegetationConversionCandidate(std::span< const std::uint8_t > yaml, std::string sourcePath, std::uint64_t maximumBytes)
Decode Unity text Material saved properties into an owning vegetation conversion baseline.
VegetationPresetContext makeVegetationPresetContext(const VegetationConversionCandidate &candidate, std::string shaderName, std::string materialName, std::string shaderPipeline, std::set< std::string > outputOptions)
Project one conversion baseline into immutable preset predicate facts.
EVENGINE_API_PLATFORM Result< std::map< std::string, VegetationPresetImage > > executeVegetationTexturePacks(const VegetationConversionCandidate &candidate, const std::map< std::string, VegetationPresetImage > &sources, std::uint64_t maximumPixels=16ull *1024ull *1024ull)
Execute all texture recipes against detached RGBA8 source images.
EVENGINE_API_PLATFORM Result< VegetationConversionResult > executeVegetationConversion(VegetationConversionCandidate source, const std::vector< VegetationPresetCommand > &commands, std::optional< asset::CanonicalMeshData > mesh, const std::map< std::string, VegetationPresetImage > &textures, float variationSeed=1.f, const std::optional< std::array< float, 16 > > &sourceToWorld={}, const std::optional< std::array< float, 9 > > &sourceDirectionToWorld={})
Apply commands and execute all available mesh and texture outputs as one transaction.
Result< std::vector< VegetationPresetCommand > > evaluateVegetationPreset(const std::map< std::string, Value > &definitions, std::string_view root, const VegetationPresetContext &context)
Decode, resolve and evaluate a library of canonical TVE preset definitions.
eve::Diagnostic Diagnostic
eve::Result< T > Result
Status invalid(const char *message)
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Owning inputs for one complete Unity Material and TVE preset conversion transaction.
Owning unpublished material, mesh and texture candidate mutated transactionally by preset commands.
std::map< std::string, std::array< double, 4 > > materialVectors
std::map< std::string, std::array< double, 4 > > materialColors
std::map< std::string, double > materialFloats
std::map< std::string, std::array< double, 4 > > materialTextureTransforms
std::map< std::string, std::string > materialTextures
Complete detached output of one vegetation preset conversion transaction.
glm::vec4 bounds