Debian Codegraph @

libs/gltfio/src/DracoCache.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 "DracoCache.h"
18
19 #if GLTFIO_DRACO_SUPPORTED
20 #include <draco/compression/decode.h>
21 #endif
22
23 #include <utils/Log.h>
24
25 #include <memory>
26 #include <vector>
27
28 using std::unique_ptr;
29 using std::vector;
30
31 using namespace utils;
32
33 namespace gltfio {
34
35 DracoMesh* DracoCache::findOrCreateMesh(const cgltf_buffer_view* key) {
36 auto iter = mCache.find(key);
37 if (iter != mCache.end()) {
38 return iter->second.get();
39 }
40 assert(key->buffer && key->buffer->data);
41 const uint8_t* compressedData = key->offset + (uint8_t*) key->buffer->data;
42 DracoMesh* mesh = DracoMesh::decode(compressedData, key->size);
43 mCache.emplace(key, mesh);
44 return mesh;
45 }
46
47 DracoMesh::DracoMesh(struct DracoMeshDetails* details) : mDetails(details) {}
48
49 #if GLTFIO_DRACO_SUPPORTED
50
51 struct DracoMeshDetails {
52 unique_ptr<draco::Mesh> mesh;
53 vector<unique_ptr<cgltf_buffer_view>> views;
54 vector<unique_ptr<cgltf_buffer>> buffers;
55 };
56
57 DracoMesh::~DracoMesh() {
58 for (auto& buffer : mDetails->buffers) {
59 free(buffer->data);
60 }
61 }
62
63 // Gets the number of components in the given cgltf vector type, or -1 for matrices.
64 static int getNumComponents(cgltf_type ctype) {
65 return ((int) ctype) <= 4 ? ((int) ctype) : -1;
66 }
67
68 // Allocates and populates the given buffer view with indices from the given Draco mesh.
69 template<typename T>
70 static void convertFaces(cgltf_accessor* target, const draco::Mesh* mesh) {
71 assert(target->stride == sizeof(T));
72
73 const cgltf_size size = mesh->num_faces() * 3 * sizeof(T);
74 cgltf_buffer_view* view = target->buffer_view;
75 cgltf_buffer* buffer = view->buffer;
76 *buffer = { nullptr, size, nullptr, malloc(size) };
77 *view = { nullptr, buffer, 0, size, 0, cgltf_buffer_view_type_indices };
78 T* dest = (T*) buffer->data;
79 for (uint32_t id = 0, n = mesh->num_faces(); id < n; ++id) {
80 draco::Mesh::Face face = mesh->face(draco::FaceIndex(id));
81 *dest++ = face[0].value();
82 *dest++ = face[1].value();
83 *dest++ = face[2].value();
84 }
85 }
86
87 // Converts vertex attributes into the desired format and populates the given cgltf buffer.
88 template<typename T>
89 static void convertAttribs(cgltf_accessor* target, const draco::PointAttribute* attr, uint32_t n) {
90 const int8_t ncomps = attr->num_components();
91 assert(ncomps <= 4 && ncomps == getNumComponents(target->type));
92 assert(target->stride == attr->num_components() * sizeof(T));
93
94 const uint32_t size = target->stride * n;
95 cgltf_buffer_view* view = target->buffer_view;
96 cgltf_buffer* buffer = view->buffer;
97 *buffer = { nullptr, size, nullptr, malloc(size) };
98 *view = { nullptr, buffer, 0, size, 0, cgltf_buffer_view_type_vertices };
99 T* dest = (T*) buffer->data;
100 for (draco::PointIndex i(0); i < n; ++i, dest += ncomps) {
101 attr->ConvertValue(attr->mapped_index(i), ncomps, dest);
102 }
103 }
104
105 DracoMesh* DracoMesh::decode(const uint8_t* data, size_t dataSize) {
106 draco::DecoderBuffer buffer;
107 buffer.Init((const char*) data, dataSize);
108 draco::Decoder decoder;
109 const auto geotype = decoder.GetEncodedGeometryType(&buffer);
110 if (!geotype.ok() || geotype.value() != draco::EncodedGeometryType::TRIANGULAR_MESH) {
111 return nullptr;
112 }
113 auto meshStatus = decoder.DecodeMeshFromBuffer(&buffer);
114 if (!meshStatus.ok()) {
115 return nullptr;
116 }
117 return new DracoMesh(new DracoMeshDetails { std::move(meshStatus).value() });
118 }
119
120 bool DracoMesh::getFaceIndices(cgltf_accessor* target) const {
121 // Return early if we've already decompressed this data.
122 if (target->buffer_view) {
123 return true;
124 }
125
126 draco::Mesh* mesh = mDetails->mesh.get();
127
128 // Check the accessor's index count against the number of faces in the Draco mesh.
129 // It would be tricky to be robust against a mismatch; see the class comment for DracoMesh.
130 uint32_t count = mesh->num_faces() * 3;
131 if (target->count != count) {
132 slog.e << "The glTF accessor wants " << target->count << " indices, "
133 << "but the decoded Draco mesh has " << count << " indices." << io::endl;
134 return false;
135 }
136
137 cgltf_buffer_view* view = new cgltf_buffer_view;
138 cgltf_buffer* buffer = view->buffer = new cgltf_buffer;
139
140 mDetails->views.emplace_back(view);
141 mDetails->buffers.emplace_back(buffer);
142
143 target->offset = 0;
144 target->buffer_view = view;
145
146 switch (target->component_type) {
147 case cgltf_component_type_r_16u: convertFaces<uint16_t>(target, mesh); break;
148 case cgltf_component_type_r_32u: convertFaces<uint32_t>(target, mesh); break;
149 case cgltf_component_type_r_8u: convertFaces<uint8_t>(target, mesh); break;
150 default:
151 slog.e << "Unexpected component type for Draco indices." << io::endl;
152 return false;
153 }
154 return true;
155 }
156
157 bool DracoMesh::getVertexAttributes(uint32_t attributeId, cgltf_accessor* target) const {
158 // Return early if we've already decompressed this data.
159 if (target->buffer_view) {
160 return true;
161 }
162
163 // Return early if no such attribute exists.
164 draco::Mesh* mesh = mDetails->mesh.get();
165 const draco::PointAttribute* attr = mesh->GetAttributeByUniqueId(attributeId);
166 if (!attr) {
167 slog.e << "Unknown Draco point attribute." << io::endl;
168 return false;
169 }
170
171 // Check if the accessor's vertex count matches with the Draco vertex count. If a mismatch
172 // occurs we try to recover by adjusting the vertex count. Even though this is a spec violation,
173 // this often occurs in the wild. If we need to be even more robust, see the class comment for
174 // DracoMesh.
175 uint32_t count = mesh->num_points();
176 if (target->count != count) {
177 slog.e << "The glTF accessor wants " << target->count << " vertices, "
178 << "but the decoded Draco mesh has " << count << " vertices." << io::endl;
179
180 // It is tempting to degrade gracefully by processing only the lesser of the two
181 // counts, but doing so would lead to invalid indices in the index buffer.
182 return false;
183 }
184
185 cgltf_buffer_view* view = new cgltf_buffer_view;
186 cgltf_buffer* buffer = view->buffer = new cgltf_buffer;
187
188 mDetails->views.emplace_back(view);
189 mDetails->buffers.emplace_back(buffer);
190
191 target->offset = 0;
192 target->buffer_view = view;
193
194 switch (target->component_type) {
195 case cgltf_component_type_r_8: convertAttribs<int8_t>(target, attr, count); break;
196 case cgltf_component_type_r_8u: convertAttribs<uint8_t>(target, attr, count); break;
197 case cgltf_component_type_r_16: convertAttribs<int16_t>(target, attr, count); break;
198 case cgltf_component_type_r_16u: convertAttribs<uint16_t>(target, attr, count); break;
199 case cgltf_component_type_r_32u: convertAttribs<uint32_t>(target, attr, count); break;
200 case cgltf_component_type_r_32f: convertAttribs<float>(target, attr, count); break;
201 default:
202 slog.e << "Unexpected component type for Draco vertices." << io::endl;
203 break;
204 }
205
206 return true;
207 }
208
209 #else // #if GLTFIO_DRACO_SUPPORTED
210
211 DracoMesh::~DracoMesh() {}
212 struct DracoMeshDetails {};
213 DracoMesh* DracoMesh::decode(const uint8_t* data, size_t dataSize) { return nullptr; }
214
215 bool DracoMesh::getFaceIndices(cgltf_accessor* target) const {
216 return false;
217 }
218
219 bool DracoMesh::getVertexAttributes(uint32_t attributeId, cgltf_accessor* target) const {
220 return false;
221 }
222
223 #endif
224
225 } // namespace gltfio