Skip to content

Accessing vertex data

Syoyo Fujita edited this page May 30, 2018 · 2 revisions

Thanks to @CheezBoiger

You can access vertex data from accessor and bufferViews in the following way.

The specs literally tell you how to access contents within a buffer, with the exception of it not telling you that 'count' is the number of values, that define some data type, of which the buffer view refers to within the buffer. Accessing vertex data from a gltf file you do as so:

const tinygltf::Model& model;
// Assuming you loaded the gltf model.
 ...
for each primitive in a mesh...
const tinygltf::Accessor& accessor = model.accessors[primitive.attributes["POSITION"]];
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];

finally, to obtain and read out each vertex position:

// cast to float type read only. Use accessor and bufview byte offsets to determine where position data 
// is located in the buffer.
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
// bufferView byteoffset + accessor byteoffset tells you where the actual position data is within the buffer. From there
// you should already know how the data needs to be interpreted.
const float* positions = reinterpret_cast<const float*>(&buffer.data[bufferView.byteOffset + accessor.byteOffset]);
// From here, you choose what you wish to do with this position data. In this case, we  will display it out.
for (size_t i = 0; i < accessor.count; ++i) {
          // Positions are Vec3 components, so for each vec3 stride, offset for x, y, and z.
           std::cout << "(" << positions[i * 3 + 0] << ", "// x
                            << positions[i * 3 + 1] << ", " // y
                            << positions[i * 3 + 2] << ")" // z
                            << "\n";
}
proceed to next primitive...

You can also incorporate this for indices, normals, texcoords, joints, weights, etc (because the component and data types are also in the specs) of a given primitive as well. Keep in mind that even though position should always be available for primitives, other attributes may not be available.

Clone this wiki locally