Debian Codegraph @

libs/gltfio/src/ResourceLoader.cpp

raw
1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gltfio/ResourceLoader.h>
18 #include <gltfio/Image.h>
19
20 #include "GltfEnums.h"
21 #include "FFilamentAsset.h"
22 #include "TangentsJob.h"
23 #include "upcast.h"
24
25 #include <filament/BufferObject.h>
26 #include <filament/Engine.h>
27 #include <filament/IndexBuffer.h>
28 #include <filament/MaterialInstance.h>
29 #include <filament/Texture.h>
30 #include <filament/VertexBuffer.h>
31
32 #include <geometry/Transcoder.h>
33
34 #include <utils/JobSystem.h>
35 #include <utils/Log.h>
36 #include <utils/Systrace.h>
37
38 #include <cgltf.h>
39
40 #include <math/quat.h>
41 #include <math/vec3.h>
42 #include <math/vec4.h>
43
44 #include <tsl/robin_map.h>
45
46 #include <string>
47
48 #if defined(__EMSCRIPTEN__) || defined(ANDROID) || defined(IOS)
49 #define USE_FILESYSTEM 0
50 #else
51 #define USE_FILESYSTEM 1
52 #include <utils/Path.h>
53 #endif
54
55 using namespace filament;
56 using namespace filament::math;
57 using namespace utils;
58
59 using filament::geometry::Transcoder;
60 using filament::geometry::ComponentType;
61
62 static const auto FREE_CALLBACK = [](void* mem, size_t, void*) { free(mem); };
63
64 namespace {
65 struct TextureCacheEntry {
66 Texture* texture;
67 std::atomic<stbi_uc*> texels;
68 uint32_t bufferSize;
69 int width;
70 int height;
71 int numComponents;
72 bool srgb;
73 bool completed;
74 };
75
76 using BufferTextureCache = tsl::robin_map<const void*, std::unique_ptr<TextureCacheEntry>>;
77 using UriTextureCache = tsl::robin_map<std::string, std::unique_ptr<TextureCacheEntry>>;
78 using UriDataCache = tsl::robin_map<std::string, gltfio::ResourceLoader::BufferDescriptor>;
79 }
80
81 namespace gltfio {
82
83 struct ResourceLoader::Impl {
84 Impl(const ResourceConfiguration& config) {
85 mGltfPath = std::string(config.gltfPath ? config.gltfPath : "");
86 mEngine = config.engine;
87 mNormalizeSkinningWeights = config.normalizeSkinningWeights;
88 mRecomputeBoundingBoxes = config.recomputeBoundingBoxes;
89 }
90
91 Engine* mEngine;
92 bool mNormalizeSkinningWeights;
93 bool mRecomputeBoundingBoxes;
94 std::string mGltfPath;
95
96 // User-provided resource data with URI string keys, populated with addResourceData().
97 // This is used on platforms without traditional file systems, such as Android, iOS, and WebGL.
98 UriDataCache mUriDataCache;
99
100 // The two texture caches are populated while textures are being decoded, and they are no longer
101 // used after all textures have been finalized. Since multiple glTF textures might be loaded
102 // from a single URI or buffer pointer, these caches prevent needless re-decoding. There are
103 // two caches: one for URI-based textures and one for buffer-based textures.
104 BufferTextureCache mBufferTextureCache;
105 UriTextureCache mUriTextureCache;
106 int mNumDecoderTasks;
107 int mNumDecoderTasksFinished;
108 JobSystem::Job* mDecoderRootJob = nullptr;
109 FFilamentAsset* mCurrentAsset = nullptr;
110
111 void computeTangents(FFilamentAsset* asset);
112 bool createTextures(bool async);
113 void cancelTextureDecoding();
114 void addTextureCacheEntry(const TextureSlot& tb);
115 void bindTextureToMaterial(const TextureSlot& tb);
116 void decodeSingleTexture();
117 void uploadPendingTextures();
118 void releasePendingTextures();
119 ~Impl();
120 };
121
122 uint32_t computeBindingSize(const cgltf_accessor* accessor);
123 uint32_t computeBindingOffset(const cgltf_accessor* accessor);
124
125 // This little struct holds a shared_ptr that wraps cgltf_data (and, potentially, glb data) while
126 // uploading vertex buffer data to the GPU.
127 struct UploadEvent {
128 FFilamentAsset::SourceHandle handle;
129 };
130
131 UploadEvent* uploadUserdata(FFilamentAsset* asset) {
132 return new UploadEvent({ asset->mSourceAsset });
133 }
134
135 static void uploadCallback(void* buffer, size_t size, void* user) {
136 auto event = (UploadEvent*) user;
137 delete event;
138 }
139
140 void importSkins(const cgltf_data* gltf, const NodeMap& nodeMap, SkinVector& dstSkins) {
141 dstSkins.resize(gltf->skins_count);
142 for (cgltf_size i = 0, len = gltf->nodes_count; i < len; ++i) {
143 const cgltf_node& node = gltf->nodes[i];
144 if (node.skin) {
145 int skinIndex = node.skin - &gltf->skins[0];
146 Entity entity = nodeMap.at(&node);
147 dstSkins[skinIndex].targets.push_back(entity);
148 }
149 }
150 for (cgltf_size i = 0, len = gltf->skins_count; i < len; ++i) {
151 Skin& dstSkin = dstSkins[i];
152 const cgltf_skin& srcSkin = gltf->skins[i];
153 if (srcSkin.name) {
154 dstSkin.name = srcSkin.name;
155 }
156
157 // Build a list of transformables for this skin, one for each joint.
158 // TODO: We've seen models with joint nodes that do not belong to the scene's node graph.
159 // e.g. BrainStem after Draco compression. That's why we have a fallback here. AssetManager
160 // should maybe create an Entity for every glTF node, period. (regardless of hierarchy)
161 // https://github.com/CesiumGS/gltf-pipeline/issues/532
162 dstSkin.joints.resize(srcSkin.joints_count);
163 for (cgltf_size i = 0, len = srcSkin.joints_count; i < len; ++i) {
164 auto iter = nodeMap.find(srcSkin.joints[i]);
165 if (iter == nodeMap.end()) {
166 dstSkin.joints[i] = nodeMap.begin()->second;
167 } else {
168 dstSkin.joints[i] = iter->second;
169 }
170 }
171
172 // Retain a copy of the inverse bind matrices because the source blob could be evicted later.
173 const cgltf_accessor* srcMatrices = srcSkin.inverse_bind_matrices;
174 dstSkin.inverseBindMatrices.resize(srcSkin.joints_count);
175 if (srcMatrices) {
176 auto dstMatrices = (uint8_t*) dstSkin.inverseBindMatrices.data();
177 uint8_t* bytes = (uint8_t*) srcMatrices->buffer_view->buffer->data;
178 if (!bytes) {
179 slog.w << "Empty animation buffer, have resources been loaded yet?" << io::endl;
180 continue;
181 }
182 auto srcBuffer = (void*) (bytes + srcMatrices->offset + srcMatrices->buffer_view->offset);
183 memcpy(dstMatrices, srcBuffer, srcSkin.joints_count * sizeof(mat4f));
184 }
185 }
186 }
187
188 static void convertBytesToShorts(uint16_t* dst, const uint8_t* src, size_t count) {
189 for (size_t i = 0; i < count; ++i) {
190 dst[i] = src[i];
191 }
192 }
193
194 static ComponentType getComponentType(const cgltf_accessor* accessor) {
195 switch (accessor->component_type) {
196 case cgltf_component_type_r_8: return ComponentType::BYTE;
197 case cgltf_component_type_r_8u: return ComponentType::UBYTE;
198 case cgltf_component_type_r_16: return ComponentType::SHORT;
199 case cgltf_component_type_r_16u: return ComponentType::USHORT;
200 default:
201 // This should be unreachable because other types do not require conversion.
202 assert_invariant(false);
203 return {};
204 }
205 }
206
207 static void convertToFloats(float* dest, const cgltf_accessor* accessor) {
208 const uint32_t dim = cgltf_num_components(accessor->type);
209 const size_t floatsSize = accessor->count * sizeof(float) * dim;
210 Transcoder transcode({
211 .componentType = getComponentType(accessor),
212 .normalized = bool(accessor->normalized),
213 .componentCount = dim,
214 .inputStrideBytes = uint32_t(accessor->stride)
215 });
216 auto bufferData = (const uint8_t*) accessor->buffer_view->buffer->data;
217 const uint8_t* source = computeBindingOffset(accessor) + bufferData;
218 transcode(dest, source, accessor->count);
219 }
220
221 static void decodeDracoMeshes(FFilamentAsset* asset) {
222 DracoCache* dracoCache = &asset->mSourceAsset->dracoCache;
223
224 // For a given primitive and attribute, find the corresponding accessor.
225 auto findAccessor = [](const cgltf_primitive* prim, cgltf_attribute_type type, cgltf_int idx) {
226 for (cgltf_size i = 0; i < prim->attributes_count; i++) {
227 const cgltf_attribute& attr = prim->attributes[i];
228 if (attr.type == type && attr.index == idx) {
229 return attr.data;
230 }
231 }
232 return (cgltf_accessor*) nullptr;
233 };
234
235 // Go through every primitive and check if it has a Draco mesh.
236 for (auto& pair : asset->mPrimitives) {
237 const cgltf_primitive* prim = pair.first;
238 if (!prim->has_draco_mesh_compression) {
239 continue;
240 }
241
242 const cgltf_draco_mesh_compression& draco = prim->draco_mesh_compression;
243
244 // If an error occurs, we can simply set the primitive's associated VertexBuffer to null.
245 // This does not cause a leak because it is a weak reference.
246 auto& vertexBuffer = pair.second;
247
248 // Check if we have already decoded this mesh.
249 DracoMesh* mesh = dracoCache->findOrCreateMesh(draco.buffer_view);
250 if (!mesh) {
251 slog.e << "Cannot decompress mesh, Draco decoding error." << io::endl;
252 vertexBuffer = nullptr;
253 continue;
254 }
255
256 // Copy over the decompressed data, converting the data type if necessary.
257 if (prim->indices && !mesh->getFaceIndices(prim->indices)) {
258 vertexBuffer = nullptr;
259 continue;
260 }
261
262 // Go through each attribute in the decompressed mesh.
263 for (cgltf_size i = 0; i < draco.attributes_count; i++) {
264
265 // In cgltf, each Draco attribute's data pointer is an attribute id, not an accessor.
266 const uint32_t id = draco.attributes[i].data - asset->mSourceAsset->hierarchy->accessors;
267
268 // Find the destination accessor; this contains the desired component type, etc.
269 const cgltf_attribute_type type = draco.attributes[i].type;
270 const cgltf_int index = draco.attributes[i].index;
271 cgltf_accessor* accessor = findAccessor(prim, type, index);
272 if (!accessor) {
273 slog.w << "Cannot find matching accessor for Draco id " << id << io::endl;
274 continue;
275 }
276
277 // Copy over the decompressed data, converting the data type if necessary.
278 if (!mesh->getVertexAttributes(id, accessor)) {
279 vertexBuffer = nullptr;
280 break;
281 }
282 }
283 }
284 }
285
286 // Parses a data URI and returns a blob that gets malloc'd in cgltf, which the caller must free.
287 // (implementation snarfed from meshoptimizer)
288 static const uint8_t* parseDataUri(const char* uri, std::string* mimeType, size_t* psize) {
289 if (strncmp(uri, "data:", 5) != 0) {
290 return nullptr;
291 }
292 const char* comma = strchr(uri, ',');
293 if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0) {
294 const char* base64 = comma + 1;
295 const size_t base64Size = strlen(base64);
296 size_t size = base64Size - base64Size / 4;
297 if (base64Size >= 2) {
298 size -= base64[base64Size - 2] == '=';
299 size -= base64[base64Size - 1] == '=';
300 }
301 void* data = 0;
302 cgltf_options options = {};
303 cgltf_result result = cgltf_load_buffer_base64(&options, size, base64, &data);
304 if (result != cgltf_result_success) {
305 return nullptr;
306 }
307 *mimeType = std::string(uri + 5, comma - 7);
308 *psize = size;
309 return (const uint8_t*) data;
310 }
311 return nullptr;
312 }
313
314 ResourceLoader::ResourceLoader(const ResourceConfiguration& config) : pImpl(new Impl(config)) { }
315
316 ResourceLoader::~ResourceLoader() {
317 delete pImpl;
318 }
319
320 void ResourceLoader::addResourceData(const char* uri, BufferDescriptor&& buffer) {
321 // Start an async marker the first time this is called and end it when
322 // finalization begins. This marker provides a rough indicator of how long
323 // the client is taking to load raw data blobs from storage.
324 if (pImpl->mUriDataCache.empty()) {
325 SYSTRACE_CONTEXT();
326 SYSTRACE_ASYNC_BEGIN("addResourceData", 1);
327 }
328 // NOTE: replacing an existing item in a robin map does not seem to behave as expected.
329 // To work around this, we explicitly erase the old element if it already exists.
330 auto iter = pImpl->mUriDataCache.find(uri);
331 if (iter != pImpl->mUriDataCache.end()) {
332 pImpl->mUriDataCache.erase(iter);
333 }
334 pImpl->mUriDataCache.emplace(uri, std::move(buffer));
335 }
336
337 bool ResourceLoader::hasResourceData(const char* uri) const {
338 return pImpl->mUriDataCache.find(uri) != pImpl->mUriDataCache.end();
339 }
340
341 void ResourceLoader::evictResourceData() {
342 // Note that this triggers BufferDescriptor callbacks.
343 pImpl->mUriDataCache.clear();
344 }
345
346 bool ResourceLoader::loadResources(FilamentAsset* asset) {
347 FFilamentAsset* fasset = upcast(asset);
348 return loadResources(fasset, false);
349 }
350
351 bool ResourceLoader::loadResources(FFilamentAsset* asset, bool async) {
352 SYSTRACE_CONTEXT();
353 SYSTRACE_ASYNC_END("addResourceData", 1);
354
355 if (asset->mResourcesLoaded) {
356 return false;
357 }
358 const cgltf_data* gltf = asset->mSourceAsset->hierarchy;
359 cgltf_options options {};
360
361 // For emscripten and Android builds we have a custom implementation of cgltf_load_buffers which
362 // looks inside a cache of externally-supplied data blobs, rather than loading from the
363 // filesystem.
364
365 SYSTRACE_NAME_BEGIN("Load buffers");
366 #if !USE_FILESYSTEM
367
368 if (gltf->buffers_count && !gltf->buffers[0].data && !gltf->buffers[0].uri && gltf->bin) {
369 if (gltf->bin_size < gltf->buffers[0].size) {
370 slog.e << "Bad size." << io::endl;
371 return false;
372 }
373 gltf->buffers[0].data = (void*) gltf->bin;
374 }
375
376 bool missingResources = false;
377
378 for (cgltf_size i = 0; i < gltf->buffers_count; ++i) {
379 if (gltf->buffers[i].data) {
380 continue;
381 }
382 const char* uri = gltf->buffers[i].uri;
383 if (uri == nullptr) {
384 continue;
385 }
386 if (strncmp(uri, "data:", 5) == 0) {
387 const char* comma = strchr(uri, ',');
388 if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0) {
389 cgltf_result res = cgltf_load_buffer_base64(&options, gltf->buffers[i].size, comma + 1, &gltf->buffers[i].data);
390 if (res != cgltf_result_success) {
391 slog.e << "Unable to load " << uri << io::endl;
392 return false;
393 }
394 } else {
395 slog.e << "Unable to load " << uri << io::endl;
396 return false;
397 }
398 } else if (strstr(uri, "://") == nullptr) {
399 auto iter = pImpl->mUriDataCache.find(uri);
400 if (iter == pImpl->mUriDataCache.end()) {
401 slog.e << "Unable to load external resource: " << uri << io::endl;
402 missingResources = true;
403 }
404 // Make a copy to allow cgltf_free() to work as expected and prevent a double-free.
405 // TODO: Future versions of CGLTF will make this easier, see the following ticket.
406 // https://github.com/jkuhlmann/cgltf/issues/94
407 gltf->buffers[i].data = malloc(iter->second.size);
408 memcpy(gltf->buffers[i].data, iter->second.buffer, iter->second.size);
409 } else {
410 slog.e << "Unable to load " << uri << io::endl;
411 return false;
412 }
413 }
414
415 if (missingResources) {
416 slog.e << "Some external resources have not been added via addResourceData()" << io::endl;
417 return false;
418 }
419
420 #else
421
422 // Read data from the file system and base64 URIs.
423 cgltf_result result = cgltf_load_buffers(&options, (cgltf_data*) gltf, pImpl->mGltfPath.c_str());
424 if (result != cgltf_result_success) {
425 slog.e << "Unable to load resources." << io::endl;
426 return false;
427 }
428
429 #endif
430 SYSTRACE_NAME_END();
431
432 #ifndef NDEBUG
433 if (cgltf_validate((cgltf_data*) gltf) != cgltf_result_success) {
434 slog.e << "Failed cgltf validation." << io::endl;
435 return false;
436 }
437 #endif
438
439 // Decompress Draco meshes early on, which allows us to exploit subsequent processing such as
440 // tangent generation.
441 decodeDracoMeshes(asset);
442
443 // Normalize skinning weights, then "import" each skin into the asset by building a mapping of
444 // skins to their affected entities.
445 if (gltf->skins_count > 0) {
446 if (pImpl->mNormalizeSkinningWeights) {
447 normalizeSkinningWeights(asset);
448 }
449 if (!asset->isInstanced()) {
450 importSkins(gltf, asset->mNodeMap, asset->mSkins);
451 } else {
452 // NOTE: This takes care of up-front instances, but dynamically added instances also
453 // need to import the skin data, which is done in AssetLoader.
454 for (FFilamentInstance* instance : asset->mInstances) {
455 importSkins(gltf, instance->nodeMap, instance->skins);
456 }
457 }
458 }
459
460 if (pImpl->mRecomputeBoundingBoxes) {
461 updateBoundingBoxes(asset);
462 }
463
464 Engine& engine = *pImpl->mEngine;
465
466 // Upload VertexBuffer and IndexBuffer data to the GPU.
467 for (auto slot : asset->mBufferSlots) {
468 const cgltf_accessor* accessor = slot.accessor;
469 if (!accessor->buffer_view) {
470 continue;
471 }
472 auto bufferData = (const uint8_t*) accessor->buffer_view->buffer->data;
473 const uint8_t* data = computeBindingOffset(accessor) + bufferData;
474 const uint32_t size = computeBindingSize(accessor);
475 if (slot.vertexBuffer) {
476 if (requiresConversion(accessor->type, accessor->component_type)) {
477 const size_t dim = cgltf_num_components(accessor->type);
478 const size_t floatsSize = accessor->count * sizeof(float) * dim;
479 float* floatsData = (float*) malloc(floatsSize);
480 convertToFloats(floatsData, accessor);
481 BufferObject* bo = BufferObject::Builder().size(floatsSize).build(engine);
482 asset->mBufferObjects.push_back(bo);
483 bo->setBuffer(engine, BufferDescriptor(floatsData, floatsSize, FREE_CALLBACK));
484 slot.vertexBuffer->setBufferObjectAt(engine, slot.bufferIndex, bo);
485 continue;
486 }
487 BufferObject* bo = BufferObject::Builder().size(size).build(engine);
488 asset->mBufferObjects.push_back(bo);
489 bo->setBuffer(engine, BufferDescriptor(data, size,
490 uploadCallback, uploadUserdata(asset)));
491 slot.vertexBuffer->setBufferObjectAt(engine, slot.bufferIndex, bo);
492 continue;
493 }
494 assert(slot.indexBuffer);
495 if (accessor->component_type == cgltf_component_type_r_8u) {
496 const size_t size16 = size * 2;
497 uint16_t* data16 = (uint16_t*) malloc(size16);
498 convertBytesToShorts(data16, data, size);
499 IndexBuffer::BufferDescriptor bd(data16, size16, FREE_CALLBACK);
500 slot.indexBuffer->setBuffer(engine, std::move(bd));
501 continue;
502 }
503 IndexBuffer::BufferDescriptor bd(data, size, uploadCallback, uploadUserdata(asset));
504 slot.indexBuffer->setBuffer(engine, std::move(bd));
505 }
506
507 // Apply sparse data modifications to base arrays, then upload the result.
508 applySparseData(asset);
509
510 // Compute surface orientation quaternions if necessary. This is similar to sparse data in that
511 // we need to generate the contents of a GPU buffer by processing one or more CPU buffer(s).
512 pImpl->computeTangents(asset);
513
514 // Non-textured renderables are now considered ready, so notify the dependency graph.
515 asset->mDependencyGraph.finalize();
516 pImpl->mCurrentAsset = asset;
517
518 // Finally, create Filament Textures and begin loading image files.
519 asset->mResourcesLoaded = pImpl->createTextures(async);
520 return asset->mResourcesLoaded;
521 }
522
523 bool ResourceLoader::asyncBeginLoad(FilamentAsset* asset) {
524 return loadResources(upcast(asset), true);
525 }
526
527 void ResourceLoader::asyncCancelLoad() {
528 pImpl->cancelTextureDecoding();
529 pImpl->mEngine->flushAndWait();
530 }
531
532 float ResourceLoader::asyncGetLoadProgress() const {
533 const float finished = pImpl->mNumDecoderTasksFinished;
534 const float total = pImpl->mNumDecoderTasks;
535 return total == 0 ? 0 : finished / total;
536 }
537
538 void ResourceLoader::asyncUpdateLoad() {
539 if (!UTILS_HAS_THREADING) {
540 pImpl->decodeSingleTexture();
541 }
542 pImpl->uploadPendingTextures();
543 }
544
545 void ResourceLoader::Impl::decodeSingleTexture() {
546 assert(!UTILS_HAS_THREADING);
547 int w, h, c;
548
549 // Check if any buffer-based textures haven't been decoded yet.
550 for (auto& pair : mBufferTextureCache) {
551 const uint8_t* sourceData = (const uint8_t*) pair.first;
552 TextureCacheEntry* entry = pair.second.get();
553 if (entry->texels) {
554 continue;
555 }
556 entry->texels = stbi_load_from_memory(sourceData, entry->bufferSize, &w, &h, &c, 4);
557 return;
558 }
559
560 // Check if any URI-based textures haven't been decoded yet.
561 for (auto& pair : mUriTextureCache) {
562 auto uri = pair.first;
563 TextureCacheEntry* entry = pair.second.get();
564 if (entry->texels) {
565 continue;
566 }
567
568 // First, check the user-supplied resource cache for this URI.
569 auto iter = mUriDataCache.find(uri);
570 if (iter != mUriDataCache.end()) {
571 const uint8_t* sourceData = (const uint8_t*) iter->second.buffer;
572 entry->texels = stbi_load_from_memory(sourceData, iter->second.size, &w, &h, &c, 4);
573 return;
574 }
575
576 // Otherwise load it from the file system if this platform supports it.
577 #if !USE_FILESYSTEM
578 slog.e << "Unable to load texture: " << uri << io::endl;
579 entry->completed = true;
580 mNumDecoderTasksFinished++;
581 return;
582 #else
583 Path fullpath = Path(mGltfPath).getParent() + uri;
584 entry->texels = stbi_load(fullpath.c_str(), &w, &h, &c, 4);
585 return;
586 #endif
587 }
588 }
589
590 void ResourceLoader::Impl::uploadPendingTextures() {
591 auto upload = [this](TextureCacheEntry* entry, Engine& engine) {
592 Texture* texture = entry->texture;
593 uint8_t* texels = entry->texels;
594 if (texture && texels && !entry->completed) {
595 Texture::PixelBufferDescriptor pbd(texels,
596 texture->getWidth() * texture->getHeight() * 4,
597 Texture::Format::RGBA, Texture::Type::UBYTE, FREE_CALLBACK);
598 texture->setImage(engine, 0, std::move(pbd));
599 texture->generateMipmaps(engine);
600 entry->completed = true;
601 mNumDecoderTasksFinished++;
602 mCurrentAsset->mDependencyGraph.markAsReady(texture);
603 }
604 };
605 for (auto& pair : mBufferTextureCache) upload(pair.second.get(), *mEngine);
606 for (auto& pair : mUriTextureCache) upload(pair.second.get(), *mEngine);
607 }
608
609 void ResourceLoader::Impl::releasePendingTextures() {
610 auto release = [this](TextureCacheEntry* entry, Engine& engine) {
611 Texture* texture = entry->texture;
612 uint8_t* texels = entry->texels;
613 if (texture && texels && !entry->completed) {
614 // Normally the ownership of these texels is transferred to PixelBufferDescriptor, but
615 // if uploads have been cancelled then we need to free them explicitly.
616 free(texels);
617 }
618 };
619 for (auto& pair : mBufferTextureCache) release(pair.second.get(), *mEngine);
620 for (auto& pair : mUriTextureCache) release(pair.second.get(), *mEngine);
621 }
622
623 void ResourceLoader::Impl::addTextureCacheEntry(const TextureSlot& tb) {
624 TextureCacheEntry* entry = nullptr;
625
626 const cgltf_texture* srcTexture = tb.texture;
627 const cgltf_buffer_view* bv = srcTexture->image->buffer_view;
628 const char* uri = srcTexture->image->uri;
629 const uint32_t totalSize = uint32_t(bv ? bv->size : 0);
630 void** data = bv ? &bv->buffer->data : nullptr;
631 const size_t offset = bv ? bv->offset : 0;
632
633 // Check if the texture binding uses BufferView data (i.e. it does not have a URI).
634 if (data) {
635 const uint8_t* sourceData = offset + (const uint8_t*) *data;
636 entry = mBufferTextureCache[sourceData] ? mBufferTextureCache[sourceData].get() : nullptr;
637 if (entry) {
638 return;
639 }
640 entry = (mBufferTextureCache[sourceData] = std::make_unique<TextureCacheEntry>()).get();
641 entry->srgb = tb.srgb;
642 if (!stbi_info_from_memory(sourceData, totalSize, &entry->width, &entry->height,
643 &entry->numComponents)) {
644 slog.e << "Unable to decode BufferView texture: " << stbi_failure_reason() << io::endl;
645 mBufferTextureCache.erase(sourceData);
646 return;
647 }
648 entry->bufferSize = totalSize;
649 return;
650 }
651
652 // Check if we already created a Texture object for this URI.
653 entry = mUriTextureCache[uri] ? mUriTextureCache[uri].get() : nullptr;
654 if (entry) {
655 return;
656 }
657
658 entry = (mUriTextureCache[uri] = std::make_unique<TextureCacheEntry>()).get();
659 entry->srgb = tb.srgb;
660
661 // Check if this is a data URI. We don't care about the MIME type since stb can infer it.
662 std::string mimeType;
663 size_t dataUriSize;
664 const uint8_t* dataUriContent = parseDataUri(uri, &mimeType, &dataUriSize);
665 if (dataUriContent) {
666 BufferDescriptor buffer(dataUriContent, dataUriSize, FREE_CALLBACK);
667 mUriDataCache.emplace(uri, std::move(buffer));
668 }
669
670 // Check the user-supplied resource cache for this URI, otherwise peek at the file.
671 auto iter = mUriDataCache.find(uri);
672 if (iter != mUriDataCache.end()) {
673 const uint8_t* sourceData = (const uint8_t*) iter->second.buffer;
674 if (!stbi_info_from_memory(sourceData, iter->second.size, &entry->width,
675 &entry->height, &entry->numComponents)) {
676 slog.e << "Unable to decode " << uri << " : " << stbi_failure_reason() << io::endl;
677 mUriTextureCache.erase(uri);
678 }
679 return;
680 }
681 #if !USE_FILESYSTEM
682 slog.e << "Unable to load texture: " << uri << io::endl;
683 #else
684 Path fullpath = Path(mGltfPath).getParent() + uri;
685 if (!stbi_info(fullpath.c_str(), &entry->width, &entry->height, &entry->numComponents)) {
686 slog.e << "Unable to decode " << fullpath.c_str() << " : " << stbi_failure_reason()
687 << io::endl;
688 mUriTextureCache.erase(uri);
689 }
690 #endif
691 }
692
693 void ResourceLoader::Impl::bindTextureToMaterial(const TextureSlot& tb) {
694 FFilamentAsset* asset = mCurrentAsset;
695
696 const cgltf_texture* srcTexture = tb.texture;
697 const cgltf_buffer_view* bv = srcTexture->image->buffer_view;
698 const char* uri = srcTexture->image->uri;
699 void** data = bv ? &bv->buffer->data : nullptr;
700 const size_t offset = bv ? bv->offset : 0;
701
702 // First check if this is a buffer-based texture.
703 if (data) {
704 const uint8_t* sourceData = offset + (const uint8_t*) *data;
705 if (auto iter = mBufferTextureCache.find(sourceData); iter != mBufferTextureCache.end()) {
706 auto& entry = iter->second;
707 if (entry.get() && entry->texture) {
708 asset->bindTexture(tb, entry->texture);
709 }
710 }
711 return;
712 }
713
714 // Next check if this is a URI-based texture.
715 if (auto iter = mUriTextureCache.find(uri); iter != mUriTextureCache.end()) {
716 auto& entry = iter->second;
717 if (entry.get() && entry->texture) {
718 asset->bindTexture(tb, entry->texture);
719 }
720 }
721 }
722
723 void ResourceLoader::Impl::cancelTextureDecoding() {
724 JobSystem* js = &mEngine->getJobSystem();
725 if (mDecoderRootJob) {
726 js->waitAndRelease(mDecoderRootJob);
727 mDecoderRootJob = nullptr;
728 }
729 releasePendingTextures();
730 mBufferTextureCache.clear();
731 mUriTextureCache.clear();
732 mCurrentAsset = nullptr;
733 mNumDecoderTasksFinished = 0;
734 mNumDecoderTasks = 0;
735 }
736
737 bool ResourceLoader::Impl::createTextures(bool async) {
738 // If any decoding jobs are still underway, wait for them to finish.
739 JobSystem* js = &mEngine->getJobSystem();
740 if (mDecoderRootJob) {
741 js->waitAndRelease(mDecoderRootJob);
742 mDecoderRootJob = nullptr;
743 }
744
745 mBufferTextureCache.clear();
746 mUriTextureCache.clear();
747
748 // First, determine texture dimensions and create texture cache entries.
749 FFilamentAsset* asset = mCurrentAsset;
750 for (auto slot : asset->mTextureSlots) {
751 addTextureCacheEntry(slot);
752 }
753
754 // Tally up the total number of textures that need to be decoded. Zero textures is a special
755 // case that needs to report 100% progress right away, so we set NumDecoderTasks and Finished
756 // both to 1. If they were both 0, this would indicate that loading has not started.
757 mNumDecoderTasks = mBufferTextureCache.size() + mUriTextureCache.size();
758 if (mNumDecoderTasks == 0) {
759 mNumDecoderTasks = 1;
760 mNumDecoderTasksFinished = 1;
761 } else {
762 mNumDecoderTasksFinished = 0;
763 }
764
765 // Next create blank Filament textures.
766 auto createTexture = [=](TextureCacheEntry* entry) {
767 entry->texture = Texture::Builder()
768 .width(entry->width)
769 .height(entry->height)
770 .levels(0xff)
771 .format(entry->srgb ? Texture::InternalFormat::SRGB8_A8 : Texture::InternalFormat::RGBA8)
772 .build(*mEngine);
773 asset->takeOwnership(entry->texture);
774 };
775 for (auto& pair : mBufferTextureCache) createTexture(pair.second.get());
776 for (auto& pair : mUriTextureCache) createTexture(pair.second.get());
777
778 // Bind the textures to material instances.
779 for (auto slot : asset->mTextureSlots) {
780 bindTextureToMaterial(slot);
781 }
782
783 // Before creating jobs for PNG / JPEG decoding, we might need to return early. On single
784 // threaded systems, it is usually fine to create jobs because the job system will simply
785 // execute serially. However if the client requests async behavior, then we need to wait
786 // until subsequent calls to asyncUpdateLoad().
787 if (!UTILS_HAS_THREADING && async) {
788 return true;
789 }
790
791 JobSystem::Job* parent = js->createJob();
792
793 // Create a copy of the shared_ptr to the source data to prevent it from being freed during
794 // the texture decoding process.
795 FFilamentAsset::SourceHandle retainSourceAsset = asset->mSourceAsset;
796
797 // Kick off jobs that decode texels from buffer pointers.
798 for (auto& pair : mBufferTextureCache) {
799 const uint8_t* sourceData = (const uint8_t*) pair.first;
800 TextureCacheEntry* entry = pair.second.get();
801 JobSystem::Job* decode = jobs::createJob(*js, parent, [retainSourceAsset, entry, sourceData] {
802 int width, height, comp;
803 entry->texels = stbi_load_from_memory(sourceData, entry->bufferSize,
804 &width, &height, &comp, 4);
805 });
806 js->run(decode);
807 }
808
809 // Kick off jobs that decode texels from URI strings.
810 for (auto& pair : mUriTextureCache) {
811 auto uri = pair.first;
812 TextureCacheEntry* entry = pair.second.get();
813
814 // First, check the user-supplied resource cache for this URI.
815 auto iter = mUriDataCache.find(uri);
816 if (iter != mUriDataCache.end()) {
817 const uint8_t* sourceData = (const uint8_t*) iter->second.buffer;
818 JobSystem::Job* decode = jobs::createJob(*js, parent, [retainSourceAsset, entry, sourceData, iter] {
819 int width, height, comp;
820 entry->texels = stbi_load_from_memory(sourceData, iter->second.size, &width,
821 &height, &comp, 4);
822 });
823 js->run(decode);
824 continue;
825 }
826
827 // Otherwise load it from the file system if this platform supports it.
828 #if !USE_FILESYSTEM
829 slog.e << "Unable to load texture: " << uri << io::endl;
830 return false;
831 #else
832 Path fullpath = Path(mGltfPath).getParent() + uri;
833 JobSystem::Job* decode = jobs::createJob(*js, parent, [retainSourceAsset, entry, fullpath] {
834 int width, height, comp;
835 entry->texels = stbi_load(fullpath.c_str(), &width, &height, &comp, 4);
836 });
837 js->run(decode);
838 #endif
839 }
840
841 if (async) {
842 mDecoderRootJob = js->runAndRetain(parent);
843 return true;
844 }
845
846 // Wait for decoding to finish.
847 js->runAndWait(parent);
848
849 // Finally, upload texels to the GPU and generate mipmaps.
850 mCurrentAsset = asset;
851 uploadPendingTextures();
852
853 return true;
854 }
855
856 void ResourceLoader::Impl::computeTangents(FFilamentAsset* asset) {
857 SYSTRACE_CALL();
858
859 const cgltf_accessor* kGenerateTangents = &asset->mGenerateTangents;
860 const cgltf_accessor* kGenerateNormals = &asset->mGenerateNormals;
861
862 // Collect all TANGENT vertex attribute slots that need to be populated.
863 tsl::robin_map<VertexBuffer*, uint8_t> baseTangents;
864 tsl::robin_map<VertexBuffer*, uint8_t> morphTangents[4];
865 for (auto slot : asset->mBufferSlots) {
866 if (slot.accessor != kGenerateTangents && slot.accessor != kGenerateNormals) {
867 continue;
868 }
869 if (slot.morphTarget) {
870 morphTangents[slot.morphTarget - 1][slot.vertexBuffer] = slot.bufferIndex;
871 continue;
872 }
873 baseTangents[slot.vertexBuffer] = slot.bufferIndex;
874 }
875
876 // Create a job description for each primitive.
877 using Params = TangentsJob::Params;
878 std::vector<Params> jobParams;
879 for (auto pair : asset->mPrimitives) {
880 VertexBuffer* vb = pair.second;
881 auto iter = baseTangents.find(vb);
882 if (iter != baseTangents.end()) {
883 jobParams.emplace_back(Params {{ pair.first }, {vb, iter->second }});
884 }
885 for (int morphTarget = 0; morphTarget < 4; morphTarget++) {
886 const auto& tangents = morphTangents[morphTarget];
887 auto iter = tangents.find(vb);
888 if (iter != tangents.end()) {
889 jobParams.emplace_back(Params {{ pair.first, morphTarget }, {vb, iter->second }});
890 }
891 }
892 }
893
894 // Kick off jobs for computing tangent frames.
895 JobSystem* js = &mEngine->getJobSystem();
896 JobSystem::Job* parent = js->createJob();
897 for (Params& params : jobParams) {
898 Params* pptr = &params;
899 js->run(jobs::createJob(*js, parent, [pptr] { TangentsJob::run(pptr); }));
900 }
901 js->runAndWait(parent);
902
903 // Finally, upload quaternions to the GPU from the main thread.
904 for (Params& params : jobParams) {
905 BufferObject* bo = BufferObject::Builder()
906 .size(params.out.vertexCount * sizeof(short4)).build(*mEngine);
907 asset->mBufferObjects.push_back(bo);
908 bo->setBuffer(*mEngine, BufferDescriptor(
909 params.out.results, bo->getByteCount(), FREE_CALLBACK));
910 params.context.vb->setBufferObjectAt(*mEngine, params.context.slot, bo);
911 }
912 }
913
914 ResourceLoader::Impl::~Impl() {
915 if (mDecoderRootJob) {
916 mEngine->getJobSystem().waitAndRelease(mDecoderRootJob);
917 }
918 }
919
920 void ResourceLoader::applySparseData(FFilamentAsset* asset) const {
921 for (auto slot : asset->mBufferSlots) {
922 const cgltf_accessor* accessor = slot.accessor;
923 if (!accessor->is_sparse) {
924 continue;
925 }
926 cgltf_size numFloats = accessor->count * cgltf_num_components(accessor->type);
927 cgltf_size numBytes = sizeof(float) * numFloats;
928 float* generated = (float*) malloc(numBytes);
929 cgltf_accessor_unpack_floats(accessor, generated, numFloats);
930 BufferObject* bo = BufferObject::Builder().size(numBytes).build(*asset->mEngine);
931 asset->mBufferObjects.push_back(bo);
932 bo->setBuffer(*pImpl->mEngine, BufferDescriptor(generated, numBytes, FREE_CALLBACK));
933 slot.vertexBuffer->setBufferObjectAt(*pImpl->mEngine, slot.bufferIndex, bo);
934 }
935 }
936
937 void ResourceLoader::normalizeSkinningWeights(FFilamentAsset* asset) const {
938 auto normalize = [](cgltf_accessor* data) {
939 if (data->type != cgltf_type_vec4 || data->component_type != cgltf_component_type_r_32f) {
940 slog.w << "Cannot normalize weights, unsupported attribute type." << io::endl;
941 return;
942 }
943 uint8_t* bytes = (uint8_t*) data->buffer_view->buffer->data;
944 bytes += data->offset + data->buffer_view->offset;
945 for (cgltf_size i = 0, n = data->count; i < n; ++i, bytes += data->stride) {
946 float4* weights = (float4*) bytes;
947 const float sum = weights->x + weights->y + weights->z + weights->w;
948 *weights /= sum;
949 }
950 };
951 const cgltf_data* gltf = asset->mSourceAsset->hierarchy;
952 cgltf_size mcount = gltf->meshes_count;
953 for (cgltf_size mindex = 0; mindex < mcount; ++mindex) {
954 const cgltf_mesh& mesh = gltf->meshes[mindex];
955 cgltf_size pcount = mesh.primitives_count;
956 for (cgltf_size pindex = 0; pindex < pcount; ++pindex) {
957 const cgltf_primitive& prim = mesh.primitives[pindex];
958 cgltf_size acount = prim.attributes_count;
959 for (cgltf_size aindex = 0; aindex < acount; ++aindex) {
960 const auto& attr = prim.attributes[aindex];
961 if (attr.type == cgltf_attribute_type_weights) {
962 normalize(attr.data);
963 }
964 }
965 }
966 }
967 }
968
969 void ResourceLoader::updateBoundingBoxes(FFilamentAsset* asset) const {
970 SYSTRACE_CALL();
971 auto& rm = pImpl->mEngine->getRenderableManager();
972 auto& tm = pImpl->mEngine->getTransformManager();
973 NodeMap& nodeMap = asset->isInstanced() ? asset->mInstances[0]->nodeMap : asset->mNodeMap;
974
975 // The purpose of the root node is to give the client a place for custom transforms.
976 // Since it is not part of the source model, it should be ignored when computing the
977 // bounding box.
978 TransformManager::Instance root = tm.getInstance(asset->getRoot());
979 std::vector<Entity> modelRoots(tm.getChildCount(root));
980 tm.getChildren(root, modelRoots.data(), modelRoots.size());
981 for (auto e : modelRoots) {
982 tm.setParent(tm.getInstance(e), 0);
983 }
984
985 auto computeBoundingBox = [](const cgltf_primitive* prim, Aabb* result) {
986 Aabb aabb;
987 for (cgltf_size slot = 0; slot < prim->attributes_count; slot++) {
988 const cgltf_attribute& attr = prim->attributes[slot];
989 const cgltf_accessor* accessor = attr.data;
990 const size_t dim = cgltf_num_components(accessor->type);
991 if (attr.type == cgltf_attribute_type_position && dim >= 3) {
992 std::vector<float> unpacked(accessor->count * dim);
993 cgltf_accessor_unpack_floats(accessor, unpacked.data(), unpacked.size());
994 for (cgltf_size i = 0, j = 0, n = accessor->count; i < n; ++i, j += dim) {
995 float3 pt(unpacked[j + 0], unpacked[j + 1], unpacked[j + 2]);
996 aabb.min = min(aabb.min, pt);
997 aabb.max = max(aabb.max, pt);
998 }
999 break;
1000 }
1001 }
1002 *result = aabb;
1003 };
1004
1005 // Collect all mesh primitives that we wish to find bounds for.
1006 std::vector<cgltf_primitive const*> prims;
1007 for (auto iter : nodeMap) {
1008 const cgltf_mesh* mesh = iter.first->mesh;
1009 if (mesh) {
1010 for (cgltf_size index = 0, nprims = mesh->primitives_count; index < nprims; ++index) {
1011 prims.push_back(&mesh->primitives[index]);
1012 }
1013 }
1014 }
1015
1016 // Kick off a bounding box job for every primitive.
1017 std::vector<Aabb> bounds(prims.size());
1018 JobSystem* js = &pImpl->mEngine->getJobSystem();
1019 JobSystem::Job* parent = js->createJob();
1020 for (size_t i = 0; i < prims.size(); ++i) {
1021 cgltf_primitive const* prim = prims[i];
1022 Aabb* result = &bounds[i];
1023 js->run(jobs::createJob(*js, parent, [prim, result, computeBoundingBox] {
1024 computeBoundingBox(prim, result);
1025 }));
1026 }
1027 js->runAndWait(parent);
1028
1029 // Compute the asset-level bounding box.
1030 size_t primIndex = 0;
1031 Aabb assetBounds;
1032 for (auto iter : nodeMap) {
1033 const cgltf_mesh* mesh = iter.first->mesh;
1034 if (mesh) {
1035 // Find the object-space bounds for the renderable by unioning the bounds of each prim.
1036 Aabb aabb;
1037 for (cgltf_size index = 0, nprims = mesh->primitives_count; index < nprims; ++index) {
1038 Aabb primBounds = bounds[primIndex++];
1039 aabb.min = min(aabb.min, primBounds.min);
1040 aabb.max = max(aabb.max, primBounds.max);
1041 }
1042 auto renderable = rm.getInstance(iter.second);
1043 rm.setAxisAlignedBoundingBox(renderable, Box().set(aabb.min, aabb.max));
1044
1045 // Transform this bounding box, then update the asset-level bounding box.
1046 auto transformable = tm.getInstance(iter.second);
1047 const mat4f worldTransform = tm.getWorldTransform(transformable);
1048 const Aabb transformed = aabb.transform(worldTransform);
1049 assetBounds.min = min(assetBounds.min, transformed.min);
1050 assetBounds.max = max(assetBounds.max, transformed.max);
1051 }
1052 }
1053
1054 for (auto e : modelRoots) {
1055 tm.setParent(tm.getInstance(e), root);
1056 }
1057
1058 asset->mBoundingBox = assetBounds;
1059 }
1060
1061 } // namespace gltfio