利用Python和C++实现解析gltf文件

 更新时间:2023年09月17日 15:43:41   作者:Hunter_pcx  
gltf是类似于stl、obj、ply等常见的3D对象存储格式,它被设计出来是为了便于渲染的数据转换和传输,本文为大家介绍了使用Python和C++解析gltf文件的方法,感兴趣的可以了解下

gltf是类似于stl、obj、ply等常见的3D对象存储格式,它被设计出来是为了便于渲染的数据转换和传输。如果你的浏览器可以连接外网,可以通过 glTF Viewer 网址打开浏览gltf的3D对象。这里介绍两种语言下从gltf拿到网格的顶点和面片数据。

一、Python

第一步安装pygltflib:

pip install pygltflib

第二步,python解析:

import pygltflib
import numpy as np
pathGltf="test.gltf"
gltf=pygltflib.GLTF2().load(pathGltf)
scene=gltf.scenes[gltf.scene]
nodes=[gltf.nodes[node] for node in scenes.nodes]
vertices=np.arry([node.mesh.primitives[0].attributes["POSITION"] for node in nodes])
print(vertices)

不知道为什么,通过上面这种方式解析,node.mesh我这里是一个int类型的值,运行代码提示node.mesh没有primitives属性,然后在网上找了下面的代码是ok的:

import pygltflib
import pathlib
import struct
# load a gltf file
fname = pathlib.Path("C:/Users/User/Desktop/cube.gltf")
gltf = GLTF2().load(fname)
# get the first mesh in the current scene
mesh = gltf.meshes[gltf.scenes[gltf.scene].nodes[0]-1]
# get the vertices for each primitive in the mesh
for primitive in mesh.primitives:
    # get the binary data for this mesh primitive from the buffer
    accessor = gltf.accessors[primitive.attributes.POSITION]
    bufferView = gltf.bufferViews[accessor.bufferView]
    buffer = gltf.buffers[bufferView.buffer]
    data = gltf.get_data_from_buffer_uri(buffer.uri)
    # pull each vertex from the binary buffer and convert it into a tuple of python floats
    vertices = []
    for i in range(accessor.count):
        index = bufferView.byteOffset + accessor.byteOffset + i*12  # the location in the buffer of this vertex
        d = data[index:index+12]  # the vertex data
        v = struct.unpack("<fff", d)   # convert from base64 to three floats
        vertices.append(v)
# unpack floats
vertices2 = []
for a,b,c in vertices:
    vertices2 += [a,b,c]
# create triangles
vertices = vertices2
triangles = []
for i in range(0,len(vertices),9):
    triangles.append(vertices[i:i+9])
# print data
print(triangles)

二、C++解析

c++依赖的库主要是draco,这个库是开源的,网上可以下载,有了draco之后代码如下:

#include<draco/io/gltf_decoder.h>
#include<draco/tools/draco_transcoder_lib.h>
// 读取gltf文件
bool parse_gltf_from_file(const std::string& filename,std::unique_ptr<draco::Mesh>& mesh){
    draco::GltfDecoder gltfDec;
    draco::StatusOr<std::unique_ptr<draco::Mesh>> stormesh=gltfDec.DecodeFromFile(filename);
    if(!stormesh.ok()){
        return false;
    }
    std::unique_ptr<draco::Mesh> pDracomesh=std::move(stormesh).value();
    std::cout<<"faces num:"<<pDracomesh->num_faces()<<std::endl;
    pDracomesh.swap(mesh);
    return true;
}
//解析出顶点和面片数据
bool get_faces_vertexes(const std::unique_ptr<draco::Mesh>& dracomesh,
                        std::vector<Eigen::Vector3>& vertexes,
                        std::vector<Eigen::Vector3i>& faces){
    auto dump_attribute_to_vec3=[](const draco::PointAttribute& att,std::vector<Eigen::Vector3>& attD){
        if(att.size()==0) return;
        std::vector<Eigen::Vector3> tmp(att.size());
        for(int i=0;i<att.size();++i){
            if(!att.ConvertValue<float,3>(draco::AttributeValueIndex(i),&tmp[i][0])) return;
        }
        attD=std::move(tmp);
    }
    // 解析顶点
    const draco::PointAttribute* posAtt=nullptr;
    std::vector<Eigen::Vector3> points;
    for(int i=0;i<dracomesh->num_attributes();++i){
        const draco::PointAttribute* pAtt=dracomesh->attribute(i);
        switch(pAtt->attribute_type()){
            case draco::PointAttribute::POSITION:
                posAtt=pAtt;
                dump_attribute_to_vec3(*pAtt,points);
                break;
        }
    }
    vertexes=points;
    // 解析面片
    faces.resize(dracomesh->num_faces());
    for(int i=0;i<dracomesh->num_faces();++i){
        for(int j=0;j<3;++j){
            const draco::PointIndex idx=dracomesh->face(draco::FaceIndex(i))[j];
            faces[i][j]=posAtt->mapped_index(idx).value();
        }
    } 
    return true;
}

以上就是利用Python和C++实现解析gltf文件的详细内容,更多关于Python解析gltf文件的资料请关注脚本之家其它相关文章!

相关文章

  • python使用itchat实现手机控制电脑

    python使用itchat实现手机控制电脑

    这篇文章主要为大家详细介绍了python使用itchat实现手机控制电脑,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • python flask web服务实现更换默认端口和IP的方法

    python flask web服务实现更换默认端口和IP的方法

    今天小编就为大家分享一篇python flask web服务实现更换默认端口和IP的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Python基础知识点 初识Python.md

    Python基础知识点 初识Python.md

    在本篇文章中我们给大家总结了关于Python基础知识点,通过初识Python.md的相关内容分享给Python初学者,一起来看下吧。
    2019-05-05
  • Django实现列表页商品数据返回教程

    Django实现列表页商品数据返回教程

    这篇文章主要介绍了Django实现列表页商品数据返回教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • 如何使用pdb进行Python调试

    如何使用pdb进行Python调试

    本篇教程中,我们主要讲解了pdb中一些基本常用的内容,包括打印表达式使用n(next)和s(step)命令调试代码断点使用unt(until)来继续执行代码显示表达式查找一个函数的调用者,对pdb Python调试相关知识感兴趣的朋友跟随小编一起看看吧
    2021-06-06
  • 基于PyQt5完成的PDF拆分功能

    基于PyQt5完成的PDF拆分功能

    这篇文章主要介绍了基于PyQt5完成的PDF拆分功能,本文介绍的pdf拆分功能还有一些待完善地方,例如可增加预览功能,实现每页预览,以及如何实现多条件拆分,需要的朋友可以参考下
    2022-06-06
  • Python 制作糗事百科爬虫实例

    Python 制作糗事百科爬虫实例

    本文是结合前面的三篇关于python制作爬虫的基础文章,给大家分享的一份爬取糗事百科的小段子的源码,有需要的小伙伴可以参考下
    2016-09-09
  • 10分钟教你用python动画演示深度优先算法搜寻逃出迷宫的路径

    10分钟教你用python动画演示深度优先算法搜寻逃出迷宫的路径

    这篇文章主要介绍了10分钟教你用python动画演示深度优先算法搜寻逃出迷宫的路径,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • 给Python的Django框架下搭建的BLOG添加RSS功能的教程

    给Python的Django框架下搭建的BLOG添加RSS功能的教程

    这篇文章主要介绍了给Python的Django框架下搭建的BLOG添加RSS功能的教程,示例代码非常简单,需要的朋友可以参考下
    2015-04-04
  • Python中按钮(BUTTON)样式属性及说明

    Python中按钮(BUTTON)样式属性及说明

    文章介绍了Python中tkinter库中的Button组件,用于在GUI中添加按钮,按钮可以包含文本或图像,并且可以通过点击执行特定函数,文章详细说明了Button组件的构造语法和常用参数,并提供了一个代码示例
    2025-01-01

最新评论