Debian Codegraph @

modules/gltf/structures/gltf_accessor.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* gltf_accessor.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "gltf_accessor.h"
32 #include "gltf_accessor.compat.inc"
33
34 #include "../gltf_state.h"
35
36 void GLTFAccessor::_bind_methods() {
37 BIND_ENUM_CONSTANT(TYPE_SCALAR);
38 BIND_ENUM_CONSTANT(TYPE_VEC2);
39 BIND_ENUM_CONSTANT(TYPE_VEC3);
40 BIND_ENUM_CONSTANT(TYPE_VEC4);
41 BIND_ENUM_CONSTANT(TYPE_MAT2);
42 BIND_ENUM_CONSTANT(TYPE_MAT3);
43 BIND_ENUM_CONSTANT(TYPE_MAT4);
44
45 BIND_ENUM_CONSTANT(COMPONENT_TYPE_NONE);
46 BIND_ENUM_CONSTANT(COMPONENT_TYPE_SIGNED_BYTE);
47 BIND_ENUM_CONSTANT(COMPONENT_TYPE_UNSIGNED_BYTE);
48 BIND_ENUM_CONSTANT(COMPONENT_TYPE_SIGNED_SHORT);
49 BIND_ENUM_CONSTANT(COMPONENT_TYPE_UNSIGNED_SHORT);
50 BIND_ENUM_CONSTANT(COMPONENT_TYPE_SIGNED_INT);
51 BIND_ENUM_CONSTANT(COMPONENT_TYPE_UNSIGNED_INT);
52 BIND_ENUM_CONSTANT(COMPONENT_TYPE_SINGLE_FLOAT);
53 BIND_ENUM_CONSTANT(COMPONENT_TYPE_DOUBLE_FLOAT);
54 BIND_ENUM_CONSTANT(COMPONENT_TYPE_HALF_FLOAT);
55 BIND_ENUM_CONSTANT(COMPONENT_TYPE_SIGNED_LONG);
56 BIND_ENUM_CONSTANT(COMPONENT_TYPE_UNSIGNED_LONG);
57
58 ClassDB::bind_static_method("GLTFAccessor", D_METHOD("from_dictionary", "dictionary"), &GLTFAccessor::from_dictionary);
59 ClassDB::bind_method(D_METHOD("to_dictionary"), &GLTFAccessor::to_dictionary);
60
61 ClassDB::bind_method(D_METHOD("get_buffer_view"), &GLTFAccessor::get_buffer_view);
62 ClassDB::bind_method(D_METHOD("set_buffer_view", "buffer_view"), &GLTFAccessor::set_buffer_view);
63 ClassDB::bind_method(D_METHOD("get_byte_offset"), &GLTFAccessor::get_byte_offset);
64 ClassDB::bind_method(D_METHOD("set_byte_offset", "byte_offset"), &GLTFAccessor::set_byte_offset);
65 ClassDB::bind_method(D_METHOD("get_component_type"), &GLTFAccessor::get_component_type);
66 ClassDB::bind_method(D_METHOD("set_component_type", "component_type"), &GLTFAccessor::set_component_type);
67 ClassDB::bind_method(D_METHOD("get_normalized"), &GLTFAccessor::get_normalized);
68 ClassDB::bind_method(D_METHOD("set_normalized", "normalized"), &GLTFAccessor::set_normalized);
69 ClassDB::bind_method(D_METHOD("get_count"), &GLTFAccessor::get_count);
70 ClassDB::bind_method(D_METHOD("set_count", "count"), &GLTFAccessor::set_count);
71 ClassDB::bind_method(D_METHOD("get_accessor_type"), &GLTFAccessor::get_accessor_type);
72 ClassDB::bind_method(D_METHOD("set_accessor_type", "accessor_type"), &GLTFAccessor::set_accessor_type);
73 ClassDB::bind_method(D_METHOD("get_type"), &GLTFAccessor::get_type);
74 ClassDB::bind_method(D_METHOD("set_type", "type"), &GLTFAccessor::set_type);
75 ClassDB::bind_method(D_METHOD("get_min"), &GLTFAccessor::get_min);
76 ClassDB::bind_method(D_METHOD("set_min", "min"), &GLTFAccessor::set_min);
77 ClassDB::bind_method(D_METHOD("get_max"), &GLTFAccessor::get_max);
78 ClassDB::bind_method(D_METHOD("set_max", "max"), &GLTFAccessor::set_max);
79 ClassDB::bind_method(D_METHOD("get_sparse_count"), &GLTFAccessor::get_sparse_count);
80 ClassDB::bind_method(D_METHOD("set_sparse_count", "sparse_count"), &GLTFAccessor::set_sparse_count);
81 ClassDB::bind_method(D_METHOD("get_sparse_indices_buffer_view"), &GLTFAccessor::get_sparse_indices_buffer_view);
82 ClassDB::bind_method(D_METHOD("set_sparse_indices_buffer_view", "sparse_indices_buffer_view"), &GLTFAccessor::set_sparse_indices_buffer_view);
83 ClassDB::bind_method(D_METHOD("get_sparse_indices_byte_offset"), &GLTFAccessor::get_sparse_indices_byte_offset);
84 ClassDB::bind_method(D_METHOD("set_sparse_indices_byte_offset", "sparse_indices_byte_offset"), &GLTFAccessor::set_sparse_indices_byte_offset);
85 ClassDB::bind_method(D_METHOD("get_sparse_indices_component_type"), &GLTFAccessor::get_sparse_indices_component_type);
86 ClassDB::bind_method(D_METHOD("set_sparse_indices_component_type", "sparse_indices_component_type"), &GLTFAccessor::set_sparse_indices_component_type);
87 ClassDB::bind_method(D_METHOD("get_sparse_values_buffer_view"), &GLTFAccessor::get_sparse_values_buffer_view);
88 ClassDB::bind_method(D_METHOD("set_sparse_values_buffer_view", "sparse_values_buffer_view"), &GLTFAccessor::set_sparse_values_buffer_view);
89 ClassDB::bind_method(D_METHOD("get_sparse_values_byte_offset"), &GLTFAccessor::get_sparse_values_byte_offset);
90 ClassDB::bind_method(D_METHOD("set_sparse_values_byte_offset", "sparse_values_byte_offset"), &GLTFAccessor::set_sparse_values_byte_offset);
91
92 ADD_PROPERTY(PropertyInfo(Variant::INT, "buffer_view"), "set_buffer_view", "get_buffer_view"); // GLTFBufferViewIndex
93 ADD_PROPERTY(PropertyInfo(Variant::INT, "byte_offset"), "set_byte_offset", "get_byte_offset"); // int
94 ADD_PROPERTY(PropertyInfo(Variant::INT, "component_type"), "set_component_type", "get_component_type"); // int
95 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "normalized"), "set_normalized", "get_normalized"); // bool
96 ADD_PROPERTY(PropertyInfo(Variant::INT, "count"), "set_count", "get_count"); // int
97 ADD_PROPERTY(PropertyInfo(Variant::INT, "accessor_type"), "set_accessor_type", "get_accessor_type"); // GLTFAccessor::GLTFAccessorType
98 ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_type", "get_type"); // Deprecated, int for GLTFAccessor::GLTFAccessorType
99 ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT64_ARRAY, "min"), "set_min", "get_min"); // Vector<real_t>
100 ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT64_ARRAY, "max"), "set_max", "get_max"); // Vector<real_t>
101 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_count"), "set_sparse_count", "get_sparse_count"); // int
102 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_buffer_view"), "set_sparse_indices_buffer_view", "get_sparse_indices_buffer_view"); // int
103 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_byte_offset"), "set_sparse_indices_byte_offset", "get_sparse_indices_byte_offset"); // int
104 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_component_type"), "set_sparse_indices_component_type", "get_sparse_indices_component_type"); // int
105 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_values_buffer_view"), "set_sparse_values_buffer_view", "get_sparse_values_buffer_view"); // int
106 ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_values_byte_offset"), "set_sparse_values_byte_offset", "get_sparse_values_byte_offset"); // int
107 }
108
109 // Property getters and setters.
110
111 GLTFBufferViewIndex GLTFAccessor::get_buffer_view() const {
112 return buffer_view;
113 }
114
115 void GLTFAccessor::set_buffer_view(GLTFBufferViewIndex p_buffer_view) {
116 buffer_view = p_buffer_view;
117 }
118
119 int64_t GLTFAccessor::get_byte_offset() const {
120 return byte_offset;
121 }
122
123 void GLTFAccessor::set_byte_offset(int64_t p_byte_offset) {
124 byte_offset = p_byte_offset;
125 }
126
127 GLTFAccessor::GLTFComponentType GLTFAccessor::get_component_type() const {
128 return component_type;
129 }
130
131 void GLTFAccessor::set_component_type(GLTFComponentType p_component_type) {
132 component_type = (GLTFComponentType)p_component_type;
133 }
134
135 bool GLTFAccessor::get_normalized() const {
136 return normalized;
137 }
138
139 void GLTFAccessor::set_normalized(bool p_normalized) {
140 normalized = p_normalized;
141 }
142
143 int64_t GLTFAccessor::get_count() const {
144 return count;
145 }
146
147 void GLTFAccessor::set_count(int64_t p_count) {
148 count = p_count;
149 }
150
151 GLTFAccessor::GLTFAccessorType GLTFAccessor::get_accessor_type() const {
152 return accessor_type;
153 }
154
155 void GLTFAccessor::set_accessor_type(GLTFAccessorType p_accessor_type) {
156 accessor_type = p_accessor_type;
157 }
158
159 int GLTFAccessor::get_type() const {
160 return (int)accessor_type;
161 }
162
163 void GLTFAccessor::set_type(int p_accessor_type) {
164 accessor_type = (GLTFAccessorType)p_accessor_type; // TODO: Register enum
165 }
166
167 Vector<double> GLTFAccessor::get_min() const {
168 return Vector<double>(min);
169 }
170
171 void GLTFAccessor::set_min(const Vector<double> &p_min) {
172 min = Vector<double>(p_min);
173 }
174
175 Vector<double> GLTFAccessor::get_max() const {
176 return Vector<double>(max);
177 }
178
179 void GLTFAccessor::set_max(const Vector<double> &p_max) {
180 max = Vector<double>(p_max);
181 }
182
183 int64_t GLTFAccessor::get_sparse_count() const {
184 return sparse_count;
185 }
186
187 void GLTFAccessor::set_sparse_count(int64_t p_sparse_count) {
188 sparse_count = p_sparse_count;
189 }
190
191 GLTFBufferViewIndex GLTFAccessor::get_sparse_indices_buffer_view() const {
192 return sparse_indices_buffer_view;
193 }
194
195 void GLTFAccessor::set_sparse_indices_buffer_view(GLTFBufferViewIndex p_sparse_indices_buffer_view) {
196 sparse_indices_buffer_view = p_sparse_indices_buffer_view;
197 }
198
199 int64_t GLTFAccessor::get_sparse_indices_byte_offset() const {
200 return sparse_indices_byte_offset;
201 }
202
203 void GLTFAccessor::set_sparse_indices_byte_offset(int64_t p_sparse_indices_byte_offset) {
204 sparse_indices_byte_offset = p_sparse_indices_byte_offset;
205 }
206
207 GLTFAccessor::GLTFComponentType GLTFAccessor::get_sparse_indices_component_type() const {
208 return sparse_indices_component_type;
209 }
210
211 void GLTFAccessor::set_sparse_indices_component_type(GLTFComponentType p_sparse_indices_component_type) {
212 sparse_indices_component_type = (GLTFComponentType)p_sparse_indices_component_type;
213 }
214
215 GLTFBufferViewIndex GLTFAccessor::get_sparse_values_buffer_view() const {
216 return sparse_values_buffer_view;
217 }
218
219 void GLTFAccessor::set_sparse_values_buffer_view(GLTFBufferViewIndex p_sparse_values_buffer_view) {
220 sparse_values_buffer_view = p_sparse_values_buffer_view;
221 }
222
223 int64_t GLTFAccessor::get_sparse_values_byte_offset() const {
224 return sparse_values_byte_offset;
225 }
226
227 void GLTFAccessor::set_sparse_values_byte_offset(int64_t p_sparse_values_byte_offset) {
228 sparse_values_byte_offset = p_sparse_values_byte_offset;
229 }
230
231 // Trivial helper functions.
232
233 void GLTFAccessor::_calculate_min_and_max(const PackedFloat64Array &p_numbers) {
234 const int64_t vector_size = _get_vector_size();
235 ERR_FAIL_COND(vector_size <= 0 || p_numbers.size() % vector_size != 0);
236 min.resize(vector_size);
237 max.resize(vector_size);
238 // Initialize min and max with the first vector element values.
239 for (int64_t in_vec = 0; in_vec < vector_size; in_vec++) {
240 min.write[in_vec] = p_numbers[in_vec];
241 max.write[in_vec] = p_numbers[in_vec];
242 }
243 // Iterate over the rest of the vectors.
244 for (int64_t which_vec = vector_size; which_vec < p_numbers.size(); which_vec += vector_size) {
245 for (int64_t in_vec = 0; in_vec < vector_size; in_vec++) {
246 min.write[in_vec] = MIN(p_numbers[which_vec + in_vec], min[in_vec]);
247 max.write[in_vec] = MAX(p_numbers[which_vec + in_vec], max[in_vec]);
248 }
249 }
250 // 3.6.2.5: For floating-point components, JSON-stored minimum and maximum values represent single precision
251 // floats and SHOULD be rounded to single precision before usage to avoid any potential boundary mismatches.
252 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#accessors-bounds
253 if (component_type == GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT) {
254 for (int64_t i = 0; i < min.size(); i++) {
255 min.write[i] = (double)(float)min[i];
256 max.write[i] = (double)(float)max[i];
257 }
258 }
259 }
260
261 void GLTFAccessor::_determine_pad_skip(int64_t &r_skip_every, int64_t &r_skip_bytes) const {
262 // 3.6.2.4. Accessors of matrix type have data stored in column-major order. The start of each column MUST be aligned to 4-byte boundaries.
263 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#data-alignment
264 switch (component_type) {
265 case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
266 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
267 if (accessor_type == GLTFAccessor::TYPE_MAT2) {
268 r_skip_every = 2;
269 r_skip_bytes = 2;
270 }
271 if (accessor_type == GLTFAccessor::TYPE_MAT3) {
272 r_skip_every = 3;
273 r_skip_bytes = 1;
274 }
275 } break;
276 case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
277 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
278 if (accessor_type == GLTFAccessor::TYPE_MAT3) {
279 r_skip_every = 6;
280 r_skip_bytes = 2;
281 }
282 } break;
283 default: {
284 } break;
285 }
286 }
287
288 int64_t GLTFAccessor::_determine_padded_byte_count(int64_t p_raw_byte_size) const {
289 // 3.6.2.4. Accessors of matrix type have data stored in column-major order. The start of each column MUST be aligned to 4-byte boundaries.
290 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#data-alignment
291 switch (component_type) {
292 case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
293 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
294 if (accessor_type == GLTFAccessor::TYPE_MAT2) {
295 return p_raw_byte_size * 2;
296 }
297 if (accessor_type == GLTFAccessor::TYPE_MAT3) {
298 return p_raw_byte_size * 4 / 3;
299 }
300 } break;
301 case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
302 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
303 if (accessor_type == GLTFAccessor::TYPE_MAT3) {
304 return p_raw_byte_size * 4 / 3;
305 }
306 } break;
307 default: {
308 } break;
309 }
310 return p_raw_byte_size;
311 }
312
313 PackedFloat64Array GLTFAccessor::_filter_numbers(const PackedFloat64Array &p_numbers) const {
314 PackedFloat64Array filtered_numbers = p_numbers;
315 for (int64_t i = 0; i < p_numbers.size(); i++) {
316 const double num = p_numbers[i];
317 if (!Math::is_finite(num)) {
318 // 3.6.2.2. "Values of NaN, +Infinity, and -Infinity MUST NOT be present."
319 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#accessor-data-types
320 filtered_numbers.set(i, 0.0);
321 } else if (component_type == GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT) {
322 filtered_numbers.set(i, (double)(float)num);
323 }
324 }
325 return filtered_numbers;
326 }
327
328 String GLTFAccessor::_get_component_type_name(const GLTFComponentType p_component) {
329 // These names are only for debugging and printing error messages, glTF uses the numeric values.
330 switch (p_component) {
331 case GLTFAccessor::COMPONENT_TYPE_NONE:
332 return "None";
333 case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
334 return "Byte";
335 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE:
336 return "UByte";
337 case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
338 return "Short";
339 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT:
340 return "UShort";
341 case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT:
342 return "Int";
343 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT:
344 return "UInt";
345 case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT:
346 return "Float";
347 case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT:
348 return "Double";
349 case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT:
350 return "Half";
351 case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG:
352 return "Long";
353 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG:
354 return "ULong";
355 }
356
357 return "<Error>";
358 }
359
360 GLTFAccessor::GLTFComponentType GLTFAccessor::_get_indices_component_type_for_size(const int64_t p_size) {
361 ERR_FAIL_COND_V(p_size < 0, GLTFAccessor::COMPONENT_TYPE_NONE);
362 // 3.7.2.1. indices accessor MUST NOT contain the maximum possible value for the component type used
363 // (i.e., 255 for unsigned bytes, 65535 for unsigned shorts, 4294967295 for unsigned ints).
364 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview
365 if (unlikely(p_size > 4294967294LL)) {
366 return GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG;
367 }
368 if (p_size > 65534LL) {
369 return GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT;
370 }
371 if (p_size > 254LL) {
372 return GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT;
373 }
374 return GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE;
375 }
376
377 GLTFAccessor::GLTFAccessorType GLTFAccessor::_get_accessor_type_from_str(const String &p_string) {
378 if (p_string == "SCALAR") {
379 return GLTFAccessor::TYPE_SCALAR;
380 }
381 if (p_string == "VEC2") {
382 return GLTFAccessor::TYPE_VEC2;
383 }
384 if (p_string == "VEC3") {
385 return GLTFAccessor::TYPE_VEC3;
386 }
387 if (p_string == "VEC4") {
388 return GLTFAccessor::TYPE_VEC4;
389 }
390 if (p_string == "MAT2") {
391 return GLTFAccessor::TYPE_MAT2;
392 }
393 if (p_string == "MAT3") {
394 return GLTFAccessor::TYPE_MAT3;
395 }
396 if (p_string == "MAT4") {
397 return GLTFAccessor::TYPE_MAT4;
398 }
399 ERR_FAIL_V(GLTFAccessor::TYPE_SCALAR);
400 }
401
402 String GLTFAccessor::_get_accessor_type_name() const {
403 switch (accessor_type) {
404 case GLTFAccessor::TYPE_SCALAR:
405 return "SCALAR";
406 case GLTFAccessor::TYPE_VEC2:
407 return "VEC2";
408 case GLTFAccessor::TYPE_VEC3:
409 return "VEC3";
410 case GLTFAccessor::TYPE_VEC4:
411 return "VEC4";
412 case GLTFAccessor::TYPE_MAT2:
413 return "MAT2";
414 case GLTFAccessor::TYPE_MAT3:
415 return "MAT3";
416 case GLTFAccessor::TYPE_MAT4:
417 return "MAT4";
418 default:
419 break;
420 }
421 ERR_FAIL_V("SCALAR");
422 }
423
424 int64_t GLTFAccessor::_get_vector_size() const {
425 switch (accessor_type) {
426 case GLTFAccessor::TYPE_SCALAR:
427 return 1;
428 case GLTFAccessor::TYPE_VEC2:
429 return 2;
430 case GLTFAccessor::TYPE_VEC3:
431 return 3;
432 case GLTFAccessor::TYPE_VEC4:
433 return 4;
434 case GLTFAccessor::TYPE_MAT2:
435 return 4;
436 case GLTFAccessor::TYPE_MAT3:
437 return 9;
438 case GLTFAccessor::TYPE_MAT4:
439 return 16;
440 default:
441 break;
442 }
443 ERR_FAIL_V(0);
444 }
445
446 int64_t GLTFAccessor::_get_numbers_per_variant_for_gltf(Variant::Type p_variant_type) {
447 // Note that these numbers are used to determine the size of the glTF accessor appropriate for the type (see `_get_vector_size`).
448 // Therefore, the only valid values this can return are 1 (SCALAR), 2 (VEC2), 3 (VEC3), 4 (VEC4/MAT2), 9 (MAT3), and 16 (MAT4).
449 // The value 0 indicates the Variant type can't map to glTF accessors, and INT64_MAX indicates it needs special handling.
450 switch (p_variant_type) {
451 case Variant::NIL:
452 case Variant::STRING:
453 case Variant::STRING_NAME:
454 case Variant::NODE_PATH:
455 case Variant::RID:
456 case Variant::OBJECT:
457 case Variant::CALLABLE:
458 case Variant::SIGNAL:
459 case Variant::DICTIONARY:
460 case Variant::ARRAY:
461 case Variant::PACKED_STRING_ARRAY:
462 case Variant::PACKED_VECTOR2_ARRAY:
463 case Variant::PACKED_VECTOR3_ARRAY:
464 case Variant::PACKED_COLOR_ARRAY:
465 case Variant::PACKED_VECTOR4_ARRAY:
466 case Variant::VARIANT_MAX:
467 return 0; // Not supported.
468 case Variant::BOOL:
469 case Variant::INT:
470 case Variant::FLOAT:
471 return 1;
472 case Variant::VECTOR2:
473 case Variant::VECTOR2I:
474 return 2;
475 case Variant::VECTOR3:
476 case Variant::VECTOR3I:
477 return 3;
478 case Variant::RECT2:
479 case Variant::RECT2I:
480 case Variant::VECTOR4:
481 case Variant::VECTOR4I:
482 case Variant::PLANE:
483 case Variant::QUATERNION:
484 case Variant::COLOR:
485 return 4;
486 case Variant::TRANSFORM2D:
487 case Variant::AABB:
488 case Variant::BASIS:
489 return 9;
490 case Variant::TRANSFORM3D:
491 case Variant::PROJECTION:
492 return 16;
493 case Variant::PACKED_BYTE_ARRAY:
494 case Variant::PACKED_INT32_ARRAY:
495 case Variant::PACKED_INT64_ARRAY:
496 case Variant::PACKED_FLOAT32_ARRAY:
497 case Variant::PACKED_FLOAT64_ARRAY:
498 return INT64_MAX; // Special, use `_get_vector_size()` only to determine size.
499 }
500 return 0;
501 }
502
503 int64_t GLTFAccessor::_get_bytes_per_component(const GLTFComponentType p_component_type) {
504 switch (p_component_type) {
505 case GLTFAccessor::COMPONENT_TYPE_NONE:
506 ERR_FAIL_V(0);
507 case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
508 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE:
509 return 1;
510 case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
511 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT:
512 case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT:
513 return 2;
514 case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT:
515 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT:
516 case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT:
517 return 4;
518 case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT:
519 case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG:
520 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG:
521 return 8;
522 }
523 ERR_FAIL_V(0);
524 }
525
526 int64_t GLTFAccessor::_get_bytes_per_vector() const {
527 const int64_t raw_byte_size = _get_bytes_per_component(component_type) * _get_vector_size();
528 return _determine_padded_byte_count(raw_byte_size);
529 }
530
531 bool GLTFAccessor::is_equal_exact(const Ref<GLTFAccessor> &p_other) const {
532 if (p_other.is_null()) {
533 return false;
534 }
535 return (buffer_view == p_other->buffer_view &&
536 byte_offset == p_other->byte_offset &&
537 component_type == p_other->component_type &&
538 normalized == p_other->normalized &&
539 count == p_other->count &&
540 accessor_type == p_other->accessor_type &&
541 min == p_other->min &&
542 max == p_other->max &&
543 sparse_count == p_other->sparse_count &&
544 sparse_indices_buffer_view == p_other->sparse_indices_buffer_view &&
545 sparse_indices_byte_offset == p_other->sparse_indices_byte_offset &&
546 sparse_indices_component_type == p_other->sparse_indices_component_type &&
547 sparse_values_buffer_view == p_other->sparse_values_buffer_view &&
548 sparse_values_byte_offset == p_other->sparse_values_byte_offset);
549 }
550
551 // Private decode functions.
552
553 PackedInt64Array GLTFAccessor::_decode_sparse_indices(const Ref<GLTFState> &p_gltf_state, const Vector<Ref<GLTFBufferView>> &p_buffer_views) const {
554 const int64_t bytes_per_component = _get_bytes_per_component(sparse_indices_component_type);
555 PackedInt64Array numbers;
556 ERR_FAIL_INDEX_V(sparse_indices_buffer_view, p_buffer_views.size(), numbers);
557 const Ref<GLTFBufferView> actual_buffer_view = p_buffer_views[sparse_indices_buffer_view];
558 const PackedByteArray raw_bytes = actual_buffer_view->load_buffer_view_data(p_gltf_state);
559 const int64_t min_raw_byte_size = bytes_per_component * sparse_count + sparse_indices_byte_offset;
560 ERR_FAIL_COND_V_MSG(raw_bytes.size() < min_raw_byte_size, numbers, "glTF import: Sparse indices buffer view did not have enough bytes to read the expected number of indices. Returning an empty array.");
561 numbers.resize(sparse_count);
562 const uint8_t *raw_pointer = raw_bytes.ptr();
563 int64_t raw_read_offset = sparse_indices_byte_offset;
564 for (int64_t i = 0; i < sparse_count; i++) {
565 const uint8_t *raw_source = &raw_pointer[raw_read_offset];
566 int64_t number = 0;
567 switch (sparse_indices_component_type) {
568 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
569 number = *(uint8_t *)raw_source;
570 } break;
571 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
572 number = *(uint16_t *)raw_source;
573 } break;
574 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT: {
575 number = *(uint32_t *)raw_source;
576 } break;
577 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG: {
578 number = *(uint64_t *)raw_source;
579 } break;
580 default: {
581 ERR_FAIL_V_MSG(PackedInt64Array(), "glTF import: Sparse indices must have an unsigned integer component type. Failed to decode, returning an empty array.");
582 }
583 }
584 numbers.set(i, number);
585 raw_read_offset += bytes_per_component;
586 }
587 ERR_FAIL_COND_V_MSG(raw_read_offset != raw_bytes.size(), numbers, "glTF import: Sparse indices buffer view size did not exactly match the expected size.");
588 return numbers;
589 }
590
591 template <typename T>
592 Vector<T> GLTFAccessor::_decode_raw_numbers(const Ref<GLTFState> &p_gltf_state, const Vector<Ref<GLTFBufferView>> &p_buffer_views, bool p_sparse_values) const {
593 const int64_t bytes_per_component = _get_bytes_per_component(component_type);
594 const int64_t bytes_per_vector = _get_bytes_per_vector();
595 const int64_t vector_size = _get_vector_size();
596 int64_t pad_skip_every = 0;
597 int64_t pad_skip_bytes = 0;
598 _determine_pad_skip(pad_skip_every, pad_skip_bytes);
599 int64_t raw_vector_count;
600 int64_t raw_buffer_view_index;
601 int64_t raw_read_offset_start;
602 if (p_sparse_values) {
603 raw_vector_count = sparse_count;
604 raw_buffer_view_index = sparse_values_buffer_view;
605 raw_read_offset_start = sparse_values_byte_offset;
606 } else {
607 raw_vector_count = count;
608 raw_buffer_view_index = buffer_view;
609 raw_read_offset_start = byte_offset;
610 }
611 const int64_t raw_number_count = raw_vector_count * vector_size;
612 Vector<T> ret_numbers;
613 if (raw_buffer_view_index == -1) {
614 ret_numbers.resize(raw_number_count);
615 // No buffer view, so fill with zeros.
616 for (int64_t i = 0; i < raw_number_count; i++) {
617 ret_numbers.set(i, T(0));
618 }
619 return ret_numbers;
620 }
621 ERR_FAIL_INDEX_V(raw_buffer_view_index, p_buffer_views.size(), ret_numbers);
622 const Ref<GLTFBufferView> raw_buffer_view = p_buffer_views[raw_buffer_view_index];
623 if (raw_buffer_view->get_byte_offset() % bytes_per_component != 0) {
624 WARN_PRINT("glTF import: Buffer view byte offset is not a multiple of accessor component size. This file is invalid per the glTF specification and will not load correctly in some glTF viewers, but Godot will try to load it anyway.");
625 }
626 if (byte_offset % bytes_per_component != 0) {
627 WARN_PRINT("glTF import: Accessor byte offset is not a multiple of accessor component size. This file is invalid per the glTF specification and will not load correctly in some glTF viewers, but Godot will try to load it anyway.");
628 }
629 int64_t declared_byte_stride = raw_buffer_view->get_byte_stride();
630 int64_t actual_byte_stride = bytes_per_vector;
631 int64_t stride_skip_every = 0;
632 int64_t stride_skip_bytes = 0;
633 if (declared_byte_stride != -1) {
634 ERR_FAIL_COND_V_MSG(declared_byte_stride % 4 != 0, ret_numbers, "glTF import: The declared buffer view byte stride " + itos(declared_byte_stride) + " was not a multiple of 4 as required by glTF. Returning an empty array.");
635 if (declared_byte_stride > bytes_per_vector) {
636 actual_byte_stride = declared_byte_stride;
637 stride_skip_every = vector_size;
638 stride_skip_bytes = declared_byte_stride - bytes_per_vector;
639 }
640 } else if (raw_buffer_view->get_vertex_attributes()) {
641 print_verbose("WARNING: glTF import: Buffer view byte stride should be declared for vertex attributes. Assuming packed data and reading anyway.");
642 }
643 const int64_t min_raw_byte_size = actual_byte_stride * (raw_vector_count - 1) + bytes_per_vector + raw_read_offset_start;
644 const PackedByteArray raw_bytes = raw_buffer_view->load_buffer_view_data(p_gltf_state);
645 ERR_FAIL_COND_V_MSG(raw_bytes.size() < min_raw_byte_size, ret_numbers, "glTF import: The buffer view size was smaller than the minimum required size for the accessor. Returning an empty array.");
646 ret_numbers.resize(raw_number_count);
647 const uint8_t *raw_pointer = raw_bytes.ptr();
648 int64_t raw_read_offset = raw_read_offset_start;
649 for (int64_t i = 0; i < raw_number_count; i++) {
650 const uint8_t *raw_source = &raw_pointer[raw_read_offset];
651 T number = 0;
652 // 3.11. Implementations MUST use following equations to decode real floating-point value f from a normalized integer c and vice-versa.
653 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#animations
654 switch (component_type) {
655 case GLTFAccessor::COMPONENT_TYPE_NONE: {
656 ERR_FAIL_V_MSG(Vector<T>(), "glTF import: Failed to decode buffer view, component type not set. Returning an empty array.");
657 } break;
658 case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE: {
659 int8_t prim = *(int8_t *)raw_source;
660 if (normalized) {
661 number = T(MAX(double(prim) / 127.0, -1.0));
662 } else {
663 number = T(prim);
664 }
665 } break;
666 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
667 uint8_t prim = *(uint8_t *)raw_source;
668 if (normalized) {
669 number = T((double(prim) / 255.0));
670 } else {
671 number = T(prim);
672 }
673 } break;
674 case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT: {
675 int16_t prim = *(int16_t *)raw_source;
676 if (normalized) {
677 number = T(MAX(double(prim) / 32767.0, -1.0));
678 } else {
679 number = T(prim);
680 }
681 } break;
682 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
683 uint16_t prim = *(uint16_t *)raw_source;
684 if (normalized) {
685 number = T(double(prim) / 65535.0);
686 } else {
687 number = T(prim);
688 }
689 } break;
690 case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT: {
691 number = T(*(int32_t *)raw_source);
692 } break;
693 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT: {
694 number = T(*(uint32_t *)raw_source);
695 } break;
696 case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT: {
697 number = T(*(float *)raw_source);
698 } break;
699 case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT: {
700 number = T(*(double *)raw_source);
701 } break;
702 case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT: {
703 number = Math::half_to_float(*(uint16_t *)raw_source);
704 } break;
705 case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG: {
706 number = T(*(int64_t *)raw_source);
707 } break;
708 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG: {
709 number = T(*(uint64_t *)raw_source);
710 } break;
711 }
712 ret_numbers.set(i, number);
713 raw_read_offset += bytes_per_component;
714 // Padding and stride skipping are distinct concepts that both need to be handled.
715 // For example, a 2-in-1 interleaved MAT3 bytes accessor has both, and would look like:
716 // AAA0 AAA0 AAA0 BBB0 BBB0 BBB0 AAA0 AAA0 AAA0 BBB0 BBB0 BBB0
717 // The "0" is skipped by the padding, and the "BBB0" is skipped by the stride.
718 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#data-alignment
719 if (unlikely(pad_skip_every > 0)) {
720 if ((i + 1) % pad_skip_every == 0) {
721 raw_read_offset += pad_skip_bytes;
722 }
723 }
724 if (unlikely(stride_skip_every > 0)) {
725 if ((i + 1) % stride_skip_every == 0) {
726 raw_read_offset += stride_skip_bytes;
727 }
728 }
729 }
730 return ret_numbers;
731 }
732
733 template <typename T>
734 Vector<T> GLTFAccessor::_decode_as_numbers(const Ref<GLTFState> &p_gltf_state) const {
735 const Vector<Ref<GLTFBufferView>> &p_buffer_views = p_gltf_state->get_buffer_views();
736 Vector<T> ret_numbers = _decode_raw_numbers<T>(p_gltf_state, p_buffer_views, false);
737 if (sparse_count == 0) {
738 return ret_numbers;
739 }
740 // Handle sparse accessors.
741 PackedInt64Array sparse_indices = _decode_sparse_indices(p_gltf_state, p_buffer_views);
742 ERR_FAIL_COND_V_MSG(sparse_indices.size() != sparse_count, ret_numbers, "glTF import: Sparse indices size does not match the sparse count.");
743 const int64_t vector_size = _get_vector_size();
744 Vector<T> sparse_values = _decode_raw_numbers<T>(p_gltf_state, p_buffer_views, true);
745 ERR_FAIL_COND_V_MSG(sparse_values.size() != sparse_count * vector_size, ret_numbers, "glTF import: Sparse values size does not match the sparse count.");
746 for (int64_t in_sparse = 0; in_sparse < sparse_count; in_sparse++) {
747 const int64_t sparse_index = sparse_indices[in_sparse];
748 const int64_t array_offset = sparse_index * vector_size;
749 ERR_FAIL_INDEX_V_MSG(array_offset, ret_numbers.size(), ret_numbers, "glTF import: Sparse indices were out of bounds for the accessor.");
750 for (int64_t in_vec = 0; in_vec < vector_size; in_vec++) {
751 ret_numbers.set(array_offset + in_vec, sparse_values[in_sparse * vector_size + in_vec]);
752 }
753 }
754 return ret_numbers;
755 }
756
757 // High-level decode functions.
758
759 PackedColorArray GLTFAccessor::decode_as_colors(const Ref<GLTFState> &p_gltf_state) const {
760 PackedColorArray ret;
761 PackedFloat32Array numbers = _decode_as_numbers<float>(p_gltf_state);
762 if (accessor_type == TYPE_VEC3) {
763 ERR_FAIL_COND_V_MSG(numbers.size() != count * 3, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
764 ret.resize(count);
765 for (int64_t i = 0; i < count; i++) {
766 const int64_t number_index = i * 3;
767 ret.set(i, Color(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], 1.0f));
768 }
769 } else if (accessor_type == TYPE_VEC4) {
770 ERR_FAIL_COND_V_MSG(numbers.size() != count * 4, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
771 ret.resize(count);
772 for (int64_t i = 0; i < count; i++) {
773 const int64_t number_index = i * 4;
774 ret.set(i, Color(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]));
775 }
776 } else {
777 ERR_FAIL_V_MSG(ret, "glTF import: The `decode_as_colors` function is designed to be fast and can only be used with accessors of type \"VEC3\" or \"VEC4\", but was called with type \"" + _get_accessor_type_name() + "\". Consider using `decode_as_variants` if you need more flexible behavior with support for any accessor type.");
778 }
779 return ret;
780 }
781
782 PackedFloat32Array GLTFAccessor::decode_as_float32s(const Ref<GLTFState> &p_gltf_state) const {
783 return _decode_as_numbers<float>(p_gltf_state);
784 }
785
786 PackedFloat64Array GLTFAccessor::decode_as_float64s(const Ref<GLTFState> &p_gltf_state) const {
787 return _decode_as_numbers<double>(p_gltf_state);
788 }
789
790 PackedInt32Array GLTFAccessor::decode_as_int32s(const Ref<GLTFState> &p_gltf_state) const {
791 return _decode_as_numbers<int32_t>(p_gltf_state);
792 }
793
794 PackedInt64Array GLTFAccessor::decode_as_int64s(const Ref<GLTFState> &p_gltf_state) const {
795 return _decode_as_numbers<int64_t>(p_gltf_state);
796 }
797
798 Vector<Quaternion> GLTFAccessor::decode_as_quaternions(const Ref<GLTFState> &p_gltf_state) const {
799 Vector<Quaternion> ret;
800 ERR_FAIL_COND_V_MSG(accessor_type != TYPE_VEC4, ret, "glTF import: The `decode_as_quaternions` function is designed to be fast and can only be used with accessors of type \"VEC4\", but was called with type \"" + _get_accessor_type_name() + "\". Consider using `decode_as_variants` if you need more flexible behavior with support for any accessor type.");
801 PackedRealArray numbers = _decode_as_numbers<real_t>(p_gltf_state);
802 ERR_FAIL_COND_V_MSG(numbers.size() != count * 4, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
803 ret.resize(count);
804 for (int64_t i = 0; i < count; i++) {
805 const int64_t number_index = i * 4;
806 ret.set(i, Quaternion(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]).normalized());
807 }
808 return ret;
809 }
810
811 Array GLTFAccessor::decode_as_variants(const Ref<GLTFState> &p_gltf_state, Variant::Type p_variant_type) const {
812 const int64_t numbers_per_variant = _get_numbers_per_variant_for_gltf(p_variant_type);
813 Array ret;
814 ERR_FAIL_COND_V_MSG(numbers_per_variant < 1, ret, "glTF import: The Variant type '" + Variant::get_type_name(p_variant_type) + "' is not supported. Returning an empty array.");
815 const PackedFloat64Array numbers = _decode_as_numbers<double>(p_gltf_state);
816 const int64_t vector_size = _get_vector_size();
817 ERR_FAIL_COND_V_MSG(vector_size < 1, ret, "glTF import: The accessor type '" + _get_accessor_type_name() + "' is not supported. Returning an empty array.");
818 const int64_t numbers_to_read = MIN(vector_size, numbers_per_variant);
819 ERR_FAIL_COND_V_MSG(numbers.size() != count * vector_size, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
820 ret.resize(count);
821 for (int64_t value_index = 0; value_index < count; value_index++) {
822 const int64_t number_index = value_index * vector_size;
823 switch (p_variant_type) {
824 case Variant::BOOL: {
825 ret[value_index] = numbers[number_index] != 0.0;
826 } break;
827 case Variant::INT: {
828 ret[value_index] = (int64_t)numbers[number_index];
829 } break;
830 case Variant::FLOAT: {
831 ret[value_index] = numbers[number_index];
832 } break;
833 case Variant::VECTOR2:
834 case Variant::RECT2:
835 case Variant::VECTOR3:
836 case Variant::VECTOR4:
837 case Variant::PLANE:
838 case Variant::QUATERNION: {
839 // General-purpose code for importing glTF accessor data with any component count into structs up to 4 `real_t`s in size.
840 Vector4 vec;
841 switch (numbers_to_read) {
842 case 1: {
843 vec = Vector4(numbers[number_index], 0.0f, 0.0f, 0.0f);
844 } break;
845 case 2: {
846 vec = Vector4(numbers[number_index], numbers[number_index + 1], 0.0f, 0.0f);
847 } break;
848 case 3: {
849 vec = Vector4(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], 0.0f);
850 } break;
851 default: {
852 vec = Vector4(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]);
853 } break;
854 }
855 if (p_variant_type == Variant::QUATERNION) {
856 vec.normalize();
857 }
858 // Evil hack that relies on the structure of Variant, but it's the
859 // only way to accomplish this without a ton of code duplication.
860 Variant variant = vec;
861 *(Variant::Type *)&variant = p_variant_type;
862 ret[value_index] = variant;
863 } break;
864 case Variant::VECTOR2I:
865 case Variant::RECT2I:
866 case Variant::VECTOR3I:
867 case Variant::VECTOR4I: {
868 // General-purpose code for importing glTF accessor data with any component count into structs up to 4 `int32_t`s in size.
869 Vector4i vec;
870 switch (numbers_to_read) {
871 case 1: {
872 vec = Vector4i((int32_t)numbers[number_index], 0, 0, 0);
873 } break;
874 case 2: {
875 vec = Vector4i((int32_t)numbers[number_index], (int32_t)numbers[number_index + 1], 0, 0);
876 } break;
877 case 3: {
878 vec = Vector4i((int32_t)numbers[number_index], (int32_t)numbers[number_index + 1], (int32_t)numbers[number_index + 2], 0);
879 } break;
880 default: {
881 vec = Vector4i((int32_t)numbers[number_index], (int32_t)numbers[number_index + 1], (int32_t)numbers[number_index + 2], (int32_t)numbers[number_index + 3]);
882 } break;
883 }
884 // Evil hack that relies on the structure of Variant, but it's the
885 // only way to accomplish this without a ton of code duplication.
886 Variant variant = vec;
887 *(Variant::Type *)&variant = p_variant_type;
888 ret[value_index] = variant;
889 } break;
890 // No more generalized hacks, each of the below types needs a lot of repetitive code.
891 case Variant::COLOR: {
892 Color color;
893 switch (numbers_to_read) {
894 case 1: {
895 color = Color(numbers[number_index], 0.0f, 0.0f, 1.0f);
896 } break;
897 case 2: {
898 color = Color(numbers[number_index], numbers[number_index + 1], 0.0f, 1.0f);
899 } break;
900 case 3: {
901 color = Color(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], 1.0f);
902 } break;
903 default: {
904 color = Color(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]);
905 } break;
906 }
907 ret[value_index] = color;
908 } break;
909 case Variant::TRANSFORM2D: {
910 Transform2D t;
911 switch (numbers_to_read) {
912 case 4: {
913 t.columns[0] = Vector2(numbers[number_index + 0], numbers[number_index + 1]);
914 t.columns[1] = Vector2(numbers[number_index + 2], numbers[number_index + 3]);
915 } break;
916 case 9: {
917 t.columns[0] = Vector2(numbers[number_index + 0], numbers[number_index + 1]);
918 t.columns[1] = Vector2(numbers[number_index + 3], numbers[number_index + 4]);
919 t.columns[2] = Vector2(numbers[number_index + 6], numbers[number_index + 7]);
920 } break;
921 case 16: {
922 t.columns[0] = Vector2(numbers[number_index + 0], numbers[number_index + 1]);
923 t.columns[1] = Vector2(numbers[number_index + 4], numbers[number_index + 5]);
924 t.columns[2] = Vector2(numbers[number_index + 12], numbers[number_index + 13]);
925 } break;
926 }
927 ret[value_index] = t;
928 } break;
929 case Variant::AABB: {
930 AABB aabb;
931 switch (numbers_to_read) {
932 case 4: {
933 aabb.position = Vector3(numbers[number_index + 0], numbers[number_index + 1], 0.0f);
934 aabb.size = Vector3(numbers[number_index + 2], numbers[number_index + 3], 0.0f);
935 } break;
936 case 9: {
937 aabb.position = Vector3(numbers[number_index + 0], numbers[number_index + 1], numbers[number_index + 2]);
938 aabb.size = Vector3(numbers[number_index + 3], numbers[number_index + 4], numbers[number_index + 5]);
939 } break;
940 case 16: {
941 aabb.position = Vector3(numbers[number_index + 0], numbers[number_index + 1], numbers[number_index + 2]);
942 aabb.size = Vector3(numbers[number_index + 4], numbers[number_index + 5], numbers[number_index + 6]);
943 } break;
944 }
945 ret[value_index] = aabb;
946 } break;
947 case Variant::BASIS: {
948 Basis b;
949 switch (numbers_to_read) {
950 case 4: {
951 b.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 2], 0.0f);
952 b.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 3], 0.0f);
953 } break;
954 case 9: {
955 b.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 3], numbers[number_index + 6]);
956 b.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 4], numbers[number_index + 7]);
957 b.rows[2] = Vector3(numbers[number_index + 2], numbers[number_index + 5], numbers[number_index + 8]);
958 } break;
959 case 16: {
960 b.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 4], numbers[number_index + 8]);
961 b.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 5], numbers[number_index + 9]);
962 b.rows[2] = Vector3(numbers[number_index + 2], numbers[number_index + 6], numbers[number_index + 10]);
963 } break;
964 }
965 ret[value_index] = b;
966 } break;
967 case Variant::TRANSFORM3D: {
968 Transform3D t;
969 switch (numbers_to_read) {
970 case 4: {
971 t.basis.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 2], 0.0f);
972 t.basis.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 3], 0.0f);
973 } break;
974 case 9: {
975 t.basis.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 3], numbers[number_index + 6]);
976 t.basis.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 4], numbers[number_index + 7]);
977 t.basis.rows[2] = Vector3(numbers[number_index + 2], numbers[number_index + 5], numbers[number_index + 8]);
978 } break;
979 case 16: {
980 t.basis.rows[0] = Vector3(numbers[number_index + 0], numbers[number_index + 4], numbers[number_index + 8]);
981 t.basis.rows[1] = Vector3(numbers[number_index + 1], numbers[number_index + 5], numbers[number_index + 9]);
982 t.basis.rows[2] = Vector3(numbers[number_index + 2], numbers[number_index + 6], numbers[number_index + 10]);
983 t.origin = Vector3(numbers[number_index + 12], numbers[number_index + 13], numbers[number_index + 14]);
984 } break;
985 }
986 ret[value_index] = t;
987 } break;
988 case Variant::PROJECTION: {
989 Projection p;
990 switch (numbers_to_read) {
991 case 4: {
992 p.columns[0] = Vector4(numbers[number_index + 0], numbers[number_index + 1], 0.0f, 0.0f);
993 p.columns[1] = Vector4(numbers[number_index + 4], numbers[number_index + 5], 0.0f, 0.0f);
994 } break;
995 case 9: {
996 p.columns[0] = Vector4(numbers[number_index + 0], numbers[number_index + 1], numbers[number_index + 2], 0.0f);
997 p.columns[1] = Vector4(numbers[number_index + 4], numbers[number_index + 5], numbers[number_index + 6], 0.0f);
998 p.columns[2] = Vector4(numbers[number_index + 8], numbers[number_index + 9], numbers[number_index + 10], 0.0f);
999 } break;
1000 case 16: {
1001 p.columns[0] = Vector4(numbers[number_index + 0], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]);
1002 p.columns[1] = Vector4(numbers[number_index + 4], numbers[number_index + 5], numbers[number_index + 6], numbers[number_index + 7]);
1003 p.columns[2] = Vector4(numbers[number_index + 8], numbers[number_index + 9], numbers[number_index + 10], numbers[number_index + 11]);
1004 p.columns[3] = Vector4(numbers[number_index + 12], numbers[number_index + 13], numbers[number_index + 14], numbers[number_index + 15]);
1005 } break;
1006 }
1007 ret[value_index] = p;
1008 } break;
1009 case Variant::PACKED_BYTE_ARRAY: {
1010 PackedByteArray packed_array;
1011 packed_array.resize(numbers_to_read);
1012 for (int64_t j = 0; j < numbers_to_read; j++) {
1013 packed_array.set(value_index, numbers[number_index + j]);
1014 }
1015 } break;
1016 case Variant::PACKED_INT32_ARRAY: {
1017 PackedInt32Array packed_array;
1018 packed_array.resize(numbers_to_read);
1019 for (int64_t j = 0; j < numbers_to_read; j++) {
1020 packed_array.set(value_index, numbers[number_index + j]);
1021 }
1022 } break;
1023 case Variant::PACKED_INT64_ARRAY: {
1024 PackedInt64Array packed_array;
1025 packed_array.resize(numbers_to_read);
1026 for (int64_t j = 0; j < numbers_to_read; j++) {
1027 packed_array.set(value_index, numbers[number_index + j]);
1028 }
1029 } break;
1030 case Variant::PACKED_FLOAT32_ARRAY: {
1031 PackedFloat32Array packed_array;
1032 packed_array.resize(numbers_to_read);
1033 for (int64_t j = 0; j < numbers_to_read; j++) {
1034 packed_array.set(value_index, numbers[number_index + j]);
1035 }
1036 } break;
1037 case Variant::PACKED_FLOAT64_ARRAY: {
1038 PackedFloat64Array packed_array;
1039 packed_array.resize(numbers_to_read);
1040 for (int64_t j = 0; j < numbers_to_read; j++) {
1041 packed_array.set(value_index, numbers[number_index + j]);
1042 }
1043 } break;
1044 default: {
1045 ERR_FAIL_V_MSG(ret, "glTF: Cannot decode accessor as Variant of type " + Variant::get_type_name(p_variant_type) + ".");
1046 }
1047 }
1048 }
1049 return ret;
1050 }
1051
1052 PackedVector2Array GLTFAccessor::decode_as_vector2s(const Ref<GLTFState> &p_gltf_state) const {
1053 PackedVector2Array ret;
1054 ERR_FAIL_COND_V_MSG(accessor_type != TYPE_VEC2, ret, "glTF import: The `decode_as_vector2s` function is designed to be fast and can only be used with accessors of type \"VEC2\", but was called with type \"" + _get_accessor_type_name() + "\". Consider using `decode_as_variants` if you need more flexible behavior with support for any accessor type.");
1055 PackedRealArray numbers = _decode_as_numbers<real_t>(p_gltf_state);
1056 ERR_FAIL_COND_V_MSG(numbers.size() != count * 2, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
1057 ret.resize(count);
1058 for (int64_t i = 0; i < count; i++) {
1059 const int64_t number_index = i * 2;
1060 ret.set(i, Vector2(numbers[number_index], numbers[number_index + 1]));
1061 }
1062 return ret;
1063 }
1064
1065 PackedVector3Array GLTFAccessor::decode_as_vector3s(const Ref<GLTFState> &p_gltf_state) const {
1066 PackedVector3Array ret;
1067 ERR_FAIL_COND_V_MSG(accessor_type != TYPE_VEC3, ret, "glTF import: The `decode_as_vector3s` function is designed to be fast and can only be used with accessors of type \"VEC3\", but was called with type \"" + _get_accessor_type_name() + "\". Consider using `decode_as_variants` if you need more flexible behavior with support for any accessor type.");
1068 PackedRealArray numbers = _decode_as_numbers<real_t>(p_gltf_state);
1069 ERR_FAIL_COND_V_MSG(numbers.size() != count * 3, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
1070 ret.resize(count);
1071 for (int64_t i = 0; i < count; i++) {
1072 const int64_t number_index = i * 3;
1073 ret.set(i, Vector3(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2]));
1074 }
1075 return ret;
1076 }
1077
1078 PackedVector4Array GLTFAccessor::decode_as_vector4s(const Ref<GLTFState> &p_gltf_state) const {
1079 PackedVector4Array ret;
1080 ERR_FAIL_COND_V_MSG(accessor_type != TYPE_VEC4, ret, "glTF import: The `decode_as_vector4s` function is designed to be fast and can only be used with accessors of type \"VEC4\", but was called with type \"" + _get_accessor_type_name() + "\". Consider using `decode_as_variants` if you need more flexible behavior with support for any accessor type.");
1081 PackedRealArray numbers = _decode_as_numbers<real_t>(p_gltf_state);
1082 ERR_FAIL_COND_V_MSG(numbers.size() != count * 4, ret, "glTF import: The accessor does not have the expected amount of numbers for the given count and vector size.");
1083 ret.resize(count);
1084 for (int64_t i = 0; i < count; i++) {
1085 const int64_t number_index = i * 4;
1086 ret.set(i, Vector4(numbers[number_index], numbers[number_index + 1], numbers[number_index + 2], numbers[number_index + 3]));
1087 }
1088 return ret;
1089 }
1090
1091 // Private encode functions.
1092
1093 PackedFloat64Array GLTFAccessor::_encode_variants_as_floats(const Array &p_input_data, Variant::Type p_variant_type) const {
1094 const int64_t vector_size = _get_vector_size();
1095 const int64_t input_size = p_input_data.size();
1096 PackedFloat64Array numbers;
1097 numbers.resize(input_size * vector_size);
1098 for (int64_t input_index = 0; input_index < input_size; input_index++) {
1099 Variant variant = p_input_data[input_index];
1100 const int64_t vector_offset = input_index * vector_size;
1101 switch (p_variant_type) {
1102 case Variant::NIL:
1103 case Variant::BOOL:
1104 case Variant::INT:
1105 case Variant::FLOAT: {
1106 // For scalar values, just append them. Variant can convert all of these to double. Some padding may also be needed.
1107 numbers.set(vector_offset, variant);
1108 if (unlikely(vector_size > 1)) {
1109 for (int64_t i = 1; i < vector_size; i++) {
1110 numbers.set(vector_offset + i, 0.0);
1111 }
1112 }
1113 } break;
1114 case Variant::PLANE:
1115 case Variant::QUATERNION:
1116 case Variant::RECT2: {
1117 // Evil hack that relies on the structure of Variant, but it's the
1118 // only way to accomplish this without a ton of code duplication.
1119 *(Variant::Type *)&variant = Variant::VECTOR4;
1120 }
1121 [[fallthrough]];
1122 case Variant::VECTOR2:
1123 case Variant::VECTOR3:
1124 case Variant::VECTOR4: {
1125 // Variant can handle converting Vector2/3/4 to Vector4 for us.
1126 Vector4 vec = variant;
1127 for (int64_t i = 0; i < vector_size; i++) {
1128 numbers.set(vector_offset + i, vec[i]);
1129 }
1130 if (unlikely(vector_size > 4)) {
1131 for (int64_t i = 4; i < vector_size; i++) {
1132 numbers.set(vector_offset + i, 0.0);
1133 }
1134 }
1135 } break;
1136 case Variant::RECT2I: {
1137 *(Variant::Type *)&variant = Variant::VECTOR4I;
1138 }
1139 [[fallthrough]];
1140 case Variant::VECTOR2I:
1141 case Variant::VECTOR3I:
1142 case Variant::VECTOR4I: {
1143 // Variant can handle converting Vector2i/3i/4i to Vector4i for us.
1144 Vector4i vec = variant;
1145 for (int64_t i = 0; i < vector_size; i++) {
1146 numbers.set(vector_offset + i, vec[i]);
1147 }
1148 if (unlikely(vector_size > 4)) {
1149 for (int64_t i = 4; i < vector_size; i++) {
1150 numbers.set(vector_offset + i, 0.0);
1151 }
1152 }
1153 } break;
1154 case Variant::COLOR: {
1155 Color c = variant;
1156 for (int64_t i = 0; i < vector_size; i++) {
1157 numbers.set(vector_offset + i, c[i]);
1158 }
1159 if (unlikely(vector_size > 4)) {
1160 for (int64_t i = 4; i < vector_size; i++) {
1161 numbers.set(vector_offset + i, 0.0);
1162 }
1163 }
1164 } break;
1165 case Variant::TRANSFORM2D:
1166 case Variant::BASIS:
1167 case Variant::TRANSFORM3D:
1168 case Variant::PROJECTION: {
1169 // Variant can handle converting Transform2D/Transform3D/Basis to Projection for us.
1170 Projection p = variant;
1171 if (vector_size == 16) {
1172 for (int64_t i = 0; i < 4; i++) {
1173 numbers.set(vector_offset + 4 * i, p.columns[i][0]);
1174 numbers.set(vector_offset + 4 * i + 1, p.columns[i][1]);
1175 numbers.set(vector_offset + 4 * i + 2, p.columns[i][2]);
1176 numbers.set(vector_offset + 4 * i + 3, p.columns[i][3]);
1177 }
1178 } else if (vector_size == 9) {
1179 for (int64_t i = 0; i < 3; i++) {
1180 numbers.set(vector_offset + 3 * i, p.columns[i][0]);
1181 numbers.set(vector_offset + 3 * i + 1, p.columns[i][1]);
1182 numbers.set(vector_offset + 3 * i + 2, p.columns[i][2]);
1183 }
1184 } else if (vector_size == 4) {
1185 numbers.set(vector_offset, p.columns[0][0]);
1186 numbers.set(vector_offset + 1, p.columns[0][1]);
1187 numbers.set(vector_offset + 2, p.columns[1][0]);
1188 numbers.set(vector_offset + 3, p.columns[1][1]);
1189 }
1190 } break;
1191 default: {
1192 ERR_FAIL_V_MSG(PackedFloat64Array(), "glTF export: Cannot encode accessor from Variant of type " + Variant::get_type_name(p_variant_type) + ".");
1193 }
1194 }
1195 }
1196 return numbers;
1197 }
1198
1199 void GLTFAccessor::_store_sparse_indices_into_state(const Ref<GLTFState> &p_gltf_state, const PackedInt64Array &p_sparse_indices, const bool p_deduplicate) {
1200 // The byte offset of a sparse accessor's indices buffer view MUST be a multiple of the indices primitive componentType.
1201 // https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/schema/accessor.sparse.indices.schema.json
1202 const int64_t bytes_per_index = _get_bytes_per_component(sparse_indices_component_type);
1203 PackedByteArray indices_bytes;
1204 indices_bytes.resize(bytes_per_index * p_sparse_indices.size());
1205 uint8_t *ret_write = indices_bytes.ptrw();
1206 int64_t ret_byte_offset = 0;
1207 for (int64_t i = 0; i < p_sparse_indices.size(); i++) {
1208 switch (sparse_indices_component_type) {
1209 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
1210 *(uint8_t *)&ret_write[ret_byte_offset] = p_sparse_indices[i];
1211 } break;
1212 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
1213 *(uint16_t *)&ret_write[ret_byte_offset] = p_sparse_indices[i];
1214 } break;
1215 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT: {
1216 *(uint32_t *)&ret_write[ret_byte_offset] = p_sparse_indices[i];
1217 } break;
1218 case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG: {
1219 *(uint64_t *)&ret_write[ret_byte_offset] = p_sparse_indices[i];
1220 } break;
1221 default: {
1222 ERR_FAIL_MSG("glTF export: Invalid sparse indices component type '" + _get_component_type_name(sparse_indices_component_type) + "' for sparse accessor indices.");
1223 } break;
1224 }
1225 ret_byte_offset += bytes_per_index;
1226 }
1227 const GLTFBufferViewIndex buffer_view_index = GLTFBufferView::write_new_buffer_view_into_state(p_gltf_state, indices_bytes, bytes_per_index, GLTFBufferView::TARGET_NONE, -1, 0, p_deduplicate);
1228 ERR_FAIL_COND_MSG(buffer_view_index == -1, "glTF export: Failed to write sparse indices into glTF state.");
1229 set_sparse_indices_buffer_view(buffer_view_index);
1230 }
1231
1232 // Low-level encode functions.
1233
1234 GLTFAccessor::GLTFComponentType GLTFAccessor::get_minimal_integer_component_type_from_ints(const PackedInt64Array &p_numbers) {
1235 bool has_negative = false;
1236 for (int64_t i = 0; i < p_numbers.size(); i++) {
1237 if (p_numbers[i] < 0) {
1238 has_negative = true;
1239 break;
1240 }
1241 }
1242 if (has_negative) {
1243 GLTFComponentType ret = GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE;
1244 for (int64_t i = 0; i < p_numbers.size(); i++) {
1245 const int64_t num = p_numbers[i];
1246 if (ret == GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE && (num < -128LL || num > 127LL)) {
1247 ret = GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT;
1248 }
1249 if (ret == GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT && (num < -32768LL || num > 32767LL)) {
1250 ret = GLTFAccessor::COMPONENT_TYPE_SIGNED_INT;
1251 }
1252 if (ret == GLTFAccessor::COMPONENT_TYPE_SIGNED_INT && (num < -2147483648LL || num > 2147483647LL)) {
1253 return GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG;
1254 }
1255 }
1256 return ret;
1257 }
1258 GLTFComponentType ret = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE;
1259 for (int64_t i = 0; i < p_numbers.size(); i++) {
1260 const int64_t num = p_numbers[i];
1261 // 3.7.2.1. indices accessor MUST NOT contain the maximum possible value for the component type used
1262 // (i.e., 255 for unsigned bytes, 65535 for unsigned shorts, 4294967295 for unsigned ints).
1263 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview
1264 if (ret == GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE && num > 254LL) {
1265 ret = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT;
1266 }
1267 if (ret == GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT && num > 65534LL) {
1268 ret = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT;
1269 }
1270 if (ret == GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT && num > 4294967294LL) {
1271 return GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG;
1272 }
1273 }
1274 return ret;
1275 }
1276
1277 PackedByteArray GLTFAccessor::encode_floats_as_bytes(const PackedFloat64Array &p_input_numbers) {
1278 // Filter and update `count`, `min`, and `max` based on the given data.
1279 PackedFloat64Array filtered_numbers = _filter_numbers(p_input_numbers);
1280 count = filtered_numbers.size() / _get_vector_size();
1281 _calculate_min_and_max(filtered_numbers);
1282 // Actually encode the data.
1283 const int64_t input_size = filtered_numbers.size();
1284 const int64_t bytes_per_component = _get_bytes_per_component(component_type);
1285 int64_t raw_byte_size = _determine_padded_byte_count(bytes_per_component * input_size);
1286 int64_t skip_every = 0;
1287 int64_t skip_bytes = 0;
1288 _determine_pad_skip(skip_every, skip_bytes);
1289 PackedByteArray ret;
1290 ret.resize(raw_byte_size);
1291 uint8_t *ret_write = ret.ptrw();
1292 int64_t ret_byte_offset = 0;
1293 for (int64_t i = 0; i < input_size; i++) {
1294 switch (component_type) {
1295 case COMPONENT_TYPE_NONE: {
1296 ERR_FAIL_V_MSG(ret, "glTF export: Invalid component type 'NONE' for glTF accessor.");
1297 } break;
1298 case COMPONENT_TYPE_SIGNED_BYTE: {
1299 *(int8_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1300 } break;
1301 case COMPONENT_TYPE_UNSIGNED_BYTE: {
1302 *(uint8_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1303 } break;
1304 case COMPONENT_TYPE_SIGNED_SHORT: {
1305 *(int16_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1306 } break;
1307 case COMPONENT_TYPE_UNSIGNED_SHORT: {
1308 *(uint16_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1309 } break;
1310 case COMPONENT_TYPE_SIGNED_INT: {
1311 *(int32_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1312 } break;
1313 case COMPONENT_TYPE_UNSIGNED_INT: {
1314 *(uint32_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1315 } break;
1316 case COMPONENT_TYPE_SINGLE_FLOAT: {
1317 *(float *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1318 } break;
1319 case COMPONENT_TYPE_DOUBLE_FLOAT: {
1320 *(double *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1321 } break;
1322 case COMPONENT_TYPE_HALF_FLOAT: {
1323 *(uint16_t *)&ret_write[ret_byte_offset] = Math::make_half_float(filtered_numbers[i]);
1324 } break;
1325 case COMPONENT_TYPE_SIGNED_LONG: {
1326 // Note: This can potentially result in precision loss because int64_t can store some values that double can't.
1327 *(int64_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1328 } break;
1329 case COMPONENT_TYPE_UNSIGNED_LONG: {
1330 // Note: This can potentially result in precision loss because uint64_t can store some values that double can't.
1331 *(uint64_t *)&ret_write[ret_byte_offset] = filtered_numbers[i];
1332 } break;
1333 default: {
1334 ERR_FAIL_V_MSG(ret, "glTF export: Godot does not support writing glTF accessor components of type '" + itos(component_type) + "'.");
1335 } break;
1336 }
1337 ret_byte_offset += bytes_per_component;
1338 if (unlikely(skip_every > 0)) {
1339 if ((i + 1) % skip_every == 0) {
1340 ret_byte_offset += skip_bytes;
1341 }
1342 }
1343 }
1344 ERR_FAIL_COND_V_MSG(ret_byte_offset != raw_byte_size, ret, "glTF export: Accessor encoded data did not write exactly the expected number of bytes.");
1345 return ret;
1346 }
1347
1348 PackedByteArray GLTFAccessor::encode_ints_as_bytes(const PackedInt64Array &p_input_numbers) {
1349 // Filter and update `count`, `min`, and `max` based on the given data.
1350 count = p_input_numbers.size() / _get_vector_size();
1351 _calculate_min_and_max(Variant(p_input_numbers));
1352 // Actually encode the data.
1353 const int64_t input_size = p_input_numbers.size();
1354 const int64_t bytes_per_component = _get_bytes_per_component(component_type);
1355 int64_t raw_byte_size = _determine_padded_byte_count(bytes_per_component * input_size);
1356 int64_t skip_every = 0;
1357 int64_t skip_bytes = 0;
1358 _determine_pad_skip(skip_every, skip_bytes);
1359 PackedByteArray ret;
1360 ret.resize(raw_byte_size);
1361 uint8_t *ret_write = ret.ptrw();
1362 int64_t ret_byte_offset = 0;
1363 for (int64_t i = 0; i < input_size; i++) {
1364 switch (component_type) {
1365 case COMPONENT_TYPE_NONE: {
1366 ERR_FAIL_V_MSG(ret, "glTF export: Invalid component type 'NONE' for glTF accessor.");
1367 } break;
1368 case COMPONENT_TYPE_SIGNED_BYTE: {
1369 *(int8_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1370 } break;
1371 case COMPONENT_TYPE_UNSIGNED_BYTE: {
1372 *(uint8_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1373 } break;
1374 case COMPONENT_TYPE_SIGNED_SHORT: {
1375 *(int16_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1376 } break;
1377 case COMPONENT_TYPE_UNSIGNED_SHORT: {
1378 *(uint16_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1379 } break;
1380 case COMPONENT_TYPE_SIGNED_INT: {
1381 *(int32_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1382 } break;
1383 case COMPONENT_TYPE_UNSIGNED_INT: {
1384 *(uint32_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1385 } break;
1386 case COMPONENT_TYPE_SINGLE_FLOAT: {
1387 *(float *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1388 } break;
1389 case COMPONENT_TYPE_DOUBLE_FLOAT: {
1390 *(double *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1391 } break;
1392 case COMPONENT_TYPE_HALF_FLOAT: {
1393 *(uint16_t *)&ret_write[ret_byte_offset] = Math::make_half_float(p_input_numbers[i]);
1394 } break;
1395 case COMPONENT_TYPE_SIGNED_LONG: {
1396 *(int64_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1397 } break;
1398 case COMPONENT_TYPE_UNSIGNED_LONG: {
1399 *(uint64_t *)&ret_write[ret_byte_offset] = p_input_numbers[i];
1400 } break;
1401 default: {
1402 ERR_FAIL_V_MSG(ret, "glTF export: Godot does not support writing glTF accessor components of type '" + itos(component_type) + "'.");
1403 } break;
1404 }
1405 ret_byte_offset += bytes_per_component;
1406 if (unlikely(skip_every > 0)) {
1407 if ((i + 1) % skip_every == 0) {
1408 ret_byte_offset += skip_bytes;
1409 }
1410 }
1411 }
1412 ERR_FAIL_COND_V_MSG(ret_byte_offset != raw_byte_size, ret, "glTF export: Accessor encoded data did not write exactly the expected number of bytes.");
1413 return ret;
1414 }
1415
1416 PackedByteArray GLTFAccessor::encode_variants_as_bytes(const Array &p_input_data, Variant::Type p_variant_type) {
1417 const int64_t bytes_per_vec = _get_bytes_per_vector();
1418 ERR_FAIL_COND_V_MSG(bytes_per_vec == 0, PackedByteArray(), "glTF export: Cannot encode an accessor of this type.");
1419 PackedFloat64Array numbers = _encode_variants_as_floats(p_input_data, p_variant_type);
1420 return encode_floats_as_bytes(numbers);
1421 }
1422
1423 GLTFAccessorIndex GLTFAccessor::store_accessor_data_into_state(const Ref<GLTFState> &p_gltf_state, const PackedByteArray &p_data_bytes, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const GLTFBufferIndex p_buffer_index, const bool p_deduplicate) {
1424 ERR_FAIL_COND_V_MSG(p_data_bytes.is_empty(), -1, "glTF export: Cannot store nothing.");
1425 // Update `count` based on the size of the data. It's possible that `count` may already be correct, but this function is public, so this prevents footguns.
1426 const int64_t bytes_per_vec = _get_bytes_per_vector();
1427 ERR_FAIL_COND_V_MSG(bytes_per_vec == 0 || p_data_bytes.size() % bytes_per_vec != 0, -1, "glTF export: Tried to store an accessor with data that is not a multiple of the accessor's bytes per vector.");
1428 count = p_data_bytes.size() / bytes_per_vec;
1429 // 3.6.2.4. The byte offset of an accessor's buffer view MUST be a multiple of the accessor's primitive size.
1430 // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#data-alignment
1431 const int64_t alignment = _get_bytes_per_component(component_type);
1432 // 3.6.2.4. Each element of a vertex attribute MUST be aligned to 4-byte boundaries inside a bufferView.
1433 int64_t byte_stride = -1;
1434 if (p_buffer_view_target == GLTFBufferView::TARGET_ARRAY_BUFFER) {
1435 byte_stride = bytes_per_vec;
1436 ERR_FAIL_COND_V_MSG(byte_stride < 4 || byte_stride % 4 != 0, -1, "glTF export: Vertex attributes using TARGET_ARRAY_BUFFER must have a byte stride that is a multiple of 4 as required by section 3.6.2.4 of the glTF specification.");
1437 }
1438 // Write the data into a new buffer view.
1439 const GLTFBufferViewIndex buffer_view_index = GLTFBufferView::write_new_buffer_view_into_state(p_gltf_state, p_data_bytes, alignment, p_buffer_view_target, byte_stride, 0, p_deduplicate);
1440 ERR_FAIL_COND_V_MSG(buffer_view_index == -1, -1, "glTF export: Accessor failed to write new buffer view into glTF state.");
1441 set_buffer_view(buffer_view_index);
1442 // Add the new accessor to the state, but check for duplicates first.
1443 Vector<Ref<GLTFAccessor>> state_accessors = p_gltf_state->get_accessors();
1444 const GLTFAccessorIndex accessor_count = state_accessors.size();
1445 for (GLTFAccessorIndex i = 0; i < accessor_count; i++) {
1446 const Ref<GLTFAccessor> &existing_accessor = state_accessors[i];
1447 if (is_equal_exact(existing_accessor)) {
1448 // An identical accessor already exists in the state, so just return the index.
1449 return i;
1450 }
1451 }
1452 Ref<GLTFAccessor> self = this;
1453 state_accessors.append(self);
1454 p_gltf_state->set_accessors(state_accessors);
1455 return accessor_count;
1456 }
1457
1458 Ref<GLTFAccessor> GLTFAccessor::make_new_accessor_without_data(GLTFAccessorType p_accessor_type, GLTFComponentType p_component_type) {
1459 Ref<GLTFAccessor> accessor;
1460 accessor.instantiate();
1461 accessor->set_accessor_type(p_accessor_type);
1462 accessor->set_component_type(p_component_type);
1463 return accessor;
1464 }
1465
1466 // High-level encode functions.
1467
1468 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_colors(const Ref<GLTFState> &p_gltf_state, const PackedColorArray &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1469 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1470 PackedFloat64Array numbers;
1471 numbers.resize(p_input_data.size() * 4);
1472 for (int64_t i = 0; i < p_input_data.size(); i++) {
1473 const Color &color = p_input_data[i];
1474 numbers.set(i * 4, color.r);
1475 numbers.set(i * 4 + 1, color.g);
1476 numbers.set(i * 4 + 2, color.b);
1477 numbers.set(i * 4 + 3, color.a);
1478 }
1479 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC4, COMPONENT_TYPE_SINGLE_FLOAT);
1480 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(numbers);
1481 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1482 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1483 }
1484
1485 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_float64s(const Ref<GLTFState> &p_gltf_state, const PackedFloat64Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1486 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1487 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_SCALAR, COMPONENT_TYPE_SINGLE_FLOAT);
1488 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(p_input_data);
1489 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1490 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1491 }
1492
1493 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_int32s(const Ref<GLTFState> &p_gltf_state, const PackedInt32Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1494 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1495 PackedInt64Array numbers;
1496 numbers.resize(p_input_data.size());
1497 for (int64_t i = 0; i < p_input_data.size(); i++) {
1498 numbers.set(i, p_input_data[i]);
1499 }
1500 const GLTFComponentType component_type = get_minimal_integer_component_type_from_ints(numbers);
1501 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_SCALAR, component_type);
1502 PackedByteArray encoded_bytes = accessor->encode_ints_as_bytes(numbers);
1503 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1504 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1505 }
1506
1507 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_int64s(const Ref<GLTFState> &p_gltf_state, const PackedInt64Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1508 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1509 const GLTFComponentType component_type = get_minimal_integer_component_type_from_ints(p_input_data);
1510 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_SCALAR, component_type);
1511 PackedByteArray encoded_bytes = accessor->encode_ints_as_bytes(p_input_data);
1512 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1513 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1514 }
1515
1516 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_quaternions(const Ref<GLTFState> &p_gltf_state, const Vector<Quaternion> &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1517 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1518 PackedFloat64Array numbers;
1519 numbers.resize(p_input_data.size() * 4);
1520 for (int64_t i = 0; i < p_input_data.size(); i++) {
1521 const Quaternion &quat = p_input_data[i];
1522 numbers.set(i * 4, quat.x);
1523 numbers.set(i * 4 + 1, quat.y);
1524 numbers.set(i * 4 + 2, quat.z);
1525 numbers.set(i * 4 + 3, quat.w);
1526 }
1527 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC4, COMPONENT_TYPE_SINGLE_FLOAT);
1528 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(numbers);
1529 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1530 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1531 }
1532
1533 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_variants(const Ref<GLTFState> &p_gltf_state, const Array &p_input_data, Variant::Type p_variant_type, GLTFAccessorType p_accessor_type, GLTFComponentType p_component_type, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1534 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1535 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(p_accessor_type, p_component_type);
1536 // Write the data into a new buffer view.
1537 PackedByteArray encoded_bytes = accessor->encode_variants_as_bytes(p_input_data, p_variant_type);
1538 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1539 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1540 }
1541
1542 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_vector2s(const Ref<GLTFState> &p_gltf_state, const PackedVector2Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1543 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1544 PackedFloat64Array numbers;
1545 numbers.resize(p_input_data.size() * 2);
1546 for (int64_t i = 0; i < p_input_data.size(); i++) {
1547 const Vector2 &vec = p_input_data[i];
1548 numbers.set(i * 2, vec.x);
1549 numbers.set(i * 2 + 1, vec.y);
1550 }
1551 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC2, COMPONENT_TYPE_SINGLE_FLOAT);
1552 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(numbers);
1553 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1554 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1555 }
1556
1557 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_vector3s(const Ref<GLTFState> &p_gltf_state, const PackedVector3Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1558 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1559 PackedFloat64Array numbers;
1560 numbers.resize(p_input_data.size() * 3);
1561 for (int64_t i = 0; i < p_input_data.size(); i++) {
1562 const Vector3 &vec = p_input_data[i];
1563 numbers.set(i * 3, vec.x);
1564 numbers.set(i * 3 + 1, vec.y);
1565 numbers.set(i * 3 + 2, vec.z);
1566 }
1567 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC3, COMPONENT_TYPE_SINGLE_FLOAT);
1568 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(numbers);
1569 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1570 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1571 }
1572
1573 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_vector4s(const Ref<GLTFState> &p_gltf_state, const PackedVector4Array &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1574 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1575 PackedFloat64Array numbers;
1576 numbers.resize(p_input_data.size() * 4);
1577 for (int64_t i = 0; i < p_input_data.size(); i++) {
1578 const Vector4 &vec = p_input_data[i];
1579 numbers.set(i * 4, vec.x);
1580 numbers.set(i * 4 + 1, vec.y);
1581 numbers.set(i * 4 + 2, vec.z);
1582 numbers.set(i * 4 + 3, vec.w);
1583 }
1584 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC4, COMPONENT_TYPE_SINGLE_FLOAT);
1585 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(numbers);
1586 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1587 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1588 }
1589
1590 GLTFAccessorIndex GLTFAccessor::encode_new_accessor_from_vector4is(const Ref<GLTFState> &p_gltf_state, const Vector<Vector4i> &p_input_data, const GLTFBufferView::ArrayBufferTarget p_buffer_view_target, const bool p_deduplicate) {
1591 ERR_FAIL_COND_V_MSG(p_input_data.is_empty(), -1, "glTF export: Cannot encode an accessor from an empty array.");
1592 PackedInt64Array numbers;
1593 numbers.resize(p_input_data.size() * 4);
1594 for (int64_t i = 0; i < p_input_data.size(); i++) {
1595 const Vector4i &vec = p_input_data[i];
1596 numbers.set(i * 4, vec.x);
1597 numbers.set(i * 4 + 1, vec.y);
1598 numbers.set(i * 4 + 2, vec.z);
1599 numbers.set(i * 4 + 3, vec.w);
1600 }
1601 const GLTFComponentType component_type = get_minimal_integer_component_type_from_ints(numbers);
1602 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC4, component_type);
1603 PackedByteArray encoded_bytes = accessor->encode_ints_as_bytes(numbers);
1604 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1605 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_buffer_view_target, 0, p_deduplicate);
1606 }
1607
1608 GLTFAccessorIndex GLTFAccessor::encode_new_sparse_accessor_from_vec3s(const Ref<GLTFState> &p_gltf_state, const PackedVector3Array &p_input_data, const PackedVector3Array &p_base_reference_data, const double p_tolerance_multiplier, const GLTFBufferView::ArrayBufferTarget p_main_buffer_view_target, const bool p_deduplicate) {
1609 const int64_t input_size = p_input_data.size();
1610 ERR_FAIL_COND_V_MSG(input_size == 0, -1, "glTF export: Cannot encode an accessor from an empty array.");
1611 const bool is_base_empty = p_base_reference_data.is_empty();
1612 ERR_FAIL_COND_V_MSG(!is_base_empty && p_base_reference_data.size() != input_size, -1, "glTF export: Base reference data must either be empty, or have the same size as the main input data.");
1613 PackedInt64Array sparse_indices;
1614 PackedFloat64Array sparse_values;
1615 PackedFloat64Array dense_values;
1616 int64_t highest_index = 0;
1617 dense_values.resize(input_size * 3);
1618 for (int64_t i = 0; i < input_size; i++) {
1619 Vector3 vec = p_input_data[i];
1620 Vector3 base_ref_vec;
1621 Vector3 displacement;
1622 if (is_base_empty) {
1623 base_ref_vec = Vector3();
1624 displacement = vec;
1625 } else {
1626 base_ref_vec = p_base_reference_data[i];
1627 displacement = vec - base_ref_vec;
1628 }
1629 if ((displacement * p_tolerance_multiplier).is_zero_approx()) {
1630 vec = base_ref_vec;
1631 } else {
1632 highest_index = i;
1633 sparse_indices.append(i);
1634 sparse_values.append(vec.x);
1635 sparse_values.append(vec.y);
1636 sparse_values.append(vec.z);
1637 }
1638 dense_values.set(i * 3, vec.x);
1639 dense_values.set(i * 3 + 1, vec.y);
1640 dense_values.set(i * 3 + 2, vec.z);
1641 }
1642 // Check if the sparse accessor actually saves space, or if it's better to just use a normal accessor.
1643 const int64_t sparse_count = sparse_indices.size();
1644 const int64_t bytes_per_value_component = _get_bytes_per_component(COMPONENT_TYPE_SINGLE_FLOAT);
1645 const GLTFComponentType indices_component_type = _get_indices_component_type_for_size(highest_index);
1646 const int64_t sparse_data_bytes = _get_bytes_per_component(indices_component_type) * sparse_count + bytes_per_value_component * sparse_values.size();
1647 const int64_t dense_data_bytes = bytes_per_value_component * 3 * input_size;
1648 // Sparse accessors require more JSON, a bit under 200 characters when minified, so factor that in.
1649 constexpr int64_t sparse_json_fluff = 200;
1650 Ref<GLTFAccessor> accessor = make_new_accessor_without_data(TYPE_VEC3, COMPONENT_TYPE_SINGLE_FLOAT);
1651 if (sparse_data_bytes + sparse_json_fluff >= dense_data_bytes) {
1652 // Sparse accessor is not worth it, just use a normal accessor instead.
1653 // However, note that we use the calculated dense values instead of the original input data.
1654 // This way, regardless of the underlying storage layout, the data is the same in both cases.
1655 PackedByteArray encoded_bytes = accessor->encode_floats_as_bytes(dense_values);
1656 ERR_FAIL_COND_V_MSG(encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1657 return accessor->store_accessor_data_into_state(p_gltf_state, encoded_bytes, p_main_buffer_view_target, 0, p_deduplicate);
1658 }
1659 // Encode as a sparse accessor.
1660 if (sparse_count > 0) {
1661 accessor->set_sparse_count(sparse_count);
1662 accessor->set_sparse_indices_component_type(indices_component_type);
1663 accessor->_store_sparse_indices_into_state(p_gltf_state, sparse_indices, p_deduplicate);
1664 const PackedByteArray sparse_values_encoded_bytes = accessor->encode_floats_as_bytes(sparse_values);
1665 ERR_FAIL_COND_V_MSG(sparse_values_encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode sparse values as bytes.");
1666 // Note: Sparse values always use TARGET_NONE, it does NOT match the target of the main buffer view.
1667 const GLTFBufferViewIndex sparse_values_buffer_view_index = GLTFBufferView::write_new_buffer_view_into_state(p_gltf_state, sparse_values_encoded_bytes, bytes_per_value_component, GLTFBufferView::TARGET_NONE, -1, 0, p_deduplicate);
1668 accessor->set_sparse_values_buffer_view(sparse_values_buffer_view_index);
1669 }
1670 // If the base reference data is empty, just directly add the accessor with only sparse data.
1671 if (is_base_empty) {
1672 // This is similar to `encode_floats_as_bytes` + `store_accessor_data_into_state` but we don't write a buffer view.
1673 // Filter and update `count`, `min`, and `max` based on the given data.
1674 accessor->set_count(input_size);
1675 const PackedFloat64Array filtered_numbers = accessor->_filter_numbers(dense_values);
1676 accessor->_calculate_min_and_max(filtered_numbers);
1677 // Add the new accessor to the state, but check for duplicates first.
1678 Vector<Ref<GLTFAccessor>> state_accessors = p_gltf_state->get_accessors();
1679 const GLTFAccessorIndex accessor_count = state_accessors.size();
1680 for (GLTFAccessorIndex i = 0; i < accessor_count; i++) {
1681 const Ref<GLTFAccessor> &existing_accessor = state_accessors[i];
1682 if (accessor->is_equal_exact(existing_accessor)) {
1683 // An identical accessor already exists in the state, so just return the index.
1684 return i;
1685 }
1686 }
1687 state_accessors.append(accessor);
1688 p_gltf_state->set_accessors(state_accessors);
1689 return accessor_count;
1690 }
1691 // Encode the base reference alongside the sparse data.
1692 PackedFloat64Array base_reference_values;
1693 base_reference_values.resize(input_size * 3);
1694 for (int64_t i = 0; i < input_size; i++) {
1695 const Vector3 &base_ref_vec = p_base_reference_data[i];
1696 base_reference_values.set(i * 3, base_ref_vec.x);
1697 base_reference_values.set(i * 3 + 1, base_ref_vec.y);
1698 base_reference_values.set(i * 3 + 2, base_ref_vec.z);
1699 }
1700 const PackedByteArray base_reference_encoded_bytes = accessor->encode_floats_as_bytes(base_reference_values);
1701 ERR_FAIL_COND_V_MSG(base_reference_encoded_bytes.is_empty(), -1, "glTF export: Accessor failed to encode data as bytes (was the input data empty?).");
1702 return accessor->store_accessor_data_into_state(p_gltf_state, base_reference_encoded_bytes, p_main_buffer_view_target, 0, p_deduplicate);
1703 }
1704
1705 // Dictionary conversion.
1706
1707 Ref<GLTFAccessor> GLTFAccessor::from_dictionary(const Dictionary &p_dict) {
1708 // See https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/schema/accessor.schema.json
1709 Ref<GLTFAccessor> accessor;
1710 accessor.instantiate();
1711 if (p_dict.has("bufferView")) {
1712 // bufferView is optional. If not present, the accessor is considered to be zero-initialized.
1713 accessor->buffer_view = p_dict["bufferView"];
1714 }
1715 if (p_dict.has("byteOffset")) {
1716 accessor->byte_offset = p_dict["byteOffset"];
1717 }
1718 if (p_dict.has("componentType")) {
1719 accessor->component_type = (GLTFAccessor::GLTFComponentType)(int32_t)p_dict["componentType"];
1720 }
1721 if (p_dict.has("count")) {
1722 accessor->count = p_dict["count"];
1723 }
1724 if (accessor->count <= 0) {
1725 ERR_PRINT("glTF import: Invalid accessor count " + itos(accessor->count) + " for accessor. Accessor count must be greater than 0.");
1726 }
1727 if (p_dict.has("max")) {
1728 accessor->max = p_dict["max"];
1729 }
1730 if (p_dict.has("min")) {
1731 accessor->min = p_dict["min"];
1732 }
1733 if (p_dict.has("normalized")) {
1734 accessor->normalized = p_dict["normalized"];
1735 }
1736 if (p_dict.has("sparse")) {
1737 // See https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/schema/accessor.sparse.schema.json
1738 const Dictionary &sparse_dict = p_dict["sparse"];
1739 ERR_FAIL_COND_V(!sparse_dict.has("count"), accessor);
1740 accessor->sparse_count = sparse_dict["count"];
1741 ERR_FAIL_COND_V(!sparse_dict.has("indices"), accessor);
1742 const Dictionary &sparse_indices_dict = sparse_dict["indices"];
1743 ERR_FAIL_COND_V(!sparse_indices_dict.has("bufferView"), accessor);
1744 accessor->sparse_indices_buffer_view = sparse_indices_dict["bufferView"];
1745 ERR_FAIL_COND_V(!sparse_indices_dict.has("componentType"), accessor);
1746 accessor->sparse_indices_component_type = (GLTFAccessor::GLTFComponentType)(int32_t)sparse_indices_dict["componentType"];
1747 if (sparse_indices_dict.has("byteOffset")) {
1748 accessor->sparse_indices_byte_offset = sparse_indices_dict["byteOffset"];
1749 }
1750 ERR_FAIL_COND_V(!sparse_dict.has("values"), accessor);
1751 const Dictionary &sparse_values_dict = sparse_dict["values"];
1752 ERR_FAIL_COND_V(!sparse_values_dict.has("bufferView"), accessor);
1753 accessor->sparse_values_buffer_view = sparse_values_dict["bufferView"];
1754 if (sparse_values_dict.has("byteOffset")) {
1755 accessor->sparse_values_byte_offset = sparse_values_dict["byteOffset"];
1756 }
1757 }
1758 accessor->accessor_type = _get_accessor_type_from_str(p_dict["type"]);
1759 return accessor;
1760 }
1761
1762 Dictionary GLTFAccessor::to_dictionary() const {
1763 Dictionary dict;
1764 if (buffer_view != -1) {
1765 // bufferView may be omitted to zero-initialize the buffer. When this happens, byteOffset MUST also be omitted.
1766 if (byte_offset > 0) {
1767 dict["byteOffset"] = byte_offset;
1768 }
1769 dict["bufferView"] = buffer_view;
1770 }
1771 dict["componentType"] = component_type;
1772 dict["count"] = count;
1773 switch (component_type) {
1774 case COMPONENT_TYPE_NONE: {
1775 ERR_PRINT("glTF export: Invalid component type 'NONE' for glTF accessor.");
1776 } break;
1777 case COMPONENT_TYPE_SIGNED_BYTE:
1778 case COMPONENT_TYPE_UNSIGNED_BYTE:
1779 case COMPONENT_TYPE_SIGNED_SHORT:
1780 case COMPONENT_TYPE_UNSIGNED_SHORT:
1781 case COMPONENT_TYPE_SIGNED_INT:
1782 case COMPONENT_TYPE_UNSIGNED_INT:
1783 case COMPONENT_TYPE_SIGNED_LONG:
1784 case COMPONENT_TYPE_UNSIGNED_LONG: {
1785 dict["max"] = PackedInt64Array(Variant(max));
1786 dict["min"] = PackedInt64Array(Variant(min));
1787 } break;
1788 case COMPONENT_TYPE_SINGLE_FLOAT:
1789 case COMPONENT_TYPE_DOUBLE_FLOAT:
1790 case COMPONENT_TYPE_HALF_FLOAT: {
1791 dict["max"] = max;
1792 dict["min"] = min;
1793 } break;
1794 }
1795 dict["normalized"] = normalized;
1796 dict["type"] = _get_accessor_type_name();
1797
1798 if (sparse_count > 0) {
1799 Dictionary sparse_indices_dict;
1800 sparse_indices_dict["bufferView"] = sparse_indices_buffer_view;
1801 sparse_indices_dict["componentType"] = sparse_indices_component_type;
1802 if (sparse_indices_byte_offset > 0) {
1803 sparse_indices_dict["byteOffset"] = sparse_indices_byte_offset;
1804 }
1805 Dictionary sparse_values_dict;
1806 sparse_values_dict["bufferView"] = sparse_values_buffer_view;
1807 if (sparse_values_byte_offset > 0) {
1808 sparse_values_dict["byteOffset"] = sparse_values_byte_offset;
1809 }
1810 Dictionary sparse_dict;
1811 sparse_dict["count"] = sparse_count;
1812 sparse_dict["indices"] = sparse_indices_dict;
1813 sparse_dict["values"] = sparse_values_dict;
1814 dict["sparse"] = sparse_dict;
1815 }
1816 return dict;
1817 }