热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用gltfsdk创建多个gltf的mesh

gltf的sdk地址这份代码的原始例子比较不好参考,创建一个三角形还比较好参考,创建多个三角形或者元素就有点懵。所以我做了个更通用的例子(

gltf 的sdk地址

这份代码的原始例子比较不好参考,创建一个三角形还比较好参考,创建多个三角形或者元素就有点懵。所以我做了个更通用的例子(即创建多个mesh)作为使用这个gltf sdk的样例。

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.#include
#include
#include
#include
#include
#include // Replace this with (and use std::filesystem rather than
// std::experimental::filesystem) if your toolchain fully supports C++17
#include #include
#include
#include #include
#include
#include using namespace std;using namespace Microsoft::glTF;namespace
{// The glTF SDK is decoupled from all file I/O by the IStreamWriter (and IStreamReader)// interface(s) and the C++ stream-based I/O library. This allows the glTF SDK to be used in// sandboxed environments, such as WebAssembly modules and UWP apps, where any file I/O code// must be platform or use-case specific.class StreamWriter : public IStreamWriter{public:StreamWriter(std::experimental::filesystem::path pathBase) : m_pathBase(std::move(pathBase)){assert(m_pathBase.has_root_path());}// Resolves the relative URIs of any external resources declared in the glTF manifeststd::shared_ptr GetOutputStream(const std::string& filename) const override{// In order to construct a valid stream:// 1. The filename argument will be encoded as UTF-8 so use filesystem::u8path to// correctly construct a path instance.// 2. Generate an absolute path by concatenating m_pathBase with the specified filename// path. The filesystem::operator/ uses the platform's preferred directory separator// if appropriate.// 3. Always open the file stream in binary mode. The glTF SDK will handle any text// encoding issues for us.auto streamPath = m_pathBase / std::experimental::filesystem::u8path(filename);auto stream = std::make_shared(streamPath, std::ios_base::binary);// Check if the stream has no errors and is ready for I/O operationsif (!stream || !(*stream)){throw std::runtime_error("Unable to create a valid output stream for uri: " + filename);}return stream;}private:std::experimental::filesystem::path m_pathBase;}; std::string AddMaterial(Document& document, Color4& color4) {// Construct a MaterialMaterial material;material.metallicRoughness.baseColorFactor = color4;material.metallicRoughness.metallicFactor = 0.2f;material.metallicRoughness.roughnessFactor = 0.4f;material.doubleSided = true;// Add it to the Document and store the generated IDauto materialId = document.materials.Append(std::move(material), AppendIdPolicy::GenerateOnEmpty).id;return materialId;}//添加顶点索引Accessorstring AddIndexAccessor(BufferBuilder& bufferBuilder, const vector &indices) {// Create a BufferView with a target of ELEMENT_ARRAY_BUFFER (as it will reference index// data) - it will be the 'current' BufferView that all the Accessors created by this// BufferBuilder will automatically referencebufferBuilder.AddBufferView(BufferViewTarget::ELEMENT_ARRAY_BUFFER);// Add an Accessor for the indices// Copy the Accessor's id - subsequent calls to AddAccessor may invalidate the returned referencereturn bufferBuilder.AddAccessor(indices, { TYPE_SCALAR, COMPONENT_UNSIGNED_SHORT }).id;}//添加顶点Accessorstring AddPositionsAccessor(BufferBuilder& bufferBuilder,const vector &positions) {// Create a BufferView with target ARRAY_BUFFER (as it will reference vertex attribute data)bufferBuilder.AddBufferView(BufferViewTarget::ARRAY_BUFFER);// Add an Accessor for the positions//std::vector positions = {// 0.0f, 0.0f, 0.0f, // Vertex 0// 1.0f, 0.0f, 0.0f, // Vertex 1// 0.0f, 1.0f, 0.0f // Vertex 2//};std::vector minValues(3U, std::numeric_limits::max());std::vector maxValues(3U, std::numeric_limits::lowest());const size_t positionCount = positions.size();// Accessor min/max properties must be set for vertex position data so calculate them herefor (size_t i = 0U, j = 0U; i (&bufferBuilder.GetResourceWriter())){bufferId = GLB_BUFFER_ID;}// Create a Buffer - it will be the 'current' Buffer that all the BufferViews// created by this BufferBuilder will automatically referencebufferBuilder.AddBuffer(bufferId);#pragma region 添加索引Accessorstd::vector indices = {0U, 1U, 2U};accessorIdIndices = AddIndexAccessor(bufferBuilder,indices);
#pragma endregion#pragma region 添加顶点Accessor// Add an Accessor for the positionsstd::vector positions = {0.0f, 0.0f, 0.0f, // Vertex 01.0f, 0.0f, 0.0f, // Vertex 10.0f, 1.0f, 0.0f // Vertex 2};accessorIdPositions = AddPositionsAccessor(bufferBuilder, positions);
#pragma endregion#pragma region 添加索引Accessorstd::vector indices2 = {0U, 1U, 2U};accessorIdIndices2 = AddIndexAccessor(bufferBuilder, indices2);
#pragma endregion#pragma region 添加顶点Accessor// Add an Accessor for the positionsstd::vector positions2 = {1.0f, 0.0f, 0.0f, // Vertex 02.0f, 0.0f, 0.0f, // Vertex 11.0f, 1.0f, 0.0f // Vertex 2};accessorIdPositions2 = AddPositionsAccessor(bufferBuilder, positions2);
#pragma endregion// Add all of the Buffers, BufferViews and Accessors that were created using BufferBuilder to// the Document. Note that after this point, no further calls should be made to BufferBuilderbufferBuilder.Output(document);// Construct a MaterialColor4 color(1.0f, 0.0f, 0.0f, 1.0f);auto materialId &#61; AddMaterial(document, color);Color4 color2(0.0f, 1.0f, 0.0f, 1.0f);auto materialId2 &#61; AddMaterial(document, color2);// Construct a MeshPrimitive. Unlike most types in glTF, MeshPrimitives are direct children// of their parent Mesh entity rather than being children of the Document. This is why they// don&#39;t have an ID member.Scene scene;AddMesh(document, materialId, accessorIdIndices, accessorIdPositions, scene);AddMesh(document, materialId2, accessorIdIndices2, accessorIdPositions2, scene);// Add it to the Document, using a utility method that also sets the Scene as the Document&#39;s defaultdocument.SetDefaultScene(std::move(scene), AppendIdPolicy::GenerateOnEmpty);}void SerializeTriangle(const std::experimental::filesystem::path& path){// Pass the absolute path, without the filename, to the stream writerauto streamWriter &#61; std::make_unique(path.parent_path());std::experimental::filesystem::path pathFile &#61; path.filename();std::experimental::filesystem::path pathFileExt &#61; pathFile.extension();auto MakePathExt &#61; [](const std::string& ext){return "." &#43; ext;};std::unique_ptr resourceWriter;// If the file has a &#39;.gltf&#39; extension then create a GLTFResourceWriterif (pathFileExt &#61;&#61; MakePathExt(GLTF_EXTENSION)){resourceWriter &#61; std::make_unique(std::move(streamWriter));}// If the file has a &#39;.glb&#39; extension then create a GLBResourceWriter. This class derives// from GLTFResourceWriter and adds support for writing manifests to a GLB container&#39;s// JSON chunk and resource data to the binary chunk.if (pathFileExt &#61;&#61; MakePathExt(GLB_EXTENSION)){resourceWriter &#61; std::make_unique(std::move(streamWriter));}if (!resourceWriter){throw std::runtime_error("Command line argument path filename extension must be .gltf or .glb");}// The Document instance represents the glTF JSON manifestDocument document;// Use the BufferBuilder helper class to simplify the process of// constructing valid glTF Buffer, BufferView and Accessor entitiesBufferBuilder bufferBuilder(std::move(resourceWriter));CreateTrianglesResources(document, bufferBuilder);//CreateTriangle2Entities(document, accessorIdIndices, accessorIdPositions);//CreateTriangle2Resources(document, bufferBuilder, accessorIdIndices, accessorIdPositions);//CreateTriangle2Entities(document, accessorIdIndices, accessorIdPositions);std::string manifest;try{// Serialize the glTF Document into a JSON manifestmanifest &#61; Serialize(document, SerializeFlags::Pretty);}catch (const GLTFException& ex){std::stringstream ss;ss <<"Microsoft::glTF::Serialize failed: ";ss <(&gltfResourceWriter)){glbResourceWriter->Flush(manifest, pathFile.u8string()); // A GLB container isn&#39;t created until the GLBResourceWriter::Flush member function is called}else{gltfResourceWriter.WriteExternal(pathFile.u8string(), manifest); // Binary resources have already been written, just need to write the manifest}}
}int main()
{const char* argv[1] &#61; {"D:\\test.gltf" };try{std::experimental::filesystem::path path &#61; argv[0U];if (path.is_relative()){auto pathCurrent &#61; std::experimental::filesystem::current_path();// Convert the relative path into an absolute path by appending the command line argument to the current pathpathCurrent /&#61; path;pathCurrent.swap(path);}if (!path.has_filename()){throw std::runtime_error("Command line argument path has no filename");}if (!path.has_extension()){throw std::runtime_error("Command line argument path has no filename extension");}SerializeTriangle(path);}catch (const std::runtime_error& ex){std::cerr <<"Error! - ";std::cerr <}

 


推荐阅读
author-avatar
airchampion
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有