Merge branch 'plutoViz' of openspace.itn.liu.se:/openspace into plutoViz

This commit is contained in:
Michal Marcinkowski
2015-02-23 17:24:18 -05:00
49 changed files with 813 additions and 1069 deletions
+1
View File
@@ -28,4 +28,5 @@ latex/
shaders/ABuffer/constants.hglsl
*.OpenSpaceGenerated.glsl
LuaScripting.txt
Properties.txt
log.html
+5 -1
View File
@@ -46,7 +46,7 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${OPENSPACE_LIBRARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OPENSPACE_BINARY_DIR})
include(cotire)
#include(cotire)
# Make sure a build type is set. Default is Debug.
if(NOT CMAKE_BUILD_TYPE)
@@ -71,6 +71,7 @@ endif ()
# Ghoul
set(GHOUL_ROOT_DIR "${OPENSPACE_EXT_DIR}/ghoul")
include_directories("${GHOUL_ROOT_DIR}/include")
include_directories("${GHOUL_ROOT_DIR}/ext/tinyobjloader")
set(BOOST_ROOT "${GHOUL_ROOT_DIR}/ext/boost")
add_subdirectory(${GHOUL_ROOT_DIR})
set(DEPENDENT_LIBS ${DEPENDENT_LIBS} Ghoul)
@@ -91,6 +92,9 @@ include_directories(${GHOUL_ROOT_DIR}/ext/boost)
find_package(SGCT REQUIRED)
include_directories(${SGCT_INCLUDE_DIRECTORIES})
set(DEPENDENT_LIBS ${DEPENDENT_LIBS} ${SGCT_LIBRARIES})
if (UNIX)
set(DEPENDENT_LIBS ${DEPENDENT_LIBS} Xcursor Xinerama)
endif ()
# GLM
set(GLM_ROOT_DIR "${GHOUL_ROOT_DIR}/ext/glm")
@@ -92,6 +92,7 @@ public:
private:
OpenSpaceEngine(std::string programName);
~OpenSpaceEngine();
OpenSpaceEngine(const OpenSpaceEngine& rhs) = delete;
void clearAllWindows();
bool gatherCommandlineArguments();
+5 -1
View File
@@ -28,6 +28,8 @@
#include <openspace/gui/guihelpcomponent.h>
#include <openspace/gui/guiperformancecomponent.h>
#include <openspace/gui/guipropertycomponent.h>
#include <openspace/gui/guiorigincomponent.h>
#include <openspace/gui/guitimecomponent.h>
#include <openspace/scripting/scriptengine.h>
namespace openspace {
@@ -60,9 +62,11 @@ public:
static openspace::scripting::ScriptEngine::LuaLibrary luaLibrary();
//protected:
GuiHelpComponent _help;
GuiOriginComponent _origin;
GuiPerformanceComponent _performance;
GuiPropertyComponent _property;
GuiHelpComponent _help;
GuiTimeComponent _time;
bool _isEnabled;
@@ -0,0 +1,97 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* 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. *
****************************************************************************************/
#ifndef __GUIORIGINCOMPONENT_H__
#define __GUIORIGINCOMPONENT_H__
#include <openspace/gui/guicomponent.h>
namespace openspace {
namespace gui {
class GuiOriginComponent : public GuiComponent {
public:
void render() override;
};
//
//class GuiPropertyComponent : public GuiComponent {
//public:
// //void registerProperty(const std::string& propertyDescription);
// void registerProperty(properties::Property* prop);
// void render();
//
//protected:
// enum class PropertyType {
// BoolProperty = 0,
// IntProperty,
// FloatProperty,
// Vec2Property,
// Vec3Property,
// StringProperty,
// OptionProperty,
// SelectionProperty,
// TriggerProperty,
// InvalidPropertyType
// };
//
// struct PropertyInfo {
// PropertyType type;
// std::string identifier;
// std::string name;
// std::string group;
// };
// typedef std::string PropertyOwner;
//
// struct Property {
// PropertyOwner owner;
// std::vector<PropertyInfo> properties;
// };
//
// void handleProperty(const ghoul::Dictionary& value);
//
// PropertyType toPropertyType(const std::string& name) const;
//
// void renderProperty(const PropertyInfo& info) const;
//
// std::set<properties::Property*> _boolProperties;
// std::set<properties::Property*> _intProperties;
// std::set<properties::Property*> _floatProperties;
// std::set<properties::Property*> _vec2Properties;
// std::set<properties::Property*> _vec3Properties;
// std::set<properties::Property*> _vec4Properties;
// std::set<properties::Property*> _stringProperties;
// std::set<properties::Property*> _optionProperties;
// std::set<properties::Property*> _selectionProperties;
// std::set<properties::Property*> _triggerProperties;
// std::map<std::string, std::vector<properties::Property*>> _propertiesByOwner;
//
// //std::vector<Property> _properties;
//};
} // namespace gui
} // namespace openspace
#endif // __GUIORIGINCOMPONENT_H__
@@ -2,7 +2,7 @@
* *
* OpenSpace *
* *
* Copyright (c) 2014-2015 *
* Copyright (c) 2014 *
* *
* 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 *
@@ -22,74 +22,76 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/interface/interface.h>
/*
#include <sgct.h>
#ifndef __GUITIMECOMPONENT_H__
#define __GUITIMECOMPONENT_H__
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <openspace/gui/guicomponent.h>
#include <algorithm>
*/
namespace openspace {
Interface::Interface(OpenSpaceEngine* ) {}
Interface::~Interface() {}
namespace gui {
void Interface::callback(const char* receivedChars) {
/*
std::cout << receivedChars;
class GuiTimeComponent : public GuiComponent {
public:
void render() override;
};
boost::property_tree::ptree pt;
std::stringstream input(receivedChars);
boost::property_tree::json_parser::read_json(input, pt);
_nodes = std::vector<Node>();
loadIntoNodes(pt);
handleNodes(); // Issue commands
_nodes.clear(); // Clean up after commands are issued
*/
}
void Interface::handleNodes() {
/*
for (int i = 0; i < _nodes.size(); ++i) {
Node node = _nodes.at(i);
if (node == "stats") {
sgct::Engine::instance()->setDisplayInfoVisibility(atoi(node._value.c_str()));
} else if (node == "graph") {
sgct::Engine::instance()->setStatsGraphVisibility(atoi(node._value.c_str()));
}
}
*/
}
// http://duck-wrath.blogspot.com/2012/02/how-to-recursive-parse.html
void Interface::loadIntoNodes(const boost::property_tree::ptree& tree, std::string parent, const int depth) {
/*
BOOST_FOREACH( boost::property_tree::ptree::value_type const&v, tree.get_child("") ) {
boost::property_tree::ptree subtree = v.second;
std::string value = v.second.data();
std::string key = v.first;
// classify and store nodes
if ( key.length() > 0 ) { // value
_nodes.push_back(Node(key, value));
} else { // array
// Find parent and add to its children vector
std::vector<Node>::iterator it = std::find(_nodes.begin(), _nodes.end(), Node(parent));
if (it != _nodes.end()) {
(*it)._children.push_back(Node(parent, value));
} else {
std::cout << "Parent not found" << std::endl;
}
}
// recursive go down the hierarchy
loadIntoNodes(subtree,key,depth+1);
}
*/
}
//
//class GuiPropertyComponent : public GuiComponent {
//public:
// //void registerProperty(const std::string& propertyDescription);
// void registerProperty(properties::Property* prop);
// void render();
//
//protected:
// enum class PropertyType {
// BoolProperty = 0,
// IntProperty,
// FloatProperty,
// Vec2Property,
// Vec3Property,
// StringProperty,
// OptionProperty,
// SelectionProperty,
// TriggerProperty,
// InvalidPropertyType
// };
//
// struct PropertyInfo {
// PropertyType type;
// std::string identifier;
// std::string name;
// std::string group;
// };
// typedef std::string PropertyOwner;
//
// struct Property {
// PropertyOwner owner;
// std::vector<PropertyInfo> properties;
// };
//
// void handleProperty(const ghoul::Dictionary& value);
//
// PropertyType toPropertyType(const std::string& name) const;
//
// void renderProperty(const PropertyInfo& info) const;
//
// std::set<properties::Property*> _boolProperties;
// std::set<properties::Property*> _intProperties;
// std::set<properties::Property*> _floatProperties;
// std::set<properties::Property*> _vec2Properties;
// std::set<properties::Property*> _vec3Properties;
// std::set<properties::Property*> _vec4Properties;
// std::set<properties::Property*> _stringProperties;
// std::set<properties::Property*> _optionProperties;
// std::set<properties::Property*> _selectionProperties;
// std::set<properties::Property*> _triggerProperties;
// std::map<std::string, std::vector<properties::Property*>> _propertiesByOwner;
//
// //std::vector<Property> _properties;
//};
} // namespace gui
} // namespace openspace
#endif // __GUITIMECOMPONENT_H__
@@ -111,9 +111,6 @@ public:
void mousePositionCallback(int x, int y);
void mouseScrollWheelCallback(int pos);
//<<<<<<< HEAD
//double dt();
//=======
double deltaTime() const;
void orbitDelta(const glm::quat& rotation);
@@ -133,6 +130,15 @@ public:
void resetKeyBindings();
void bindKey(int key, const std::string& lua);
void setInteractionSensitivity(float sensitivity);
float interactionSensitivity() const;
void setInvertRoll(bool invert);
bool invertRoll() const;
void setInvertRotation(bool invert);
bool invertRotation() const;
/**
* Returns the Lua library that contains all Lua functions available to affect the
* interaction. The functions contained are
@@ -145,13 +151,6 @@ public:
private:
friend class Controller;
//<<<<<<< HEAD
// Camera* _camera;
// bool _enabled;
// SceneGraphNode* _node;
//
// double _dt;
//=======
InteractionHandler(const InteractionHandler&) = delete;
InteractionHandler& operator=(const InteractionHandler&) = delete;
InteractionHandler(InteractionHandler&&) = delete;
@@ -163,24 +162,16 @@ private:
double _deltaTime;
std::mutex _mutex;
//<<<<<<< HEAD
// // used for calling when updating and deallocation
// std::vector<ExternalControl*> _controllers;
//
// // for locking and unlocking
// std::mutex _cameraGuard;
bool _validKeyLua;
std::multimap<int, std::string > _keyLua;
float _controllerSensitivity;
bool _invertRoll;
bool _invertRotation;
KeyboardController* _keyboardController;
MouseController* _mouseController;
std::vector<Controller*> _controllers;
// glm::vec3 mapToTrackball(glm::vec2 mousePos);
// glm::vec3 mapToCamera(glm::vec3 trackballPos);
// void trackballRotate(int x, int y);
};
} // namespace interaction
@@ -208,7 +208,7 @@ std::string NumericalProperty<T>::className() const {
template <typename T>
bool NumericalProperty<T>::setLua(lua_State* state)
{
bool success;
bool success = false;
T value = PropertyDelegate<NumericalProperty<T>>::template fromLuaValue<T>(state, success);
if (success)
TemplateProperty<T>::setValue(value);
@@ -69,7 +69,8 @@ public:
* Adds the passed option to the list of available options. The <code>value</code> of
* the <code>option</code> must not have been registered previously, or a warning will
* be logged.
* \param option The option that will be added to the list of available options
* \param value The option that will be added to the list of available options
* \param desc The description of the value that will be added
*/
void addOption(int value, std::string desc);
@@ -192,7 +192,7 @@ const std::type_info& TemplateProperty<T>::type() const {
template <typename T>
bool TemplateProperty<T>::setLua(lua_State* state)
{
bool success;
bool success = false;
T thisValue = PropertyDelegate<TemplateProperty<T>>::template fromLuaValue<T>(state, success);
if (success)
set(boost::any(thisValue));
@@ -26,7 +26,7 @@
#define __WAVEFRONTOBJECT_H__
#include <openspace/rendering/model/modelgeometry.h>
#include <openspace/util/tiny_obj_loader.h>
#include <tiny_obj_loader.h>
namespace openspace {
@@ -26,7 +26,7 @@
#define __PlanetGeometryProjection_H__
#include <openspace/properties/propertyowner.h>
#include <openspace/rendering/planets/RenderablePlanetProjection.h>
#include <openspace/rendering/planets/renderableplanetprojection.h>
#include <ghoul/misc/dictionary.h>
namespace openspace {
@@ -85,7 +85,6 @@ private:
float _increment;
float _oldTime = 0;
float _dtEt;
};
} // namespace openspace
@@ -420,7 +420,7 @@ TEST_F(SpiceManagerTest, getSubObserverPoint){
double targetEt;
double subObserverPoint_ref[3];
double vectorToSurfacePoint_ref[3];
static SpiceChar * method[2] = { "Intercept: ellipsoid", "Near point: ellipsoid" };
static SpiceChar* method[2] = { static_cast<char*>("Intercept: ellipsoid"), static_cast<char*>("Near point: ellipsoid") };
str2et_c("2004 jun 11 19:32:00", &et);
+3 -1
View File
@@ -36,8 +36,10 @@ namespace openspace {
class ImageSequencer {
public:
ImageSequencer();
static ImageSequencer& ref();
bool loadSequence(const std::string dir);
bool loadSequence(const std::string& dir);
bool parsePlaybook(const std::string& dir, const std::string& type, std::string year = "2015");
bool parsePlaybookFile(const std::string& fileName, std::string year = "2015");
@@ -62,7 +62,7 @@ public:
glm::vec3 vec3() const;
// return the full psc as dvec4()
glm::dvec4& dvec4() const;
glm::dvec4 dvec4() const;
// rescaled return as dvec3
glm::dvec3 dvec3() const;
@@ -38,6 +38,7 @@ public:
PowerScaledSphere(const PowerScaledScalar& radius,
int segments = 8);
~PowerScaledSphere();
PowerScaledSphere(const PowerScaledSphere& cpy);
bool initialize();
+32 -26
View File
@@ -112,7 +112,7 @@ public:
/**
* Determines whether values exist for some <code>item</code> for any
* code>body</code> in the kernel pool by passing it to the <code>bodfnd_c</code>
* <code>body</code> in the kernel pool by passing it to the <code>bodfnd_c</code>
* function.
* http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html
* \param body The name of the body that should be sampled
@@ -219,7 +219,7 @@ public:
std::vector<double>& v) const;
bool spacecraftClockToET(const std::string craftIdCode, double& craftTicks, double& et);
bool spacecraftClockToET(const std::string& craftIdCode, double& craftTicks, double& et);
/**
* Converts the <code>timeString</code> representing a date to a double precision
@@ -260,8 +260,9 @@ public:
* \param from The frame to be converted from
* \param to The frame to be converted to
* \param ephemerisTime Time at which to get rotational matrix that transforms vector
* \return <code>true</code> if the conversion succeeded, <code>false</code> otherwise
*/
void frameConversion(glm::dvec3& v, const std::string from, const std::string to, double ephemerisTime) const;
bool frameConversion(glm::dvec3& v, const std::string& from, const std::string& to, double ephemerisTime) const;
/**
* Finds the projection of one vector onto another vector.
@@ -317,18 +318,18 @@ public:
* the surface intercept of the ray on a target body at a specified
* epoch, optionally corrected for light time and stellar
* aberration.
* \param method Computation method.
* \param target Name of target body.
* \param et Epoch in ephemeris seconds past J2000 TDB.
* \param fixref Body-fixed, body-centered target body frame.
* \param abcorr Aberration correction.
* \param obsrvr Name of observing body.
* \param dref Reference frame of ray's direction vector.
* \param dvec Ray's direction vector.
* \param spoint Surface intercept point on the target body.
* \param trgepc Intercept epoch.
* \param srfvec Vector from observer to intercept point.
* \param found Flag indicating whether intercept was found.
* \param target Name of target body.
* \param observer Name of observing body.
* \param fovFrame Reference frame of ray's direction vector.
* \param bodyFixedFrame Body-fixed, body-centered target body frame.
* \param method Computation method.
* \param aberrationCorrection Aberration correction.
* \param ephemerisTime Epoch in ephemeris seconds past J2000 TDB.
* \param targetEpoch Intercept epoch.
* \param directionVector Ray's direction vector.
* \param surfaceIntercept Surface intercept point on the target body.
* \param surfaceVector Vector from observer to intercept point.
* \return Flag indicating whether intercept was found.
* For further details, refer to
* http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sincpt_c.html
*/
@@ -347,14 +348,15 @@ public:
/**
* Determine if a specified ephemeris object is within the
* field-of-view (FOV) of a specified instrument at a given time.
* \param Name or ID code string of the instrument.
* \param Name or ID code string of the target.
* \param Type of shape model used for the target.
* \param Body-fixed, body-centered frame for target body.
* \param Aberration correction method.
* \param Name or ID code string of the observer.
* \param Time of the observation (seconds past J2000).
* \param Visibility flag (SPICETRUE/SPICEFALSE).
* \param instrument Name or ID code string of the instrument.
* \param target Name or ID code string of the target.
* \param observer Name or ID code string of the observer.
* \param aberrationCorrection Aberration correction method.
* \param method Type of shape model used for the target.
* \param referenceFrame Body-fixed, body-centered frame for target body.
* \param targetEpoch Time of the observation (seconds past J2000).
* \param isVisible <code>true</code> if the target is visible
* \return The success of the function
* For further detail, refer to
* http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/fovtrg_c.html
*/
@@ -364,7 +366,9 @@ public:
const std::string& method,
const std::string& referenceFrame,
const std::string& aberrationCorrection,
double& targetEpoch) const;
double& targetEpoch,
bool& isVisible
) const;
/**
* This method performs the same computation as the function its overloading
* with the exception that in doing so it assumes the inertial bodyfixed frame
@@ -376,7 +380,9 @@ public:
const std::string& observer,
const std::string& method,
const std::string& aberrationCorrection,
double& targetEpoch) const;
double& targetEpoch,
bool& isVisible
) const;
/**
* Returns the state vector (<code>position</code> and <code>velocity</code>) of a
@@ -570,7 +576,7 @@ public:
* surface point on a body with the NAIF ID of <code>id</code> to rectangular
* <code>coordinates</code>. For further details, refer to
* http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfrec_c.html.
* \param body The body on which the <code>longitude</code> and <code>latitude</code>
* \param id The body on which the <code>longitude</code> and <code>latitude</code>
* are defined. This body needs to have a defined radius for this function to work
* \param longitude The longitude of the point on the <code>body</code> in radians
* \param latitude The latitude of the point on the <code>body</code> in radians
-94
View File
@@ -1,94 +0,0 @@
//
// Copyright 2012-2013, Syoyo Fujita.
//
// Licensed under 2-clause BSD liecense.
//
#ifndef _TINY_OBJ_LOADER_H
#define _TINY_OBJ_LOADER_H
#include <string>
#include <vector>
#include <map>
namespace tinyobj {
typedef struct {
std::string name;
float ambient[3];
float diffuse[3];
float specular[3];
float transmittance[3];
float emission[3];
float shininess;
float ior; // index of refraction
float dissolve; // 1 == opaque; 0 == fully transparent
// illumination model (see http://www.fileformat.info/format/material/)
int illum;
std::string ambient_texname;
std::string diffuse_texname;
std::string specular_texname;
std::string normal_texname;
std::map<std::string, std::string> unknown_parameter;
} material_t;
typedef struct {
std::vector<float> positions;
std::vector<float> normals;
std::vector<float> texcoords;
std::vector<unsigned int> indices;
std::vector<int> material_ids; // per-mesh material ID
} mesh_t;
typedef struct {
std::string name;
mesh_t mesh;
} shape_t;
class MaterialReader {
public:
MaterialReader() {}
virtual ~MaterialReader() {}
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap) = 0;
};
class MaterialFileReader : public MaterialReader {
public:
MaterialFileReader(const std::string &mtl_basepath)
: m_mtlBasePath(mtl_basepath) {}
virtual ~MaterialFileReader() {}
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap);
private:
std::string m_mtlBasePath;
};
/// Loads .obj from a file.
/// 'shapes' will be filled with parsed shape data
/// The function returns error string.
/// Returns empty string when loading .obj success.
/// 'mtl_basepath' is optional, and used for base path for .mtl file.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
const char *filename, const char *mtl_basepath = NULL);
/// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve
/// std::istream for materials.
/// Returns empty string when loading .obj success.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
std::istream &inStream, MaterialReader &readMatFn);
/// Loads materials into std::map
/// Returns an empty string if successful
std::string LoadMtl(std::map<std::string, int> &material_map,
std::vector<material_t> &materials, std::istream &inStream);
}
#endif // _TINY_OBJ_LOADER_H
@@ -22,54 +22,7 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef INTERFACE_H_
#define INTERFACE_H_
#include <openspace/engine/openspaceengine.h>
#include <boost/property_tree/ptree.hpp>
#include <openspace/engine/openspaceengine.h>
#include <vector>
namespace openspace {
class Interface {
struct Node {
std::string _key;
std::string _value;
std::vector<Node> _children;
Node(std::string key, std::string value) {
_key = key;
_value = value;
_children = std::vector<Node>();
}
Node(std::string key) {
_key = key;
_value = "";
_children = std::vector<Node>();
}
inline bool operator==(const Node& rhs){
return (strcmp(_key.c_str(), rhs._key.c_str()) == 0);
}
inline bool operator==(const std::string& rhs){
return (strcmp(_key.c_str(), rhs.c_str()) == 0);
}
};
public:
Interface(OpenSpaceEngine* engine);
~Interface();
void callback(const char * receivedChars);
private:
void handleNodes();
void loadIntoNodes(const boost::property_tree::ptree& tree, std::string parent = "", const int depth = 0);
// OpenSpaceEngine* _engine;
std::vector<Node> _nodes;
};
} // namespace openspace
#endif /* INTERFACE_H_ */
#define OPENSPACE_VERSION_MAJOR 0
#define OPENSPACE_VERSION_MINOR 0
#define OPENSPACE_VERSION_BUILD 1
#define OPENSPACE_VERSION_STRING "prerelease-1"
+4 -1
View File
@@ -1,4 +1,7 @@
--openspace.setPropertyValue('Earth.renderable.colorTexture', '${OPENSPACE_DATA}/modules/mars/textures/mars.png')
openspace.setInvertRoll(true);
-- openspace.time.setTime("2007 FEB 27 16:30:00")
-- openspace.time.setDeltaTime(50);
openspace.time.setTime("2015-07-14T10:50:00.00") -- PLUTO
-- NH takes series of images from visible to dark side (across terminator)
+5 -10
View File
@@ -28,6 +28,8 @@
set(SOURCE_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(HEADER_ROOT_DIR ${CMAKE_SOURCE_DIR}/include)
set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${HEADER_ROOT_DIR}/openspace/version.h)
file(GLOB CONFIGURATION_SOURCE ${SOURCE_ROOT_DIR}/configuration/*.cpp)
set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${CONFIGURATION_SOURCE})
file(GLOB CONFIGURATION_HEADER ${HEADER_ROOT_DIR}/openspace/configuration/*.h)
@@ -126,13 +128,6 @@ file(GLOB FLARE_HEADER ${HEADER_ROOT_DIR}/openspace/flare/*.h)
set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${FLARE_HEADER})
source_group(Flare FILES ${FLARE_SOURCE} ${FLARE_HEADER})
file(GLOB INTERFACE_SOURCE ${SOURCE_ROOT_DIR}/interface/*.cpp)
set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${INTERFACE_SOURCE})
file(GLOB INTERFACE_HEADER ${HEADER_ROOT_DIR}/openspace/interface/*.h)
set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${INTERFACE_HEADER})
source_group(Interface FILES ${INTERFACE_SOURCE} ${INTERFACE_HEADER})
include_directories(${HEADER_ROOT_DIR})
include_directories(${GHOUL_ROOT_DIR}/ext/boost)
@@ -155,9 +150,9 @@ include_directories("${HEADER_ROOT_DIR}")
add_executable(OpenSpace ${SOURCE_ROOT_DIR}/main.cpp ${OPENSPACE_HEADER} ${OPENSPACE_SOURCE})
target_link_libraries(OpenSpace ${DEPENDENT_LIBS})
if (NOT UNIX)
cotire(OpenSpace)
endif ()
#if (NOT UNIX)
#cotire(OpenSpace)
#endif ()
GhoulCopySharedLibraries(OpenSpace)
add_subdirectory(tests)
+5 -1
View File
@@ -27,6 +27,7 @@
// sgct
#define SGCT_WINDOWS_INCLUDE
#include <sgct.h>
#include <openspace/version.h>
#include <openspace/engine/configurationmanager.h>
#include <openspace/engine/logfactory.h>
@@ -154,7 +155,6 @@ bool OpenSpaceEngine::create(int argc, char** argv,
return false;
// Parse commandline arguments
std::vector<std::string> remainingArguments;
_engine->_commandlineParser->setCommandLine(argc, argv, &sgctArguments);
const bool executeSuccess = _engine->_commandlineParser->execute();
if (!executeSuccess)
@@ -186,6 +186,10 @@ bool OpenSpaceEngine::create(int argc, char** argv,
// Initialize the requested logs from the configuration file
_engine->configureLogging();
LINFOC("OpenSpace Version", OPENSPACE_VERSION_MAJOR << "." <<
OPENSPACE_VERSION_MINOR << "." <<
OPENSPACE_VERSION_BUILD << " (" << OPENSPACE_VERSION_STRING << ")");
// Create directories that doesn't exist
auto tokens = FileSys.tokens();
for (const std::string& token : tokens) {
+12
View File
@@ -466,6 +466,18 @@ void GUI::renderMainWindow() {
ImGui::Checkbox("Properties", &_property._isEnabled);
ImGui::Checkbox("Performance", &_performance._isEnabled);
_origin.render();
_time.render();
// These are temporary until the scalegraph is in effect ---abock
bool toSun = ImGui::Button("Coordinate System to Sun");
bool toPluto = ImGui::Button("Coordinate System to Pluto");
if (toSun)
OsEng.scriptEngine()->queueScript("openspace.changeViewPointToSun();");
if (toPluto)
OsEng.scriptEngine()->queueScript("openspace.changeViewPointToPluto();");
ImGui::Checkbox("Help", &_help._isEnabled);
ImGui::End();
+182
View File
@@ -0,0 +1,182 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* 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. *
****************************************************************************************/
#include <openspace/gui/guiorigincomponent.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scenegraph/scenegraphnode.h>
#include <openspace/interaction/interactionhandler.h>
#include <ghoul/misc/assert.h>
#include "imgui.h"
namespace {
const std::string _loggerCat = "GuiOriginComponent";
}
namespace openspace {
namespace gui {
void GuiOriginComponent::render() {
const SceneGraphNode* currentFocus = OsEng.interactionHandler()->focusNode();
std::vector<SceneGraphNode*> nodes = OsEng.renderEngine()->sceneGraph()->allSceneGraphNodes();
std::sort(nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); });
auto it = std::find(nodes.begin(), nodes.end(), currentFocus);
ghoul_assert(it != nodes.end(), "Focus node not found");
std::string nodeNames = "";
for (SceneGraphNode* n : nodes)
nodeNames += n->name() + '\0';
int position = it - nodes.begin();
bool result = ImGui::Combo("Origin", &position, nodeNames.c_str());
if (result) {
LINFO("openspace.setOrigin('" + nodes[position]->name() + "');");
OsEng.scriptEngine()->queueScript("openspace.setOrigin('" + nodes[position]->name() + "');");
}
}
} // gui
} // openspace
// ImGui::Begin("Properties", &_isEnabled, size, 0.5f);
// //ImGui::ShowUserGuide();
// ImGui::Spacing();
// for (const auto& p : _propertiesByOwner) {
// if (ImGui::CollapsingHeader(p.first.c_str())) {
// for (properties::Property* prop : p.second) {
// if (_boolProperties.find(prop) != _boolProperties.end()) {
// renderBoolProperty(prop, p.first);
// continue;
// }
// if (_intProperties.find(prop) != _intProperties.end()) {
// renderIntProperty(prop, p.first);
// continue;
// }
// if (_floatProperties.find(prop) != _floatProperties.end()) {
// renderFloatProperty(prop, p.first);
// continue;
// }
// if (_vec2Properties.find(prop) != _vec2Properties.end()) {
// renderVec2Property(prop, p.first);
// continue;
// }
// if (_vec3Properties.find(prop) != _vec3Properties.end()) {
// renderVec3Property(prop, p.first);
// continue;
// }
// if (_vec4Properties.find(prop) != _vec4Properties.end()) {
// renderVec4Property(prop, p.first);
// continue;
// }
// if (_optionProperties.find(prop) != _optionProperties.end()) {
// renderOptionProperty(prop, p.first);
// continue;
// }
// if (_triggerProperties.find(prop) != _triggerProperties.end()) {
// renderTriggerProperty(prop, p.first);
// continue;
// }
// if (_selectionProperties.find(prop) != _selectionProperties.end()) {
// renderSelectionProperty(prop, p.first);
// continue;
// }
// if (_stringProperties.find(prop) != _stringProperties.end()) {
// renderStringProperty(prop, p.first);
// continue;
// }
// }
// }
// }
//ImGui::End();
//}
//
//GuiPropertyComponent::PropertyType GuiPropertyComponent::toPropertyType(
// const std::string& name) const
//{
// if (name == "BoolProperty")
// return PropertyType::BoolProperty;
// if (name == "IntProperty")
// return PropertyType::IntProperty;
// if (name == "FloatProperty")
// return PropertyType::FloatProperty;
// if (name == "Vec2Property")
// return PropertyType::Vec2Property;
// if (name == "Vec3Property")
// return PropertyType::Vec3Property;
// if (name == "StringProperty")
// return PropertyType::StringProperty;
// if (name == "OptionProperty")
// return PropertyType::OptionProperty;
// if (name == "SelectionProperty")
// return PropertyType::SelectionProperty;
// if (name == "TriggerProperty")
// return PropertyType::TriggerProperty;
//
// LWARNING("Unsupported property type '" << name << "'");
// return PropertyType::InvalidPropertyType;
//}
//
//void GuiPropertyComponent::renderProperty(const PropertyInfo& info) const {
// switch (info.type) {
// case PropertyType::BoolProperty:
// {
// // BoolProperty* p = static_cast<BoolProperty*>(prop);
// // std::string name = p->guiName();
//
// // BoolProperty::ValueType value = *p;
// // ImGui::Checkbox((ownerName + "." + name).c_str(), &value);
// // p->set(value);
//
//
//
//
// break;
// }
// default:
// LERROR("Missing case statement: {" << int(info.type) << "," << info.identifier << "}");
// //ghoul_assert(false, "Missing case statement");
// }
//
//}
+79
View File
@@ -0,0 +1,79 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* 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. *
****************************************************************************************/
#include <openspace/gui/guitimecomponent.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/time.h>
#include <ghoul/misc/assert.h>
#include "imgui.h"
namespace {
const std::string _loggerCat = "GuiTimeComponent";
}
namespace openspace {
namespace gui {
void GuiTimeComponent::render() {
float deltaTime = Time::ref().deltaTime();
bool changed = ImGui::SliderFloat("Delta Time", &deltaTime, -100.f, 100.f);
if (changed)
OsEng.scriptEngine()->queueScript("openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")");
//char dateBuffer[512] = {};
//ImGui::InputText("Date", dateBuffer, 512);
//bool pressed = ImGui::Button("Set Date");
//if (pressed)
// OsEng.scriptEngine()->queueScript("openspace.time.setTime('" + std::string(dateBuffer) + "')");
//const SceneGraphNode* currentFocus = OsEng.interactionHandler()->focusNode();
//std::vector<SceneGraphNode*> nodes = OsEng.renderEngine()->sceneGraph()->allSceneGraphNodes();
//std::sort(nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); });
//auto it = std::find(nodes.begin(), nodes.end(), currentFocus);
//ghoul_assert(it != nodes.end(), "Focus node not found");
//std::string nodeNames = "";
//for (SceneGraphNode* n : nodes)
// nodeNames += n->name() + '\0';
//int position = it - nodes.begin();
//bool result = ImGui::Combo("Origin", &position, nodeNames.c_str());
//if (result) {
// LINFO("openspace.setOrigin('" + nodes[position]->name() + "');");
// OsEng.scriptEngine()->queueScript("openspace.setOrigin('" + nodes[position]->name() + "');");
//}
}
} // gui
} // openspace
+152 -8
View File
@@ -193,7 +193,7 @@ namespace luascriptfunctions {
*/
int setOrigin(lua_State* L) {
using ghoul::lua::luaTypeToString;
const std::string _loggerCat = "LuaInteractionHandler";
const std::string _loggerCat = "lua.setOrigin";
int nArguments = lua_gettop(L);
if (nArguments != 1)
@@ -223,7 +223,7 @@ int setOrigin(lua_State* L) {
*/
int bindKey(lua_State* L) {
using ghoul::lua::luaTypeToString;
const std::string _loggerCat = "LuaInteractionHandler";
const std::string _loggerCat = "lua.bindKey";
int nArguments = lua_gettop(L);
if (nArguments != 2)
@@ -256,7 +256,7 @@ int bindKey(lua_State* L) {
*/
int clearKeys(lua_State* L) {
using ghoul::lua::luaTypeToString;
const std::string _loggerCat = "LuaInteractionHandler";
const std::string _loggerCat = "lua.clearKeys";
int nArguments = lua_gettop(L);
if (nArguments != 0)
@@ -298,6 +298,84 @@ int distance(lua_State* L) {
return 0;
}
/**
* \ingroup LuaScripts
* setInteractionSensitivity(double):
* Changes the global interaction sensitivity to the passed value
*/
int setInteractionSensitivity(lua_State* L) {
int nArguments = lua_gettop(L);
if (nArguments != 1)
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
double sensitivity = luaL_checknumber(L, -1);
OsEng.interactionHandler()->setInteractionSensitivity(sensitivity);
return 0;
}
/**
* \ingroup LuaScripts
* interactionSensitivity():
* Returns the current, global interaction sensitivity
*/
int interactionSensitivity(lua_State* L) {
float sensitivity = OsEng.interactionHandler()->interactionSensitivity();
lua_pushnumber(L, sensitivity);
return 1;
}
/**
* \ingroup LuaScripts
* setInvertRoll(bool):
* Determines if the roll movement is inverted
*/
int setInvertRoll(lua_State* L) {
int nArguments = lua_gettop(L);
if (nArguments != 1)
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
bool invert = lua_toboolean(L, -1);
OsEng.interactionHandler()->setInvertRoll(invert);
return 0;
}
/**
* \ingroup LuaScripts
* invertRoll():
* Returns the current setting for inversion of roll movement
*/
int invertRoll(lua_State* L) {
bool invert = OsEng.interactionHandler()->invertRoll();
lua_pushboolean(L, invert);
return 1;
}
/**
* \ingroup LuaScripts
* setInvertRotation(bool):
* Determines if the rotation movement is inverted
*/
int setInvertRotation(lua_State* L) {
int nArguments = lua_gettop(L);
if (nArguments != 1)
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
bool invert = lua_toboolean(L, -1);
OsEng.interactionHandler()->setInvertRotation(invert);
return 0;
}
/**
* \ingroup LuaScripts
* invertRotation():
* Returns the current setting for inversion of rotation movement
*/
int invertRotation(lua_State* L) {
bool invert = OsEng.interactionHandler()->invertRotation();
lua_pushboolean(L, invert);
return 1;
}
} // namespace luascriptfunctions
//InteractionHandler::InteractionHandler() {
@@ -360,6 +438,11 @@ namespace interaction {
InteractionHandler::InteractionHandler()
: _camera(nullptr)
, _focusNode(nullptr)
, _deltaTime(0.0)
, _validKeyLua(false)
, _controllerSensitivity(10.f)
, _invertRoll(false)
, _invertRotation(false)
, _keyboardController(nullptr)
, _mouseController(nullptr)
{
@@ -528,9 +611,9 @@ void InteractionHandler::orbit(const float &dx, const float &dy, const float &dz
glm::vec3 cameraRight = glm::cross(_camera->viewDirection(), cameraUp);
glm::mat4 transform;
transform = glm::rotate(dx * 10, cameraUp) * transform;
transform = glm::rotate(dy * 10, cameraRight) * transform;
transform = glm::rotate(dz * 10, _camera->viewDirection()) * transform;
transform = glm::rotate(dx * 10.f, cameraUp) * transform;
transform = glm::rotate(dy * 10.f, cameraRight) * transform;
transform = glm::rotate(dz * 10.f, _camera->viewDirection()) * transform;
//get "old" focus position
@@ -794,7 +877,7 @@ void InteractionHandler::lookAt(const glm::quat& rotation)
//
void InteractionHandler::keyboardCallback(int key, int action) {
// TODO package in script
const float speed = 2.75f;
const float speed = _controllerSensitivity;
const float dt = static_cast<float>(_deltaTime);
if (action == SGCT_PRESS || action == SGCT_REPEAT) {
@@ -947,7 +1030,44 @@ scripting::ScriptEngine::LuaLibrary InteractionHandler::luaLibrary() {
&luascriptfunctions::distance,
"number",
"Change distance to origin"
}
},
{
"setInteractionSensitivity",
&luascriptfunctions::setInteractionSensitivity,
"number",
"Sets the global interaction sensitivity"
},
{
"interactionSensitivity",
&luascriptfunctions::interactionSensitivity,
"",
"Gets the current global interaction sensitivity"
},
{
"setInvertRoll",
&luascriptfunctions::setInvertRoll,
"bool",
"Sets the setting if roll movements are inverted"
},
{
"invertRoll",
&luascriptfunctions::invertRoll,
"",
"Returns the status of roll movement inversion"
},
{
"setInvertRotation",
&luascriptfunctions::setInvertRotation,
"bool",
"Sets the setting if rotation movements are inverted"
},
{
"invertRotation",
&luascriptfunctions::invertRotation,
"",
"Returns the status of rotation movement inversion"
}
}
};
}
@@ -962,6 +1082,30 @@ double InteractionHandler::deltaTime() const {
return _deltaTime;
}
void InteractionHandler::setInteractionSensitivity(float sensitivity) {
_controllerSensitivity = sensitivity;
}
float InteractionHandler::interactionSensitivity() const {
return _controllerSensitivity;
}
void InteractionHandler::setInvertRoll(bool invert) {
_invertRoll = invert;
}
bool InteractionHandler::invertRoll() const {
return _invertRoll;
}
void InteractionHandler::setInvertRotation(bool invert) {
_invertRotation = invert;
}
bool InteractionHandler::invertRotation() const {
return _invertRotation;
}
} // namespace interaction
//>>>>>>> feature/interactionhandler
} // namespace openspace
+1 -1
View File
@@ -43,9 +43,9 @@ namespace interaction {
void KeyboardControllerFixed::keyPressed(KeyAction action, Key key, KeyModifier modifier) {
// TODO package in script
const float speed = 2.75;
const float dt = static_cast<float>( _handler->deltaTime());
if(action == KeyAction::Press|| action == KeyAction::Repeat) {
const float speed = 2.75;
if (key == Key::S) {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
-2
View File
@@ -128,8 +128,6 @@ void LuaConsole::initialize() {
file.close();
_commands = _commandsHistory;
}
else
LERROR("Could not open file '" << absPath(_filename) << "' for reading history");
_commands.push_back("");
_activeCommand = _commands.size() - 1;
}
+15 -10
View File
@@ -24,6 +24,8 @@
#include <openspace/interaction/mousecontroller.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/interaction/interactionhandler.h>
namespace openspace {
@@ -147,13 +149,13 @@ void TrackballMouseController::update(const double& dt){
OrbitalMouseController::OrbitalMouseController()
: MouseController()
, _leftMouseButtonDown(false)
, _rightMouseButtonDown(false)
, _middleMouseButtonDown(false)
, _currentCursorPos(0)
, _rotationSpeed(10.f)
, _navigationSpeed(3.f)
: MouseController()
, _leftMouseButtonDown(false)
, _rightMouseButtonDown(false)
, _middleMouseButtonDown(false)
, _currentCursorPos(0)
, _rotationSpeed(10.f)
, _navigationSpeed(3.f)
{
for (int n = 0; n < 3; ++n){
_previousCursorPos[n] = glm::vec2(0);
@@ -222,12 +224,15 @@ void OrbitalMouseController::scrollWheel(int pos) {
}
void OrbitalMouseController::update(const double& dt){
const float interactionSpeed = OsEng.interactionHandler()->interactionSensitivity();
const bool rotationInvert = OsEng.interactionHandler()->invertRotation();
const bool rollInvert = OsEng.interactionHandler()->invertRoll();
//if (_leftMouseButtonDown || _rightMouseButtonDown || _middleMouseButtonDown){
_handler->orbit(
static_cast<float>(_leftMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].x * _rotationSpeed,
static_cast<float>(_leftMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].y * _rotationSpeed,
static_cast<float>(_middleMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonMiddle].x * _rotationSpeed,
static_cast<float>(_leftMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].x * interactionSpeed * (rotationInvert ? -1.f : 1.f),
static_cast<float>(_leftMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonLeft].y * interactionSpeed * (rotationInvert ? -1.f : 1.f),
static_cast<float>(_middleMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonMiddle].x * interactionSpeed * (rollInvert ? -1.f : 1.f),
static_cast<float>(_rightMouseButtonDown) * static_cast<float>(dt) * _currentCursorDiff[MouseButtons::ButtonRight].y * _navigationSpeed);
//}
+11 -9
View File
@@ -50,6 +50,7 @@ WavefrontGeometry::WavefrontGeometry(const ghoul::Dictionary& dictionary)
// The name is passed down from the SceneGraphNode
std::string name;
bool success = dictionary.getValue(keyName, name);
ghoul_assert(success, "Name tag was not present");
std::string file;
success = dictionary.getValue(constants::modelgeometry::keyObjFile, file);
@@ -59,23 +60,24 @@ WavefrontGeometry::WavefrontGeometry(const ghoul::Dictionary& dictionary)
}
const std::string filename = FileSys.absolutePath(file);
std::ifstream ifile(filename.c_str());
if (ifile){
LDEBUG("Found file..\n");
ifile.close();
loadObj(filename.c_str());
}
else {
LERROR("Did not find file..\n");
}
if (FileSys.fileExists(filename))
loadObj(filename.c_str());
else
LERROR("Could not load OBJ file '" << filename << "': File not found");
}
void WavefrontGeometry::loadObj(const char *filename){
// temporary
const char *mtl_basepat = filename;
LINFO("Loading OBJ file '" << filename << "'");
std::string err = tinyobj::LoadObj(shapes, materials, filename, mtl_basepat);
if (!err.empty()) {
LERROR(err);
return;
}
LINFO("Loaded Mesh");
LINFO("Number of Shapes: " << shapes.size());
LINFO("Number of Materials: " << materials.size());
@@ -22,7 +22,7 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/rendering/planets/PlanetGeometryProjection.h>
#include <openspace/rendering/planets/planetgeometryprojection.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/constants.h>
#include <openspace/util/factorymanager.h>
+1 -1
View File
@@ -81,7 +81,7 @@ RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary)
dictionary.getValue(keyFrame, _frame);
bool b1 = dictionary.getValue(keyBody, _target);
dictionary.getValue(keyBody, _target);
//assert(b1 == true);
// TODO: textures need to be replaced by a good system similar to the geometry as soon
@@ -23,7 +23,7 @@
****************************************************************************************/
// open space includes
#include <openspace/rendering/planets/RenderablePlanetProjection.h>
#include <openspace/rendering/planets/renderableplanetprojection.h>
#include <openspace/util/constants.h>
#include <openspace/rendering/planets/planetgeometryprojection.h>
@@ -392,8 +392,8 @@ void RenderablePlanetProjection::update(const UpdateData& data){
std::string _fovTarget = "";
for (int i = 0; i < 2; i++){
_withinFOV = openspace::SpiceManager::ref().targetWithinFieldOfView(_instrumentID, potential[i], _projectorID, "ELLIPSOID", _aberration, _time[0]);
if (_withinFOV){
bool success = openspace::SpiceManager::ref().targetWithinFieldOfView(_instrumentID, potential[i], _projectorID, "ELLIPSOID", _aberration, _time[0], _withinFOV);
if (success && _withinFOV){
_fovTarget = potential[i];
break;
}
@@ -22,7 +22,7 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/rendering/planets/SimpleSphereGeometryProjection.h>
#include <openspace/rendering/planets/simplespheregeometryprojection.h>
#include <openspace/util/constants.h>
namespace {
+4 -4
View File
@@ -385,10 +385,10 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon()
}
fileName = absPath(fileName);
KameleonWrapper::Model modelType;
if (model == vectorFieldKameleonModelBATSRUS)
modelType = KameleonWrapper::Model::BATSRUS;
else {
//KameleonWrapper::Model modelType;
if (model != vectorFieldKameleonModelBATSRUS) {
//modelType = KameleonWrapper::Model::BATSRUS;
//else {
LERROR(keyVectorField << "." << keyVectorFieldVolumeModel << " model '" <<
model << "' not supported");
return {};
+3 -3
View File
@@ -443,10 +443,10 @@ void RenderableFov::render(const RenderData& data){
_fovTarget = potential[0]; //default
for (int i = 0; i < 2; i++){
_withinFOV = openspace::SpiceManager::ref().targetWithinFieldOfView(_instrumentID, potential[i],
bool success = openspace::SpiceManager::ref().targetWithinFieldOfView(_instrumentID, potential[i],
_spacecraft, _method,
_aberrationCorrection, _time);
if (_withinFOV){
_aberrationCorrection, _time, _withinFOV);
if (success && _withinFOV){
_fovTarget = potential[i];
break;
}
+1
View File
@@ -120,6 +120,7 @@ bool RenderableSphere::isReady() const {
}
bool RenderableSphere::initialize() {
delete _sphere;
_sphere = new PowerScaledSphere(_size.value(), _segments);
_sphere->initialize();
+1 -2
View File
@@ -345,8 +345,7 @@ ghoul::opengl::Texture* RenderableVolume::loadTransferFunction(const std::string
} else if(key == "upper" && tokenSize == 2) {
upper = stringToNumber<float>(tokens.at(1),upperLowerValidator);
} else if(key == "mappingkey" && tokenSize == 6) {
float intensity = 1.0f;
intensity = stringToNumber<float>(tokens.at(1), intensityValidator);
float intensity = stringToNumber<float>(tokens.at(1), intensityValidator);
for(int i = 0; i < 4; ++i)
rgba[i] = stringToNumber<float>(tokens.at(i+2));
+10 -8
View File
@@ -124,6 +124,8 @@ namespace openspace {
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
const int type = lua_type(L, -1);
if (type != LUA_TBOOLEAN)
return luaL_error(L, "Expected argument of type 'bool'");
bool b = lua_toboolean(L, -1) != 0;
OsEng.renderEngine()->toggleVisualizeABuffer(b);
return 0;
@@ -140,6 +142,8 @@ namespace openspace {
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
const int type = lua_type(L, -1);
if (type != LUA_TBOOLEAN)
return luaL_error(L, "Expected argument of type 'bool'");
bool b = lua_toboolean(L, -1) != 0;
OsEng.renderEngine()->toggleInfoText(b);
return 0;
@@ -400,7 +404,6 @@ namespace openspace {
// converts the quaternion used to rotation matrices
_mainCamera->compileViewRotationMatrix();
UpdateData a = { Time::ref().currentTime(), Time::ref().deltaTime() };
// update and evaluate the scene starting from the root node
_sceneGraph->update({
@@ -484,11 +487,11 @@ namespace openspace {
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
int startY = ySize - 2 * font_size_mono;
const glm::vec2 scaling = _mainCamera->scaling();
const glm::vec3 viewdirection = _mainCamera->viewDirection();
const psc position = _mainCamera->position();
const psc origin = OsEng.interactionHandler()->focusNode()->worldPosition();
const PowerScaledScalar pssl = (position - origin).length();
const glm::vec2& scaling = _mainCamera->scaling();
const glm::vec3& viewdirection = _mainCamera->viewDirection();
const psc& position = _mainCamera->position();
const psc& origin = OsEng.interactionHandler()->focusNode()->worldPosition();
const PowerScaledScalar& pssl = (position - origin).length();
// GUI PRINT
// Using a macro to shorten line length and increase readability
@@ -509,8 +512,7 @@ namespace openspace {
PrintText(i++, "Scaling: (% .5f, % .5f)", scaling[0], scaling[1]);
double remaining = openspace::ImageSequencer::ref().getNextCaptureTime() - Time::ref().currentTime();
double t = 0.0;
t = 1.f - remaining / openspace::ImageSequencer::ref().getIntervalLength();
double t = 1.f - remaining / openspace::ImageSequencer::ref().getIntervalLength();
std::string progress = "|";
int g = ((t)* 20) + 1;
for (int i = 0; i < g; i++) progress.append("-"); progress.append(">");
+2 -2
View File
@@ -217,7 +217,7 @@ void SceneGraphNode::evaluate(const Camera* camera, const psc& parentPosition) {
//const psc toCamera = thisPosition - camPos;
// init as not visible
_boundingSphereVisible = false;
//_boundingSphereVisible = false;
_renderableVisible = false;
#ifndef OPENSPACE_VIDEO_EXPORT
@@ -414,7 +414,7 @@ SceneGraphNode* SceneGraphNode::childNode(const std::string& name)
void SceneGraphNode::updateCamera(Camera* camera) const{
psc origin = worldPosition();
int i = 0;
//int i = 0;
// the camera position
psc relative = camera->position();
+2 -2
View File
@@ -48,8 +48,8 @@
// projection
#include <openspace/rendering/planets/renderableplanetprojection.h>
#include <openspace/rendering/planets/SimpleSphereGeometryProjection.h>
#include <openspace/rendering/planets/PlanetGeometryProjection.h>
#include <openspace/rendering/planets/simplespheregeometryprojection.h>
#include <openspace/rendering/planets/planetgeometryprojection.h>
// std
+10 -7
View File
@@ -58,24 +58,27 @@ auto cmp = [](const ImageParams &a, const ImageParams &b)->bool{
std::vector<ImageParams> _timeStamps;
ImageSequencer::ImageSequencer()
: _nextCapture(0.0)
, _defaultCaptureImage(absPath("${OPENSPACE_DATA}/scene/common/textures/placeholder.png"))
{}
ImageSequencer& ImageSequencer::ref() {
assert(_sequencer != nullptr);
return *_sequencer;
}
void ImageSequencer::initialize(){
void ImageSequencer::initialize() {
assert(_sequencer == nullptr);
_sequencer = new ImageSequencer;
_sequencer->_nextCapture = 0.0;
_sequencer->_defaultCaptureImage = absPath("${OPENSPACE_DATA}/scene/common/textures/placeholder.png");
}
void ImageSequencer::deinitialize(){
void ImageSequencer::deinitialize() {
delete _sequencer;
_sequencer = nullptr;
}
void ImageSequencer::createImage(double t1, double t2, std::string instrument, std::string path){
void ImageSequencer::createImage(double t1, double t2, std::string instrument, std::string path) {
// insert
ImageParams image;
image.startTime = t1;
@@ -318,7 +321,7 @@ bool ImageSequencer::parsePlaybookFile(const std::string& fileName, std::string
return true;
}
bool ImageSequencer::loadSequence(const std::string dir){
bool ImageSequencer::loadSequence(const std::string& dir) {
ghoul::filesystem::Directory sequenceDir(dir, true);
std::vector<std::string> sequencePaths = sequenceDir.read(true, false); // check inputs
for (auto path : sequencePaths){
+1 -1
View File
@@ -106,7 +106,7 @@ glm::vec3 PowerScaledCoordinate::vec3() const
_vec[2] * pow(k, _vec[3]));
}
glm::dvec4& PowerScaledCoordinate::dvec4() const
glm::dvec4 PowerScaledCoordinate::dvec4() const
{
//return _vec;
return glm::dvec4(_vec);
+17 -6
View File
@@ -125,8 +125,22 @@ PowerScaledSphere::PowerScaledSphere(const PowerScaledScalar& radius, int segmen
}
}
PowerScaledSphere::~PowerScaledSphere()
PowerScaledSphere::PowerScaledSphere(const PowerScaledSphere& cpy)
: _vaoID(cpy._vaoID)
, _vBufferID(cpy._vBufferID)
, _iBufferID(cpy._iBufferID)
, _isize(cpy._isize)
, _vsize(cpy._vsize)
, _varray(new Vertex[_vsize])
, _iarray(new int[_isize])
{
// @TODO This needs to be tested ---abock
std::memcpy(_varray, cpy._varray, _vsize * sizeof(Vertex));
std::memcpy(_iarray, cpy._iarray, _isize * sizeof(int));
}
PowerScaledSphere::~PowerScaledSphere() {
if (_varray)
delete[] _varray;
if (_iarray)
@@ -140,10 +154,8 @@ PowerScaledSphere::~PowerScaledSphere()
glDeleteVertexArrays(1, &_vaoID);
}
bool PowerScaledSphere::initialize()
{
bool PowerScaledSphere::initialize() {
// Initialize and upload to graphics card
GLuint errorID;
if (_vaoID == 0)
glGenVertexArrays(1, &_vaoID);
@@ -188,8 +200,7 @@ bool PowerScaledSphere::initialize()
return true;
}
void PowerScaledSphere::render()
{
void PowerScaledSphere::render() {
glBindVertexArray(_vaoID); // select first VAO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID);
glDrawElements(GL_TRIANGLES, _isize, GL_UNSIGNED_INT, 0);
+43 -19
View File
@@ -46,9 +46,9 @@ void SpiceManager::initialize() {
_manager->_lastAssignedKernel = 0;
// Set the SPICE library to not exit the program if an error occurs
erract_c("SET", 0, "REPORT");
erract_c("SET", 0, static_cast<char*>("REPORT"));
// But we do not want SPICE to print the errors, we will fetch them ourselves
errprt_c("SET", 0, "NONE");
errprt_c("SET", 0, static_cast<char*>("NONE"));
}
void SpiceManager::deinitialize() {
@@ -59,8 +59,8 @@ void SpiceManager::deinitialize() {
_manager = nullptr;
// Set values back to default
erract_c("SET", 0, "DEFAULT");
errprt_c("SET", 0, "DEFAULT");
erract_c("SET", 0, static_cast<char*>("DEFAULT"));
errprt_c("SET", 0, static_cast<char*>("DEFAULT"));
}
SpiceManager& SpiceManager::ref() {
@@ -95,6 +95,7 @@ SpiceManager::KernelIdentifier SpiceManager::loadKernel(const std::string& fileP
}
FileSys.setCurrentDirectory(fileDirectory);
LINFO("Loading SPICE kernel '" << path << "'");
// Load the kernel
furnsh_c(path.c_str());
@@ -126,6 +127,7 @@ void SpiceManager::unloadKernel(KernelIdentifier kernelId) {
if (it != _loadedKernels.end()) {
// No need to check for errors as we do not allow empty path names
LINFO("Unloading SPICE kernel '" << it->path << "'");
unload_c(it->path.c_str());
_loadedKernels.erase(it);
}
@@ -142,6 +144,7 @@ void SpiceManager::unloadKernel(const std::string& filePath) {
[&path](const KernelInformation& info) { return info.path == path; });
if (it != _loadedKernels.end()) {
LINFO("Unloading SPICE kernel '" << path << "'");
unload_c(path.c_str());
_loadedKernels.erase(it);
}
@@ -239,11 +242,12 @@ bool SpiceManager::getValue(const std::string& body, const std::string& value,
return !hasError;
}
bool SpiceManager::spacecraftClockToET(const std::string craftIdCode, double& craftTicks, double& et){
bool SpiceManager::spacecraftClockToET(const std::string& craftIdCode, double& craftTicks, double& et){
int craftID;
getNaifId(craftIdCode, craftID);
sct2e_c(craftID, craftTicks, &et);
return true;
bool hasError = checkForError("Error transforming spacecraft clock of '" + craftIdCode + "' at time " + std::to_string(craftTicks));
return !hasError;
}
bool SpiceManager::getETfromDate(const std::string& timeString,
@@ -307,12 +311,12 @@ bool SpiceManager::getTargetPosition(const std::string& target,
psc& position,
double& lightTime) const
{
double pos[3] = { NULL, NULL, NULL };
double pos[3] = { 0.0, 0.0, 0.0};
spkpos_c(target.c_str(), ephemerisTime, referenceFrame.c_str(),
aberrationCorrection.c_str(), observer.c_str(), pos, &lightTime);
if (pos[0] == NULL || pos[1] == NULL || pos[2] == NULL)
if (pos[0] == 0.0 || pos[1] == 0.0|| pos[2] == 0.0)
return false;
position = PowerScaledCoordinate::CreatePowerScaledCoordinate(pos[0], pos[1], pos[2]);
@@ -321,18 +325,22 @@ bool SpiceManager::getTargetPosition(const std::string& target,
}
// do NOT remove this method.
void SpiceManager::frameConversion(glm::dvec3& v, const std::string from, const std::string to, double ephemerisTime) const{
bool SpiceManager::frameConversion(glm::dvec3& v, const std::string& from, const std::string& to, double ephemerisTime) const{
glm::dmat3 transform;
// get rotation matrix from frame A - frame B
pxform_c(from.c_str(), to.c_str(), ephemerisTime, (double(*)[3])glm::value_ptr(transform));
bool hasError = checkForError("Error converting from frame '" + from +
"' to frame '" + to + "' at time " + std::to_string(ephemerisTime));
if (hasError)
return false;
// re-express vector in new frame
mxv_c((double(*)[3])glm::value_ptr(transform), glm::value_ptr(v), glm::value_ptr(v));
return true;
}
glm::dvec3 SpiceManager::orthogonalProjection(glm::dvec3& v1, glm::dvec3& v2){
glm::dvec3 projected;
vproj_c(glm::value_ptr(v1), glm::value_ptr(v2), glm::value_ptr(projected));
return projected;
}
@@ -342,9 +350,12 @@ bool SpiceManager::targetWithinFieldOfView(const std::string& instrument,
const std::string& method,
const std::string& referenceFrame,
const std::string& aberrationCorrection,
double& targetEpoch) const{
double& targetEpoch,
bool& isVisible
) const
{
int visible ;
int visible;
fovtrg_c(instrument.c_str(),
target.c_str(),
method.c_str(),
@@ -353,7 +364,12 @@ bool SpiceManager::targetWithinFieldOfView(const std::string& instrument,
observer.c_str(),
&targetEpoch,
&visible);
return visible;
isVisible = (visible == SPICETRUE);
bool hasError = checkForError("Checking if target '" + target +
"' is in view of instrument '" + instrument + "' failed");
return !hasError;
}
bool SpiceManager::targetWithinFieldOfView(const std::string& instrument,
@@ -361,7 +377,9 @@ bool SpiceManager::targetWithinFieldOfView(const std::string& instrument,
const std::string& observer,
const std::string& method,
const std::string& aberrationCorrection,
double& targetEpoch) const{
double& targetEpoch,
bool& isVisible
) const{
int visible;
@@ -376,7 +394,12 @@ bool SpiceManager::targetWithinFieldOfView(const std::string& instrument,
observer.c_str(),
&targetEpoch,
&visible);
return visible;
isVisible = (visible == SPICETRUE);
bool hasError = checkForError("Checking if target '" + target +
"' is in view of instrument '" + instrument + "' failed");
return !hasError;
}
@@ -507,12 +530,12 @@ bool SpiceManager::getPositionPrimeMeridian(const std::string& fromFrame,
glm::dmat3& positionMatrix) const{
int id;
getNaifId(body.c_str(), id);
getNaifId(body, id);
tipbod_c(fromFrame.c_str(), id, ephemerisTime, (double(*)[3])glm::value_ptr(positionMatrix));
bool hasError = checkForError("Error retrieving position transform matrix from "
"frame '" + fromFrame + "' to frame '" + body +
"at time '" + std::to_string(ephemerisTime) + "'");
"at time '" + std::to_string(ephemerisTime) + "' for prime meridian");
positionMatrix = glm::transpose(positionMatrix);
return !hasError;
@@ -544,7 +567,8 @@ bool SpiceManager::getPositionTransformMatrix(const std::string& fromFrame,
bool hasError = checkForError("Error retrieving position transform matrix from "
"frame '" + fromFrame + "' to frame '" + toFrame +
"' at time '" + std::to_string(ephemerisTimeTo) + "'");
"' from time '" + std::to_string(ephemerisTimeFrom) + " to time '"
+ std::to_string(ephemerisTimeTo) + "'");
positionMatrix = glm::transpose(positionMatrix);
return !hasError;
@@ -690,10 +714,10 @@ void SpiceManager::applyTransformationMatrix(glm::dvec3& position,
}
bool SpiceManager::checkForError(std::string errorMessage) {
static char msg[1024];
int failed = failed_c();
if (failed) {
static char msg[1024];
if (!errorMessage.empty()) {
getmsg_c("LONG", 1024, msg);
LERROR(errorMessage);
-698
View File
@@ -1,698 +0,0 @@
//
// Copyright 2012-2015, Syoyo Fujita.
//
// Licensed under 2-clause BSD liecense.
//
//
// version 0.9.8: Fix multi-materials(per-face material ID).
// version 0.9.7: Support multi-materials(per-face material ID) per
// object/group.
// version 0.9.6: Support Ni(index of refraction) mtl parameter.
// Parse transmittance material parameter correctly.
// version 0.9.5: Parse multiple group name.
// Add support of specifying the base path to load material file.
// version 0.9.4: Initial suupport of group tag(g)
// version 0.9.3: Fix parsing triple 'x/y/z'
// version 0.9.2: Add more .mtl load support
// version 0.9.1: Add initial .mtl load support
// version 0.9.0: Initial
//
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include <openspace/util/tiny_obj_loader.h>
namespace tinyobj {
struct vertex_index {
int v_idx, vt_idx, vn_idx;
vertex_index(){};
vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx){};
vertex_index(int vidx, int vtidx, int vnidx)
: v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx){};
};
// for std::map
static inline bool operator<(const vertex_index &a, const vertex_index &b) {
if (a.v_idx != b.v_idx)
return (a.v_idx < b.v_idx);
if (a.vn_idx != b.vn_idx)
return (a.vn_idx < b.vn_idx);
if (a.vt_idx != b.vt_idx)
return (a.vt_idx < b.vt_idx);
return false;
}
struct obj_shape {
std::vector<float> v;
std::vector<float> vn;
std::vector<float> vt;
};
static inline bool isSpace(const char c) { return (c == ' ') || (c == '\t'); }
static inline bool isNewLine(const char c) {
return (c == '\r') || (c == '\n') || (c == '\0');
}
// Make index zero-base, and also support relative index.
static inline int fixIndex(int idx, int n) {
if (idx > 0) return idx - 1;
if (idx == 0) return 0;
return n + idx; // negative value = relative
}
static inline std::string parseString(const char *&token) {
std::string s;
token += strspn(token, " \t");
int e = strcspn(token, " \t\r");
s = std::string(token, &token[e]);
token += e;
return s;
}
static inline int parseInt(const char *&token) {
token += strspn(token, " \t");
int i = atoi(token);
token += strcspn(token, " \t\r");
return i;
}
static inline float parseFloat(const char *&token) {
token += strspn(token, " \t");
float f = (float)atof(token);
token += strcspn(token, " \t\r");
return f;
}
static inline void parseFloat2(float &x, float &y, const char *&token) {
x = parseFloat(token);
y = parseFloat(token);
}
static inline void parseFloat3(float &x, float &y, float &z,
const char *&token) {
x = parseFloat(token);
y = parseFloat(token);
z = parseFloat(token);
}
// Parse triples: i, i/j/k, i//k, i/j
static vertex_index parseTriple(const char *&token, int vsize, int vnsize,
int vtsize) {
vertex_index vi(-1);
vi.v_idx = fixIndex(atoi(token), vsize);
token += strcspn(token, "/ \t\r");
if (token[0] != '/') {
return vi;
}
token++;
// i//k
if (token[0] == '/') {
token++;
vi.vn_idx = fixIndex(atoi(token), vnsize);
token += strcspn(token, "/ \t\r");
return vi;
}
// i/j/k or i/j
vi.vt_idx = fixIndex(atoi(token), vtsize);
token += strcspn(token, "/ \t\r");
if (token[0] != '/') {
return vi;
}
// i/j/k
token++; // skip '/'
vi.vn_idx = fixIndex(atoi(token), vnsize);
token += strcspn(token, "/ \t\r");
return vi;
}
static unsigned int
updateVertex(std::map<vertex_index, unsigned int> &vertexCache,
std::vector<float> &positions, std::vector<float> &normals,
std::vector<float> &texcoords,
const std::vector<float> &in_positions,
const std::vector<float> &in_normals,
const std::vector<float> &in_texcoords, const vertex_index &i) {
const std::map<vertex_index, unsigned int>::iterator it = vertexCache.find(i);
if (it != vertexCache.end()) {
// found cache
return it->second;
}
assert(in_positions.size() > (unsigned int)(3 * i.v_idx + 2));
positions.push_back(in_positions[3 * i.v_idx + 0]);
positions.push_back(in_positions[3 * i.v_idx + 1]);
positions.push_back(in_positions[3 * i.v_idx + 2]);
if (i.vn_idx >= 0) {
normals.push_back(in_normals[3 * i.vn_idx + 0]);
normals.push_back(in_normals[3 * i.vn_idx + 1]);
normals.push_back(in_normals[3 * i.vn_idx + 2]);
}
if (i.vt_idx >= 0) {
texcoords.push_back(in_texcoords[2 * i.vt_idx + 0]);
texcoords.push_back(in_texcoords[2 * i.vt_idx + 1]);
}
unsigned int idx = positions.size() / 3 - 1;
vertexCache[i] = idx;
return idx;
}
void InitMaterial(material_t &material) {
material.name = "";
material.ambient_texname = "";
material.diffuse_texname = "";
material.specular_texname = "";
material.normal_texname = "";
for (int i = 0; i < 3; i++) {
material.ambient[i] = 0.f;
material.diffuse[i] = 0.f;
material.specular[i] = 0.f;
material.transmittance[i] = 0.f;
material.emission[i] = 0.f;
}
material.illum = 0;
material.dissolve = 1.f;
material.shininess = 1.f;
material.ior = 1.f;
material.unknown_parameter.clear();
}
static bool exportFaceGroupToShape(
shape_t &shape, std::map<vertex_index, unsigned int> vertexCache,
const std::vector<float> &in_positions,
const std::vector<float> &in_normals,
const std::vector<float> &in_texcoords,
const std::vector<std::vector<vertex_index> > &faceGroup,
const int material_id, const std::string &name, bool clearCache) {
if (faceGroup.empty()) {
return false;
}
// Flatten vertices and indices
for (size_t i = 0; i < faceGroup.size(); i++) {
const std::vector<vertex_index> &face = faceGroup[i];
vertex_index i0 = face[0];
vertex_index i1(-1);
vertex_index i2 = face[1];
size_t npolys = face.size();
// Polygon -> triangle fan conversion
for (size_t k = 2; k < npolys; k++) {
i1 = i2;
i2 = face[k];
unsigned int v0 = updateVertex(
vertexCache, shape.mesh.positions, shape.mesh.normals,
shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i0);
unsigned int v1 = updateVertex(
vertexCache, shape.mesh.positions, shape.mesh.normals,
shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i1);
unsigned int v2 = updateVertex(
vertexCache, shape.mesh.positions, shape.mesh.normals,
shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i2);
shape.mesh.indices.push_back(v0);
shape.mesh.indices.push_back(v1);
shape.mesh.indices.push_back(v2);
shape.mesh.material_ids.push_back(material_id);
}
}
shape.name = name;
if (clearCache)
vertexCache.clear();
return true;
}
std::string LoadMtl(std::map<std::string, int> &material_map,
std::vector<material_t> &materials,
std::istream &inStream) {
material_map.clear();
std::stringstream err;
material_t material;
int maxchars = 8192; // Alloc enough size.
std::vector<char> buf(maxchars); // Alloc enough size.
while (inStream.peek() != -1) {
inStream.getline(&buf[0], maxchars);
std::string linebuf(&buf[0]);
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\n')
linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\r')
linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
// Skip leading space.
const char *token = linebuf.c_str();
token += strspn(token, " \t");
assert(token);
if (token[0] == '\0')
continue; // empty line
if (token[0] == '#')
continue; // comment line
// new mtl
if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) {
// flush previous material.
if (!material.name.empty()) {
material_map.insert(
std::pair<std::string, int>(material.name, materials.size()));
materials.push_back(material);
}
// initial temporary material
InitMaterial(material);
// set new mtl name
char namebuf[4096];
token += 7;
sscanf(token, "%s", namebuf);
material.name = namebuf;
continue;
}
// ambient
if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) {
token += 2;
float r, g, b;
parseFloat3(r, g, b, token);
material.ambient[0] = r;
material.ambient[1] = g;
material.ambient[2] = b;
continue;
}
// diffuse
if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) {
token += 2;
float r, g, b;
parseFloat3(r, g, b, token);
material.diffuse[0] = r;
material.diffuse[1] = g;
material.diffuse[2] = b;
continue;
}
// specular
if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) {
token += 2;
float r, g, b;
parseFloat3(r, g, b, token);
material.specular[0] = r;
material.specular[1] = g;
material.specular[2] = b;
continue;
}
// transmittance
if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) {
token += 2;
float r, g, b;
parseFloat3(r, g, b, token);
material.transmittance[0] = r;
material.transmittance[1] = g;
material.transmittance[2] = b;
continue;
}
// ior(index of refraction)
if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) {
token += 2;
material.ior = parseFloat(token);
continue;
}
// emission
if (token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) {
token += 2;
float r, g, b;
parseFloat3(r, g, b, token);
material.emission[0] = r;
material.emission[1] = g;
material.emission[2] = b;
continue;
}
// shininess
if (token[0] == 'N' && token[1] == 's' && isSpace(token[2])) {
token += 2;
material.shininess = parseFloat(token);
continue;
}
// illum model
if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) {
token += 6;
material.illum = parseInt(token);
continue;
}
// dissolve
if ((token[0] == 'd' && isSpace(token[1]))) {
token += 1;
material.dissolve = parseFloat(token);
continue;
}
if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) {
token += 2;
material.dissolve = parseFloat(token);
continue;
}
// ambient texture
if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) {
token += 7;
material.ambient_texname = token;
continue;
}
// diffuse texture
if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) {
token += 7;
material.diffuse_texname = token;
continue;
}
// specular texture
if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) {
token += 7;
material.specular_texname = token;
continue;
}
// normal texture
if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) {
token += 7;
material.normal_texname = token;
continue;
}
// unknown parameter
const char *_space = strchr(token, ' ');
if (!_space) {
_space = strchr(token, '\t');
}
if (_space) {
int len = _space - token;
std::string key(token, len);
std::string value = _space + 1;
material.unknown_parameter.insert(
std::pair<std::string, std::string>(key, value));
}
}
// flush last material.
material_map.insert(
std::pair<std::string, int>(material.name, materials.size()));
materials.push_back(material);
return err.str();
}
std::string MaterialFileReader::operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap) {
std::string filepath;
if (!m_mtlBasePath.empty()) {
filepath = std::string(m_mtlBasePath) + matId;
} else {
filepath = matId;
}
std::ifstream matIStream(filepath.c_str());
return LoadMtl(matMap, materials, matIStream);
}
std::string LoadObj(std::vector<shape_t> &shapes,
std::vector<material_t> &materials, // [output]
const char *filename, const char *mtl_basepath) {
shapes.clear();
std::stringstream err;
std::ifstream ifs(filename);
if (!ifs) {
err << "Cannot open file [" << filename << "]" << std::endl;
return err.str();
}
std::string basePath;
if (mtl_basepath) {
basePath = mtl_basepath;
}
MaterialFileReader matFileReader(basePath);
return LoadObj(shapes, materials, ifs, matFileReader);
}
std::string LoadObj(std::vector<shape_t> &shapes,
std::vector<material_t> &materials, // [output]
std::istream &inStream, MaterialReader &readMatFn) {
std::stringstream err;
std::vector<float> v;
std::vector<float> vn;
std::vector<float> vt;
std::vector<std::vector<vertex_index> > faceGroup;
std::string name;
// material
std::map<std::string, int> material_map;
std::map<vertex_index, unsigned int> vertexCache;
int material = -1;
shape_t shape;
int maxchars = 8192; // Alloc enough size.
std::vector<char> buf(maxchars); // Alloc enough size.
while (inStream.peek() != -1) {
inStream.getline(&buf[0], maxchars);
std::string linebuf(&buf[0]);
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\n')
linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\r')
linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
// Skip leading space.
const char *token = linebuf.c_str();
token += strspn(token, " \t");
assert(token);
if (token[0] == '\0')
continue; // empty line
if (token[0] == '#')
continue; // comment line
// vertex
if (token[0] == 'v' && isSpace((token[1]))) {
token += 2;
float x, y, z;
parseFloat3(x, y, z, token);
v.push_back(x);
v.push_back(y);
v.push_back(z);
continue;
}
// normal
if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) {
token += 3;
float x, y, z;
parseFloat3(x, y, z, token);
vn.push_back(x);
vn.push_back(y);
vn.push_back(z);
continue;
}
// texcoord
if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) {
token += 3;
float x, y;
parseFloat2(x, y, token);
vt.push_back(x);
vt.push_back(y);
continue;
}
// face
if (token[0] == 'f' && isSpace((token[1]))) {
token += 2;
token += strspn(token, " \t");
std::vector<vertex_index> face;
while (!isNewLine(token[0])) {
vertex_index vi =
parseTriple(token, v.size() / 3, vn.size() / 3, vt.size() / 2);
face.push_back(vi);
int n = strspn(token, " \t\r");
token += n;
}
faceGroup.push_back(face);
continue;
}
// use mtl
if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) {
char namebuf[4096];
token += 7;
sscanf(token, "%s", namebuf);
// Create face group per material.
bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
faceGroup, material, name, true);
if (ret) {
faceGroup.clear();
}
if (material_map.find(namebuf) != material_map.end()) {
material = material_map[namebuf];
} else {
// { error!! material not found }
material = -1;
}
continue;
}
// load mtl
if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) {
char namebuf[4096];
token += 7;
sscanf(token, "%s", namebuf);
std::string err_mtl = readMatFn(namebuf, materials, material_map);
if (!err_mtl.empty()) {
faceGroup.clear(); // for safety
return err_mtl;
}
continue;
}
// group name
if (token[0] == 'g' && isSpace((token[1]))) {
// flush previous face group.
bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
faceGroup, material, name, true);
if (ret) {
shapes.push_back(shape);
}
shape = shape_t();
// material = -1;
faceGroup.clear();
std::vector<std::string> names;
while (!isNewLine(token[0])) {
std::string str = parseString(token);
names.push_back(str);
token += strspn(token, " \t\r"); // skip tag
}
assert(names.size() > 0);
// names[0] must be 'g', so skipt 0th element.
if (names.size() > 1) {
name = names[1];
} else {
name = "";
}
continue;
}
// object name
if (token[0] == 'o' && isSpace((token[1]))) {
// flush previous face group.
bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
faceGroup, material, name, true);
if (ret) {
shapes.push_back(shape);
}
// material = -1;
faceGroup.clear();
shape = shape_t();
// @todo { multiple object name? }
char namebuf[4096];
token += 2;
sscanf(token, "%s", namebuf);
name = std::string(namebuf);
continue;
}
// Ignore unknown command.
}
bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup,
material, name, true);
if (ret) {
shapes.push_back(shape);
}
faceGroup.clear(); // for safety
return err.str();
}
}
+10
View File
@@ -0,0 +1,10 @@
unreachableCode:src/properties/matrixproperty.cpp
duplicateBreak:src/properties/matrixproperty.cpp
unreachableCode:src/properties/scalarproperty.cpp
duplicateBreak:src/properties/scalarproperty.cpp
unreachableCode:src/properties/stringproperty.cpp
duplicateBreak:src/properties/stringproperty.cpp
unreachableCode:src/properties/vectorproperty.cpp
duplicateBreak:src/properties/vectorproperty.cpp
commaSeparatedReturn