Code Monkey home page Code Monkey logo

tinygltf's Introduction

Header only C++ tiny glTF library(loader/saver).

TinyGLTF is a header only C++11 glTF 2.0 https://github.com/KhronosGroup/glTF library.

TinyGLTF uses Niels Lohmann's json library (https://github.com/nlohmann/json), so now it requires C++11 compiler. (Also, you can use RadpidJSON as an JSON backend) If you are looking for old, C++03 version, please use devel-picojson branch (but not maintained anymore).

Status

Currently TinyGLTF is stable and maintenance mode. No drastic changes and feature additions planned.

  • 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).
  • v2.5.0 Add SetPreserveImageChannels() option to load image data as is.
  • v2.4.0 Experimental RapidJSON support. Experimental C++14 support(C++14 may give better performance)
  • v2.3.0 Modified Material representation according to glTF 2.0 schema(and introduced TextureInfo class)
  • v2.2.0 release(Support loading 16bit PNG. Sparse accessor support)
  • v2.1.0 release(Draco decoding support)
  • v2.0.0 release(22 Aug, 2018)!

Branches

  • sajson : Use sajson to parse JSON. Parsing only but faster compile time(2x reduction compared to json.hpp and RapidJson), but not well maintained.

Builds

Build status

C/C++ CI

Features

Probably mostly feature-complete. Last missing feature is Draco encoding: #207

  • Written in portable C++. C++-11 with STL dependency only.
    • macOS + clang(LLVM)
    • iOS + clang
    • Linux + gcc/clang
    • Windows + MinGW
    • Windows + Visual Studio 2015 Update 3 or later.
      • Visual Studio 2013 is not supported since they have limited C++11 support and failed to compile json.hpp.
    • Android NDK
    • Android + CrystaX(NDK drop-in replacement) GCC
    • Web using Emscripten(LLVM)
  • Moderate parsing time and memory consumption.
  • glTF specification v2.0.0
    • ASCII glTF
      • Load
      • Save
    • Binary glTF(GLB)
      • Load
      • Save(.bin embedded .glb)
  • Buffers
    • Parse BASE64 encoded embedded buffer data(DataURI).
    • Load .bin file.
  • Image(Using stb_image)
    • Parse BASE64 encoded embedded image data(DataURI).
    • Load external image file.
    • Load PNG(8bit and 16bit)
    • Load JPEG(8bit only)
    • Load BMP
    • Load GIF
    • Custom Image decoder callback(e.g. for decoding OpenEXR image)
  • Morph traget
    • Sparse accessor
  • Load glTF from memory
  • Custom callback handler
    • Image load
    • Image save
  • Extensions
    • Draco mesh decoding
    • Draco mesh encoding

Note on extension property

In extension(ExtensionMap), JSON number value is parsed as int or float(number) and stored as tinygltf::Value object. If you want a floating point value from tinygltf::Value, use GetNumberAsDouble() method.

IsNumber() returns true if the underlying value is an int value or a floating point value.

Examples

  • glview : Simple glTF geometry viewer.
  • validator : Simple glTF validator with JSON schema.
  • basic : Basic glTF viewer with texturing support.
  • build-gltf : Build simple glTF scene from a scratch.

WASI/WASM build

Users who want to run TinyGLTF securely and safely(e.g. need to handle malcious glTF file to serve online glTF conver), I recommend to build TinyGLTF for WASM target. WASI build example is located in wasm .

Projects using TinyGLTF

  • px_render Single header C++ Libraries for Thread Scheduling, Rendering, and so on... https://github.com/pplux/px
  • Physical based rendering with Vulkan using glTF 2.0 models https://github.com/SaschaWillems/Vulkan-glTF-PBR
  • GLTF loader plugin for OGRE 2.1. Support for PBR materials via HLMS/PBS https://github.com/Ybalrid/Ogre_glTF
  • TinyGltfImporter plugin for Magnum, a lightweight and modular C++11/C++14 graphics middleware for games and data visualization.
  • Diligent Engine - A modern cross-platform low-level graphics library and rendering framework
  • Lighthouse 2: a rendering framework for real-time ray tracing / path tracing experiments. https://github.com/jbikker/lighthouse2
  • QuickLook GLTF - quicklook plugin for macos. Also SceneKit wrapper for tinygltf.
  • GlslViewer - live GLSL coding for MacOS and Linux
  • Vulkan-Samples - The Vulkan Samples is collection of resources to help you develop optimized Vulkan applications.
  • TDME2 - TDME2 - ThreeDeeMiniEngine2 is a lightweight 3D engine including tools suited for 3D game development using C++11
  • SanityEngine - A C++/D3D12 renderer focused on the personal and professional development of its developer
  • Open3D - A Modern Library for 3D Data Processing
  • Supernova Engine - Game engine for 2D and 3D projects with Lua or C++ in data oriented design.
  • Wicked Engine - 3D engine with modern graphics
  • Your projects here! (Please send PR)

TODOs

  • Robust URI decoding/encoding. #369
  • Mesh Compression/decompression(Open3DGC, etc)
    • Load Draco compressed mesh
    • Save Draco compressed mesh
    • Open3DGC?
  • Support extensions and extras property
  • HDR image?
    • OpenEXR extension through TinyEXR.
  • 16bit PNG support in Serialization
  • Write example and tests for animation and skin

Optional

  • Write C++ code generator which emits C++ code from JSON schema for robust parsing?

Licenses

TinyGLTF is licensed under MIT license.

TinyGLTF uses the following third party libraries.

  • json.hpp : Copyright (c) 2013-2017 Niels Lohmann. MIT license.
  • base64 : Copyright (C) 2004-2008 René Nyffenegger
  • stb_image.h : v2.08 - public domain image loader - Github link
  • stb_image_write.h : v1.09 - public domain image writer - Github link

Build and example

Copy stb_image.h, stb_image_write.h, json.hpp and tiny_gltf.h to your project.

Loading glTF 2.0 model

// Define these only in *one* .cc file.
#define TINYGLTF_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
// #define TINYGLTF_NOEXCEPTION // optional. disable exception handling.
#include "tiny_gltf.h"

using namespace tinygltf;

Model model;
TinyGLTF loader;
std::string err;
std::string warn;

bool ret = loader.LoadASCIIFromFile(&model, &err, &warn, argv[1]);
//bool ret = loader.LoadBinaryFromFile(&model, &err, &warn, argv[1]); // for binary glTF(.glb)

if (!warn.empty()) {
  printf("Warn: %s\n", warn.c_str());
}

if (!err.empty()) {
  printf("Err: %s\n", err.c_str());
}

if (!ret) {
  printf("Failed to parse glTF\n");
  return -1;
}

Loader options

  • TinyGLTF::SetPreserveimageChannels(bool onoff). true to preserve image channels as stored in image file for loaded image. false by default for backward compatibility(image channels are widen to RGBA 4 channels). Effective only when using builtin image loader(STB image loader).

Compile options

  • TINYGLTF_NOEXCEPTION : Disable C++ exception in JSON parsing. You can use -fno-exceptions or by defining the symbol JSON_NOEXCEPTION and TINYGLTF_NOEXCEPTION to fully remove C++ exception codes when compiling TinyGLTF.
  • TINYGLTF_NO_STB_IMAGE : Do not load images with stb_image. Instead use TinyGLTF::SetImageLoader(LoadimageDataFunction LoadImageData, void *user_data) to set a callback for loading images.
  • TINYGLTF_NO_STB_IMAGE_WRITE : Do not write images with stb_image_write. Instead use TinyGLTF::SetImageWriter(WriteimageDataFunction WriteImageData, void *user_data) to set a callback for writing images.
  • TINYGLTF_NO_EXTERNAL_IMAGE : Do not try to load external image file. This option would be helpful if you do not want to load image files during glTF parsing.
  • TINYGLTF_ANDROID_LOAD_FROM_ASSETS: Load all files from packaged app assets instead of the regular file system. Note: You must pass a valid asset manager from your android app to tinygltf::asset_manager beforehand.
  • TINYGLTF_ENABLE_DRACO: Enable Draco compression. User must provide include path and link correspnding libraries in your project file.
  • TINYGLTF_NO_INCLUDE_JSON : Disable including json.hpp from within tiny_gltf.h because it has been already included before or you want to include it using custom path before including tiny_gltf.h.
  • TINYGLTF_NO_INCLUDE_RAPIDJSON : Disable including RapidJson's header files from within tiny_gltf.h because it has been already included before or you want to include it using custom path before including tiny_gltf.h.
  • TINYGLTF_NO_INCLUDE_STB_IMAGE : Disable including stb_image.h from within tiny_gltf.h because it has been already included before or you want to include it using custom path before including tiny_gltf.h.
  • TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE : Disable including stb_image_write.h from within tiny_gltf.h because it has been already included before or you want to include it using custom path before including tiny_gltf.h.
  • TINYGLTF_USE_RAPIDJSON : Use RapidJSON as a JSON parser/serializer. RapidJSON files are not included in TinyGLTF repo. Please set an include path to RapidJSON if you enable this feature.
  • TINYGLTF_USE_CPP14 : Use C++14 feature(requires C++14 compiler). This may give better performance than C++11.

CMake options

You can add tinygltf using add_subdirectory feature. If you add tinygltf to your project using add_subdirectory, it would be better to set TINYGLTF_HEADER_ONLY on(just add an include path to tinygltf) and TINYGLTF_INSTALL off(Which does not install tinygltf files).

// Your project's CMakeLists.txt
...

set(TINYGLTF_HEADER_ONLY ON CACHE INTERNAL "" FORCE)
set(TINYGLTF_INSTALL OFF CACHE INTERNAL "" FORCE)
add_subdirectory(/path/to/tinygltf)

Saving gltTF 2.0 model

  • Buffers.
    • To file
    • Embedded
    • Draco compressed?
  • Images
    • To file
    • Embedded
  • Binary(.glb)
    • .bin embedded single .glb
    • External .bin

Running tests.

glTF parsing test

Setup

Python required. Git clone https://github.com/KhronosGroup/glTF-Sample-Models to your local dir.

Run parsing test

After building loader_example, edit test_runner.py, then,

$ python test_runner.py

Unit tests

$ cd tests
$ make
$ ./tester
$ ./tester_noexcept

Fuzzing tests

See tests/fuzzer for details.

After running fuzzer on Ryzen9 3950X a week, at least LoadASCIIFromString looks safe except for out-of-memory error in Fuzzer. We may be better to introduce bounded memory size checking when parsing glTF data.

Third party licenses

tinygltf's People

Contributors

abwood avatar adamfull avatar agnat avatar alvarobarua avatar aurl avatar bowald avatar daemyung avatar davidsm64 avatar epajarre avatar geometrian avatar harokyang avatar holzon avatar jrkoonce avatar kacprzak avatar kh4n avatar kroko avatar lukesanantonio avatar mosra avatar nbickford-nv avatar nyalldawson avatar pknowlesnv avatar ptc-tgamper avatar rhiskey avatar selmar avatar snowapril avatar squareys avatar srirachasource avatar syoyo avatar viperscape avatar ybalrid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinygltf's Issues

add Image bufferview to json, if no uri

static void SerializeGltfImage(Image &image, json &o)
{
if (!image.mimeType.empty())
{
// (required if no uri)
// (required if no uri) ["image/jpeg", "image/png",
// "image/bmp", "image/gif"]
SerializeStringProperty("mimeType", image.mimeType, o);
SerializeNumberProperty("bufferview", image.bufferView, o);
}
else if (!image.uri.empty())
{
SerializeStringProperty("uri", image.uri, o);
}

Windows compile error

By default there will be a compile error in most Visual Studio projects due to a Windows macro for min and max. You can fix this by replacing this line in picojson.h:
if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival && ival <= std::numeric_limits<int64_t>::max() &&
With this:
if (errno == 0 && (std::numeric_limits<int64_t>::min)() <= ival && ival <= (std::numeric_limits<int64_t>::max)() &&

TODO: Implement serializer

Implement glTF 2.0 serializer(saver)

@AurL, I have refactored devel branch and now devel branch will be ready to accept serializer PR from you. Could you please send your serializer PR to devel branch?

#include <Windows.h> should be #include <windows.h>

Hey there! Really cool library! Been using it to great success in the last few days. C:

But I was just about to cross-compile a Windows build for someone using MinGW on a Linux box when I got an error about Windows.h not being found in tiny_gltf.h. Looking online, I saw people using lowercase windows.h rather than uppercase Windows.h, so I tried making the change, and the compilation was successful.

Probably the compiler on Windows is case-insensitive and so it works either way, but it has to be lowercase on MinGW on Linux at least. Too quick a fix for me to do the whole pull request routine for, since it's just a matter of one letter in one file, but it's on line 683. c;

Fixed it myself for myself, but might as well fix it for others in the future. Thanks!

Retrieve material texture index values

Given the example below, I'm not sure how to get the Index values of both the normal and base textures. Is there an example showing this?

    "materials" : [
        {
            "name" : "Material",
            "normalTexture" : {
                "index" : 1
            },
            "pbrMetallicRoughness" : {
                "baseColorFactor" : [
                    0.800000011920929,
                    0.800000011920929,
                    0.800000011920929,
                    1.0
                ],
                "baseColorTexture" : {
                    "index" : 0
                },
                "metallicFactor" : 0.0
            }
        }
    ],

[feature] Support HDR texture

Support HDR image format for the texture as an extension.

  • 16bit PNG
  • Radiance RGBE
  • EXR(through TinyEXR)
  • DNG/TIFF(through tinydngloader)
  • BC6H
  • HDR format from KTX/KTX2?

Empty Value objects & extensions

Hi,

I have some problems with value objects. This is only really a concern when it comes to extensions, because just the definition of an extension may change behaviour, even if the object is empty (e.g. all parameters are default values).

Right now, when reading the gltf file, any empty objects are completely ignored, which results in their type being TYPE_NULL.

The same goes for writing. When writing a Value::Object, if the object is empty, it is not written to the output.

This makes a lot of sense for normal gltf objects, however for extensions this poses a problem. Extensions can (and often will) modify the default behaviour if they are present, even if they do not define any of their properties (e.g. their properties are all default values).

The spec defines the extensions object like this: Dictionary object with extension-specific objects. Strictly speaking, this means all values contained by the extensions object should be objects themselves.

I suggest we modify the ParseExtensionsProperty and SerializeExtensionMap to always serialize the top-level values in the extensions object as objects.

This means we will be able to read and subsequently write this, which is currently not possible:

"materials": [
    {
        "name": "WHITE",
        "extensions": {
            "VENDOR_material_some_ext": {
            }
        }
    },

memory leak using LoadASCIIFromString

loading a simple cube GLTF with embedded mesh data (no additional files) leaks 2 allocations. works fine with GLB equivalent.

i detected this using a custom memory allocator which asserts if every alloc isnt freed on exit.

tested with vs2015

devel & master Branches way out of sync?

I just noticed this when looking at the branch tree, master was recently (June 4th) modified with some fixes, but it was last changed a very long time before that. Was this a mistake?

Make overriding FileExists, LoadExternalFile, ExpandFilePath, ... possible

tinygltf currently assumes that external files physically reside on the host's filesystem. In many game engines and similiar programs, however, files are packed in virtual "container" files and/or managed by libraries such as PhysicsFS that do not directly access the physical filesystem.

A simple way to solve this issue would be making the prototypes ofFileExists, LoadExternalFile, ExpandFilePath and any other file I/O functions be visible to the user and letting their default implementations be disabled by #define TINYGLTF_NO_FS_IMPLEMENTATION.

I could try implementing this functionality and pushing it to the repo if you would like.

Current index of array elements

Unless there is a better parsing method idk about, it seems very useful to have the ability to self-identify which index an item is. For example, if I pass in a tinygltf::Node to a function I am finding myself also passing its index as a 2nd parameter. I also will pass in the top tinygltf::Model but then I need to transverse the entire list of Nodes to check if its the same if I am trying to match an animation sampler up to it.

Not sure if this is outside scope of tinygltf, but seems like the simplest fix for an issue I keep reincurring.

Generic extension support

Hi,

Currently, if I want to develop and use a custom extension, I would have to add parsing of this extension to the code.

Instead, would it not be more convenient to put every ParameterMap inside... well.. another map, indexing by string?

Something like this:

typedef std::map<std::string, ParameterMap> ExtensionMap;

ParseExtensions(...)

struct Material {
  ...
  ExtensionMap extensions;
  ...
}

... {
  if (it.key() == "extensions")
  {
    ExtensionMap extensions;
    if(ParseExtensions(...)) {
      material->extensions = extensions;
    }
  }
}

More simple example?

I cannot figure out how to use this to draw models. Is it possible to have a more simple example, I'm finding the glview example is difficult to follow.
As an example I have so far a basic work in progress https://gist.github.com/viperscape/989cf91ecbd42a2dd89780e30a166c0a
I think my drawMesh is to blame: https://gist.github.com/viperscape/989cf91ecbd42a2dd89780e30a166c0a#file-main-cpp-L88

I was able to render a triangle of vertex points using the same shader and model-view functions. So I must be missing something inherent with how gltf works and how the example was laid out.

Any help is appreciated! If this is too off-topic for an issue, feel free to close

logic error

i think there is logic error in line 1709?
// Write image to disc
FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr);
if (fs != nullptr && fs->WriteWholeFile == nullptr) {
......

Reading GLTF data from model

Somewhere here should be a code which translates data from model to meshes/materials/textures

right now it returns true but actually there is nothing in the output buffers.
After that it crashed inside nanort when it calculates BoundingBox with 0 elements inside mesh(This looks like a separate issue).

How

Translate Model to output buffers or log message about TODO.

Option to store raw(encoded) pixels to Image

It would be nice to add an option not decoding pixels(e.g. jpg/png) during glTF parsing for example faster glTF parsing.

For that purpose, easiest way is add an option something raw or undecoded flag to Image.

Missing iOS header

Hello again! I have another quick fix to suggest after another cross-compiling adventure. c:

I got errors compiling to iOS because the checks for TARGET_OS_IPHONE failed and the library ended up trying to do things it was not meant to try to do on iOS; this is because you forgot to do this in order to include the definition (which in my experience is not meant to be set by the IDE for an iOS project but by including this file):

#if __APPLE__
    #include "TargetConditionals.h"
#endif

I added it right before namespace gltf but feel free to put it where you think makes sense and that should fix it. c:

bufferView byteStride is read into the byteLength field

Offending line of code: ParseNumberProperty(&byteLength, err, o, "byteStride", false);

Since many glTF files exclude this property, many files will load fine. One example asset I found which will cause this issue is "GearboxAssy.glb" from glTF-Sample-Models.

Validations on glTF Models

I used tinygltf in a project, and one thing I think most will need are sanity checks done on the loaded tinyglt::Model object, beyond the basics already provided. A few things which would be useful:

  1. Verify that a buffer view does not exceed the bounds of the buffer that it references. Similarly, that an accessor does not exceed the buffer view bounds, if it references a buffer view.
  2. Check for illegal loops in the node hierarchy ("no node may be a direct or indirect descendant of more than one node").
  3. Check the various index references into other sections of the glTF document are not out of range (e.g. if there are 10 nodes and a scene references node 11, that is wrong).
    I mention these because they could protect against potentially malicious models. Of course glTF a complex format and the number of validations could go into the hundreds I'm sure.

Now this project is self-described as "tiny" so one question I have is where does this functionality belong? Possible locations:

  1. Built into TinyGLTFLoader class.
  2. Same header, separate class.
  3. Separate header file.
  4. Completely separate project.

To me option three feels right by keeping the functionality completely optional but readily available. I'd be interested in getting the ball rolling on this. Thoughts?

compile error

I tried to load a model with your example but the visual gave me this compile errors for TinyGLTF class declaration:

everity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "bool __cdecl tinygltf::LoadImageData(struct tinygltf::Image *,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > *,int,int,unsigned char const *,int,void *)" (?LoadImageData@tinygltf@@YA_NPAUImage@1@PAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HHPBEHPAX@Z) referenced in function "public: __thiscall tinygltf::TinyGLTF::TinyGLTF(void)" (??0TinyGLTF@tinygltf@@QAE@XZ)

and

Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "bool __cdecl tinygltf::WriteImageData(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const *,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const *,struct tinygltf::Image *,bool,void *)" (?WriteImageData@tinygltf@@YA_NPBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0PAUImage@1@_NPAX@Z) referenced in function "public: __thiscall tinygltf::TinyGLTF::TinyGLTF(void)" (??0TinyGLTF@tinygltf@@QAE@XZ)

I am using MSV 2015

What to do with bufferView.byteStride when it is unspecified.

Hi,

I bumped into a small problem while implementing the loading of glTF assets into a project via this library.

When the byteStride of a buffer view is not defined inside the glTF file, the glTF standard states that this means "the data is tightly packed".

The current way tinygltf handle this is by putting the byteStride member of the bufferView object to zero.

I think a saner thing to do as a loading library, would be to actually put there the value it should have when reading the buffer as just a plain array of the underlying datatype.

This permit the library user to just iterate through the data with the same code, with no regards into checking if the byteStride is 0, and thus making this kind of code work all the time.

In that case, making byteStride be sizeof(component_type) * countOfElementsInType Where countOfElementsInType is equal to the number of variable you need to get one element in the array (e.g. for a buffer of FLOAT that represent a VEC3, be equal to sizeof(float) * 3)

for(size_t i = 0; i < bufferLenghtInElements; ++i)
{
    //Access the data of each element of the buffer
    buffer.data[(bufferView.byteOffset + accessor.byteOffset) + i * bufferView.byteStride]
}

Strictly speaking, this is okay according to the representation of the file we do here in C++ in regards to the data that was in the JSON file, and how the specification say we should interpret it.

Here's where the standard defines what not setting the byteStride means : https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment

What do you think about this ?

Thanks again for the awesome work on this "tiny" library ;-)

String tags in original gltf outputs as empty string ""

I'm trying to integrate tinygltf in my framework. A simple way to manage all the resources loaded is storing them in a map container using strings. On any string tag like material name, mesh name, texture name etc i am always getting empty string "".

getting vertex buffer from Mesh

Hi,
I'm trying to bind tinygltf to my graphics engine but there something I either don't understand or isn't supported.
According to this spec:
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0
I should be able to get the vertex buffer from the Mesh. I was expecting to do something like:
model->accessors[mesh.primitives[i].BufferViewIndex]
and then getting the buffer to call glBufferStorage/glBufferData but the Primitive only contain "indices" and "material".

I cannot just loop through all model_->bufferViews because I need to know which bufferView is owned to which mesh.

Inputs to loader_example that cause assert/abort behavior

Hi,

I used afl-fuzz (American Fuzzy Lop) to fuzz test input to the loader_example program. It triggered assertions (abort behavior, I believe to be intentional) but no major issues were found. I wanted to let you know in case these are worth your time to fix. If not, then please close this issue at your leasire.

Input files and a few example stack traces can be found here: https://github.com/rwhitworth/tinygltf-fuzz/tree/master/2017-07-31

Loading a GLB file without BIN data fails

Forwarding from a colleague.

In addition to not passing the header size check, accessors, bufferviews and buffers are still flagged as required in the loading process, but in fact are not present in this scenario and should be skipped.

The GLB file format specification specifies that the Bin header & data of a GLB file are not mandatory (it says the number of BIN headers can be 0 or 1). However, if I try to load a GLB from memory with no Bin buffer, the loader fails.
This is due to the “LoadBinaryFromMemory” methods that checks the size of the binary data. In case the Bin buffer is not present, the size is exactly 20 + size of JSON contents. The test is done with a greater or equal operator, and so it passes and returns false.
The suggested fix is to change this operator to a “greater than” operator.

That is:

if ((20 + model_length >= size) || (model_length < 1) ||
    (model_format != 0x4E4F534A)) {  // 0x4E4F534A = JSON format.
    if (err) {
      (*err) = "Invalid glTF binary.";
    }
    return false;
  }

Would become:

  if ((20 + model_length > size) || (model_length < 1) || // specification allows a GLB file with no bin buffer
      (model_format != 0x4E4F534A)) {  // 0x4E4F534A = JSON format.
    if (err) {
      (*err) = "Invalid glTF binary.";
    }
    return false;
  }

Buffer.uri not set after loading buffer

This seems inconsistent with loading images. In addition, we actually need the uri for caching purposes.

Is there a specific reason for this, or can we perhaps save it? : )

Validation for serialization

Hi,

I'm wondering if there is currently any way to validate that serialization is working correctly? The project I'm working on has many and rather large models, so any mismatch is a potentially large time-waster. There have been a few errors before (as I've seen and submitted pull requests to fix them), so this could help in both catching mistakes and testing new implementations.

E.g. I would like to compare model data using the equals == operator. If it is a wanted feature, I could make a pull request.

Alternatively, I imagine the json parser implements the equals operator, so perhaps we could refactor to make use of that?

Any ideas and concerns are welcome.

Premake 5 warnings on Windows build

Hi,
The "glview" project runs fine on Windows, but I noticed that there were some errors when building using the "premake4.lua" script with Premake 5. I've changed some of the flags based on the following logs:

Build logs

This version of "premake5.lua" generates a project without errors, which might be useful to copy:

solution "glview"
   -- location ( "build" )
   configurations { "Debug", "Release" }
   platforms {"native", "x64", "x32"}
   
   project "glview"

      kind "ConsoleApp"
      language "C++"
	  cppdialect "C++11"
      files { "glview.cc", "trackball.cc" }
      includedirs { "./" }
      includedirs { "../../" }

      configuration { "linux" }
         linkoptions { "`pkg-config --libs glfw3`" }
         links { "GL", "GLU", "m", "GLEW", "X11", "Xrandr", "Xinerama", "Xi", "Xxf86vm", "Xcursor", "dl" }

      configuration { "windows" }
         -- Edit path to glew and GLFW3 fit to your environment.
         includedirs { "../../../../local/glew-1.13.0/include/" }
         includedirs { "../../../../local/glfw-3.2.bin.WIN32/include/" }
         libdirs { "../../../../local/glew-1.13.0/lib/Release/Win32/" }
         libdirs { "../../../../local/glfw-3.2.bin.WIN32/lib-vc2013/" }
         links { "glfw3", "gdi32", "winmm", "user32", "glew32", "glu32","opengl32", "kernel32" }
         defines { "_CRT_SECURE_NO_WARNINGS" }

      configuration { "macosx" }
         includedirs { "/usr/local/include" }
         buildoptions { "-Wno-deprecated-declarations" }
         libdirs { "/usr/local/lib" }
         links { "glfw3", "GLEW" }
         linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" }

      configuration "Debug"
         defines { "DEBUG" }
		 symbols "On"
		 warnings "Extra"

      configuration "Release"
         defines { "NDEBUG" }
		 optimize "On"
		 warnings "Extra"

Data URI buffers in binary files not read

ran into this likely rare case, where a data uri was used for a buffer inside of a glb file. the parser skipped over it.

suggested change, inside of ParseBuffer right after the !uri.empty() check,
make sure to try to parse a datauri first,
see below.
snip---------------------------------------
if (is_binary) {
// Still binary glTF accepts external dataURI. First try external resources.

if (!uri.empty()) {
    if (IsDataURI(uri)) {   // <--- Here
        if (!DecodeDataURI(&buffer->data, uri, bytes, true)) {
            if (err) {
                (*err) += "Failed to decode 'uri' : " + uri + " in Buffer\n";
            }
            return false;
        }
    }
    else {
        // Assume external .bin file.
        LoadExternalFile(&buffer->data, err, uri, basedir, bytes, true);
    }		
} else {
  // load data from (embedded) binary data

snip--------------------------------------------

Impossible to get camera information ?

As far As I understand the tiny_gltf I should use the camera index Node::camera and use it to find the good camera in corresponding std::vector in tinygltf::Model.

The problem is there is no std::vector in Model, grep -i "Camera" only give me the class definition of Camera and there is no reference to camera loading in the examples that I could find.

On my engine I will assume that the camera position/rotation is the node position/rotation but I can't get more information from the node (fov, aspect ratio, zfar/znear etc...)

Did I missed something or it isn't implemented ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.