载入中...
搜索中...
未找到
StructuredModelCommon.cpp
浏览该文件的文档.
3
4#include <cmath>
5#include <limits>
6
8Result<void> appendTriangle(asset::CanonicalMeshData& mesh, const std::array<std::array<double, 3>, 3>& triangle,
10 const auto vertices = mesh.positions.size() / 3;
11 if (vertices + 3 > limits.maximumVerticesPerPrimitive ||
12 mesh.indices.size() + 3 > limits.maximumIndicesPerPrimitive ||
13 (vertices + 3) * 28 + 24 > limits.maximumDecodedBytes)
15 DiagnosticCode::InvalidArgument, "structured model triangle budget exceeded", {}, {}, "asset.import"));
16 for (const auto& point : triangle)
17 for (double value : point)
18 if (!std::isfinite(value) || std::abs(value) > std::numeric_limits<float>::max())
20 DiagnosticCode::ParseError, "nonfinite or overflowing model coordinate", {}, {}, "asset.import"));
21 auto rounded = triangle;
22 for (auto& point : rounded)
23 for (auto& value : point) value = static_cast<float>(value);
24 std::array<double, 3> a{}, b{}, normal{};
25 for (std::size_t i = 0; i < 3; ++i) {
26 a[i] = rounded[1][i] - rounded[0][i];
27 b[i] = rounded[2][i] - rounded[0][i];
28 }
29 normal = {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]};
30 const double length = std::hypot(normal[0], normal[1], normal[2]);
31 if (!std::isfinite(length) || length == 0)
33 Diagnostic::error(DiagnosticCode::ParseError, "degenerate model triangle", {}, {}, "asset.import"));
34 for (std::size_t vertex = 0; vertex < 3; ++vertex) {
35 for (std::size_t axis = 0; axis < 3; ++axis) {
36 mesh.positions.push_back(float(triangle[vertex][axis]));
37 mesh.normals.push_back(float(normal[axis] / length));
38 }
39 mesh.indices.push_back(static_cast<std::uint32_t>(vertices + vertex));
40 }
41 return Result<void>::success();
42}
43
45 std::string_view format, std::map<std::string, MeshPart> parts,
46 const std::map<std::string, std::vector<std::uint8_t>>& sources,
47 std::vector<ImportFinding> findings, const AssetImportLimits& limits) {
48 using Output = Result<PreparedAssetImport>;
49 if (parts.empty() || parts.size() * 2 + 1 > limits.maximumAssets || sourceName.empty() ||
50 sourceName.size() > limits.maximumStringBytes)
52 "model must contain bounded triangle parts and a source name", {}, {},
53 "asset.import"));
54 auto manifest = detail::baseManifest(identity, "eve." + std::string(format));
55 if (!manifest) return Output::failure(manifest.status());
57 out.manifest = std::move(manifest).takeValue();
58 out.findings = std::move(findings);
59 const auto sceneId = identity.packageId.child(std::string(format) + ":scene");
60 auto sceneRef = detail::assetRef(sceneId);
61 if (!sceneRef) return Output::failure(sceneRef.status());
62 auto addDefinition = [&](PersistentId id, std::string type, unsigned version,
63 Value::Object definition) -> Result<AssetRef> {
64 auto reference = detail::assetRef(id);
65 if (!reference) return reference;
66 auto json = Value(std::move(definition)).toJson();
67 if (!json) return Result<AssetRef>::failure(json.status());
68 const auto path = "assets/" + id.format() + "/asset.json";
69 std::vector<std::uint8_t> bytes(json.value().begin(), json.value().end());
70 out.manifest.assets.push_back({reference.value(),
71 std::move(type),
73 path,
75 {"source:" + std::string(format)}});
76 out.entries.push_back({path, std::move(bytes)});
77 return reference;
78 };
79 Value::Array nodes, renderers;
80 const auto rootId = sceneId.child("root");
81 auto node = [](PersistentId id, std::int64_t index, std::int64_t parent, std::string name) -> Value {
82 return Value::Object{{"objectId", id.format()}, {"sourceFileId", index},
83 {"parentSourceFileId", parent}, {"name", std::move(name)},
84 {"position", Value::Array{0, 0, 0}}, {"rotation", Value::Array{0, 0, 0, 1}},
85 {"scale", Value::Array{1, 1, 1}}};
86 };
87 nodes.push_back(node(rootId, 1, 0, std::string(sourceName)));
88 std::uint64_t totalBytes = 0;
89 for (auto& [name, part] : parts) {
90 asset::CanonicalMeshLimits meshLimits{limits.maximumVerticesPerPrimitive, limits.maximumIndicesPerPrimitive,
92 auto blob = asset::encodeCanonicalMesh(part.mesh, meshLimits);
93 if (!blob) return Output::failure(blob.status());
94 if (blob.value().size() > limits.maximumDecodedBytes - totalBytes)
96 "model exceeds total decoded budget", {}, {}, "asset.import"));
97 totalBytes += blob.value().size();
98 const auto meshId = identity.packageId.child(std::string(format) + ":mesh:" + name);
99 const auto blobPath = "assets/" + meshId.format() + "/mesh.bin";
100 std::array<double, 3> minimum{}, maximum{};
101 for (std::size_t axis = 0; axis < 3; ++axis) minimum[axis] = maximum[axis] = part.mesh.positions[axis];
102 for (std::size_t i = 0; i < part.mesh.positions.size(); ++i) {
103 minimum[i % 3] = std::min(minimum[i % 3], double(part.mesh.positions[i]));
104 maximum[i % 3] = std::max(maximum[i % 3], double(part.mesh.positions[i]));
105 }
106 auto meshRef = addDefinition(meshId, "eve.mesh", 2,
107 {{"schema", "eve.mesh"},
108 {"schemaVersion", 2},
109 {"topology", "triangles"},
110 {"vertexCount", std::int64_t(part.mesh.positions.size() / 3)},
111 {"indexCount", std::int64_t(part.mesh.indices.size())},
112 {"positions", true},
113 {"normals", true},
114 {"texcoordSets", Value::Array{}},
115 {"coordinateSystem", "right-handed-x-right-y-up-minus-z-forward"},
116 {"unit", "meter"},
117 {"frontFace", "counter-clockwise"},
118 {"boundsMin", Value::Array{minimum[0], minimum[1], minimum[2]}},
119 {"boundsMax", Value::Array{maximum[0], maximum[1], maximum[2]}},
120 {"blob", blobPath}});
121 if (!meshRef) return Output::failure(meshRef.status());
122 out.entries.push_back({blobPath, std::move(blob).takeValue()});
123 const auto materialId = identity.packageId.child(std::string(format) + ":material:" + name);
124 auto materialRef =
125 addDefinition(materialId, "eve.material", 15,
126 {{"schema", "eve.material"},
127 {"schemaVersion", 15},
128 {"alphaToCoverage", false},
129 {"shadingModel", "pbr"},
130 {"surfaceMode", part.color[3] < 1 ? "transparent" : "opaque"},
131 {"blendMode", "alpha"},
132 {"baseColor", Value::Array{part.color[0], part.color[1], part.color[2], part.color[3]}},
133 {"metallic", 0.0},
134 {"roughness", 0.45},
135 {"doubleSided", true}});
136 if (!materialRef) return Output::failure(materialRef.status());
137 const auto objectId = sceneId.child(name);
138 nodes.push_back(node(objectId, std::int64_t(nodes.size() + 1), 1, name));
139 renderers.emplace_back(Value::Object{{"objectId", objectId.format()},
140 {"mesh", meshRef.value().format()},
141 {"material", materialRef.value().format()},
142 {"enabled", true},
143 {"castShadows", true},
144 {"receiveShadows", true}});
145 const auto prefix = "renderers[" + std::to_string(renderers.size() - 1) + "]";
146 out.manifest.dependencies.push_back({sceneRef.value(),
147 meshRef.value(),
149 prefix + ".mesh",
150 {},
151 "eve.mesh/2",
152 {}});
153 out.manifest.dependencies.push_back({sceneRef.value(),
154 materialRef.value(),
156 prefix + ".material",
157 {},
158 "eve.material/15",
159 {}});
160 out.manifest.entrypoints.emplace("mesh:" + name, meshRef.value());
161 out.sourceMappings.push_back({name, meshRef.value()});
162 }
163 auto scene = addDefinition(sceneId, "eve.scene-template", 3,
164 {{"schema", "eve.scene-template"},
165 {"schemaVersion", 3},
166 {"coordinateSystem", "right-handed-x-right-y-up-minus-z-forward"},
167 {"nodes", std::move(nodes)},
168 {"renderers", std::move(renderers)}});
169 if (!scene) return Output::failure(scene.status());
170 out.manifest.entrypoints.emplace("default", scene.value());
171 Value::Array sourceIndex;
172 std::uint64_t sourceBytes = 0;
173 for (const auto& [name, bytes] : sources) {
174 if (bytes.size() > limits.maximumSourceBytes - sourceBytes)
175 return Output::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "model sources exceed budget", {},
176 {}, "asset.import"));
177 sourceBytes += bytes.size();
178 const auto path = "sources/" + std::to_string(sourceIndex.size()) + ".txt";
179 sourceIndex.emplace_back(Value::Object{{"name", name}, {"path", path}, {"hash", detail::sha256(bytes)}});
180 out.entries.push_back({path, bytes});
181 }
182 out.manifest.provenance["sourceName"] = std::string(sourceName);
183 out.manifest.provenance["sources"] = std::move(sourceIndex);
184 auto report = detail::finalizeImportReport(out, identity, format, "1");
185 if (!report) return Output::failure(report.status());
186 return Output::success(std::move(out));
187}
188} // namespace eve::asset_import::structured_detail
std::vector< eve::artifact::PartView > parts
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::string name
Definition ECS.cpp:154
int triangle
Definition FluidSdf.cpp:554
std::vector< std::uint8_t > blob
float maximum[3]
float minimum[3]
float length
JointPoint2D axis
const ColourScope * parent
std::map< std::string, Node > nodes
std::string id
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
OceanMeshSettings mesh
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::string path
Definition PlayHost.cpp:111
std::weak_ptr< PrimitiveScene > scene
Object::Ptr value
const RoadNode * node
ScriptStructure out
std::array< double, 2 > vertices[3]
std::vector< ImportFinding > findings
const AssetImportLimits & limits
uint32_t index
glm::vec3 point
uint64_t identity
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Id128 public API.
Definition Identity.h:111
std::string sha256(std::span< const std::uint8_t > bytes)
Sha 256.
EVENGINE_API_PLATFORM Result< void > finalizeImportReport(PreparedAssetImport &prepared, const ImportPackageIdentity &package, std::string_view sourceEngine, std::string_view sourceVersion, Value::Object options={})
Append the deterministic mandatory import report and bind it from provenance.
Result< asset::EvaManifest > baseManifest(const ImportPackageIdentity &package, std::string_view importer)
Base manifest.
Result< AssetRef > assetRef(PersistentId id)
Asset ref.
Result< void > appendTriangle(asset::CanonicalMeshData &mesh, const std::array< std::array< double, 3 >, 3 > &triangle, const AssetImportLimits &limits)
Result< PreparedAssetImport > packageModel(const ImportPackageIdentity &identity, std::string_view sourceName, std::string_view format, std::map< std::string, MeshPart > parts, const std::map< std::string, std::vector< std::uint8_t > > &sources, std::vector< ImportFinding > findings, const AssetImportLimits &limits)
EVENGINE_API_FOUNDATION Result< std::vector< std::uint8_t > > encodeCanonicalMesh(const CanonicalMeshData &mesh, const CanonicalMeshLimits &limits={})
Encode an owning snapshot to EVMESH v3, or v2 when no named attributes exist. Borrows input synchrono...
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Owning CPU mesh snapshot; UV arrays are packed ST pairs indexed by source set number....
Allocation limits checked before decoding any vertex arrays. UV count is byte-budget bounded.
Parser and allocation budgets applied to untrusted importer inputs.
Common stable package metadata supplied by an import transaction.
Owning, validated source archive candidate not yet published to disk/database.