Skip to content

Commit

Permalink
Merge branch 'gltf-loader'
Browse files Browse the repository at this point in the history
Now that cesium-native has merged
CesiumGS/cesium-native#610, merge in the vsgCs
glTF model loading code. This isn't working yet, but it should be
carried along in the master branch.
  • Loading branch information
timoore committed Dec 27, 2023
2 parents 9667145 + a49da64 commit 91e2896
Show file tree
Hide file tree
Showing 7 changed files with 401 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/applications/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
add_subdirectory(csclient)
add_subdirectory(gltfviewer)
add_subdirectory(worldviewer)

17 changes: 17 additions & 0 deletions src/applications/gltfviewer/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
set(SOURCES
gltfviewer.cpp
)

SET(TARGET_SRC ${SOURCES})

INCLUDE_DIRECTORIES(${Vulkan_INCLUDE_DIR})

add_executable(gltfviewer ${SOURCES})

target_link_libraries(gltfviewer vsgCs CsApp vsg::vsg)

target_link_libraries(gltfviewer vsgImGui::vsgImGui)

install(TARGETS gltfviewer
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
210 changes: 210 additions & 0 deletions src/applications/gltfviewer/gltfviewer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
#include "vsgCs/GltfLoader.h"
#include "vsgCs/pbr.h"
#include "vsgCs/RuntimeEnvironment.h"
#include "vsgCs/runtimeSupport.h"

#include <vsg/all.h>

#include <iostream>

int main(int argc, char** argv)
{
vsg::CommandLine arguments(&argc, argv);
auto environment = vsgCs::RuntimeEnvironment::get();
auto window = environment->openWindow(arguments, "worldviewer");


bool add_amient = true;
bool add_directional = true;
bool add_point = true;
bool add_spotlight = true;
bool add_headlight = arguments.read("--headlight");
if (add_headlight || arguments.read({"--no-lights", "-n"}))
{
add_amient = false;
add_directional = false;
add_point = false;
add_spotlight = false;
}

// Set up the view shading parameters in the vsgCs way
auto scene = vsg::StateGroup::create();
// Bind the lighting for the whole world
auto bindViewDescriptorSets
= vsg::BindViewDescriptorSets::create(VK_PIPELINE_BIND_POINT_GRAPHICS,
vsgCs::RuntimeEnvironment::get()->genv->overlayPipelineLayout,
vsgCs::pbr::VIEW_DESCRIPTOR_SET);
scene->add(bindViewDescriptorSets);
auto loader = vsgCs::GltfLoader::create();

if (argc>1)
{
vsg::Path filename = argv[1];
auto model = vsgCs::ref_ptr_cast<vsg::Node>(loader->read(filename, vsgCs::RuntimeEnvironment::get()->options));
if (!model)
{
std::cout<<"Faled to load "<<filename<<std::endl;
return 1;
}
scene->addChild(model);
}

// compute the bounds of the scene graph to help position camera
auto bounds = vsg::visit<vsg::ComputeBounds>(scene).bounds;

if (add_amient || add_directional || add_point || add_spotlight || add_headlight)
{
auto span = vsg::length(bounds.max - bounds.min);
auto group = vsg::Group::create();
group->addChild(scene);

// ambient light
if (add_amient)
{
auto ambientLight = vsg::AmbientLight::create();
ambientLight->name = "ambient";
ambientLight->color.set(1.0, 1.0, 1.0);
ambientLight->intensity = 0.01;
group->addChild(ambientLight);
}

// directional light
if (add_directional)
{
auto directionalLight = vsg::DirectionalLight::create();
directionalLight->name = "directional";
directionalLight->color.set(1.0, 1.0, 1.0);
directionalLight->intensity = 0.15;
directionalLight->direction.set(0.0, -1.0, -1.0);
group->addChild(directionalLight);
}

// point light
if (add_point)
{
auto pointLight = vsg::PointLight::create();
pointLight->name = "point";
pointLight->color.set(1.0, 1.0, 0.0);
pointLight->intensity = span*0.5;
pointLight->position.set(bounds.min.x, bounds.min.y, bounds.max.z + span*0.3);

// enable culling of the point light by decorating with a CullGroup
auto cullGroup = vsg::CullGroup::create();
cullGroup->bound.center = pointLight->position;
cullGroup->bound.radius = span;

cullGroup->addChild(pointLight);

group->addChild(cullGroup);
}

// spot light
if (add_spotlight)
{
auto spotLight = vsg::SpotLight::create();
spotLight->name = "spot";
spotLight->color.set(0.0, 1.0, 1.0);
spotLight->intensity = span*0.5;
spotLight->position.set(bounds.max.x + span*0.1, bounds.min.y - span*0.1, bounds.max.z + span*0.3);
spotLight->direction = (bounds.min+bounds.max)*0.5 - spotLight->position;
spotLight->innerAngle = vsg::radians(8.0);
spotLight->outerAngle = vsg::radians(9.0);

// enable culling of the spot light by decorating with a CullGroup
auto cullGroup = vsg::CullGroup::create();
cullGroup->bound.center = spotLight->position;
cullGroup->bound.radius = span;

cullGroup->addChild(spotLight);

group->addChild(cullGroup);
}

if (add_headlight)
{
auto ambientLight = vsg::AmbientLight::create();
ambientLight->name = "ambient";
ambientLight->color.set(1.0, 1.0, 1.0);
ambientLight->intensity = 0.1;

auto directionalLight = vsg::DirectionalLight::create();
directionalLight->name = "head light";
directionalLight->color.set(1.0, 1.0, 1.0);
directionalLight->intensity = 0.9;
directionalLight->direction.set(0.0, 0.0, -1.0);

auto absoluteTransform = vsg::AbsoluteTransform::create();
absoluteTransform->addChild(ambientLight);
absoluteTransform->addChild(directionalLight);

group->addChild(absoluteTransform);
}
scene->addChild(group);
}


// create the viewer and assign window(s) to it
auto viewer = vsg::Viewer::create();

if (!window)
{
std::cout << "Could not create windows." << std::endl;
return 1;
}

viewer->addWindow(window);

vsg::ref_ptr<vsg::LookAt> lookAt;

vsg::dvec3 centre = (bounds.min + bounds.max) * 0.5;
double radius = vsg::length(bounds.max - bounds.min) * 0.6;

// set up the camera
lookAt = vsg::LookAt::create(centre + vsg::dvec3(0.0, -radius * 3.5, 0.0), centre, vsg::dvec3(0.0, 0.0, 1.0));

double nearFarRatio = 0.001;
auto perspective = vsg::Perspective::create(30.0, static_cast<double>(window->extent2D().width) / static_cast<double>(window->extent2D().height), nearFarRatio * radius, radius * 10.0);

auto camera = vsg::Camera::create(perspective, lookAt, vsg::ViewportState::create(window->extent2D()));

// add the camera and scene graph to View
auto view = vsg::View::create();
view->camera = camera;
view->addChild(scene);

// add close handler to respond the close window button and pressing escape
viewer->addEventHandler(vsg::CloseHandler::create(viewer));
viewer->addEventHandler(vsg::Trackball::create(camera));

auto renderGraph = vsg::RenderGraph::create(window, view);
// The classic VSG background, translated into sRGB values.
renderGraph->setClearValues({{0.02899f, 0.02899f, 0.13321f}});

auto commandGraph = vsg::CommandGraph::create(window, renderGraph);
viewer->assignRecordAndSubmitTaskAndPresentation({commandGraph});

viewer->compile();

auto startTime = vsg::clock::now();
double numFramesCompleted = 0.0;

// rendering main loop
while (viewer->advanceToNextFrame())
{
// pass any events into EventHandlers assigned to the Viewer
viewer->handleEvents();
viewer->update();
viewer->recordAndSubmit();
viewer->present();

numFramesCompleted += 1.0;
}

auto duration = std::chrono::duration<double, std::chrono::seconds::period>(vsg::clock::now() - startTime).count();
if (numFramesCompleted > 0.0)
{
std::cout << "Average frame rate = " << (numFramesCompleted / duration) << std::endl;
}

return 0;
}
2 changes: 2 additions & 0 deletions src/vsgCs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ set(LIB_PUBLIC_HEADERS
${CMAKE_CURRENT_BINARY_DIR}/Export.h
GeoNode.h
GeospatialServices.h
GltfLoader.h
GraphicsEnvironment.h
jsonUtils.h
LoadGltfResult.h
Expand All @@ -35,6 +36,7 @@ set(SOURCES
CompilableImage.cpp
GeoNode.cpp
GeospatialServices.cpp
GltfLoader.cpp
GraphicsEnvironment.cpp
jsonUtils.cpp
ModelBuilder.cpp
Expand Down
114 changes: 114 additions & 0 deletions src/vsgCs/GltfLoader.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/* <editor-fold desc="MIT License">
Copyright(c) 2023 Timothy Moore
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</editor-fold> */

#include "GltfLoader.h"

#include "ModelBuilder.h"
#include "OpThreadTaskProcessor.h"
#include "RuntimeEnvironment.h"
#include "runtimeSupport.h"
#include "Styling.h"


#include <CesiumAsync/IAssetAccessor.h>
#include <CesiumAsync/IAssetResponse.h>
#include <CesiumGltfContent/GltfUtilities.h>

#include <filesystem>

using namespace vsgCs;

GltfLoader::GltfLoader(vsg::ref_ptr<RuntimeEnvironment> in_env)
: env(in_env)
{
}

struct ParseGltfResult
{
ParseGltfResult(const std::string& error, std::shared_ptr<CesiumAsync::IAssetRequest> in_request)
: request(in_request)
{
gltfResult.errors.push_back(error);
}
ParseGltfResult(CesiumGltfReader::GltfReaderResult&& result,
std::shared_ptr<CesiumAsync::IAssetRequest> in_request)
: gltfResult(std::move(result)) ,request(in_request)
{
}

ParseGltfResult()
{
}
CesiumGltfReader::GltfReaderResult gltfResult;
std::shared_ptr<CesiumAsync::IAssetRequest> request;
};

struct ReadGltfResult
{
vsg::ref_ptr<vsg::Node> node;
std::vector<std::string> errors;
};

CesiumAsync::Future<GltfLoader::ReadGltfResult> GltfLoader::loadGltfNode(std::string uri) const
{
std::vector<CesiumAsync::IAssetAccessor::THeader> headers;
auto accessor = env-> getAssetAccessor();
return reader.loadGltf(getAsyncSystem(), uri, headers, accessor)
.thenInWorkerThread([this](CesiumGltfReader::GltfReaderResult&& gltfResult)
{
CreateModelOptions modelOptions{};
ModelBuilder modelBuilder(env->genv, &*gltfResult.model, modelOptions);
glm::dmat4 yUp(1.0);
yUp = CesiumGltfContent::GltfUtilities::applyGltfUpAxisTransform(*gltfResult.model, yUp);
auto modelNode = modelBuilder();
if (isIdentity(yUp))
{
return ReadGltfResult{modelNode, {}};
}
auto transformNode = vsg::MatrixTransform::create(glm2vsg(yUp));
transformNode->addChild(modelNode);
return ReadGltfResult{transformNode, {}};
});
}

vsg::ref_ptr<vsg::Object>
GltfLoader::read(const vsg::Path& path, vsg::ref_ptr<const vsg::Options> options) const
{
using namespace CesiumGltfReader;
auto realPath = vsg::findFile(path, options);
if (realPath.empty())
{
vsg::fatal("Can't find file ", path);
}
// Really need an absolute path in order to make a URI
std::filesystem::path p = realPath.string();
auto absPath = std::filesystem::absolute(p);
auto uriPath = "file://" + absPath.string();
auto future = loadGltfNode(uriPath);
getAsyncSystem().dispatchMainThreadTasks();

auto loadResult = future.wait();

return loadResult.node;
}
Loading

0 comments on commit 91e2896

Please sign in to comment.