Compare commits

...

18 Commits

Author SHA1 Message Date
Syoyo Fujita
fda7422022 Merge pull request #501 from msklywenn/release
Fix Animation extensions being loaded in place of Sampler extensions
2024-08-08 21:47:56 +09:00
Daniel Borges
decfabd67e Merge branch 'syoyo:release' into release 2024-08-08 10:25:11 +02:00
Syoyo Fujita
10b23b6af2 Merge pull request #496 from ptc-tgamper/bug/issue-495
Allow WriteImageDataFunction() callback to be called with empty images
2024-07-26 21:44:16 +09:00
Thomas Gamper
fe3cfbe996 fixes #495
Fix issues that block custom image loaders and writers to deal with empty images
2024-07-23 11:45:54 +02:00
Daniel Borges
3b73caa8e8 fixed ParseAnimation loading animation's extensions into sampler instead of sample's extensions. 2024-07-19 12:34:16 +02:00
Syoyo Fujita
fea6786129 Merge pull request #493 from ptc-tgamper/bug/model_clear_on_load
Properly clear the model before loading
2024-07-06 02:43:52 +09:00
Thomas Gamper
fb58f88a4e Properly clear the model before loading 2024-07-05 08:57:36 +02:00
Syoyo Fujita
143ff45b61 Update README.md 2024-07-04 03:01:46 +09:00
Syoyo Fujita
cfbec35dc7 Merge pull request #492 from danwillm/inverse-bind-matrix
Make inverseBindMatrices optional
2024-07-04 02:59:35 +09:00
danwillm
4ad8c82c9e Add test for inverse bind matrices being optional 2024-07-01 22:32:17 +01:00
danwillm
2e7ba45a6c Make inverseBindMatrices optional 2024-07-01 18:31:00 +01:00
Syoyo Fujita
cf9767668a bump minor version. 2024-06-28 21:30:43 +09:00
Syoyo Fujita
8a269aa5e9 Merge pull request #491 from ptc-tgamper/bug/image_saving
Fix images not being saved due to missing filesystem callbacks
2024-06-28 21:24:53 +09:00
Thomas Gamper
38614763e9 fixes #487
Support image as_is flag in loading and saving
2024-06-28 12:17:38 +02:00
Thomas Gamper
3245906248 fixes #473
tiny_gltf.h - explicitly pass filesystem callbacks to image related functions
tester.cc - add respective test case, fix image uri test case
2024-06-25 15:12:30 +02:00
Syoyo Fujita
847df8456a Merge pull request #489 from SeanCurtis-TRI/PR_callback_as_function
Update typedefs of C-style function pointers to std::function
2024-06-12 04:01:37 +09:00
Sean Curtis
6482c08cf7 Remove asserts 2024-06-10 14:18:31 -07:00
Sean Curtis
e08df72575 Update typedefs of C-style function pointers to std::function
This allows for the callback to maintain their own state (without recourse
to globals).

In addition, added some incidental clean up:

  - URICallback, passed by pointer, is now asserted to be non-null before
    accessing.
  - FSCallbacks are validated when they are set (in debug builds).
2024-06-06 07:45:01 -07:00
4 changed files with 435 additions and 160 deletions

View File

@@ -9,7 +9,7 @@ If you are looking for old, C++03 version, please use `devel-picojson` branch (b
## Status
Currently TinyGLTF is stable and maintenance mode. No drastic changes and feature additions planned.
- v2.9.0 Various fixes and improvements. Filesystem callback API change.
- v2.8.0 Add URICallbacks for custom URI handling in Buffer and Image. PR#397
- v2.7.0 Change WriteImageDataFunction user callback function signature. PR#393
- v2.6.0 Support serializing sparse accessor(Thanks to @fynv).

BIN
tests/issue-492.glb Normal file

Binary file not shown.

View File

@@ -474,7 +474,7 @@ TEST_CASE("image-uri-spaces", "[issue-236]") {
}
REQUIRE(true == ret);
REQUIRE(err.empty());
REQUIRE(!warn.empty()); // relative image path won't exist in tests/
REQUIRE(warn.empty());
REQUIRE(saved.images.size() == model.images.size());
// The image uri in CubeImageUriMultipleSpaces.gltf is not encoded and
@@ -662,10 +662,11 @@ TEST_CASE("serialize-image-callback", "[issue-394]") {
auto writer = [](const std::string *basepath, const std::string *filename,
const tinygltf::Image *image, bool embedImages,
const tinygltf::URICallbacks *uri_cb, std::string *out_uri,
void *user_pointer) -> bool {
const tinygltf::FsCallbacks* fs, const tinygltf::URICallbacks *uri_cb,
std::string *out_uri, void *user_pointer) -> bool {
(void)basepath;
(void)image;
(void)fs;
(void)uri_cb;
REQUIRE(*filename == "foo");
REQUIRE(embedImages == true);
@@ -699,12 +700,13 @@ TEST_CASE("serialize-image-failure", "[issue-394]") {
auto writer = [](const std::string *basepath, const std::string *filename,
const tinygltf::Image *image, bool embedImages,
const tinygltf::URICallbacks *uri_cb, std::string *out_uri,
void *user_pointer) -> bool {
const tinygltf::FsCallbacks* fs, const tinygltf::URICallbacks *uri_cb,
std::string *out_uri, void *user_pointer) -> bool {
(void)basepath;
(void)filename;
(void)image;
(void)embedImages;
(void)fs;
(void)uri_cb;
(void)out_uri;
(void)user_pointer;
@@ -1056,3 +1058,192 @@ TEST_CASE("serialize-lods", "[lods]") {
CHECK(nodeWithoutLods.extensions.count("MSFT_lod") == 0);
}
}
TEST_CASE("write-image-issue", "[issue-473]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
REQUIRE(model.images.size() == 2);
REQUIRE(model.images[0].uri == "Cube_BaseColor.png");
REQUIRE(model.images[1].uri == "Cube_MetallicRoughness.png");
REQUIRE_FALSE(model.images[0].image.empty());
REQUIRE_FALSE(model.images[1].image.empty());
ok = ctx.WriteGltfSceneToFile(&model, "Cube.gltf");
REQUIRE(ok);
for (const auto& image : model.images) {
std::fstream file(image.uri);
CHECK(file.good());
}
}
TEST_CASE("images-as-is", "[issue-487]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
ctx.SetImagesAsIs(true);
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : model.images) {
CHECK(image.as_is == true);
CHECK_FALSE(image.uri.empty());
CHECK_FALSE(image.image.empty());
#ifndef TINYGLTF_NO_STB_IMAGE
// Make sure we can decode the images
int w = -1, h = -1, component = -1;
unsigned char *data = stbi_load_from_memory(image.image.data(), static_cast<int>(image.image.size()), &w, &h, &component, 0);
CHECK(data != nullptr);
CHECK(w == 512);
CHECK(h == 512);
CHECK(component >= 3);
stbi_image_free(data);
#endif
}
// Write glTF model to disk, and images as separate files
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube_with_image_files.gltf");
REQUIRE(ok);
// All the images should have been written to disk with their original data
for (const auto& image : model.images) {
// Make sure the image files exist
std::fstream file(image.uri);
CHECK(file.good());
#ifndef TINYGLTF_NO_STB_IMAGE
// Make sure we can load the images
int w = -1, h = -1, component = -1;
unsigned char *data = stbi_load(image.uri.c_str(), &w, &h, &component, 0);
CHECK(data != nullptr);
CHECK(w == 512);
CHECK(h == 512);
CHECK(component >= 3);
stbi_image_free(data);
#endif
}
}
// Write glTF model to disk, and embed images as data URIs
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube_with_embedded_images.gltf", true, false);
REQUIRE(ok);
// Load above model again, and check if the images are loaded properly
tinygltf::Model embeddedImages;
ctx.SetImagesAsIs(false);
bool ok = ctx.LoadASCIIFromFile(&embeddedImages, &err, &warn, "Cube_with_embedded_images.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : embeddedImages.images) {
CHECK(image.as_is == false);
CHECK_FALSE(image.mimeType.empty());
CHECK_FALSE(image.image.empty());
CHECK(image.width == 512);
CHECK(image.height == 512);
CHECK(image.component >= 3);
}
}
// Write glTF model to disk, as GLB
{
ok = ctx.WriteGltfSceneToFile(&model, "Cube.glb", true, true, true, true);
REQUIRE(ok);
// Load above model again, and check if the images are loaded properly
tinygltf::Model glbModel;
ctx.SetImagesAsIs(false);
bool ok = ctx.LoadBinaryFromFile(&glbModel, &err, &warn, "Cube.glb");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
for (const auto& image : glbModel.images) {
CHECK(image.as_is == false);
CHECK_FALSE(image.mimeType.empty());
CHECK_FALSE(image.image.empty());
CHECK(image.width == 512);
CHECK(image.height == 512);
CHECK(image.component >= 3);
}
}
}
TEST_CASE("inverse-bind-matrices-optional", "[issue-492]") {
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
std::string err;
std::string warn;
bool ret = ctx.LoadBinaryFromFile(&model, &err, &warn, "issue-492.glb");
if (!warn.empty()) {
std::cout << "WARN:" << warn << std::endl;
}
if (!err.empty()) {
std::cerr << "ERR:" << err << std::endl;
}
REQUIRE(true == ret);
REQUIRE(err.empty());
}
bool LoadImageData(tinygltf::Image * /* image */, const int /* image_idx */, std::string * /* err */,
std::string * /* warn */, int /* req_width */, int /* req_height */,
const unsigned char * /* bytes */, int /* size */, void * /*user_data */) {
return true;
}
bool WriteImageData(const std::string * /* basepath */, const std::string * /* filename */,
const tinygltf::Image *image, bool /* embedImages */,
const tinygltf::FsCallbacks * /* fs_cb */, const tinygltf::URICallbacks * /* uri_cb */,
std::string * /* out_uri */, void * user_pointer) {
REQUIRE(user_pointer != nullptr);
auto counter = static_cast<int*>(user_pointer);
*counter = *counter + 1;
return true;
}
TEST_CASE("empty-images-not-written", "[issue-495]") {
std::string err;
std::string warn;
tinygltf::Model model;
tinygltf::TinyGLTF ctx;
ctx.SetImageLoader(LoadImageData, nullptr);
bool ok = ctx.LoadASCIIFromFile(&model, &err, &warn, "../models/Cube/Cube.gltf");
REQUIRE(ok);
REQUIRE(err.empty());
REQUIRE(warn.empty());
CHECK(model.images.size() == 2);
for (const auto& image : model.images) {
// No data loaded or decoded
CHECK(image.image.empty());
// The URI is kept
CHECK_FALSE(image.uri.empty());
// The URI should not be a data URI
CHECK(image.uri.find("data:") != 0);
}
// Now write the loaded model
int counter = 0;
ctx.SetImageWriter(WriteImageData, &counter);
ok = ctx.WriteGltfSceneToFile(&model, "issue-495-external.gltf");
CHECK(ok);
// WriteImageData should be invoked for both images
CHECK(counter == 2);
}

View File

@@ -25,7 +25,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Version: - v2.8.10
// Version: - v2.9.*
// See https://github.com/syoyo/tinygltf/releases for release history.
//
// Tiny glTF loader is using following third party libraries:
@@ -43,9 +43,11 @@
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <string>
#include <utility>
#include <vector>
// Auto-detect C++14 standard version
@@ -647,9 +649,7 @@ struct Image {
// When this flag is true, data is stored to `image` in as-is format(e.g. jpeg
// compressed for "image/jpeg" mime) This feature is good if you use custom
// image loader function. (e.g. delayed decoding of images for faster glTF
// parsing) Default parser for Image does not provide as-is loading feature at
// the moment. (You can manipulate this by providing your own LoadImageData
// function)
// parsing).
bool as_is{false};
Image() = default;
@@ -1263,17 +1263,18 @@ enum SectionCheck {
/// image URIs differently, for example. See
/// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris
///
typedef bool (*URIEncodeFunction)(const std::string &in_uri,
const std::string &object_type,
std::string *out_uri, void *user_data);
using URIEncodeFunction = std::function<bool(
const std::string & /* in_uri */, const std::string & /* object_type */,
std::string * /* out_uri */, void * /* user_data */)>;
///
/// URIDecodeFunction type. Signature for custom URI decoding of external
/// resources such as .bin and image files. Used by tinygltf when computing
/// filenames to write resources.
///
typedef bool (*URIDecodeFunction)(const std::string &in_uri,
std::string *out_uri, void *user_data);
using URIDecodeFunction =
std::function<bool(const std::string & /* in_uri */,
std::string * /* out_uri */, void * /* user_data */)>;
// Declaration of default uri decode function
bool URIDecode(const std::string &in_uri, std::string *out_uri,
@@ -1290,69 +1291,36 @@ struct URICallbacks {
};
///
/// LoadImageDataFunction type. Signature for custom image loading callbacks.
/// FileExistsFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *,
std::string *, int, int,
const unsigned char *, int,
void *user_pointer);
///
/// WriteImageDataFunction type. Signature for custom image writing callbacks.
/// The out_uri parameter becomes the URI written to the gltf and may reference
/// a file or contain a data URI.
///
typedef bool (*WriteImageDataFunction)(const std::string *basepath,
const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb,
std::string *out_uri,
void *user_pointer);
#ifndef TINYGLTF_NO_STB_IMAGE
// Declaration of default image loader callback
bool LoadImageData(Image *image, const int image_idx, std::string *err,
std::string *warn, int req_width, int req_height,
const unsigned char *bytes, int size, void *);
#endif
#ifndef TINYGLTF_NO_STB_IMAGE_WRITE
// Declaration of default image writer callback
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb, std::string *out_uri, void *);
#endif
///
/// FilExistsFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *);
using FileExistsFunction = std::function<bool(
const std::string & /* abs_filename */, void * /* user_data */)>;
///
/// ExpandFilePathFunction type. Signature for custom filesystem callbacks.
///
typedef std::string (*ExpandFilePathFunction)(const std::string &, void *);
using ExpandFilePathFunction =
std::function<std::string(const std::string &, void *)>;
///
/// ReadWholeFileFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *,
std::string *, const std::string &,
void *);
using ReadWholeFileFunction = std::function<bool(
std::vector<unsigned char> *, std::string *, const std::string &, void *)>;
///
/// WriteWholeFileFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &,
const std::vector<unsigned char> &,
void *);
using WriteWholeFileFunction =
std::function<bool(std::string *, const std::string &,
const std::vector<unsigned char> &, void *)>;
///
/// GetFileSizeFunction type. Signature for custom filesystem callbacks.
///
typedef bool (*GetFileSizeFunction)(size_t *filesize_out, std::string *err,
const std::string &abs_filename,
void *userdata);
using GetFileSizeFunction =
std::function<bool(size_t *filesize_out, std::string *err,
const std::string &abs_filename, void *userdata)>;
///
/// A structure containing all required filesystem callbacks and a pointer to
@@ -1393,6 +1361,40 @@ bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
const std::string &filepath, void *);
#endif
///
/// LoadImageDataFunction type. Signature for custom image loading callbacks.
///
using LoadImageDataFunction = std::function<bool(
Image * /* image */, const int /* image_idx */, std::string * /* err */,
std::string * /* warn */, int /* req_width */, int /* req_height */,
const unsigned char * /* bytes */, int /* size */, void * /*user_data */)>;
///
/// WriteImageDataFunction type. Signature for custom image writing callbacks.
/// The out_uri parameter becomes the URI written to the gltf and may reference
/// a file or contain a data URI.
///
using WriteImageDataFunction = std::function<bool(
const std::string * /* basepath */, const std::string * /* filename */,
const Image *image, bool /* embedImages */,
const FsCallbacks * /* fs_cb */, const URICallbacks * /* uri_cb */,
std::string * /* out_uri */, void * /* user_pointer */)>;
#ifndef TINYGLTF_NO_STB_IMAGE
// Declaration of default image loader callback
bool LoadImageData(Image *image, const int image_idx, std::string *err,
std::string *warn, int req_width, int req_height,
const unsigned char *bytes, int size, void *);
#endif
#ifndef TINYGLTF_NO_STB_IMAGE_WRITE
// Declaration of default image writer callback
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const FsCallbacks* fs_cb, const URICallbacks *uri_cb,
std::string *out_uri, void *);
#endif
///
/// glTF Parser/Serializer context.
///
@@ -1475,7 +1477,8 @@ class TinyGLTF {
void SetParseStrictness(ParseStrictness strictness);
///
/// Set callback to use for loading image data
/// Set callback to use for loading image data. Passing the nullptr is akin to
/// calling RemoveImageLoader().
///
void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data);
@@ -1490,14 +1493,18 @@ class TinyGLTF {
void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data);
///
/// Set callbacks to use for URI encoding and decoding and their user data
/// Set callbacks to use for URI encoding and decoding and their user data.
/// Returns false if there is an error with the callbacks. If err is not
/// nullptr, explanation will be written there.
///
void SetURICallbacks(URICallbacks callbacks);
bool SetURICallbacks(URICallbacks callbacks, std::string* err = nullptr);
///
/// Set callbacks to use for filesystem (fs) access and their user data
/// Set callbacks to use for filesystem (fs) access and their user data.
/// Returns false if there is an error with the callbacks. If err is not
/// nullptr, explanation will be written there.
///
void SetFsCallbacks(FsCallbacks callbacks);
bool SetFsCallbacks(FsCallbacks callbacks, std::string* err = nullptr);
///
/// Set serializing default values(default = false).
@@ -1535,6 +1542,17 @@ class TinyGLTF {
preserve_image_channels_ = onoff;
}
bool GetPreserveImageChannels() const { return preserve_image_channels_; }
///
/// Specifiy whether image data is decoded/decompressed during load, or left as is
///
void SetImagesAsIs(bool onoff) {
images_as_is_ = onoff;
}
bool GetImagesAsIs() const { return images_as_is_; }
///
/// Set maximum allowed external file size in bytes.
/// Default: 2GB
@@ -1546,8 +1564,6 @@ class TinyGLTF {
size_t GetMaxExternalFileSize() const { return max_external_file_size_; }
bool GetPreserveImageChannels() const { return preserve_image_channels_; }
private:
///
/// Loads glTF asset from string(memory).
@@ -1572,6 +1588,8 @@ class TinyGLTF {
bool preserve_image_channels_ = false; /// Default false(expand channels to
/// RGBA) for backward compatibility.
bool images_as_is_ = false; /// Default false (decode/decompress images)
size_t max_external_file_size_{
size_t((std::numeric_limits<int32_t>::max)())}; // Default 2GB
@@ -1897,6 +1915,9 @@ struct LoadImageDataOption {
// channels) default `false`(channels are expanded to RGBA for backward
// compatibility).
bool preserve_channels{false};
// true: do not decode/decompress image data.
// default `false`: decode/decompress image data.
bool as_is{false};
};
// Equals function for Value, for recursivity
@@ -2571,7 +2592,11 @@ void TinyGLTF::SetParseStrictness(ParseStrictness strictness) {
}
void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) {
LoadImageData = func;
if (func == nullptr) {
RemoveImageLoader();
return;
}
LoadImageData = std::move(func);
load_image_user_data_ = user_data;
user_image_loader_ = true;
}
@@ -2601,48 +2626,65 @@ bool LoadImageData(Image *image, const int image_idx, std::string *err,
int w = 0, h = 0, comp = 0, req_comp = 0;
unsigned char *data = nullptr;
// Try to decode image header
if (!stbi_info_from_memory(bytes, size, &w, &h, &comp)) {
// On failure, if we load images as is, we just warn.
std::string* msgOut = option.as_is ? warn : err;
if (msgOut) {
(*msgOut) +=
"Unknown image format. STB cannot decode image header for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
}
if (!option.as_is) {
// If we decode images, error out.
return false;
} else {
// If we load images as is, we copy the image data,
// set all image properties to invalid, and report success.
image->width = image->height = image->component = -1;
image->bits = image->pixel_type = -1;
image->image.resize(static_cast<size_t>(size));
std::copy(bytes, bytes + size, image->image.begin());
return true;
}
}
int bits = 8;
int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
if (stbi_is_16_bit_from_memory(bytes, size)) {
bits = 16;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
}
// preserve_channels true: Use channels stored in the image file.
// false: force 32-bit textures for common Vulkan compatibility. It appears
// that some GPU drivers do not support 24-bit images for Vulkan
req_comp = option.preserve_channels ? 0 : 4;
int bits = 8;
int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
req_comp = (option.preserve_channels || option.as_is) ? 0 : 4;
// It is possible that the image we want to load is a 16bit per channel image
// We are going to attempt to load it as 16bit per channel, and if it worked,
// set the image data accordingly. We are casting the returned pointer into
// unsigned char, because we are representing "bytes". But we are updating
// the Image metadata to signal that this image uses 2 bytes (16bits) per
// channel:
if (stbi_is_16_bit_from_memory(bytes, size)) {
data = reinterpret_cast<unsigned char *>(
stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
if (data) {
bits = 16;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
unsigned char* data = nullptr;
// Perform image decoding if requested
if (!option.as_is) {
// If the image is marked as 16 bit per channel, attempt to decode it as such first.
// If that fails, we are going to attempt to load it as 8 bit per channel image.
if (bits == 16) {
data = reinterpret_cast<unsigned char *>(stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
}
}
// at this point, if data is still NULL, it means that the image wasn't
// 16bit per channel, we are going to load it as a normal 8bit per channel
// image as we used to do:
// if image cannot be decoded, ignore parsing and keep it by its path
// don't break in this case
// FIXME we should only enter this function if the image is embedded. If
// image->uri references
// an image file, it should be left as it is. Image loading should not be
// mandatory (to support other formats)
if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
if (!data) {
// NOTE: you can use `warn` instead of `err`
if (err) {
(*err) +=
"Unknown image format. STB cannot decode image data for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
// Load as 8 bit per channel data
if (!data) {
data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
if (!data) {
if (err) {
(*err) +=
"Unknown image format. STB cannot decode image data for image[" +
std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
}
return false;
}
// If we were succesful, mark as 8 bit
bits = 8;
pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
}
return false;
}
if ((w < 1) || (h < 1)) {
@@ -2688,16 +2730,26 @@ bool LoadImageData(Image *image, const int image_idx, std::string *err,
image->component = comp;
image->bits = bits;
image->pixel_type = pixel_type;
image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
stbi_image_free(data);
image->as_is = option.as_is;
if (option.as_is) {
// Store the original image data
image->image.resize(static_cast<size_t>(size));
std::copy(bytes, bytes + size, image->image.begin());
}
else {
// Store the decoded image data
image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
}
stbi_image_free(data);
return true;
}
#endif
void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) {
WriteImageData = func;
WriteImageData = std::move(func);
write_image_user_data_ = user_data;
}
@@ -2713,36 +2765,51 @@ static void WriteToMemory_stbi(void *context, void *data, int size) {
bool WriteImageData(const std::string *basepath, const std::string *filename,
const Image *image, bool embedImages,
const URICallbacks *uri_cb, std::string *out_uri,
void *fsPtr) {
const FsCallbacks* fs_cb, const URICallbacks *uri_cb,
std::string *out_uri, void *) {
// Early out on empty images, report the original uri if the image was not written.
if (image->image.empty()) {
*out_uri = *filename;
return true;
}
const std::string ext = GetFilePathExtension(*filename);
// Write image to temporary buffer
std::string header;
std::vector<unsigned char> data;
if (ext == "png") {
if ((image->bits != 8) ||
(image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
// Unsupported pixel format
return false;
}
// If the image data is already encoded, take it as is
if (image->as_is) {
data = image->image;
}
if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 0)) {
return false;
if (ext == "png") {
if (!image->as_is) {
if ((image->bits != 8) ||
(image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
// Unsupported pixel format
return false;
}
if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 0)) {
return false;
}
}
header = "data:image/png;base64,";
} else if (ext == "jpg") {
if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
if (!image->as_is &&
!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0], 100)) {
return false;
}
header = "data:image/jpeg;base64,";
} else if (ext == "bmp") {
if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
if (!image->as_is &&
!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
image->height, image->component,
&image->image[0])) {
return false;
@@ -2763,12 +2830,11 @@ bool WriteImageData(const std::string *basepath, const std::string *filename,
}
} else {
// Write image to disc
FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr);
if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) {
if ((fs_cb != nullptr) && (fs_cb->WriteWholeFile != nullptr)) {
const std::string imagefilepath = JoinPath(*basepath, *filename);
std::string writeError;
if (!fs->WriteWholeFile(&writeError, imagefilepath, data,
fs->user_data)) {
if (!fs_cb->WriteWholeFile(&writeError, imagefilepath, data,
fs_cb->user_data)) {
// Could not write image file to disc; Throw error ?
return false;
}
@@ -2788,14 +2854,36 @@ bool WriteImageData(const std::string *basepath, const std::string *filename,
}
#endif
void TinyGLTF::SetURICallbacks(URICallbacks callbacks) {
assert(callbacks.decode);
if (callbacks.decode) {
uri_cb = callbacks;
bool TinyGLTF::SetURICallbacks(URICallbacks callbacks, std::string* err) {
if (callbacks.decode == nullptr) {
if (err != nullptr) {
*err = "URI Callback require a non-null decode function.";
}
return false;
}
if (callbacks.decode) {
uri_cb = std::move(callbacks);
}
return true;
}
void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; }
bool TinyGLTF::SetFsCallbacks(FsCallbacks callbacks, std::string *err) {
// If callbacks are defined at all, they must all be defined.
if (callbacks.FileExists == nullptr || callbacks.ExpandFilePath == nullptr ||
callbacks.ReadWholeFile == nullptr ||
callbacks.WriteWholeFile == nullptr ||
callbacks.GetFileSizeInBytes == nullptr) {
if (err != nullptr) {
*err =
"FS Callbacks must be completely defined. At least one callback is "
"null.";
}
return false;
}
fs = std::move(callbacks);
return true;
}
#ifdef _WIN32
static inline std::wstring UTF8ToWchar(const std::string &str) {
@@ -3199,8 +3287,9 @@ static std::string MimeToExt(const std::string &mimeType) {
static bool UpdateImageObject(const Image &image, std::string &baseDir,
int index, bool embedImages,
const FsCallbacks *fs_cb,
const URICallbacks *uri_cb,
WriteImageDataFunction *WriteImageData,
const WriteImageDataFunction& WriteImageData,
void *user_data, std::string *out_uri) {
std::string filename;
std::string ext;
@@ -3226,13 +3315,14 @@ static bool UpdateImageObject(const Image &image, std::string &baseDir,
filename = std::to_string(index) + "." + ext;
}
// If callback is set and image data exists, modify image data object. If
// image data does not exist, this is not considered a failure and the
// original uri should be maintained.
// If callback is set, modify image data object.
// Note that the callback is also invoked for images without data.
// The default callback implementation simply returns true for
// empty images and sets the out URI to filename.
bool imageWritten = false;
if (*WriteImageData != nullptr && !filename.empty() && !image.image.empty()) {
imageWritten = (*WriteImageData)(&baseDir, &filename, &image, embedImages,
uri_cb, out_uri, user_data);
if (WriteImageData != nullptr && !filename.empty()) {
imageWritten = WriteImageData(&baseDir, &filename, &image, embedImages,
fs_cb, uri_cb, out_uri, user_data);
if (!imageWritten) {
return false;
}
@@ -4214,7 +4304,7 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
bool store_original_json_for_extras_and_extensions,
const std::string &basedir, const size_t max_file_size,
FsCallbacks *fs, const URICallbacks *uri_cb,
LoadImageDataFunction *LoadImageData = nullptr,
const LoadImageDataFunction& LoadImageData = nullptr,
void *load_image_user_data = nullptr) {
// A glTF image must either reference a bufferView or an image uri
@@ -4304,7 +4394,7 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
}
} else {
// Assume external file
// Keep texture path (for textures that cannot be decoded)
// Unconditionally keep the external URI of the image
image->uri = uri;
#ifdef TINYGLTF_NO_EXTERNAL_IMAGE
return true;
@@ -4345,14 +4435,15 @@ static bool ParseImage(Image *image, const int image_idx, std::string *err,
#endif
}
if (*LoadImageData == nullptr) {
if (LoadImageData == nullptr) {
if (err) {
(*err) += "No LoadImageData callback specified.\n";
}
return false;
}
return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0),
static_cast<int>(img.size()), load_image_user_data);
return LoadImageData(image, image_idx, err, warn, 0, 0, &img.at(0),
static_cast<int>(img.size()), load_image_user_data);
}
static bool ParseTexture(Texture *texture, std::string *err,
@@ -5514,7 +5605,7 @@ static bool ParseAnimation(Animation *animation, std::string *err,
}
sampler.input = inputIndex;
sampler.output = outputIndex;
ParseExtrasAndExtensions(&sampler, err, o,
ParseExtrasAndExtensions(&sampler, err, s,
store_original_json_for_extras_and_extensions);
animation->samplers.emplace_back(std::move(sampler));
@@ -5577,7 +5668,7 @@ static bool ParseSkin(Skin *skin, std::string *err, const detail::json &o,
skin->skeleton = skeleton;
int invBind = -1;
ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin");
ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", false, "Skin");
skin->inverseBindMatrices = invBind;
ParseExtrasAndExtensions(skin, err, o,
@@ -6025,16 +6116,8 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
}
}
model->buffers.clear();
model->bufferViews.clear();
model->accessors.clear();
model->meshes.clear();
model->cameras.clear();
model->nodes.clear();
model->extensionsUsed.clear();
model->extensionsRequired.clear();
model->extensions.clear();
model->defaultScene = -1;
// Reset the model
(*model) = Model();
// 1. Parse Asset
{
@@ -6325,6 +6408,7 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
load_image_user_data = load_image_user_data_;
} else {
load_image_option.preserve_channels = preserve_image_channels_;
load_image_option.as_is = images_as_is_;
load_image_user_data = reinterpret_cast<void *>(&load_image_option);
}
@@ -6341,7 +6425,7 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
if (!ParseImage(&image, idx, err, warn, o,
store_original_json_for_extras_and_extensions_, base_dir,
max_external_file_size_, &fs, &uri_cb,
&this->LoadImageData, load_image_user_data)) {
this->LoadImageData, load_image_user_data)) {
return false;
}
@@ -6370,7 +6454,7 @@ bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
}
const Buffer &buffer = model->buffers[size_t(bufferView.buffer)];
if (*LoadImageData == nullptr) {
if (LoadImageData == nullptr) {
if (err) {
(*err) += "No LoadImageData callback specified.\n";
}
@@ -6750,7 +6834,7 @@ bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err,
// 'SHOULD' in glTF spec means 'RECOMMENDED',
// So there is a situation that Chunk1(BIN) is composed of zero-sized BIN data
// (chunksize(0) + binformat(BIN) = 8bytes).
//
//
if ((header_and_json_size + 8ull) > uint64_t(length)) {
if (err) {
(*err) =
@@ -8513,7 +8597,7 @@ bool TinyGLTF::WriteGltfSceneToStream(const Model *model, std::ostream &stream,
// we
std::string uri;
if (!UpdateImageObject(model->images[i], dummystring, int(i), true,
&uri_cb, &this->WriteImageData,
&fs, &uri_cb, this->WriteImageData,
this->write_image_user_data_, &uri)) {
return false;
}
@@ -8621,7 +8705,7 @@ bool TinyGLTF::WriteGltfSceneToFile(const Model *model,
std::string uri;
if (!UpdateImageObject(model->images[i], baseDir, int(i), embedImages,
&uri_cb, &this->WriteImageData,
&fs, &uri_cb, this->WriteImageData,
this->write_image_user_data_, &uri)) {
return false;
}