载入中...
搜索中...
未找到
UnityFbx.cpp
浏览该文件的文档.
4
5#if defined(__EMSCRIPTEN__)
6namespace eve::asset_import {
7Result<PreparedAssetImport> prepareUnityFbx(const UnityProjectImportRequest&, const UnitySourceAsset& source) {
9 "FBX conversion requires the desktop Assimp provider",
10 source.path, {}, "asset.import"));
11}
12} // namespace eve::asset_import
13#else
14#include <assimp/postprocess.h>
15#include <assimp/scene.h>
16#include <xxHash/xxhash.h>
17#include <assimp/Exporter.hpp>
18#include <assimp/IOSystem.hpp>
19#include <assimp/Importer.hpp>
20
21#include <algorithm>
22#include <bit>
23#include <cmath>
24#include <filesystem>
25#include <functional>
26#include <memory>
27#include <regex>
28#include <set>
29
30namespace eve::asset_import {
31namespace {
32// Third-party IO boundary: the in-memory FBX is the only authorized input.
33class NoExternalIO final : public Assimp::IOSystem {
34public:
35 bool Exists(const char*) const override { return false; }
36 char getOsSeparator() const override { return '/'; }
37 Assimp::IOStream* Open(const char*, const char*) override { return nullptr; }
38 void Close(Assimp::IOStream*) override {}
39};
40
41std::optional<double> setting(const std::string& text, const std::string& name) {
42 std::smatch match;
43 if (!std::regex_search(text, match, std::regex("(?:^|\\n) " + name + ": *([^\\r\\n]+)"))) return {};
44 try {
45 std::size_t end = 0;
46 const auto token = match[1].str();
47 const auto value = std::stod(token, &end);
48 if (end != token.size() || !std::isfinite(value)) return {};
49 return value;
50 } catch (...) {
51 return {};
52 }
53}
54
55std::set<std::int64_t> referencedMeshIds(const UnityProjectImportRequest& request,
56 std::string_view sourceGuid) {
57 std::set<std::int64_t> result;
58 const std::regex reference("m_Mesh: *\\{fileID: *(-?[0-9]+), *guid: *" +
59 std::string(sourceGuid) + R"(, *type: *[23]\})",
60 std::regex::icase);
61 for (const auto& [path, bytes] : request.files) {
62 if (unity_detail::foldAscii(std::filesystem::path(path).extension().string()) != ".prefab" || bytes.empty())
63 continue;
64 const std::string text(bytes.begin(), bytes.end());
65 for (std::sregex_iterator match(text.begin(), text.end(), reference), end; match != end; ++match) {
66 try {
67 std::size_t parsed = 0;
68 const auto id = std::stoll((*match)[1].str(), &parsed);
69 if (parsed == static_cast<std::size_t>((*match)[1].length()) && id != 0) result.emplace(id);
70 } catch (...) {
71 }
72 }
73 }
74 return result;
75}
76
77void put32(std::vector<std::uint8_t>& bytes, std::uint32_t value) {
78 for (unsigned shift = 0; shift < 32; shift += 8) bytes.push_back(std::uint8_t(value >> shift));
79}
80
81Result<PreparedAssetImport> meshImport(const UnityProjectImportRequest& request, const UnitySourceAsset& source,
82 const aiMesh& mesh, std::int64_t fileId, std::optional<unsigned> submesh,
83 float scale) {
84 if (!mesh.HasPositions() || !mesh.HasNormals() || !mesh.HasTextureCoords(0) || mesh.HasBones() ||
85 mesh.mNumAnimMeshes)
88 "FBX static mesh requires positions, imported normals and UV0; skin/morph conversion is unavailable",
89 source.path, {}, "asset.import"));
90 std::uint64_t vertexFloats = 6;
91 for (unsigned set = 0; set < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++set)
92 if (mesh.HasTextureCoords(set)) vertexFloats += 2;
93 if (mesh.HasTangentsAndBitangents()) vertexFloats += 4;
94 for (unsigned set = 0; set < AI_MAX_NUMBER_OF_COLOR_SETS; ++set)
95 if (mesh.HasVertexColors(set)) vertexFloats += 4;
97 std::uint64_t(mesh.mNumFaces) * 3 > request.limits.maximumIndicesPerPrimitive ||
98 vertexFloats > request.limits.maximumDecodedBytes / 4 / mesh.mNumVertices ||
99 std::uint64_t(mesh.mNumVertices) * vertexFloats * 4 + std::uint64_t(mesh.mNumFaces) * 12 >
102 DiagnosticCode::InvalidArgument, "FBX mesh exceeds budget", source.path, {}, "asset.import"));
103 std::vector<std::uint8_t> buffer;
104 auto scalar = [&](float value) { put32(buffer, std::bit_cast<std::uint32_t>(value)); };
105 // Unity's FBX importer reflects X. The canonical right-handed basis then reflects Z.
106 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
107 scalar(-mesh.mVertices[i].x * scale);
108 scalar(mesh.mVertices[i].y * scale);
109 scalar(-mesh.mVertices[i].z * scale);
110 }
111 const auto normalOffset = buffer.size();
112 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
113 scalar(-mesh.mNormals[i].x);
114 scalar(mesh.mNormals[i].y);
115 scalar(-mesh.mNormals[i].z);
116 }
117 Value::Array views, accessors;
118 auto stream = [&](std::size_t offset, std::size_t length, std::uint64_t count, const char* type, int component) {
119 const auto index = std::int64_t(views.size());
120 views.emplace_back(Value::Object{{"buffer", Value(std::int64_t(0))},
121 {"byteOffset", Value(std::int64_t(offset))},
122 {"byteLength", Value(std::int64_t(length))}});
123 accessors.emplace_back(Value::Object{{"bufferView", Value(index)},
124 {"componentType", Value(std::int64_t(component))},
125 {"count", Value(std::int64_t(count))},
126 {"type", Value(type)}});
127 };
128 stream(0, normalOffset, mesh.mNumVertices, "VEC3", 5126);
129 stream(normalOffset, buffer.size() - normalOffset, mesh.mNumVertices, "VEC3", 5126);
130 Value::Object attributes{{"POSITION", Value(std::int64_t(0))}, {"NORMAL", Value(std::int64_t(1))}};
131 for (unsigned set = 0; set < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++set) {
132 if (!mesh.HasTextureCoords(set)) continue;
133 const auto offset = buffer.size();
134 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
135 // Canonical image rows/glTF UV origin are top-left; Unity mesh UV origin is bottom-left.
136 scalar(mesh.mTextureCoords[set][i].x);
137 scalar(1.f - mesh.mTextureCoords[set][i].y);
138 }
139 const auto accessor = std::int64_t(accessors.size());
140 stream(offset, buffer.size() - offset, mesh.mNumVertices, "VEC2", 5126);
141 attributes["TEXCOORD_" + std::to_string(set)] = Value(accessor);
142 }
143 if (mesh.HasTangentsAndBitangents()) {
144 const auto offset = buffer.size();
145 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
146 scalar(-mesh.mTangents[i].x);
147 scalar(mesh.mTangents[i].y);
148 scalar(-mesh.mTangents[i].z);
149 const auto& n = mesh.mNormals[i];
150 const auto& t = mesh.mTangents[i];
151 const auto& b = mesh.mBitangents[i];
152 const auto handedness =
153 ((n.y * t.z - n.z * t.y) * b.x + (n.z * t.x - n.x * t.z) * b.y + (n.x * t.y - n.y * t.x) * b.z) < 0.f
154 ? -1.f
155 : 1.f;
156 scalar(handedness);
157 }
158 const auto accessor = std::int64_t(accessors.size());
159 stream(offset, buffer.size() - offset, mesh.mNumVertices, "VEC4", 5126);
160 attributes["TANGENT"] = Value(accessor);
161 }
162 for (unsigned set = 0; set < AI_MAX_NUMBER_OF_COLOR_SETS; ++set) {
163 if (!mesh.HasVertexColors(set)) continue;
164 const auto offset = buffer.size();
165 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
166 scalar(mesh.mColors[set][i].r);
167 scalar(mesh.mColors[set][i].g);
168 scalar(mesh.mColors[set][i].b);
169 scalar(mesh.mColors[set][i].a);
170 }
171 const auto accessor = std::int64_t(accessors.size());
172 stream(offset, buffer.size() - offset, mesh.mNumVertices, "VEC4", 5126);
173 attributes["COLOR_" + std::to_string(set)] = Value(accessor);
174 }
175 const auto indexOffset = buffer.size();
176 for (unsigned i = 0; i < mesh.mNumFaces; ++i) {
177 if (mesh.mFaces[i].mNumIndices != 3)
179 DiagnosticCode::Unsupported, "FBX contains non-triangle primitives", source.path, {}, "asset.import"));
180 for (unsigned j = 0; j < 3; ++j) put32(buffer, mesh.mFaces[i].mIndices[j]);
181 }
182 const auto indexAccessor = std::int64_t(accessors.size());
183 stream(indexOffset, buffer.size() - indexOffset, std::uint64_t(mesh.mNumFaces) * 3, "SCALAR", 5125);
184 Value primitive(Value::Object{{"attributes", Value(std::move(attributes))}, {"indices", Value(indexAccessor)}});
185 Value document(Value::Object{
186 {"asset", Value(Value::Object{{"version", Value("2.0")}})},
187 {"buffers", Value(Value::Array{Value(Value::Object{{"uri", Value("mesh.bin")},
188 {"byteLength", Value(std::int64_t(buffer.size()))}})})},
189 {"bufferViews", Value(std::move(views))},
190 {"accessors", Value(std::move(accessors))},
191 {"meshes",
192 Value(Value::Array{Value(Value::Object{{"primitives", Value(Value::Array{std::move(primitive)})}})})}});
193 auto json = document.toJson();
194 if (!json) return Result<PreparedAssetImport>::failure(json.status());
195 auto identity = request.package;
196 std::string identityKey = "unity:" + source.guid + ":" + std::to_string(fileId);
197 if (submesh) identityKey += ":submesh:" + std::to_string(*submesh);
198 identity.packageId = identity.packageId.child(identityKey);
200 source.path,
201 {json.value().begin(), json.value().end()},
202 {{"mesh.bin", std::move(buffer)}},
203 request.limits});
204 if (!result) return result;
205 for (auto& mapping : result.value().sourceMappings)
206 mapping.sourceObject = std::to_string(fileId) +
207 (submesh ? "/submesh/" + std::to_string(*submesh) : std::string{});
208 return result;
209}
210
211Result<PreparedAssetImport> characterImport(const UnityProjectImportRequest& request, const UnitySourceAsset& source,
212 const aiScene& scene) {
213 // Keep bones, inverse bind matrices and channels in one document. Splitting meshes
214 // here would lose the node indices shared by skins and animation tracks.
215 Assimp::Exporter exporter;
216 const auto* blob = exporter.ExportToBlob(&scene, "glb2");
217 if (!blob || !blob->data || blob->size == 0 || blob->size > request.limits.maximumSourceBytes)
219 Diagnostic::error(DiagnosticCode::Unsupported, "FBX character could not be converted to bounded glTF 2.0",
220 source.path, {}, "asset.import"));
221 const auto* begin = static_cast<const std::uint8_t*>(blob->data);
222 auto identity = request.package;
223 identity.packageId = identity.packageId.child("unity:" + source.guid + ":character");
224 auto prepared = prepareGltfImport({identity, source.path, {begin, begin + blob->size}, {}, request.limits});
225 if (!prepared) return prepared;
226 prepared.value().findings.push_back({source.path, "FBX.character", ImportDisposition::Translated,
227 "skinned meshes, skeleton and animation clips converted through glTF 2.0"});
228 return prepared;
229}
230} // namespace
231
233 const auto& input = request.files.at(source.path);
234 const auto& metadata = request.files.at(source.path + ".meta");
235 const std::string meta(metadata.begin(), metadata.end());
236 const auto scale = setting(meta, "globalScale");
237 const auto generationSetting = setting(meta, "fileIdsGeneration");
238 const auto generation = generationSetting.value_or(1.0);
239 if ((generation != 1 && generation != 2) || !scale || *scale <= 0 || setting(meta, "useFileScale") != 1 ||
240 setting(meta, "normalImportMode") != 0 || setting(meta, "swapUVChannels") != 0)
243 "FBX requires supported file IDs, positive scale, file units, imported normals and original UV0",
244 source.path, {}, "asset.import"));
245 if (input.empty() || input.size() > request.limits.maximumSourceBytes)
247 DiagnosticCode::InvalidArgument, "FBX source exceeds budget", source.path, {}, "asset.import"));
248 Assimp::Importer importer;
249 importer.SetIOHandler(new NoExternalIO());
250 const auto* scene = importer.ReadFileFromMemory(input.data(), input.size(),
251 aiProcess_Triangulate | aiProcess_CalcTangentSpace, "fbx");
252 if (!scene || !scene->mRootNode)
254 Diagnostic::error(DiagnosticCode::ParseError, importer.GetErrorString(), source.path, {}, "asset.import"));
255 if (scene->mNumMeshes > request.limits.maximumAssets)
257 DiagnosticCode::Unsupported, "FBX mesh budget is unsupported", source.path, {}, "asset.import"));
258 std::uint64_t meshBytes = 0;
259 for (unsigned i = 0; i < scene->mNumMeshes; ++i) {
260 const auto& mesh = *scene->mMeshes[i];
261 const auto bytes = std::uint64_t(mesh.mNumVertices) * 32 + std::uint64_t(mesh.mNumFaces) * 12;
264 "aggregate FBX mesh budget exceeded",
265 source.path, {}, "asset.import"));
266 meshBytes += bytes;
267 }
268 double units = 0;
269 float floatUnits = 0;
270 if (scene->mMetaData) {
271 if (!scene->mMetaData->Get("UnitScaleFactor", units) && scene->mMetaData->Get("UnitScaleFactor", floatUnits))
272 units = floatUnits;
273 }
274 const double factor = units * 0.01 * *scale;
275 if (!std::isfinite(factor) || factor <= 0 || factor > std::numeric_limits<float>::max())
277 DiagnosticCode::Unsupported, "FBX file unit scale is unavailable", source.path, {}, "asset.import"));
278 if (scene->mNumAnimations || std::any_of(scene->mMeshes, scene->mMeshes + scene->mNumMeshes,
279 [](const aiMesh* mesh) { return mesh->HasBones(); })) {
280 // The static converter applies this basis and metre scale to vertices.
281 // For a character it must instead encompass the entire node/skin/clip tree.
282 std::unique_ptr<aiScene> characterScene(importer.GetOrphanedScene());
283 aiMatrix4x4 correction;
284 correction.a1 = -float(factor);
285 correction.b2 = float(factor);
286 correction.c3 = -float(factor);
287 characterScene->mRootNode->mTransformation = correction * characterScene->mRootNode->mTransformation;
288 return characterImport(request, source, *characterScene);
289 }
290 auto manifest = detail::baseManifest(request.package, "eve.unity-fbx/1");
291 if (!manifest) return Result<PreparedAssetImport>::failure(manifest.status());
293 out.manifest = std::move(manifest).takeValue();
294 const auto referencedIds = generation == 1 ? referencedMeshIds(request, source.guid) : std::set<std::int64_t>{};
295 std::uint32_t meshNodeCount = 0;
296 std::function<void(const aiNode&)> countMeshNodes = [&](const aiNode& node) {
297 if (node.mNumMeshes) ++meshNodeCount;
298 for (unsigned index = 0; index < node.mNumChildren; ++index) countMeshNodes(*node.mChildren[index]);
299 };
300 countMeshNodes(*scene->mRootNode);
301 if (generation == 1 && meshNodeCount > 1 &&
302 std::any_of(referencedIds.begin(), referencedIds.end(), [](std::int64_t id) {
303 return id < 4300000 || id >= 4400000 || ((id - 4300000) & 1) != 0;
304 }))
307 "legacy FBX has non-indexed mesh references that cannot be mapped to multiple nodes",
308 source.path, {}, "asset.import"));
309 std::set<std::string> names;
310 std::set<std::int64_t> ids;
311 std::uint32_t nodeCount = 0;
312 std::function<Result<void>(const aiNode&, unsigned)> visit = [&](const aiNode& node,
313 unsigned depth) -> Result<void> {
314 if (++nodeCount > request.limits.maximumAssets || depth > 256)
316 DiagnosticCode::InvalidArgument, "FBX hierarchy exceeds budget", source.path, {}, "asset.import"));
317 if (node.mNumMeshes) {
318 const std::string name(node.mName.C_Str());
319 if (name.empty() || !names.insert(name).second)
321 "FBX requires unique mesh-bearing node names",
322 source.path, {}, "asset.import"));
323 std::int64_t id = 0;
324 if (generation == 2) {
325 const std::string key = "Type:Mesh->" + name + "0";
326 id = std::bit_cast<std::int64_t>(std::uint64_t(XXH64(key.data(), key.size(), 0)));
327 } else if (meshNodeCount == 1 && referencedIds.size() == 1) {
328 id = *referencedIds.begin();
329 } else {
330 id = std::int64_t(4300000) + std::int64_t(node.mMeshes[0]) * 2;
331 }
332 if (id == 0 || !ids.insert(id).second)
334 DiagnosticCode::Conflict, "FBX subasset identity collision", source.path, {}, "asset.import"));
335 for (unsigned slot = 0; slot < node.mNumMeshes; ++slot) {
336 if (node.mMeshes[slot] >= scene->mNumMeshes)
338 DiagnosticCode::ParseError, "FBX mesh index is invalid", source.path, {}, "asset.import"));
339 const auto submesh = node.mNumMeshes > 1 ? std::optional<unsigned>(slot) : std::nullopt;
340 auto converted = meshImport(request, source, *scene->mMeshes[node.mMeshes[slot]], id, submesh,
341 float(factor));
342 if (!converted) return Result<void>::failure(converted.status());
343 auto& part = converted.value();
344 const std::string entrypoint = std::to_string(id) +
345 (submesh ? "/submesh/" + std::to_string(*submesh) : std::string{});
346 out.manifest.entrypoints.emplace(entrypoint, part.manifest.assets.front().asset);
347 for (auto& asset : part.manifest.assets) out.manifest.assets.push_back(std::move(asset));
348 for (auto& entry : part.entries)
349 if (entry.path.starts_with("assets/")) out.entries.push_back(std::move(entry));
350 for (auto& mapping : part.sourceMappings) out.sourceMappings.push_back(std::move(mapping));
351 }
352 out.findings.push_back(
353 {source.path, "FBX.mesh:" + std::to_string(id), ImportDisposition::Translated, name});
354 }
355 for (unsigned i = 0; i < node.mNumChildren; ++i) {
356 auto result = visit(*node.mChildren[i], depth + 1);
357 if (!result) return result;
358 }
359 return Result<void>::success();
360 };
361 auto traversed = visit(*scene->mRootNode, 0);
362 if (!traversed) return Result<PreparedAssetImport>::failure(traversed.status());
363 if (out.manifest.assets.empty())
365 DiagnosticCode::Unsupported, "FBX contains no static meshes", source.path, {}, "asset.import"));
366 out.findings.push_back({source.path, "FBX.vertexStreams", ImportDisposition::Translated,
367 "positions, imported normals, tangents, vertex colors and all available UV sets retained"});
368 return Result<PreparedAssetImport>::success(std::move(out));
369}
370} // namespace eve::asset_import
371#endif
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< std::uint8_t > blob
const GltfImportRequest & request
glm::vec3 n
Definition Grass.cpp:63
float length
size_t offset
std::array< float, 3 > scale
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
OceanGpuFrameToken token
OceanMeshSettings mesh
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string path
Definition PlayHost.cpp:111
std::weak_ptr< PrimitiveScene > scene
Object::Ptr value
float t
std::map< std::string, double > attributes
std::string slot
const RoadNode * node
std::string text
ScriptStructure out
std::string_view source
size_t begin
size_t end
std::string string
int count
std::vector< UnitCandidate > units
std::int64_t fileId
Direct Unity text-serialization adapter for TerrainData and Prefab assets.
std::uint32_t depth
uint32_t index
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
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Id128 child(std::string_view role) const noexcept
Derives a deterministic child UUID for a hierarchical identity.
Definition Identity.h:191
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
std::string extension(std::string_view name)
Extension.
Result< asset::EvaManifest > baseManifest(const ImportPackageIdentity &package, std::string_view importer)
Base manifest.
void put32(std::vector< std::uint8_t > &bytes, std::uint32_t value)
Append little-endian uint32 to owned storage.
std::string foldAscii(std::string value)
Fold ascii.
Result< PreparedAssetImport > prepareUnityFbx(const UnityProjectImportRequest &request, const UnitySourceAsset &source)
Prepare static meshes or a skinned FBX character with explicit Unity importer settings.
Definition UnityFbx.cpp:232
EVENGINE_API_PLATFORM Result< PreparedAssetImport > prepareGltfImport(const GltfImportRequest &request)
Decode triangle primitives from glTF 2.0 into canonical typed mesh blobs.
@ Exists
Passes when the keyed value is present; expected is ignored.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Owning, validated source archive candidate not yet published to disk/database.
In-memory Unity project slice; keys are normalized project-relative paths.
Immutable-by-convention owning source index entry; no borrowed source addresses.
Definition UnitySource.h:38