Merged master into NewAtmosphere.

This commit is contained in:
Jonathas Costa
2017-05-18 12:33:08 -04:00
105 changed files with 2686 additions and 3276 deletions

View File

@@ -24,8 +24,7 @@ function preInitialization()
-- 6:20 -> 23:20 day before in UTC
]]--
openspace.time.setTime("2016-03-08T22:45:00")
--openspace.time.setTime("2016-03-08T22:45:00")
-- Total Lunar Eclipse Jan 31, 2018 at 10:51:13 UTC
-- Regions seeing, at least, some parts of the eclipse: North/East Europe,
@@ -33,6 +32,9 @@ function preInitialization()
-- Pacific, Atlantic, Indian Ocean, Arctic, Antarctica.
--openspace.time.setTime("2018-01-31T10:30:00")
openspace.time.setTime("2017-05-17T08:00:00")
dofile(openspace.absPath('${SCRIPTS}/bind_common_keys.lua'))
end
@@ -43,7 +45,7 @@ function postInitialization()
graphical settings for the renderables.
]]--
openspace.printInfo("Setting default values")
openspace.setPropertyValue("Sun.renderable.enabled", true)
openspace.setPropertyValue("Sun.renderable.enabled", false)
openspace.setPropertyValue("SunMarker.renderable.enabled", false)
openspace.setPropertyValue("EarthMarker.renderable.enabled", false)
openspace.setPropertyValue("Constellation Bounds.renderable.enabled", false)
@@ -67,8 +69,8 @@ return {
ScenePath = ".",
CommonFolder = "common",
Camera = {
--Focus = "Earth",
Focus = "Mars",
Focus = "Earth",
--Focus = "Mars",
--Position = {526781518487.171326, 257168309890.072144, -1381125204152.817383},
--Rotation = {-0.106166, 0.981574, -0.084545, 0.134513},
--Position = {-21230341452.764542, -75199905816.520981, 126295587136.952240},
@@ -87,8 +89,8 @@ return {
--"moon",
"lodglobes/earth",
"lodglobes/mars",
"lodglobes/moon",
--"lodglobes/mars",
--"lodglobes/moon",
--"toyvolume",
--"earth",

View File

@@ -57,7 +57,7 @@ return {
SegmentsPerPatch = 64,
Atmosphere = {
-- Atmosphere radius in Km
AtmoshereRadius = 6420,
AtmoshereRadius = 6450,
PlanetRadius = 6378.1366,
PlanetAverageGroundReflectance = 0.1,
Rayleigh = {

View File

@@ -4,7 +4,7 @@ return {
Parent = "SolarSystem",
Renderable = {
Type = "RenderableSphere",
Size = { 10, 20 },
Size = 10E20,
Segments = 40,
Texture = "textures/eso0932a_blend.png",
Orientation = "Inside/Outside"

View File

@@ -4,7 +4,7 @@ return {
Parent = "SolarSystem",
Renderable = {
Type = "RenderableSphere",
Size = { 10, 22 },
Size = 10E22,
Segments = 40,
Texture = "textures/DarkUniverse_mellinger_8k.jpg",
Orientation = "Inside/Outside"

View File

@@ -30,7 +30,7 @@ return {
},
PerformShading = false,
},
Transformation = {
Transform = {
Translation = {
Type = "SpiceTranslation",
Body = "SUN",
@@ -56,7 +56,7 @@ return {
Texture = "textures/sun-glare.png",
BlendMode = "Additive"
},
Transformation = {
Transform = {
Translation = {
Type = "SpiceTranslation",
Body = "SUN",

View File

@@ -6,6 +6,7 @@
<span class="documentation-key">{{key}}</span> <span class="documentation-type">{{#if remoteScripting}}Remote scripting{{else}}Local scripting{{/if}}</span>
</a>
<p>{{script}}</p>
<p>{{documentation}}</p>
</p>
</div>
</div>

View File

@@ -18,7 +18,6 @@
<div class="container-fluid documentation-container">
<h1>OpenSpace Scene Properties</h1>
<p>Version: {{version.[0]}}.{{version.[1]}}.{{version.[2]}}</p>
<p>Scene name: {{sceneFilename}}</p>
<p>Generated: {{generationTime}}</p>
{{#each propertyOwners}}

View File

@@ -53,7 +53,7 @@ window.onload = function () {
var data = {
propertyOwners: propertyOwners,
version: version,
sceneFilename: sceneFilename,
// sceneFilename: sceneFilename,
generationTime: generationTime
}

View File

@@ -26,8 +26,9 @@
#define __OPENSPACE_CORE___DOCUMENTATIONENGINE___H__
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/documentationgenerator.h>
#include <ghoul/designpattern/singleton.h>
#include <ghoul/misc/exception.h>
namespace openspace {
@@ -38,7 +39,9 @@ namespace documentation {
* produced in the application an write them out as a documentation file for human
* consumption.
*/
class DocumentationEngine : public ghoul::Singleton<DocumentationEngine> {
class DocumentationEngine : public ghoul::Singleton<DocumentationEngine>
, public DocumentationGenerator
{
public:
/**
* This exception is thrown by the addDocumentation method if a provided Documentation
@@ -57,16 +60,7 @@ public:
Documentation documentation;
};
/**
* Write the collected Documentation%s to disk at the \p filename in the specified
* \p type. A new file is created and silently overwritten in the location that
* \p filename is pointed to.
* \param filename The file that is to be created containing all the Documentation
* information.
* \param type The type of documentation that is written. Currently allowed values are
* \c text and \c html
*/
void writeDocumentation(const std::string& filename, const std::string& type);
DocumentationEngine();
/**
* Adds the \p documentation to the list of Documentation%s that are written to a
@@ -90,6 +84,8 @@ public:
static DocumentationEngine& ref();
private:
std::string generateJson() const override;
/// The list of all Documentation%s that are stored by the DocumentationEngine
std::vector<Documentation> _documentations;

View File

@@ -0,0 +1,105 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* 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 __OPENSPACE_CORE___DOCUMENTATIONGENERATOR___H__
#define __OPENSPACE_CORE___DOCUMENTATIONGENERATOR___H__
#include <string>
#include <vector>
namespace openspace {
/*
* This abstract class is used for instances when another class has the ability to
* generate a Handlebar generated documentation file that contains valuable information
* for the user. Instances of this are the DocumentationEngine results, the list of
* Property%s generated by the Scene, or the FactoryEngine results. The documentation is
* generated through the writeDocumentation method.
*
* The concrete subclass needs to overload the generateJson class that will return the
* Json that is parsed by Handlebar to generate the webpage.
*
* A list of Handlebar templates, the variable name for the result of the generateJson
* method, and the Javascript file that contains additional logic is passed in the
* constructor.
*/
class DocumentationGenerator {
public:
/// This struct contains a single Handlebar template, with the name and the filename
struct HandlebarTemplate {
std::string name; ///< The name of the Handlebar template defined in \m filename
std::string filename; ///< The filename referenced in the \m name
};
/**
* The constructor that is used to set the member variables later used in the
* writeDocumentation method.
* \param name The name of the written documentation
* \param jsonName The variable name of the value generated by the generateJson
* \param handlebarTemplates A list of Handlebar templates that is added to the
* documentation file
* \param javascriptFilename The path to a Javascript source file that is added to the
* documentation and that can contain additional functionality
* \pre name must not be empty
* \pre jsonName must not be empty
* \pre Each handlebarTemplates' \c name must not be empty
* \pre javascriptFilename must not be empty
*/
DocumentationGenerator(std::string name, std::string jsonName,
std::vector<HandlebarTemplate> handlebarTemplates,
std::string javascriptFilename);
/// Default constructor
virtual ~DocumentationGenerator() = default;
/**
* Create the documentation into the provided filename. Any existing file will be
* silently overwritten. This method will call the generateJson method that can be
* used by concrete subclasses to provide the actual data that is provided in the
* documentation.
* \param filename The filename in which the documentation is written
*/
void writeDocumentation(const std::string& filename);
protected:
/**
* This abstract method is used by concrete subclasses to provide the actual data that
* is used in the documentation written by this DocumentationGenerator class. The JSON
* string returned by this function will be stored in the variable with the
* \c jsonName as passed in the constructor.
* \return A JSON script that is parsed and stored in the variable passed in the
* DocumentationGenerator constructor
*/
virtual std::string generateJson() const = 0;
private:
const std::string _name;
const std::string _jsonName;
const std::vector<HandlebarTemplate> _handlebarTemplates;
const std::string _javascriptFile;
};
} // namespace openspace
#endif // __OPENSPACE_CORE___DOCUMENTATIONGENERATOR___H__

View File

@@ -25,9 +25,11 @@
#ifndef __OPENSPACE_CORE___INTERACTIONHANDLER___H__
#define __OPENSPACE_CORE___INTERACTIONHANDLER___H__
#include <openspace/documentation/documentationgenerator.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/interaction/interactionmode.h>
#include <openspace/network/parallelconnection.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
@@ -47,8 +49,7 @@ class SceneGraphNode;
namespace interaction {
class InteractionHandler : public properties::PropertyOwner
class InteractionHandler : public properties::PropertyOwner, public DocumentationGenerator
{
public:
InteractionHandler();
@@ -121,7 +122,6 @@ public:
void saveCameraStateToFile(const std::string& filepath);
void restoreCameraStateFromFile(const std::string& filepath);
void writeKeyboardDocumentation(const std::string& type, const std::string& file);
private:
using Synchronized = ghoul::Boolean;
@@ -131,6 +131,8 @@ private:
Synchronized synchronization;
std::string documentation;
};
std::string generateJson() const override;
void setInteractionMode(std::shared_ptr<InteractionMode> interactionMode);

View File

@@ -62,26 +62,25 @@ public:
* Returns the name of the MissionPhase.
* \return The name of the MissionPhase
*/
const std::string& name() const;
std::string name() const;
/**
* Returns the TimeRange of the MissionPhase.
* \return The TimeRange of the MissionPhase
*/
const TimeRange& timeRange() const;
TimeRange timeRange() const;
/**
* Returns the description of the MissionPhase.
* \return The description of the MissionPhase
*/
const std::string& description() const;
std::string description() const;
/**
* Returns all subphases sorted by start time.
* \return All subphases sorted by start time
*/
const std::vector<MissionPhase>& phases() const;
std::vector<MissionPhase> phases() const;
using Trace = std::vector<std::reference_wrapper<const MissionPhase>>;
@@ -111,6 +110,7 @@ protected:
* \param time The time which the subphases have to cover to be added to the \p trace
* \param trace The list of MissionPhase%s that are active during the time \p time
* \param maxDepth The maximum depth of levels that will be considered
* \pre maxDepth must not be negative
*/
void phaseTrace(double time, Trace& trace, int maxDepth) const;
@@ -139,7 +139,7 @@ using Mission = MissionPhase;
* \pre \p filename must not contain tokens
* \pre \p filename must exist
*/
Mission missionFromFile(std::string filename);
Mission missionFromFile(const std::string& filename);
} // namespace openspace

View File

@@ -30,6 +30,7 @@
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/numericalproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
//glm includes
#include <glm/gtx/quaternion.hpp>

View File

@@ -28,20 +28,21 @@
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
// Forward declare to minimize dependencies
namespace ghoul {
namespace opengl {
class ProgramObject;
class Texture;
}
class Dictionary;
}
} // namespace ghoul
namespace openspace {
struct RenderData;
struct UpdateData;
struct RendererTasks;
namespace documentation { struct Documentation; }
// Forward declare to minimize dependencies

View File

@@ -25,21 +25,13 @@
#ifndef __OPENSPACE_CORE___RENDERENGINE___H__
#define __OPENSPACE_CORE___RENDERENGINE___H__
#include <openspace/performance/performancemanager.h>
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/intproperty.h>
#include <openspace/properties/triggerproperty.h>
#include <openspace/rendering/raycastermanager.h>
#include <openspace/rendering/deferredcastermanager.h>
#include <openspace/rendering/renderer.h>
#include <openspace/rendering/screenspacerenderable.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/util/syncdata.h>
namespace ghoul {
namespace fontrendering {
@@ -50,17 +42,22 @@ namespace opengl {
}
class Dictionary;
class SharedMemory;
}
} // namespace ghoul
namespace openspace {
// Forward declare to minimize dependencies
namespace performance { class PerformanceManager; }
namespace scripting { struct LuaLibrary; }
class Camera;
class SyncBuffer;
class RaycasterManager;
class DeferredcasterManager;
class Renderer;
class Scene;
class SceneManager;
class ScreenLog;
class ScreenSpaceRenderable;
class Syncable;
class SyncBuffer;
class RenderEngine : public properties::PropertyOwner {
public:
@@ -77,7 +74,7 @@ public:
};
RenderEngine();
~RenderEngine() = default;
~RenderEngine();
void initialize();
void initializeGL();
@@ -207,6 +204,7 @@ private:
//FrametimeType _frametimeType;
properties::BoolProperty _showDate;
properties::BoolProperty _showInfo;
properties::BoolProperty _showLog;
@@ -215,7 +213,7 @@ private:
properties::BoolProperty _applyWarping;
properties::BoolProperty _showFrameNumber;
properties::BoolProperty _disableMasterRendering;
properties::BoolProperty _disableSceneOnMaster;
properties::BoolProperty _disableSceneTranslationOnMaster;
float _globalBlackOutFactor;
float _fadeDuration;

View File

@@ -25,6 +25,8 @@
#ifndef __OPENSPACE_CORE___SCENE___H__
#define __OPENSPACE_CORE___SCENE___H__
#include <openspace/documentation/documentationgenerator.h>
#include <vector>
#include <map>
#include <set>
@@ -45,7 +47,7 @@ class SceneGraphNode;
// Notifications:
// SceneGraphFinishedLoading
class Scene {
class Scene : public DocumentationGenerator {
public:
using UpdateDependencies = ghoul::Boolean;
@@ -135,11 +137,6 @@ public:
*/
const std::map<std::string, SceneGraphNode*>& nodesByName() const;
/**
* Output property documentation to a file.
*/
void writePropertyDocumentation(const std::string& filename, const std::string& type, const std::string& sceneFilename);
/**
* Returns the Lua library that contains all Lua functions available to change the
* scene graph. The functions contained are
@@ -152,7 +149,9 @@ public:
static documentation::Documentation Documentation();
private:
private:
std::string generateJson() const override;
void sortTopologically();
std::unique_ptr<SceneGraphNode> _root;

View File

@@ -25,16 +25,12 @@
#ifndef __OPENSPACE_CORE___SCENEGRAPHNODE___H__
#define __OPENSPACE_CORE___SCENEGRAPHNODE___H__
#include <openspace/rendering/renderable.h>
#include <openspace/scene/translation.h>
#include <openspace/scene/rotation.h>
#include <openspace/scene/scale.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/scene/scene.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/glm.h>
#include <ghoul/misc/boolean.h>
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <vector>
@@ -43,6 +39,16 @@ namespace ghoul { class Dictionary; }
namespace openspace {
class Camera;
struct RenderData;
class Renderable;
struct RendererTasks;
class Rotation;
class Translation;
class Scale;
class Scene;
struct UpdateData;
namespace documentation { struct Documentation; }
class SceneGraphNode : public properties::PropertyOwner {

View File

@@ -25,9 +25,11 @@
#ifndef __OPENSPACE_CORE___SCRIPTENGINE___H__
#define __OPENSPACE_CORE___SCRIPTENGINE___H__
#include <openspace/scripting/lualibrary.h>
#include <openspace/documentation/documentationgenerator.h>
#include <openspace/util/syncdata.h>
#include <openspace/scripting/lualibrary.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/lua/luastate.h>
#include <ghoul/misc/boolean.h>
@@ -50,9 +52,12 @@ namespace scripting {
* <code>openspace</code> namespac prefix in Lua. The same functions can be exposed to
* other Lua states by passing them to the #initializeLuaState method.
*/
class ScriptEngine : public Syncable {
class ScriptEngine : public Syncable, public DocumentationGenerator {
public:
using RemoteScripting = ghoul::Boolean;
ScriptEngine();
/**
* Initializes the internal Lua state and registers a common set of library functions
* \throw LuaRuntimeException If the creation of the new Lua state fails
@@ -73,8 +78,6 @@ public:
bool runScript(const std::string& script);
bool runScriptFile(const std::string& filename);
void writeDocumentation(const std::string& filename, const std::string& type) const;
bool writeLog(const std::string& script);
virtual void presync(bool isMaster);
@@ -106,6 +109,8 @@ private:
void addBaseLibrary();
void remapPrintFunction();
std::string generateJson() const override;
ghoul::lua::LuaState _state;
std::set<LuaLibrary> _registeredLibraries;

View File

@@ -25,6 +25,8 @@
#ifndef __OPENSPACE_CORE___FACTORYMANAGER___H__
#define __OPENSPACE_CORE___FACTORYMANAGER___H__
#include <openspace/documentation/documentationgenerator.h>
#include <ghoul/misc/exception.h>
#include <ghoul/misc/templatefactory.h>
@@ -37,7 +39,7 @@ namespace openspace {
* them available through the #addFactory and #factory methods. Each
* ghoul::TemplateFactory can only be added once and can be accessed by its type.
*/
class FactoryManager {
class FactoryManager : public DocumentationGenerator {
public:
/// This exception is thrown if the ghoul::TemplateFactory could not be found in the
/// #factory method
@@ -55,6 +57,8 @@ public:
/// The type describing the ghoul::TemplateFactory that could not be found
std::string type;
};
FactoryManager();
/**
* Static initializer that initializes the static member. This needs to be done before
@@ -104,17 +108,9 @@ public:
template <class T>
ghoul::TemplateFactory<T>* factory() const;
/**
* Writes a documentation for the FactoryMananger that contains all of the registered
* factories and for each factory all registered class names.
* \param file The file to which the documentation will be written
* \param type The type of documentation that will be written
* \pre \p file must not be empty
* \pre \p type must not be empty
*/
void writeDocumentation(const std::string& file, const std::string& type);
private:
std::string generateJson() const override;
/// Singleton member for the Factory Manager
static FactoryManager* _manager;

View File

@@ -75,7 +75,12 @@ public:
* have in order to be stored in the ScreenLog
*/
ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel = LogLevel::Info);
/**
* Destructor
*/
~ScreenLog();
/**
* Overwritten ghoul::loggling::Log method that is called whenever a new log message
* shall be stored.

View File

@@ -29,12 +29,13 @@
#include <string>
#include <vector>
#include <openspace/rendering/deferredcaster.h>
#include <ghoul/opengl/textureunit.h>
//#include <ghoul/opengl/textureunit.h>
namespace ghoul {
namespace opengl {
class Texture;
class Texture;
class ProgramObject;
}
}

View File

@@ -28,7 +28,6 @@ set(HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/rendering/modelgeometry.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablepath.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphere.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphericalgrid.h
@@ -47,7 +46,6 @@ set(SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/rendering/modelgeometry.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablepath.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphere.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablesphericalgrid.cpp

View File

@@ -32,7 +32,6 @@
#include <ghoul/misc/assert.h>
#include <modules/base/rendering/renderablemodel.h>
#include <modules/base/rendering/renderablepath.h>
#include <modules/base/rendering/renderablesphere.h>
#include <modules/base/rendering/renderablesphericalgrid.h>
#include <modules/base/rendering/renderabletrailorbit.h>
@@ -77,7 +76,6 @@ void BaseModule::internalInitialize() {
ghoul_assert(fRenderable, "Renderable factory was not created");
fRenderable->registerClass<RenderableModel>("RenderableModel");
fRenderable->registerClass<RenderablePath>("RenderablePath");
fRenderable->registerClass<RenderablePlane>("RenderablePlane");
fRenderable->registerClass<RenderableSphere>("RenderableSphere");
fRenderable->registerClass<RenderableSphericalGrid>("RenderableSphericalGrid");
@@ -97,7 +95,7 @@ void BaseModule::internalInitialize() {
auto fScale = FactoryManager::ref().factory<Scale>();
ghoul_assert(fScale, "Scale factory was not created");
fScale->registerClass <StaticScale> ("StaticScale");
fScale->registerClass<StaticScale>("StaticScale");
auto fModelGeometry = FactoryManager::ref().factory<modelgeometry::ModelGeometry>();
ghoul_assert(fModelGeometry, "Model geometry factory was not created");
@@ -106,10 +104,16 @@ void BaseModule::internalInitialize() {
std::vector<documentation::Documentation> BaseModule::documentations() const {
return {
StaticScale::Documentation(),
StaticTranslation::Documentation(),
RenderableModel::Documentation(),
RenderablePlane::Documentation(),
RenderableSphere::Documentation(),
RenderableTrailOrbit::Documentation(),
RenderableTrailTrajectory::Documentation(),
ScreenSpaceFramebuffer::Documentation(),
ScreenSpaceImage::Documentation(),
StaticRotation::Documentation(),
StaticScale::Documentation(),
StaticTranslation::Documentation(),
modelgeometry::ModelGeometry::Documentation(),
};
}

View File

@@ -25,20 +25,24 @@
#include <modules/base/rendering/modelgeometry.h>
#include <openspace/documentation/verifier.h>
#include <openspace/rendering/renderable.h>
#include <openspace/util/factorymanager.h>
#include <ghoul/filesystem/cachemanager.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/misc/invariants.h>
#include <fstream>
namespace {
const char* _loggerCat = "ModelGeometry";
const char* keyGeomModelFile = "GeometryFile";
const char* KeyName = "Name";
const char* KeyType = "Type";
const char* KeyGeomModelFile = "GeometryFile";
const int8_t CurrentCacheVersion = 3;
const char* keyType = "Type";
const char* keyName = "Name";
}
} // namespace
namespace openspace {
namespace modelgeometry {
@@ -50,13 +54,13 @@ documentation:: Documentation ModelGeometry::Documentation() {
"base_geometry_model",
{
{
keyType,
KeyType,
new StringVerifier,
"The type of the Model Geometry that should be generated",
Optional::No
},
{
keyGeomModelFile,
KeyGeomModelFile,
new StringVerifier,
"The file that should be loaded in this ModelGeometry. The file can "
"contain filesystem tokens or can be specified relatively to the "
@@ -71,25 +75,18 @@ documentation:: Documentation ModelGeometry::Documentation() {
std::unique_ptr<ModelGeometry> ModelGeometry::createFromDictionary(
const ghoul::Dictionary& dictionary)
{
if (!dictionary.hasKeyAndValue<std::string>(keyType)) {
if (!dictionary.hasKeyAndValue<std::string>(KeyType)) {
throw ghoul::RuntimeError("Dictionary did not contain a key 'Type'");
}
std::string geometryType = dictionary.value<std::string>(keyType);
const std::string geometryType = dictionary.value<std::string>(KeyType);
auto factory = FactoryManager::ref().factory<ModelGeometry>();
std::unique_ptr<ModelGeometry> result = factory->create(geometryType, dictionary);
if (result == nullptr) {
throw ghoul::RuntimeError(
"Failed to create a ModelGeometry object of type '" + geometryType + "'"
);
}
return result;
return factory->create(geometryType, dictionary);;
}
ModelGeometry::ModelGeometry(const ghoul::Dictionary& dictionary)
: properties::PropertyOwner("ModelGeometry")
, _parent(nullptr)
, _mode(GL_TRIANGLES)
{
documentation::testSpecificationAndThrow(
@@ -98,11 +95,7 @@ ModelGeometry::ModelGeometry(const ghoul::Dictionary& dictionary)
"ModelGeometry"
);
std::string name;
bool success = dictionary.getValue(keyName, name);
ghoul_assert(success, "Name tag was not present");
_file = absPath(dictionary.value<std::string>(keyGeomModelFile));
_file = absPath(dictionary.value<std::string>(KeyGeomModelFile));
}
double ModelGeometry::boundingRadius() const {
@@ -119,10 +112,6 @@ double ModelGeometry::boundingRadius() const {
return maxDist;
}
ModelGeometry::~ModelGeometry() {
}
void ModelGeometry::render() {
glBindVertexArray(_vaoID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo);
@@ -135,39 +124,67 @@ void ModelGeometry::changeRenderMode(const GLenum mode) {
}
bool ModelGeometry::initialize(Renderable* parent) {
_parent = parent;
float maximumDistanceSquared = 0;
for (auto v: _vertices)
{
for (const Vertex& v : _vertices) {
maximumDistanceSquared = glm::max(
glm::pow(v.location[0], 2.f) +
glm::pow(v.location[1], 2.f) +
glm::pow(v.location[2], 2.f), maximumDistanceSquared);
}
_parent->setBoundingSphere(glm::sqrt(maximumDistanceSquared));
parent->setBoundingSphere(glm::sqrt(maximumDistanceSquared));
if (_vertices.empty())
if (_vertices.empty()) {
return false;
}
glGenVertexArrays(1, &_vaoID);
glGenBuffers(1, &_vbo);
glGenBuffers(1, &_ibo);
glBindVertexArray(_vaoID);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, _vertices.size() * sizeof(Vertex), _vertices.data(), GL_STATIC_DRAW);
glBufferData(
GL_ARRAY_BUFFER,
_vertices.size() * sizeof(Vertex),
_vertices.data(),
GL_STATIC_DRAW
);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, location)));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, tex)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, normal)));
glVertexAttribPointer(
0,
4,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, location))
);
glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, tex))
);
glVertexAttribPointer(
2,
3,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, normal))
);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size() * sizeof(int), _indices.data(), GL_STATIC_DRAW);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
_indices.size() * sizeof(int),
_indices.data(),
GL_STATIC_DRAW
);
glBindVertexArray(0);
@@ -181,37 +198,42 @@ void ModelGeometry::deinitialize() {
}
bool ModelGeometry::loadObj(const std::string& filename) {
std::string cachedFile = FileSys.cacheManager()->cachedFilename(
const std::string cachedFile = FileSys.cacheManager()->cachedFilename(
filename,
ghoul::filesystem::CacheManager::Persistent::Yes
);
);
bool hasCachedFile = FileSys.fileExists(cachedFile);
const bool hasCachedFile = FileSys.fileExists(cachedFile);
if (hasCachedFile) {
LINFO("Cached file '" << cachedFile << "' used for Model file '" << filename << "'");
LINFO("Cached file '" << cachedFile << "' used for file '" << filename << "'");
bool success = loadCachedFile(cachedFile);
if (success)
const bool success = loadCachedFile(cachedFile);
if (success) {
return true;
else
}
else {
FileSys.cacheManager()->removeCacheFile(filename);
}
// Intentional fall-through to the 'else' computation to generate the cache
// file for the next run
}
else {
LINFO("Cached file '" << cachedFile << "' used for Model file '" << filename << "' not found");
LINFO(
"Cached file '" << cachedFile << "' for file '" << filename << "' not found"
);
}
LINFO("Loading Model file '" << filename << "'");
bool success = loadModel(filename);
const bool modelSuccess = loadModel(filename);
if (!success)
if (!modelSuccess) {
return false;
}
LINFO("Saving cache");
success = saveCachedFile(cachedFile);
const bool cacheSuccess = saveCachedFile(cachedFile);
return success;
return cacheSuccess;
}
bool ModelGeometry::saveCachedFile(const std::string& filename) {
@@ -271,22 +293,6 @@ bool ModelGeometry::loadCachedFile(const std::string& filename) {
}
}
bool ModelGeometry::getVertices(std::vector<Vertex>* vertexList) {
vertexList->clear();
for (auto v : _vertices)
vertexList->push_back(v);
return !(vertexList->empty());
}
bool ModelGeometry::getIndices(std::vector<int>* indexList) {
indexList->clear();
for (auto i : _indices)
indexList->push_back(i);
return !(indexList->empty());
}
void ModelGeometry::setUniforms(ghoul::opengl::ProgramObject&) {}
} // namespace modelgeometry

View File

@@ -27,36 +27,46 @@
#include <openspace/properties/propertyowner.h>
#include <modules/base/rendering/renderablemodel.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul { class Dictionary; }
#include <memory>
namespace ghoul {
class Dictionary;
namespace opengl { class ProgramObject; }
} // namespace ghoul
namespace openspace {
namespace documentation { struct Documentation; }
class Renderable;
namespace documentation { struct Documentation; }
namespace modelgeometry {
class ModelGeometry : public properties::PropertyOwner {
public:
static std::unique_ptr<ModelGeometry> createFromDictionary(
const ghoul::Dictionary& dictionary
);
struct Vertex {
GLfloat location[4];
GLfloat tex[2];
GLfloat normal[3];
};
static std::unique_ptr<ModelGeometry> createFromDictionary(
const ghoul::Dictionary& dictionary
);
ModelGeometry(const ghoul::Dictionary& dictionary);
virtual ~ModelGeometry();
virtual ~ModelGeometry() = default;
virtual bool initialize(Renderable* parent);
virtual void deinitialize();
void render();
virtual bool loadModel(const std::string& filename) = 0;
void changeRenderMode(const GLenum mode);
bool getVertices(std::vector<Vertex>* vertexList);
bool getIndices(std::vector<int>* indexList);
//bool getVertices(std::vector<Vertex>* vertexList);
//bool getIndices(std::vector<int>* indexList);
double boundingRadius() const;
@@ -65,8 +75,6 @@ public:
static documentation::Documentation Documentation();
protected:
Renderable* _parent;
bool loadObj(const std::string& filename);
bool loadCachedFile(const std::string& filename);
bool saveCachedFile(const std::string& filename);

View File

@@ -24,15 +24,9 @@
#include <modules/base/rendering/multimodelgeometry.h>
#include "ghoul/logging/logmanager.h"
#include "ghoul/io/model/modelreadermultiformat.h"
#include "ghoul/opengl/vertexbufferobject.h"
#include <openspace/util/powerscaledcoordinate.h>
namespace {
const std::string _loggerCat = "MultiModelGeometry";
}
#include <cstring>
namespace openspace {
namespace modelgeometry {
@@ -43,25 +37,13 @@ MultiModelGeometry::MultiModelGeometry(const ghoul::Dictionary& dictionary)
loadObj(_file);
}
bool MultiModelGeometry::initialize(Renderable* parent) {
bool success = ModelGeometry::initialize(parent);
return success;
}
void MultiModelGeometry::deinitialize() {
ModelGeometry::deinitialize();
}
bool MultiModelGeometry::loadModel(const std::string& filename) {
ghoul::io::ModelReaderMultiFormat modelReader;
std::vector<ghoul::io::ModelReaderBase::Vertex> vertices;
std::vector<int> indices;
modelReader.loadModel(filename, vertices, indices);
ghoul::io::ModelReaderMultiFormat().loadModel(filename, vertices, indices);
_vertices.reserve(vertices.size());
for (const auto & v : vertices) {
for (const ghoul::io::ModelReaderBase::Vertex& v : vertices) {
Vertex vv;
memcpy(vv.location, v.location, sizeof(GLfloat) * 3);
vv.location[3] = 1.0;

View File

@@ -38,9 +38,6 @@ class MultiModelGeometry : public ModelGeometry {
public:
MultiModelGeometry(const ghoul::Dictionary& dictionary);
bool initialize(Renderable* parent) override;
void deinitialize() override;
private:
bool loadModel(const std::string& filename);
};

View File

@@ -24,129 +24,141 @@
#include <modules/base/rendering/renderablemodel.h>
#include <openspace/rendering/renderengine.h>
#include <modules/base/rendering/modelgeometry.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/configurationmanager.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/filesystem/filesystem.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/time.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/time.h>
#include <openspace/util/updatestructures.h>
#include <openspace/scene/scene.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/misc/invariants.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
namespace {
const std::string _loggerCat = "RenderableModel";
const char* keyGeometry = "Geometry";
const char* KeyGeometry = "Geometry";
const char* KeyTexture = "Textures.Color";
const char* KeyModelTransform = "Rotation.ModelTransform";
const char* KeyFading = "Shading.Fadeable";
const char* keyBody = "Body";
const char* keyStart = "StartTime";
const char* keyEnd = "EndTime";
const char* keyFading = "Shading.Fadeable";
const char* keyModelTransform = "Rotation.ModelTransform";
//const std::string keyGhosting = "Shading.Ghosting";
}
} // namespace
namespace openspace {
documentation::Documentation RenderableModel::Documentation() {
using namespace documentation;
return {
"RenderableModel",
"base_renderable_model",
{
{
KeyGeometry,
new ReferencingVerifier("base_geometry_model"),
"This specifies the model that is rendered by the Renderable.",
Optional::No
},
{
KeyTexture,
new StringVerifier,
"A color texture that can be applied to the model specified by the "
"Geometry.",
Optional::Yes
},
{
KeyModelTransform,
new DoubleMatrix3Verifier,
"Specifies a distinct transformation matrix that is applied to the "
"model. If it is not specified, it is equal to the Identity matrix.",
Optional::Yes
},
{
KeyFading,
new BoolVerifier,
"Specifies whether the model should be periodically fading in and out. "
"If this value is not specified, it will not fade.",
Optional::Yes
}
}
};
}
RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _geometry(nullptr)
, _colorTexturePath("colorTexture", "Color Texture")
, _performFade("performFading", "Perform Fading", false)
, _performShading("performShading", "Perform Shading", true)
, _fading("fading", "Fade", 0)
, _debugModelRotation("modelrotation", "Model Rotation", glm::vec3(0.f), glm::vec3(0.f), glm::vec3(360.f))
, _programObject(nullptr)
, _texture(nullptr)
, _geometry(nullptr)
, _alpha(1.f)
//, _isGhost(false)
, _performShading("performShading", "Perform Shading", true)
, _frameCount(0)
, _modelTransform(1.0)
{
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(success, "Name was not passed to RenderableModel");
ghoul_precondition(
dictionary.hasKeyAndValue<std::string>(SceneGraphNode::KeyName),
"Name was not passed to RenderableModel"
);
ghoul::Dictionary geometryDictionary;
success = dictionary.getValue(keyGeometry, geometryDictionary);
if (success) {
geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = modelgeometry::ModelGeometry::createFromDictionary(geometryDictionary);
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableModel"
);
if (dictionary.hasKey(KeyGeometry)) {
std::string name = dictionary.value<std::string>(SceneGraphNode::KeyName);
ghoul::Dictionary dict = dictionary.value<ghoul::Dictionary>(KeyGeometry);
dict.setValue(SceneGraphNode::KeyName, name);
_geometry = modelgeometry::ModelGeometry::createFromDictionary(dict);
}
std::string texturePath = "";
success = dictionary.getValue("Textures.Color", texturePath);
if (success)
_colorTexturePath = absPath(texturePath);
if (dictionary.hasKey(KeyTexture)) {
_colorTexturePath = absPath(dictionary.value<std::string>(KeyTexture));
}
if (dictionary.hasKey(KeyModelTransform)) {
_modelTransform = dictionary.value<glm::dmat3>(KeyModelTransform);
}
if (dictionary.hasKey(KeyFading)) {
_performFade = dictionary.value<bool>(KeyFading);
}
addPropertySubOwner(_geometry.get());
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderableModel::loadTexture, this));
addProperty(_debugModelRotation);
//dictionary.getValue(keySource, _source);
//dictionary.getValue(keyDestination, _destination);
if (dictionary.hasKeyAndValue<glm::dmat3>(keyModelTransform))
dictionary.getValue(keyModelTransform, _modelTransform);
else
_modelTransform = glm::dmat3(1.f);
dictionary.getValue(keyBody, _target);
//openspace::SpiceManager::ref().addFrame(_target, _source);
//setBoundingSphere(pss(1.f, 9.f));
addProperty(_performShading);
if (dictionary.hasKeyAndValue<bool>(keyFading)) {
bool fading;
dictionary.getValue(keyFading, fading);
_performFade = fading;
}
addProperty(_performFade);
//if (dictionary.hasKeyAndValue<bool>(keyGhosting)) {
// bool ghosting;
// dictionary.getValue(keyGhosting, ghosting);
// _isGhost = ghosting;
//}
}
bool RenderableModel::isReady() const {
bool ready = true;
ready &= (_programObject != nullptr);
ready &= (_texture != nullptr);
return ready;
return _programObject && _texture;
}
bool RenderableModel::initialize() {
bool completeSuccess = true;
if (_programObject == nullptr) {
// NH shader
RenderEngine& renderEngine = OsEng.renderEngine();
_programObject = renderEngine.buildRenderProgram("ModelProgram",
"${MODULE_BASE}/shaders/model_vs.glsl",
"${MODULE_BASE}/shaders/model_fs.glsl");
if (!_programObject)
return false;
}
_programObject = OsEng.renderEngine().buildRenderProgram(
"ModelProgram",
"${MODULE_BASE}/shaders/model_vs.glsl",
"${MODULE_BASE}/shaders/model_fs.glsl"
);
loadTexture();
bool completeSuccess = true;
completeSuccess &= (_texture != nullptr);
completeSuccess &= _geometry->initialize(this);
//completeSuccess &= !_source.empty();
//completeSuccess &= !_destination.empty();
return completeSuccess;
}
@@ -157,10 +169,8 @@ bool RenderableModel::deinitialize() {
}
_texture = nullptr;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_programObject) {
renderEngine.removeRenderProgram(_programObject);
OsEng.renderEngine().removeRenderProgram(_programObject);
_programObject = nullptr;
}
@@ -176,30 +186,18 @@ void RenderableModel::render(const RenderData& data) {
}
else if (!_performFade && _fading < 1.f) {
_fading = _fading + 0.01f;
}
// debug rotation controlled from GUI
glm::mat4 unitMat4(1);
glm::vec3 debugEulerRot = glm::radians(_debugModelRotation.value());
glm::mat4 rotX = glm::rotate(unitMat4, debugEulerRot.x, glm::vec3(1, 0, 0));
glm::mat4 rotY = glm::rotate(unitMat4, debugEulerRot.y, glm::vec3(0, 1, 0));
glm::mat4 rotZ = glm::rotate(unitMat4, debugEulerRot.z, glm::vec3(0, 0, 1));
glm::dmat4 debugModelRotation = rotX * rotY * rotZ;
// Model transform and view transform needs to be in double precision
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation
glm::dmat4(data.modelTransform.rotation) * // Spice rotation
glm::dmat4(glm::scale(glm::dmat4(_modelTransform), glm::dvec3(data.modelTransform.scale)));
debugModelRotation; // debug model rotation controlled from GUI
glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
glm::vec3 directionToSun = glm::normalize(_sunPos - data.modelTransform.translation);
glm::vec3 directionToSunViewSpace = glm::mat3(data.camera.combinedViewMatrix()) * directionToSun;
_programObject->setUniform("transparency", _alpha);
_programObject->setUniform("directionToSunViewSpace", directionToSunViewSpace);
_programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
_programObject->setUniform("projectionTransform", data.camera.projectionMatrix());
@@ -216,7 +214,6 @@ void RenderableModel::render(const RenderData& data) {
_geometry->render();
// disable shader
_programObject->deactivate();
}
@@ -224,23 +221,6 @@ void RenderableModel::update(const UpdateData& data) {
if (_programObject->isDirty()) {
_programObject->rebuildFromFile();
}
// double _time = data.time;
//if (_isGhost){
// futureTime = openspace::ImageSequencer::ref().getNextCaptureTime();
// double remaining = openspace::ImageSequencer::ref().getNextCaptureTime() - data.time;
// double interval = openspace::ImageSequencer::ref().getIntervalLength();
// double t = 1.f - remaining / openspace::ImageSequencer::ref().getIntervalLength();
// if (interval > 60) {
// if (t < 0.8)
// _fading = static_cast<float>(t);
// else if (t >= 0.95)
// _fading = _fading - 0.5f;
// }
// else
// _fading = 0.f;
// _time = futureTime;
//}
_sunPos = OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition();
}
@@ -250,7 +230,10 @@ void RenderableModel::loadTexture() {
if (_colorTexturePath.value() != "") {
_texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath));
if (_texture) {
LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'");
LDEBUGC(
"RenderableModel",
"Loaded texture from '" << absPath(_colorTexturePath) << "'"
);
_texture->uploadTexture();
_texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);
}

View File

@@ -31,15 +31,23 @@
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <openspace/properties/vector/vec3property.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <memory>
namespace ghoul {
namespace opengl {
class ProgramObject;
class Texture;
} // namespace opengl
} // namespace ghoul
namespace openspace {
struct RenderData;
struct UpdateData;
namespace documentation { struct Documentation; }
namespace modelgeometry {
class ModelGeometry;
}
@@ -56,35 +64,24 @@ public:
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
static documentation::Documentation Documentation();
protected:
void loadTexture();
private:
std::unique_ptr<modelgeometry::ModelGeometry> _geometry;
properties::StringProperty _colorTexturePath;
properties::BoolProperty _performFade;
properties::BoolProperty _performShading;
properties::FloatProperty _fading;
std::unique_ptr<ghoul::opengl::ProgramObject> _programObject;
std::unique_ptr<ghoul::opengl::Texture> _texture;
std::unique_ptr<modelgeometry::ModelGeometry> _geometry;
glm::dmat3 _modelTransform;
float _alpha;
//glm::dmat3 _stateMatrix;
//std::string _source;
//std::string _destination;
std::string _target;
//bool _isGhost;
int _frameCount;
glm::dvec3 _sunPos;
properties::BoolProperty _performShading;
properties::Vec3Property _debugModelRotation;
};
} // namespace openspace

View File

@@ -1,269 +0,0 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* 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 <modules/base/rendering/renderablepath.h>
#include <openspace/util/time.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/interaction/interactionhandler.h>
#include <fstream>
/* TODO for this class:
* In order to add geometry shader (for pretty-draw),
* need to pack each consecutive point pair into a vec2
* in order to draw quad between them.
*/
namespace {
const std::string _loggerCat = "RenderableTrail";
//constants
const char* keyName = "Name";
const char* keyBody = "Body";
const char* keyObserver = "Observer";
const char* keyFrame = "Frame";
const char* keyPathModule = "ModulePath";
const char* keyColor = "RGB";
const char* keyTimeSteps = "TimeSteps";
const char* keyPointSteps = "PointSteps";
const char* keyDrawLine = "DrawLine";
const char* keRenderDistanceInterval = "RenderDistanceInterval";
}
namespace openspace {
RenderablePath::RenderablePath(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _lineWidth("lineWidth", "Line Width", 2.f, 1.f, 20.f)
, _drawLine("drawline", "Draw Line", false)
, _programObject(nullptr)
, _successfullDictionaryFetch(true)
, _vaoID(0)
, _vBufferID(0)
, _needsSweep(true)
, _start(0.0)
, _stop(0.0)
{
_successfullDictionaryFetch &= dictionary.getValue(keyBody, _target);
_successfullDictionaryFetch &= dictionary.getValue(keyObserver, _observer);
_successfullDictionaryFetch &= dictionary.getValue(keyFrame, _frame);
_successfullDictionaryFetch &= dictionary.getValue(keyTimeSteps, _increment);
float fPointSteps; // Dictionary can not pick out ints...
if (!dictionary.getValue(keyPointSteps, fPointSteps))
fPointSteps = 4;
_pointSteps = static_cast<int>(fPointSteps);
glm::vec3 color(0.f);
if (dictionary.hasKeyAndValue<glm::vec3>(keyColor))
dictionary.getValue(keyColor, color);
_lineColor = color;
bool drawLine = false;
if (dictionary.hasKeyAndValue<bool>(keyDrawLine))
dictionary.getValue(keyDrawLine, drawLine);
_drawLine = drawLine;
addProperty(_drawLine);
addProperty(_lineWidth);
_distanceFade = 1.0;
}
bool RenderablePath::initialize() {
if (!_successfullDictionaryFetch) {
LERROR("The following keys need to be set in the Dictionary. Cannot initialize!");
LERROR(keyBody << ": " << _target);
LERROR(keyObserver << ": " << _observer);
LERROR(keyFrame << ": " << _frame);
return false;
}
bool completeSuccess = true;
RenderEngine& renderEngine = OsEng.renderEngine();
_programObject = renderEngine.buildRenderProgram("PathProgram",
"${MODULE_BASE}/shaders/path_vs.glsl",
"${MODULE_BASE}/shaders/path_fs.glsl");
if (!_programObject)
return false;
bool intervalSet = hasTimeInterval();
if (intervalSet) {
completeSuccess &= getInterval(_start, _stop);
}
return completeSuccess;
}
bool RenderablePath::deinitialize() {
glDeleteVertexArrays(1, &_vaoID);
_vaoID = 0;
glDeleteBuffers(1, &_vBufferID);
_vBufferID = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_programObject) {
renderEngine.removeRenderProgram(_programObject);
_programObject = nullptr;
}
return true;
}
bool RenderablePath::isReady() const {
return (_programObject != nullptr) && _successfullDictionaryFetch;
}
void RenderablePath::render(const RenderData& data) {
double time = openspace::Time::ref().j2000Seconds();
if (_start > time || _stop < time)
return;
size_t nPointsToDraw = _vertexArray.size();// (time - _start) / (_stop - _start) * (_vertexArray.size()) + 1 + 0.5;
_programObject->activate();
// Calculate variables to be used as uniform variables in shader
glm::dvec3 bodyPosition = data.modelTransform.translation;
// Model transform and view transform needs to be in double precision
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), bodyPosition); // Translation
glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
_programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
_programObject->setUniform("projectionTransform", data.camera.projectionMatrix());
_programObject->setUniform("pointSteps", _pointSteps);
_programObject->setUniform("color", _lineColor);
if (_drawLine) {
glLineWidth(_lineWidth);
glBindVertexArray(_vaoID);
glDrawArrays(GL_LINE_STRIP, 0, static_cast<GLsizei>(nPointsToDraw));
glBindVertexArray(0);
glLineWidth(1.f);
}
glEnable(GL_PROGRAM_POINT_SIZE);
glBindVertexArray(_vaoID);
glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(nPointsToDraw));
glBindVertexArray(0);
glDisable(GL_PROGRAM_POINT_SIZE);
_programObject->deactivate();
}
void RenderablePath::update(const UpdateData& data) {
if (data.isTimeJump)
_needsSweep = true;
if (_needsSweep) {
calculatePath(_observer);
sendToGPU();
_needsSweep = false;
}
if (_programObject->isDirty())
_programObject->rebuildFromFile();
}
void RenderablePath::calculatePath(std::string observer) {
double interval = (_stop - _start);
int segments = static_cast<int>(interval /_increment);
if (segments == 0)
return;
double lightTime;
// bool correctPosition = true;
double currentTime = _start;
_vertexArray.resize(segments);
//psc pscPos;
//float r, g, b;
//float g = _lineColor[1];
//float b = _lineColor[2];
glm::vec3 position;
for (int i = 0; i < segments; i++) {
position =
glm::vec3(SpiceManager::ref().targetPosition(_target, observer, _frame, {}, currentTime, lightTime));
// Convert from 100 m to m
position *= 10e2;
//pscPos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);
//pscPos[3] += 3;
//if (!correctPosition) {
// r = 1.f;
// g = b = 0.5f;
//}
//else if ((i % 8) == 0) {
// r = _lineColor[0];
// g = _lineColor[1];
// b = _lineColor[2];
//}
//else {
// r = g = b = 0.6f;
//}
//add position
_vertexArray[i] = { position[0], position[1], position[2], 1.0f };
//add color for position
//_vertexArray[i + 1] = { r, g, b, a };
currentTime += _increment;
}
_lastPosition = glm::vec4(position, 1.0f);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferID);
glBufferSubData(GL_ARRAY_BUFFER, 0, _vertexArray.size() * sizeof(VertexInfo), &_vertexArray[0]);
}
void RenderablePath::sendToGPU() {
glGenVertexArrays(1, &_vaoID);
glGenBuffers(1, &_vBufferID);
glBindVertexArray(_vaoID);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferID);
glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(VertexInfo), NULL, GL_STREAM_DRAW); // orphaning the buffer, sending NULL data.
glBufferSubData(GL_ARRAY_BUFFER, 0, _vertexArray.size() * sizeof(VertexInfo), &_vertexArray[0]);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
//glEnableVertexAttribArray(1);
//glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexInfo) * 2, (void*)(sizeof(VertexInfo)));
glBindVertexArray(0);
}
} // namespace openspace

View File

@@ -1,94 +0,0 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* 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 __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__
#define __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__
#include <openspace/rendering/renderable.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul {
namespace opengl {
class ProgramObject;
class Texture;
}
}
namespace openspace {
class RenderablePath : public Renderable {
public:
RenderablePath(const ghoul::Dictionary& dictionary);
bool initialize() override;
bool deinitialize() override;
bool isReady() const override;
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
void calculatePath(std::string observer);
private:
struct VertexInfo {
float x, y, z, e;
//float r, g, b, a;
};
void sendToGPU();
void addPosition(glm::vec3 pos);
void addColor(glm::vec4 col);
glm::vec3 _lineColor;
glm::vec4 _lastPosition;
properties::FloatProperty _lineWidth;
properties::BoolProperty _drawLine;
std::unique_ptr<ghoul::opengl::ProgramObject> _programObject;
bool _successfullDictionaryFetch;
std::string _target;
std::string _observer;
std::string _frame;
GLuint _vaoID;
GLuint _vBufferID;
bool _needsSweep;
std::vector<VertexInfo> _vertexArray;
float _increment;
double _start;
double _stop;
float _distanceFade;
int _pointSteps;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_BASE___RENDERABLEPATH___H__

View File

@@ -22,14 +22,14 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/engine/configurationmanager.h>
#include <modules/base/rendering/renderableplane.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/powerscaledcoordinate.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <modules/newhorizons/rendering/renderableplanetprojection.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/filesystem/filesystem>
#include <ghoul/io/texture/texturereader.h>
@@ -38,108 +38,106 @@
#include <ghoul/opengl/textureunit.h>
namespace {
static const std::string _loggerCat = "RenderablePlane";
const char* keyFieldlines = "Fieldlines";
const char* keyFilename = "File";
const char* keyHints = "Hints";
const char* keyShaders = "Shaders";
const char* keyVertexShader = "VertexShader";
const char* keyFragmentShader = "FragmentShader";
}
const char* KeySize = "Size";
const char* KeyBillboard = "Billboard";
const char* KeyBlendMode = "BlendMode";
const char* KeyTexture = "Texture";
} // namespace
namespace openspace {
documentation::Documentation RenderablePlane::Documentation() {
using namespace documentation;
return {
"Renderable Plane",
"base_renderable_plane",
{
{
KeySize,
new DoubleVerifier,
"Specifies the size of the square plane in meters.",
Optional::No
},
{
KeyBillboard,
new BoolVerifier,
"Specifies whether the plane is a billboard, which means that it is "
"always facing the camera. If this is false, it can be oriented using "
"other transformations. The default is 'false'.",
Optional::Yes
},
{
KeyBlendMode,
new StringInListVerifier({ "Normal", "Additive" }),
"Specifies the blend mode that is applied to this plane. The default "
"value is 'Normal'.",
Optional::Yes
},
{
KeyTexture,
new StringVerifier,
"Specifies the texture that is applied to this plane. This image has to "
"be a square image.",
Optional::No
}
}
};
}
RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _texturePath("texture", "Texture")
, _billboard("billboard", "Billboard", false)
, _projectionListener("projectionListener", "DisplayProjections", false)
, _size("size", "Size", 10, 0, std::pow(10, 25))
, _origin(Origin::Center)
, _shader(nullptr)
, _textureIsDirty(false)
, _texture(nullptr)
, _blendMode(BlendMode::Normal)
, _quad(0)
, _vertexPositionBuffer(0)
, _planeIsDirty(false)
, _textureIsDirty(false)
{
dictionary.getValue("Size", _size);
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderablePlane"
);
if (dictionary.hasKey("Name")) {
dictionary.getValue("Name", _nodeName);
_size = dictionary.value<double>(KeySize);
if (dictionary.hasKey(KeyBillboard)) {
_billboard = dictionary.value<bool>(KeyBillboard);
}
std::string origin;
if (dictionary.getValue("Origin", origin)) {
if (origin == "LowerLeft") {
_origin = Origin::LowerLeft;
if (dictionary.hasKey(KeyBlendMode)) {
const std::string v = dictionary.value<std::string>(KeyBlendMode);
if (v == "Normal") {
_blendMode = BlendMode::Normal;
}
else if (origin == "LowerRight") {
_origin = Origin::LowerRight;
}
else if (origin == "UpperLeft") {
_origin = Origin::UpperLeft;
}
else if (origin == "UpperRight") {
_origin = Origin::UpperRight;
}
else if (origin == "Center") {
_origin = Origin::Center;
}
}
// Attempt to get the billboard value
bool billboard = false;
if (dictionary.getValue("Billboard", billboard)) {
_billboard = billboard;
}
if (dictionary.hasKey("ProjectionListener")){
bool projectionListener = false;
if (dictionary.getValue("ProjectionListener", projectionListener)) {
_projectionListener = projectionListener;
}
}
std::string blendMode;
if (dictionary.getValue("BlendMode", blendMode)) {
if (blendMode == "Additive") {
else if (v == "Additive") {
_blendMode = BlendMode::Additive;
setRenderBin(Renderable::RenderBin::Transparent);
}
}
std::string texturePath = "";
bool success = dictionary.getValue("Texture", texturePath);
if (success) {
_texturePath = absPath(texturePath);
_textureFile = new ghoul::filesystem::File(_texturePath);
}
_texturePath = absPath(dictionary.value<std::string>(KeyTexture));
_textureFile = std::make_unique<ghoul::filesystem::File>(_texturePath);
addProperty(_billboard);
addProperty(_texturePath);
_texturePath.onChange(std::bind(&RenderablePlane::loadTexture, this));
_textureFile->setCallback([&](const ghoul::filesystem::File&) { _textureIsDirty = true; });
_texturePath.onChange([this]() {loadTexture(); });
_textureFile->setCallback(
[this](const ghoul::filesystem::File&) { _textureIsDirty = true; }
);
addProperty(_size);
//_size.onChange(std::bind(&RenderablePlane::createPlane, this));
_size.onChange([this](){ _planeIsDirty = true; });
setBoundingSphere(_size);
}
RenderablePlane::~RenderablePlane() {
delete _textureFile;
_textureFile = nullptr;
}
bool RenderablePlane::isReady() const {
bool ready = true;
if (!_shader)
ready &= false;
if(!_texture)
ready &= false;
return ready;
return _shader && _texture;
}
bool RenderablePlane::initialize() {
@@ -147,17 +145,10 @@ bool RenderablePlane::initialize() {
glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
createPlane();
if (_shader == nullptr) {
// Plane Program
RenderEngine& renderEngine = OsEng.renderEngine();
_shader = renderEngine.buildRenderProgram("PlaneProgram",
"${MODULE_BASE}/shaders/plane_vs.glsl",
"${MODULE_BASE}/shaders/plane_fs.glsl"
);
if (!_shader)
return false;
}
_shader = OsEng.renderEngine().buildRenderProgram("PlaneProgram",
"${MODULE_BASE}/shaders/plane_vs.glsl",
"${MODULE_BASE}/shaders/plane_fs.glsl"
);
loadTexture();
@@ -171,16 +162,8 @@ bool RenderablePlane::deinitialize() {
glDeleteBuffers(1, &_vertexPositionBuffer);
_vertexPositionBuffer = 0;
if (!_projectionListener){
// its parents job to kill texture
// iff projectionlistener
_texture = nullptr;
}
delete _textureFile;
_textureFile = nullptr;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_shader) {
renderEngine.removeRenderProgram(_shader);
@@ -191,44 +174,35 @@ bool RenderablePlane::deinitialize() {
}
void RenderablePlane::render(const RenderData& data) {
glm::mat4 scaleTransform = glm::mat4(1.0);
// Activate shader
_shader->activate();
if (_projectionListener){
//get parent node-texture and set with correct dimensions
SceneGraphNode* textureNode = OsEng.renderEngine().scene()->sceneGraphNode(_nodeName)->parent();
if (textureNode != nullptr){
RenderablePlanetProjection* t = static_cast<RenderablePlanetProjection*>(textureNode->renderable());
_texture = std::unique_ptr<ghoul::opengl::Texture>(&(t->baseTexture()));
unsigned int h = _texture->height();
unsigned int w = _texture->width();
float scale = static_cast<float>(h) / static_cast<float>(w);
scaleTransform = glm::scale(glm::mat4(1.0), glm::vec3(1.f, scale, 1.f));
}
}
//if (_projectionListener){
// //get parent node-texture and set with correct dimensions
// SceneGraphNode* textureNode = OsEng.renderEngine().scene()->sceneGraphNode(_nodeName)->parent();
// if (textureNode != nullptr){
// RenderablePlanetProjection* t = static_cast<RenderablePlanetProjection*>(textureNode->renderable());
// _texture = std::unique_ptr<ghoul::opengl::Texture>(&(t->baseTexture()));
// unsigned int h = _texture->height();
// unsigned int w = _texture->width();
// float scale = static_cast<float>(h) / static_cast<float>(w);
// scaleTransform = glm::scale(glm::mat4(1.0), glm::vec3(1.f, scale, 1.f));
// }
//}
// Model transform and view transform needs to be in double precision
glm::dmat4 rotationTransform;
if (_billboard)
rotationTransform = glm::inverse(glm::dmat4(data.camera.viewRotationMatrix()));
else
rotationTransform = glm::dmat4(data.modelTransform.rotation);
const glm::dmat4 rotationTransform = _billboard ?
glm::inverse(glm::dmat4(data.camera.viewRotationMatrix())) :
glm::dmat4(data.modelTransform.rotation);
glm::dmat4 modelTransform =
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
rotationTransform *
glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))) *
glm::dmat4(scaleTransform);
glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
glm::dmat4(1.0);
const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
_shader->setUniform("modelViewProjectionTransform",
data.camera.projectionMatrix() * glm::mat4(modelViewTransform));
//_shader->setUniform("ViewProjection", data.camera.viewProjectionMatrix());
//_shader->setUniform("ModelTransform", transform);
//setPscUniforms(*_shader.get(), data.camera, data.position);
ghoul::opengl::TextureUnit unit;
unit.activate();
_texture->bind();
@@ -276,9 +250,14 @@ void RenderablePlane::update(const UpdateData&) {
void RenderablePlane::loadTexture() {
if (_texturePath.value() != "") {
std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
std::unique_ptr<ghoul::opengl::Texture> texture =
ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
if (texture) {
LDEBUG("Loaded texture from '" << absPath(_texturePath) << "'");
LDEBUGC(
"RenderablePlane",
"Loaded texture from '" << absPath(_texturePath) << "'"
);
texture->uploadTexture();
// Textures of planets looks much smoother with AnisotropicMipMap rather than linear
@@ -286,19 +265,15 @@ void RenderablePlane::loadTexture() {
_texture = std::move(texture);
delete _textureFile;
_textureFile = new ghoul::filesystem::File(_texturePath);
_textureFile = std::make_unique<ghoul::filesystem::File>(_texturePath);
_textureFile->setCallback([&](const ghoul::filesystem::File&) { _textureIsDirty = true; });
}
}
}
void RenderablePlane::createPlane() {
// ============================
// GEOMETRY (quad)
// ============================
const GLfloat size = _size;
const GLfloat vertex_data[] = {
const GLfloat vertexData[] = {
// x y z w s t
-size, -size, 0.f, 0.f, 0.f, 0.f,
size, size, 0.f, 0.f, 1.f, 1.f,
@@ -308,13 +283,28 @@ void RenderablePlane::createPlane() {
size, size, 0.f, 0.f, 1.f, 1.f,
};
glBindVertexArray(_quad); // bind array
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
glBindVertexArray(_quad);
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(0));
glVertexAttribPointer(
0,
4,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 6,
reinterpret_cast<void*>(0)
);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4));
glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 6,
reinterpret_cast<void*>(sizeof(GLfloat) * 4)
);
}
} // namespace openspace

View File

@@ -29,35 +29,31 @@
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/util/updatestructures.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul {
namespace filesystem {
class File;
}
namespace opengl {
class ProgramObject;
class Texture;
}
namespace filesystem { class File; }
namespace opengl {
class ProgramObject;
class Texture;
}
} // namespace ghoul
namespace openspace {
struct LinePoint;
struct RenderData;
struct UpdateData;
namespace documentation { struct Documentation; }
struct LinePoint;
class RenderablePlane : public Renderable {
enum class Origin {
LowerLeft, LowerRight, UpperLeft, UpperRight, Center
};
public:
enum class BlendMode : int {
Normal = 0,
Additive
};
RenderablePlane(const ghoul::Dictionary& dictionary);
~RenderablePlane();
bool initialize() override;
bool deinitialize() override;
@@ -67,27 +63,32 @@ public:
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
static documentation::Documentation Documentation();
private:
enum class BlendMode : int {
Normal = 0,
Additive
};
void loadTexture();
void createPlane();
properties::StringProperty _texturePath;
properties::BoolProperty _billboard;
properties::BoolProperty _projectionListener;
properties::FloatProperty _size;
Origin _origin;
std::string _nodeName;
bool _planeIsDirty;
std::unique_ptr<ghoul::opengl::ProgramObject> _shader;
bool _textureIsDirty;
std::unique_ptr<ghoul::opengl::Texture> _texture;
std::unique_ptr<ghoul::filesystem::File> _textureFile;
BlendMode _blendMode;
ghoul::filesystem::File* _textureFile;
GLuint _quad;
GLuint _vertexPositionBuffer;
bool _planeIsDirty;
bool _textureIsDirty;
};
} // namespace openspace

View File

@@ -24,38 +24,77 @@
#include <modules/base/rendering/renderablesphere.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/filesystem/filesystem.h>
#include <openspace/util/powerscaledsphere.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/opengl/programobject.h>
#define _USE_MATH_DEFINES
#include <math.h>
namespace {
static const std::string _loggerCat = "RenderableSphere";
const char* keySize = "Size";
const char* keySegments = "Segments";
const char* keyTexture = "Texture";
const char* keyOrientation = "Orientation";
const char* KeySize = "Size";
const char* KeySegments = "Segments";
const char* KeyTexture = "Texture";
const char* KeyOrientation = "Orientation";
enum Orientation {
Outside = 1,
Inside = 2
};
}
} // namespace
namespace openspace {
documentation::Documentation RenderableSphere::Documentation() {
using namespace documentation;
return {
"RenderableSphere",
"base_renderable_sphere",
{
{
KeySize,
new DoubleVerifier,
"Specifies the radius of the sphere in meters.",
Optional::No
},
{
KeySegments,
new IntVerifier,
"Specifies the number of segments the sphere is separated in.",
Optional::No
},
{
KeyTexture,
new StringVerifier,
"Specifies the texture that is applied to the sphere.",
Optional::No
},
{
KeyOrientation,
new StringInListVerifier({ "Inside", "Outside", "Inside/Outside" }),
"Specifies whether the texture is applied to the inside of the sphere, "
"the outside of the sphere, or both. The default value is 'Outside'.",
Optional::Yes
}
}
};
}
RenderableSphere::RenderableSphere(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _texturePath("texture", "Texture")
, _orientation("orientation", "Orientation")
, _size("size", "Size", glm::vec2(1.f, 1.f), glm::vec2(0.f), glm::vec2(100.f))
, _size("size", "Size", 1.f, 0.f, std::pow(10.f, 45))
, _segments("segments", "Segments", 8, 4, 100)
, _transparency("transparency", "Transparency", 1.f, 0.f, 1.f)
, _shader(nullptr)
@@ -63,67 +102,68 @@ RenderableSphere::RenderableSphere(const ghoul::Dictionary& dictionary)
, _sphere(nullptr)
, _sphereIsDirty(false)
{
if (dictionary.hasKeyAndValue<glm::vec2>(keySize)) {
glm::vec2 size;
dictionary.getValue(keySize, size);
_size = size;
}
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableSphere"
);
if (dictionary.hasKeyAndValue<glm::vec2>(keySegments)) {
int segments;
dictionary.getValue(keySegments, segments);
_segments = segments;
}
if (dictionary.hasKeyAndValue<std::string>(keyTexture)) {
std::string texture;
dictionary.getValue(keyTexture, texture);
_texturePath = absPath(texture);
}
_size = dictionary.value<double>(KeySize);
_segments = static_cast<int>(dictionary.value<double>(KeySegments));
_texturePath = absPath(dictionary.value<std::string>(KeyTexture));
_orientation.addOption(Outside, "Outside");
_orientation.addOption(Inside, "Inside");
_orientation.addOption(Outside | Inside, "Outside + Inside");
_orientation.addOption(Outside | Inside, "Inside/Outside");
if (dictionary.hasKeyAndValue<std::string>(keyOrientation)) {
std::string orientation;
dictionary.getValue(keyOrientation, orientation);
if (orientation == "Outside")
_orientation = Outside;
else if (orientation == "Inside")
if (dictionary.hasKey(KeyOrientation)) {
const std::string v = dictionary.value<std::string>(KeyOrientation);
if (v == "Inside") {
_orientation = Inside;
else
}
else if (v == "Outside") {
_orientation = Outside;
}
else if (v == "Inside/Outside") {
_orientation = Outside | Inside;
}
else {
ghoul_assert(false, "Missing 'case' label");
}
}
else {
_orientation = Outside;
}
addProperty(_orientation);
addProperty(_size);
_size.onChange([this](){ _sphereIsDirty = true; });
addProperty(_segments);
_segments.onChange([this](){ _sphereIsDirty = true; });
addProperty(_transparency);
addProperty(_texturePath);
_texturePath.onChange(std::bind(&RenderableSphere::loadTexture, this));
_texturePath.onChange([this]() {loadTexture(); });
setRenderBin(Renderable::RenderBin::Transparent);
}
bool RenderableSphere::isReady() const {
return (_sphere != nullptr) && (_shader != nullptr) && (_texture != nullptr);
return _shader && _texture;
}
bool RenderableSphere::initialize() {
delete _sphere;
_sphere = new PowerScaledSphere(_size.value(), _segments);
_sphere = std::make_unique<PowerScaledSphere>(
PowerScaledScalar::CreatePSS(_size), _segments
);
_sphere->initialize();
// pscstandard
RenderEngine& renderEngine = OsEng.renderEngine();
_shader = renderEngine.buildRenderProgram("Sphere",
_shader = OsEng.renderEngine().buildRenderProgram("Sphere",
"${MODULE_BASE}/shaders/sphere_vs.glsl",
"${MODULE_BASE}/shaders/sphere_fs.glsl");
if (!_shader)
return false;
loadTexture();
@@ -131,28 +171,21 @@ bool RenderableSphere::initialize() {
}
bool RenderableSphere::deinitialize() {
delete _sphere;
_sphere = nullptr;
_texture = nullptr;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_shader) {
renderEngine.removeRenderProgram(_shader);
OsEng.renderEngine().removeRenderProgram(_shader);
_shader = nullptr;
}
return true;
}
void RenderableSphere::render(const RenderData& data) {
glm::mat4 transform = glm::mat4(1.0);
transform = glm::rotate(transform, static_cast<float>(M_PI_2), glm::vec3(1, 0, 0));
// Activate shader
using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError;
_shader->activate();
@@ -171,20 +204,40 @@ void RenderableSphere::render(const RenderData& data) {
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
bool usingFramebufferRenderer =
OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer;
bool usingABufferRenderer =
OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::ABuffer;
if (usingABufferRenderer) {
_shader->setUniform("additiveBlending", true);
}
if (usingFramebufferRenderer) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
_sphere->render();
if (usingFramebufferRenderer) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
_shader->setIgnoreUniformLocationError(IgnoreError::No);
_shader->deactivate();
}
void RenderableSphere::update(const UpdateData&) {
if (_shader->isDirty())
if (_shader->isDirty()) {
_shader->rebuildFromFile();
}
if (_sphereIsDirty) {
delete _sphere;
_sphere = new PowerScaledSphere(_size.value(), _segments);
_sphere = std::make_unique<PowerScaledSphere>(
PowerScaledScalar::CreatePSS(_size), _segments
);
_sphere->initialize();
_sphereIsDirty = false;
}
@@ -194,7 +247,10 @@ void RenderableSphere::loadTexture() {
if (_texturePath.value() != "") {
std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(_texturePath);
if (texture) {
LDEBUG("Loaded texture from '" << absPath(_texturePath) << "'");
LDEBUGC(
"RenderableSphere",
"Loaded texture from '" << absPath(_texturePath) << "'"
);
texture->uploadTexture();
// Textures of planets looks much smoother with AnisotropicMipMap rather than linear

View File

@@ -26,19 +26,26 @@
#define __OPENSPACE_MODULE_BASE___RENDERABLESPHERE___H__
#include <openspace/rendering/renderable.h>
#include <openspace/util/updatestructures.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/scalar/intproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <openspace/properties/vector/vec2property.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
namespace ghoul {
namespace opengl {
class ProgramObject;
class Texture;
}
} // namespace ghoul
namespace openspace {
class PowerScaledSphere;
struct RenderData;
struct UpdateData;
namespace documentation { struct Documentation; }
class RenderableSphere : public Renderable {
public:
@@ -52,13 +59,15 @@ public:
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
static documentation::Documentation Documentation();
private:
void loadTexture();
properties::StringProperty _texturePath;
properties::OptionProperty _orientation;
properties::Vec2Property _size;
properties::FloatProperty _size;
properties::IntProperty _segments;
properties::FloatProperty _transparency;
@@ -66,7 +75,7 @@ private:
std::unique_ptr<ghoul::opengl::ProgramObject> _shader;
std::unique_ptr<ghoul::opengl::Texture> _texture;
PowerScaledSphere* _sphere;
std::unique_ptr<PowerScaledSphere> _sphere;
bool _sphereIsDirty;
};

View File

@@ -27,6 +27,7 @@
#include <openspace/engine/configurationmanager.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/glm.h>
#define _USE_MATH_DEFINES
@@ -61,7 +62,8 @@ RenderableSphericalGrid::RenderableSphericalGrid(const ghoul::Dictionary& dictio
staticGrid = dictionary.getValue(KeyGridParentsRotation, _parentsRotation);
}
dictionary.getValue(KeyGridSegments, _segments);
_segments = static_cast<int>(dictionary.value<double>(KeyGridSegments));
//dictionary.getValue(KeyGridSegments, _segments);
/*glm::vec2 radius;

View File

@@ -32,6 +32,7 @@
#include <ghoul/opengl/texture.h>
namespace openspace {
class RenderableSphericalGrid : public Renderable{
public:
RenderableSphericalGrid(const ghoul::Dictionary& dictionary);

View File

@@ -29,6 +29,9 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/translation.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
namespace {
const char* KeyTranslation = "Translation";

View File

@@ -73,6 +73,8 @@ class Translation;
*/
class RenderableTrail : public Renderable {
public:
~RenderableTrail() = default;
bool initialize() override;
bool deinitialize() override;

View File

@@ -27,6 +27,9 @@
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/scene/translation.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <numeric>

View File

@@ -28,6 +28,7 @@
#include <openspace/documentation/verifier.h>
#include <openspace/scene/translation.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
// This class creates the entire trajectory at once and keeps it in memory the entire
// time. This means that there is no need for updating the trail at runtime, but also that

View File

@@ -32,6 +32,8 @@
#include <openspace/properties/scalar/intproperty.h>
#include <openspace/properties/stringproperty.h>
#include <ghoul/opengl/programobject.h>
namespace openspace {
namespace documentation { struct Documentation; }

View File

@@ -23,6 +23,8 @@
****************************************************************************************/
#include <modules/base/rendering/screenspaceframebuffer.h>
#include <openspace/documentation/documentation.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/camera.h>
@@ -34,11 +36,27 @@
namespace openspace {
documentation::Documentation ScreenSpaceFramebuffer::Documentation() {
using namespace documentation;
return {
"ScreenSpace Framebuffer",
"base_screenspace_framebuffer",
{},
Exhaustive::Yes
};
}
ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary)
: ScreenSpaceRenderable(dictionary)
, _size("size", "Size", glm::vec4(0), glm::vec4(0), glm::vec4(2000))
, _framebuffer(nullptr)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"ScreenSpaceFramebuffer"
);
_id = id();
setName("ScreenSpaceFramebuffer" + std::to_string(_id));

View File

@@ -34,6 +34,9 @@
#include <modules/base/rendering/screenspaceimage.h>
namespace openspace {
namespace documentation { struct Documentation; }
/**
* @brief Creates a texture by rendering to a framebuffer, this is then used on a screen space plane.
* @details This class lets you ass renderfunctions that should render to a framebuffer with an attached texture.
@@ -54,6 +57,8 @@ public:
void addRenderFunction(std::shared_ptr<std::function<void()>> renderFunction);
void removeAllRenderFunctions();
static documentation::Documentation Documentation();
private:
void createFragmentbuffer();
static int id();

View File

@@ -24,6 +24,9 @@
#include <modules/base/rendering/screenspaceimage.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/wrapper/windowwrapper.h>
#include <openspace/rendering/renderengine.h>
@@ -36,39 +39,66 @@ namespace {
const char* KeyName = "Name";
const char* KeyTexturePath = "TexturePath";
const char* KeyUrl = "URL";
}
} // namespace
namespace openspace {
documentation::Documentation ScreenSpaceImage::Documentation() {
using namespace openspace::documentation;
return {
"ScreenSpace Image",
"base_screenspace_image",
{
{
KeyName,
new StringVerifier,
"Specifies the GUI name of the ScreenspaceImage",
Optional::Yes
},
{
KeyTexturePath,
new StringVerifier,
"Specifies the image that is shown on the screenspace-aligned plane. If "
"this value is set and the URL is not, the disk image is used.",
Optional::Yes
}
}
};
}
ScreenSpaceImage::ScreenSpaceImage(const ghoul::Dictionary& dictionary)
: ScreenSpaceRenderable(dictionary)
, _downloadImage(false)
, _textureIsDirty(false)
, _texturePath("texturePath", "Texture path", "")
{
std::string name;
if (dictionary.getValue(KeyName, name)) {
setName(name);
} else {
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"ScreenSpaceImage"
);
if (dictionary.hasKey(KeyName)) {
setName(dictionary.value<std::string>(KeyName));
}
else {
static int id = 0;
setName("ScreenSpaceImage " + std::to_string(id));
++id;
}
addProperty(_texturePath);
std::string texturePath;
if (dictionary.getValue(KeyTexturePath, texturePath)) {
_texturePath = texturePath;
_texturePath.onChange([this]() { _textureIsDirty = true; });
_texturePath = dictionary.value<std::string>(KeyTexturePath);
}
if (dictionary.getValue(KeyUrl, _url)) {
_downloadImage = true;
}
}
ScreenSpaceImage::~ScreenSpaceImage() {}
_texturePath.onChange([this]() { _textureIsDirty = true; });
addProperty(_texturePath);
}
bool ScreenSpaceImage::initialize() {
_originalViewportSize = OsEng.windowWrapper().currentWindowResolution();

View File

@@ -33,11 +33,12 @@
#include <ghoul/opengl/texture.h>
namespace openspace {
namespace documentation { struct Documentation; }
class ScreenSpaceImage : public ScreenSpaceRenderable {
public:
ScreenSpaceImage(const ghoul::Dictionary& dictionary);
~ScreenSpaceImage();
bool initialize() override;
bool deinitialize() override;
@@ -45,6 +46,8 @@ public:
void update() override;
bool isReady() const override;
static documentation::Documentation Documentation();
protected:
void loadTexture();
void updateTexture();

View File

@@ -38,11 +38,13 @@ documentation::Documentation StaticScale::Documentation() {
return {
"Static Scaling",
"base_scale_static",
{{
KeyValue,
new DoubleVerifier,
"The scaling factor by which the scenegraph node is scaled."
}}
{
{
KeyValue,
new DoubleVerifier,
"The scaling factor by which the scenegraph node is scaled."
}
}
};
}

View File

@@ -28,6 +28,7 @@
#include <openspace/rendering/renderable.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <openspace/util/updatestructures.h>
namespace ghoul {

View File

@@ -28,10 +28,12 @@
#include <openspace/util/powerscaledcoordinate.h>
#include <modules/kameleon/include/kameleonwrapper.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/misc/assert.h>
#include <ghoul/opengl/programobject.h>
#include <fstream>

View File

@@ -44,7 +44,7 @@ namespace ghoul {
namespace openspace {
class RenderData;
struct RenderData;
class RaycastData;
class GalaxyRaycaster : public VolumeRaycaster {

View File

@@ -41,6 +41,8 @@
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/opengl/programobject.h>
#include <fstream>

View File

@@ -30,6 +30,7 @@
#include <modules/globebrowsing/tile/tileselector.h>
#include <modules/globebrowsing/tile/tilemetadata.h>
#include <modules/globebrowsing/rendering/layer/layergroup.h>
#include <openspace/util/updatestructures.h>
namespace openspace {

View File

@@ -29,6 +29,7 @@
#include <modules/globebrowsing/globes/renderableglobe.h>
#include <modules/globebrowsing/rendering/layer/layermanager.h>
#include <modules/globebrowsing/tile/tileprovider/tileprovider.h>
#include <openspace/util/updatestructures.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -29,6 +29,7 @@
#include <modules/globebrowsing/globes/renderableglobe.h>
#include <modules/globebrowsing/rendering/layer/layermanager.h>
#include <modules/globebrowsing/tile/tileprovider/tileprovider.h>
#include <openspace/util/updatestructures.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -26,6 +26,7 @@
#include <modules/globebrowsing/chunk/chunk.h>
#include <modules/globebrowsing/globes/renderableglobe.h>
#include <openspace/util/updatestructures.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -26,6 +26,7 @@
#include <modules/globebrowsing/chunk/chunk.h>
#include <modules/globebrowsing/globes/renderableglobe.h>
#include <openspace/util/updatestructures.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -29,6 +29,9 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/wrapper/windowwrapper.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -27,6 +27,8 @@
#include <openspace/rendering/renderable.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul { namespace opengl {
class ProgramObject;
} }

View File

@@ -24,6 +24,7 @@
#include <modules/globebrowsing/other/distanceswitch.h>
#include <openspace/rendering/renderable.h>
#include <openspace/util/updatestructures.h>
namespace openspace {
namespace globebrowsing {

View File

@@ -31,6 +31,7 @@
#include <modules/globebrowsing/rendering/gpu/gpulayermanager.h>
#include <modules/globebrowsing/rendering/layer/layergroup.h>
#include <modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h>
#include <openspace/util/updatestructures.h>
namespace {
const char* keyFrame = "Frame";

View File

@@ -30,6 +30,8 @@
#include <ghoul/filesystem/filesystem.h>
#include <modules/iswa/util/dataprocessortext.h>
#include <ghoul/opengl/programobject.h>
namespace {
const std::string _loggerCat = "DataCygnet";
}

View File

@@ -25,6 +25,8 @@
#include <modules/iswa/rendering/dataplane.h>
#include <modules/iswa/util/dataprocessortext.h>
#include <ghoul/opengl/programobject.h>
namespace {
const std::string _loggerCat = "DataPlane";
}

View File

@@ -26,6 +26,8 @@
#include <openspace/util/powerscaledsphere.h>
#include <modules/iswa/util/dataprocessorjson.h>
#include <ghoul/opengl/programobject.h>
#ifdef WIN32
#define _USE_MATH_DEFINES
#include <math.h>

View File

@@ -28,6 +28,10 @@
#include <openspace/util/time.h>
#include <openspace/util/transformationmanager.h>
#include <modules/iswa/rendering/iswabasegroup.h>
#include <openspace/util/powerscaledcoordinate.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
namespace {
const std::string _loggerCat = "IswaCygnet";

View File

@@ -26,6 +26,7 @@
#include <openspace/engine/openspaceengine.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/opengl/programobject.h>
namespace {
const std::string _loggerCat = "TexturePlane";

View File

@@ -49,8 +49,8 @@ namespace ghoul {
namespace openspace {
class RenderData;
class RaycastData;
struct RenderData;
struct RaycastData;
class KameleonVolumeRaycaster : public VolumeRaycaster {
public:

View File

@@ -48,7 +48,7 @@ namespace ghoul {
namespace openspace {
class RenderData;
struct RenderData;
class RaycastData;
class MultiresVolumeRaycaster : public VolumeRaycaster {

View File

@@ -24,12 +24,17 @@
#include <modules/newhorizons/rendering/renderablecrawlingline.h>
#include <modules/newhorizons/util/imagesequencer.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <modules/newhorizons/util/imagesequencer.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/glm.h>
namespace {
const char* KeySource = "Source";

View File

@@ -28,6 +28,7 @@
#include <openspace/rendering/renderable.h>
#include <ghoul/glm.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace openspace {

View File

@@ -30,6 +30,7 @@
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>

View File

@@ -34,6 +34,7 @@
#include <openspace/util/spicemanager.h>
#include <ghoul/glm.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul {
namespace opengl {

View File

@@ -31,6 +31,7 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scene/scene.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
#include <openspace/util/updatestructures.h>

View File

@@ -34,6 +34,8 @@
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/vector/vec3property.h>
#include <openspace/util/powerscaledcoordinate.h>
namespace ghoul {
namespace opengl {
class ProgramObject;

View File

@@ -30,6 +30,7 @@
#include <openspace/engine/configurationmanager.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scene/scene.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>

View File

@@ -27,6 +27,8 @@
#include <openspace/rendering/renderable.h>
#include <ghoul/opengl/ghoul_gl.h>
#include <memory>
namespace ghoul {

View File

@@ -33,10 +33,10 @@
#include <openspace/util/spicemanager.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul {
namespace opengl {
class ProgramObject;
}
namespace opengl { class ProgramObject; }
}
namespace openspace {

View File

@@ -36,6 +36,7 @@
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/framebufferobject.h>
#include <ghoul/opengl/textureconversion.h>
#include <ghoul/opengl/textureunit.h>

View File

@@ -28,6 +28,7 @@
#include <openspace/interaction/interactionhandler.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scene/scene.h>
#include <ghoul/misc/assert.h>

View File

@@ -22,17 +22,17 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
// openspace
#include <modules/space/rendering/renderableconstellationbounds.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <modules/space/rendering/renderableconstellationbounds.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
// ghoul
#include <ghoul/filesystem/filesystem.h>
// std
#include <fstream>
#define _USE_MATH_DEFINES
#include <math.h>
@@ -41,13 +41,12 @@
#include "SpiceZpr.h"
namespace {
const std::string _loggerCat = "RenderableConstellationBounds";
const char* KeyVertexFile = "File";
const char* KeyConstellationFile = "ConstellationFile";
const char* KeyReferenceFrame = "ReferenceFrame";
const char* keyVertexFile = "File";
const char* keyConstellationFile = "ConstellationFile";
const char* keyReferenceFrame = "ReferenceFrame";
const char* defaultReferenceFrame = "J2000";
const char* DefaultReferenceFrame = "J2000";
float deg2rad(float deg) {
return static_cast<float>((deg / 360.f) * 2.f * M_PI);
@@ -56,12 +55,45 @@ namespace {
// 360 degrees / 24h = 15 degrees/h
return deg2rad(rightAscension * 15);
}
}
} // namespace
namespace openspace {
documentation::Documentation RenderableConstellationBounds::Documentation() {
using namespace documentation;
return {
"RenderableConstellationBounds",
"space_renderable_constellationbounds",
{
{
KeyVertexFile,
new StringVerifier,
"Specifies the file containing the bounds information about the "
"constellation locations.",
Optional::No
},
{
KeyConstellationFile,
new StringVerifier,
"Specifies the file that contains the mapping between constellation "
"abbreviations and full name of the constellation. If the file is "
"omitted, the abbreviations are used as the full names.",
Optional::Yes
},
{
KeyReferenceFrame,
new StringVerifier,
"The reference frame in which the constellation points are stored in. "
"Defaults to <code>J2000< / code>",
Optional::Yes
}
}
};
}
RenderableConstellationBounds::RenderableConstellationBounds(
const ghoul::Dictionary& dictionary)
const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _vertexFilename("")
, _constellationFilename("")
@@ -71,66 +103,64 @@ RenderableConstellationBounds::RenderableConstellationBounds(
, _vao(0)
, _vbo(0)
{
bool success = dictionary.getValue(keyVertexFile, _vertexFilename);
if (!success) {
LERROR("RenderableConstellationBounds did not contain a key '" <<
keyVertexFile << "'");
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableConstellationBounds"
);
_vertexFilename = dictionary.value<std::string>(KeyVertexFile);
if (dictionary.hasKey(KeyConstellationFile)) {
_constellationFilename = dictionary.value<std::string>(KeyConstellationFile);
}
dictionary.getValue(keyConstellationFile, _constellationFilename);
success = dictionary.getValue(keyReferenceFrame, _originReferenceFrame);
if (!success) {
_originReferenceFrame = defaultReferenceFrame;
if (dictionary.hasKey(KeyReferenceFrame)) {
_originReferenceFrame = dictionary.value<std::string>(KeyReferenceFrame);
}
else {
_originReferenceFrame = DefaultReferenceFrame;
}
addProperty(_distance);
addProperty(_constellationSelection);
_constellationSelection.onChange(
std::bind(&RenderableConstellationBounds::selectionPropertyHasChanged, this)
[this]() { selectionPropertyHasChanged(); }
);
}
bool RenderableConstellationBounds::initialize() {
RenderEngine& renderEngine = OsEng.renderEngine();
_program = renderEngine.buildRenderProgram("ConstellationBounds",
_program = OsEng.renderEngine().buildRenderProgram("ConstellationBounds",
"${MODULE_SPACE}/shaders/constellationbounds_vs.glsl",
"${MODULE_SPACE}/shaders/constellationbounds_fs.glsl");
if (!_program)
return false;
bool loadSuccess = loadVertexFile();
if (!loadSuccess)
if (!loadSuccess) {
return false;
}
loadSuccess = loadConstellationFile();
if (!loadSuccess)
if (!loadSuccess) {
return false;
}
fillSelectionProperty();
if (_vao == 0) {
glGenVertexArrays(1, &_vao);
LDEBUG("Generating Vertex Array id '" << _vao << "'");
}
if (_vbo == 0) {
glGenBuffers(1, &_vbo);
LDEBUG("Generating Vertex Buffer Object id '" << _vbo << "'");
}
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);
glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER,
_vertexValues.size() * 3 * sizeof(float),
&_vertexValues[0],
GL_STATIC_DRAW
);
glBufferData(
GL_ARRAY_BUFFER,
_vertexValues.size() * 3 * sizeof(float),
&_vertexValues[0],
GL_STATIC_DRAW
);
GLint positionAttrib = _program->attributeLocation("in_position");
glEnableVertexAttribArray(positionAttrib);
glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return true;
@@ -142,9 +172,8 @@ bool RenderableConstellationBounds::deinitialize() {
glDeleteVertexArrays(1, &_vao);
_vao = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_program) {
renderEngine.removeRenderProgram(_program);
OsEng.renderEngine().removeRenderProgram(_program);
_program = nullptr;
}
@@ -152,7 +181,7 @@ bool RenderableConstellationBounds::deinitialize() {
}
bool RenderableConstellationBounds::isReady() const {
return (_vao != 0) && (_vbo != 0) && (_program != nullptr);
return (_vao != 0) && (_vbo != 0) && _program;
}
void RenderableConstellationBounds::render(const RenderData& data) {
@@ -168,7 +197,6 @@ void RenderableConstellationBounds::render(const RenderData& data) {
for (const ConstellationBound& bound : _constellationBounds) {
if (bound.isEnabled) {
glDrawArrays(
//GL_LINE_STRIP,
GL_LINE_LOOP,
static_cast<GLsizei>(bound.startIndex),
static_cast<GLsizei>(bound.nVertices)
@@ -188,46 +216,49 @@ void RenderableConstellationBounds::update(const UpdateData& data) {
}
bool RenderableConstellationBounds::loadVertexFile() {
if (_vertexFilename.empty())
return false;
std::string fileName = absPath(_vertexFilename);
std::ifstream file(fileName);
if (!file.good()) {
LERROR("Could not open file '" << fileName << "' for reading");
if (_vertexFilename.empty()) {
return false;
}
std::string fileName = absPath(_vertexFilename);
std::ifstream file;
file.exceptions(std::ifstream::goodbit);
file.open(fileName);
ConstellationBound currentBound;
currentBound.constellationAbbreviation = "";
std::string currentLine;
int currentLineNumber = 1;
float ra;
float dec;
std::string constellationName;
double rectangularValues[3];
// Overview of the reading algorithm:
// We keep an active ConstellationBound (currentBound) and update it until we read
// a new constellation name, at which point the currentBound is stored away, a new,
// empty ConstellationBound is created and set at the currentBound
while (file.good()) {
std::getline(file, currentLine);
if (currentLine.empty())
if (currentLine.empty()) {
continue;
}
// @CHECK: Is this the best way of doing this? ---abock
std::stringstream s(currentLine);
float ra;
s >> ra;
float dec;
s >> dec;
std::string constellationName;
s >> constellationName;
if (!s.good()) {
// If this evaluates to true, the stream was not completely filled, which
// means that the line was incomplete, so there was an error
LERROR("Error reading file '" << fileName << "' at line #" << currentLineNumber);
LERRORC(
"RenderableConstellationBounds",
"Error reading file '" << fileName << "' at line #" << currentLineNumber
);
break;
}
@@ -254,6 +285,7 @@ bool RenderableConstellationBounds::loadVertexFile() {
// Convert the (right ascension, declination) to rectangular coordinates)
// The 1.0 is the distance of the celestial sphere, we will scale that in the
// render function
double rectangularValues[3];
radrec_c(1.0, ra, dec, rectangularValues);
// Add the new vertex to our list of vertices
@@ -277,39 +309,43 @@ bool RenderableConstellationBounds::loadVertexFile() {
}
bool RenderableConstellationBounds::loadConstellationFile() {
if (_constellationFilename.empty())
if (_constellationFilename.empty()) {
return true;
std::string fileName = absPath(_constellationFilename);
std::ifstream file(fileName);
if (!file.good()) {
LERROR("Could not open file '" << fileName << "' for reading");
return false;
}
std::ifstream file;
file.exceptions(std::ifstream::goodbit);
file.open(absPath(_constellationFilename));
std::string line;
int index = 0;
while (file.good()) {
std::getline(file, line);
if (line.empty())
std::getline(file, line);
if (line.empty()) {
continue;
}
std::string abbreviation;
std::stringstream s(line);
s >> abbreviation;
auto it = std::find_if(_constellationBounds.begin(), _constellationBounds.end(),
auto it = std::find_if(
_constellationBounds.begin(),
_constellationBounds.end(),
[abbreviation](const ConstellationBound& bound) {
return bound.constellationAbbreviation == abbreviation;
});
}
);
if (it == _constellationBounds.end()) {
LERROR("Could not find constellation '" << abbreviation << "' in list");
LERRORC(
"RenderableConstellationBounds",
"Could not find constellation '" << abbreviation << "' in list"
);
return false;
}
// Update the constellations full name
s >> it->constellationFullName;
++index;
}
@@ -329,18 +365,21 @@ void RenderableConstellationBounds::selectionPropertyHasChanged() {
const std::vector<int>& values = _constellationSelection;
// If no values are selected (the default), we want to show all constellations
if (values.size() == 0) {
for (ConstellationBound& b : _constellationBounds)
for (ConstellationBound& b : _constellationBounds) {
b.isEnabled = true;
}
}
else {
// In the worst case, this algorithm runs with 2 * nConstellations, which is
// acceptable as the number of constellations is < 100
// First disable all constellations
for (ConstellationBound& b : _constellationBounds)
for (ConstellationBound& b : _constellationBounds) {
b.isEnabled = false;
}
// then re-enable the ones for which we have indices
for (int value : values)
for (int value : values) {
_constellationBounds[value].isEnabled = true;
}
}
}

View File

@@ -34,6 +34,8 @@
namespace openspace {
namespace documentation { struct Documentation; }
/**
* This class renders the constellation bounds as defined in
* http://cdsarc.u-strasbg.fr/viz-bin/Cat?cat=VI%2F49. It contains the bounds on the
@@ -42,14 +44,6 @@ namespace openspace {
* The bounds are drawn as lines on a sphere with variable radius, set by the
* <code>_distance</code> property. Currently, all constellation bounds are lines, which
* leads to artifacts if the radius is very small.
* Renderable configuration attributes:
* <code>File</code> [string] (required): The file that contains the bounds and the
* abbreviations for the different constellations
* <code>ConstellationFile</code> [string]: The file that contains the mapping between
* abbreviations and full names. If the file is omitted, the abbreviations are used as the
* full names.
* <code>ReferenceFrame</code> [string]: The reference frame in which the points contained
* in the <code>File</code> are stored in. Defaults to <code>J2000</code>
*/
class RenderableConstellationBounds : public Renderable {
public:
@@ -63,6 +57,8 @@ public:
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
static documentation::Documentation Documentation();
private:
/// Stores the constellation bounds
struct ConstellationBound {
@@ -106,7 +102,7 @@ private:
/// The list of all loaded constellation bounds
std::vector<ConstellationBound> _constellationBounds;
typedef std::array<float, 3> Vertex;
using Vertex = std::array<float, 3>;
std::vector<Vertex> _vertexValues; ///< A list of all vertices of all bounds
/// The radius of the celestial sphere onto which the bounds are drawn

View File

@@ -22,9 +22,11 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
// open space includes
#include <modules/space/rendering/renderableplanet.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/configurationmanager.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
@@ -39,6 +41,7 @@
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/misc/invariants.h>
#include <memory>
#include <fstream>
@@ -48,21 +51,76 @@
namespace {
const char* KeyGeometry = "Geometry";
const char* KeyRadius = "Radius";
const char* KeyColorTexture = "Textures.Color";
const char* KeyNightTexture = "Textures.Night";
const char* KeyHeightTexture = "Textures.Height";
const char* KeyShading = "PerformShading";
static const std::string _loggerCat = "RenderablePlanet";
const char* keyFrame = "Frame";
const char* keyGeometry = "Geometry";
const char* keyRadius = "Radius";
const char* keyShading = "PerformShading";
const char* keyShadowGroup = "Shadow_Group";
const char* keyShadowSource = "Source";
const char* keyShadowCaster = "Caster";
// const char* keyPlanetRadius = "PlanetRadius";
const char* keyBody = "Body";
}
} // namespace
namespace openspace {
documentation::Documentation RenderablePlanet::Documentation() {
using namespace documentation;
return {
"RenderablePlanet",
"space_renderable_planet",
{
{
KeyGeometry,
new ReferencingVerifier("space_geometry_planet"),
"Specifies the planet geometry that is used for this RenderablePlanet.",
Optional::No
},
{
KeyRadius,
new DoubleVerifier,
"Specifies the radius of the planet. If this value is not specified, it "
"will try to query the SPICE library for radius values.",
Optional::Yes
},
{
KeyColorTexture,
new StringVerifier,
"Specifies the color texture that is used for this RenderablePlanet.",
Optional::Yes
},
{
KeyHeightTexture,
new StringVerifier,
"Specifies the height texture that is used for this RenderablePlanet.",
Optional::Yes
},
{
KeyNightTexture,
new StringVerifier,
"Specifies the texture that is used for the night side of this "
"RenderablePlanet.",
Optional::Yes
},
{
KeyShading,
new BoolVerifier,
"Specifies whether the planet should be rendered shaded by the Sun. If "
"this value is 'false', any existing night texture will not be used. "
"This value defaults to 'true'.",
Optional::Yes
}
}
};
}
RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _colorTexturePath("colorTexture", "Color Texture")
@@ -74,118 +132,85 @@ RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary)
, _heightExaggeration("heightExaggeration", "Height Exaggeration", 1.f, 0.f, 10.f)
, _geometry(nullptr)
, _performShading("performShading", "Perform Shading", true)
, _rotation("rotation", "Rotation", 0, 0, 360)
, _alpha(1.f)
, _planetRadius(0.f)
, _hasNightTexture(false)
, _hasHeightTexture(false)
, _shadowEnabled(false)
{
std::string name;
bool success = dictionary.getValue(SceneGraphNode::KeyName, name);
ghoul_assert(
success,
std::string("RenderablePlanet need the '") + SceneGraphNode::KeyName +
"' be specified"
ghoul_precondition(
dictionary.hasKeyAndValue<std::string>(SceneGraphNode::KeyName),
"RenderablePlanet needs the name to be specified"
);
ghoul::Dictionary geometryDictionary;
success = dictionary.getValue(keyGeometry, geometryDictionary);
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderablePlanet"
);
const std::string name = dictionary.value<std::string>(SceneGraphNode::KeyName);
glm::dvec3 radius;
bool accutareRadius = false;
try {
SpiceManager::ref().getValue(name, "RADII", radius);
accutareRadius = true;
} catch (const SpiceManager::SpiceException& e) {
accutareRadius = false;
ghoul::Dictionary geomDict = dictionary.value<ghoul::Dictionary>(KeyGeometry);
if (dictionary.hasKey(KeyRadius)) {
// If the user specified a radius, we want to use this
_planetRadius = dictionary.value<double>(KeyRadius);
}
if (accutareRadius) {
else if (SpiceManager::ref().hasValue(name, "RADII") ) {
// If the user didn't specfify a radius, but Spice has a radius, we can use this
glm::dvec3 radius;
SpiceManager::ref().getValue(name, "RADII", radius);
radius *= 1000.0; // Spice gives radii in KM.
std::swap(radius[1], radius[2]); // z is equivalent to y in our coordinate system
geometryDictionary.setValue(keyRadius, radius);
geomDict.setValue(KeyRadius, radius);
_planetRadius = (radius.x + radius.y + radius.z) / 3.0;
}
else {
LERRORC("RenderablePlanet", "Missing radius specification");
}
if (success) {
//geometryDictionary.setValue(SceneGraphNode::KeyName, name);
_geometry = planetgeometry::PlanetGeometry::createFromDictionary(geometryDictionary);
float planetRadius;
if (accutareRadius) {
_planetRadius = (radius[0] + radius[1] + radius[2]) / 3.0;
} else if (geometryDictionary.getValue(keyRadius, planetRadius)) {
_planetRadius = planetRadius;
}
else {
LWARNING("No Radius value specified for " << name << " planet.");
}
_geometry = planetgeometry::PlanetGeometry::createFromDictionary(geomDict);
if (dictionary.hasKey(KeyColorTexture)) {
_colorTexturePath = absPath(dictionary.value<std::string>(KeyColorTexture));
}
//===============================================================
//======== Reads Body and Frame Entries in mod file =============
//===============================================================
dictionary.getValue(keyFrame, _frame);
dictionary.getValue(keyBody, _target);
//============================================================
//======== Reads the Texture Entries in mod file =============
//============================================================
// TODO: textures need to be replaced by a good system similar to the geometry as soon
// as the requirements are fixed (ab)
std::string texturePath = "";
success = dictionary.getValue("Textures.Color", texturePath);
if (success)
_colorTexturePath = absPath(texturePath);
std::string nightTexturePath = "";
dictionary.getValue("Textures.Night", nightTexturePath);
if (nightTexturePath != ""){
if (dictionary.hasKey(KeyNightTexture)) {
_hasNightTexture = true;
_nightTexturePath = absPath(nightTexturePath);
_nightTexturePath = absPath(dictionary.value<std::string>(KeyNightTexture));
}
std::string heightMapTexturePath = "";
dictionary.getValue("Textures.Height", heightMapTexturePath);
if (heightMapTexturePath != "") {
if (dictionary.hasKey(KeyHeightTexture)) {
_hasHeightTexture = true;
_heightMapTexturePath = absPath(heightMapTexturePath);
_heightMapTexturePath = absPath(dictionary.value<std::string>(KeyHeightTexture));
}
if (dictionary.hasKey(KeyShading)) {
_performShading = dictionary.value<bool>(KeyShading);
}
addPropertySubOwner(_geometry.get());
auto loadTextureCallback = [this]() {loadTexture(); };
addProperty(_colorTexturePath);
_colorTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this));
_colorTexturePath.onChange(loadTextureCallback);
addProperty(_nightTexturePath);
_nightTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this));
_nightTexturePath.onChange(loadTextureCallback);
addProperty(_heightMapTexturePath);
_heightMapTexturePath.onChange(std::bind(&RenderablePlanet::loadTexture, this));
_heightMapTexturePath.onChange(loadTextureCallback);
addProperty(_heightExaggeration);
//=========================================================
//======== Shading and Rotation as Properties =============
//=========================================================
if (dictionary.hasKeyAndValue<bool>(keyShading)) {
bool shading;
dictionary.getValue(keyShading, shading);
_performShading = shading;
}
addProperty(_performShading);
// Mainly for debugging purposes @AA
addProperty(_rotation);
//================================================================
//======== Reads Shadow (Eclipses) Entries in mod file ===========
//================================================================
ghoul::Dictionary shadowDictionary;
success = dictionary.getValue(keyShadowGroup, shadowDictionary);
bool success = dictionary.getValue(keyShadowGroup, shadowDictionary);
bool disableShadows = false;
if (success) {
std::vector< std::pair<std::string, float > > sourceArray;
@@ -259,9 +284,6 @@ RenderablePlanet::RenderablePlanet(const ghoul::Dictionary& dictionary)
}
}
RenderablePlanet::~RenderablePlanet() {
}
bool RenderablePlanet::initialize() {
RenderEngine& renderEngine = OsEng.renderEngine();
@@ -280,8 +302,6 @@ bool RenderablePlanet::initialize() {
"shadowNightProgram",
"${MODULE_SPACE}/shaders/shadow_nighttexture_vs.glsl",
"${MODULE_SPACE}/shaders/shadow_nighttexture_fs.glsl");
if (!_programObject)
return false;
}
else if (_programObject == nullptr && _shadowEnabled) {
// shadow program
@@ -289,8 +309,6 @@ bool RenderablePlanet::initialize() {
"shadowProgram",
"${MODULE_SPACE}/shaders/shadow_vs.glsl",
"${MODULE_SPACE}/shaders/shadow_fs.glsl");
if (!_programObject)
return false;
}
else if (_programObject == nullptr && _hasNightTexture) {
// Night texture program
@@ -298,8 +316,6 @@ bool RenderablePlanet::initialize() {
"nightTextureProgram",
"${MODULE_SPACE}/shaders/nighttexture_vs.glsl",
"${MODULE_SPACE}/shaders/nighttexture_fs.glsl");
if (!_programObject)
return false;
}
else if (_programObject == nullptr) {
// pscstandard
@@ -307,8 +323,6 @@ bool RenderablePlanet::initialize() {
"pscstandard",
"${MODULE_SPACE}/shaders/renderableplanet_vs.glsl",
"${MODULE_SPACE}/shaders/renderableplanet_fs.glsl");
if (!_programObject)
return false;
}
using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError;
@@ -336,7 +350,7 @@ bool RenderablePlanet::initialize() {
}
bool RenderablePlanet::deinitialize() {
if(_geometry) {
if (_geometry) {
_geometry->deinitialize();
_geometry = nullptr;
}
@@ -347,9 +361,9 @@ bool RenderablePlanet::deinitialize() {
_programObject = nullptr;
}
_geometry = nullptr;
_texture = nullptr;
_nightTexture = nullptr;
_geometry = nullptr;
_texture = nullptr;
_nightTexture = nullptr;
return true;
}

View File

@@ -52,6 +52,8 @@ namespace planetgeometry {
class PlanetGeometry;
}
namespace documentation { struct Documentation; }
class RenderablePlanet : public Renderable {
public:
// Shadow structure
@@ -69,8 +71,7 @@ public:
};
public:
explicit RenderablePlanet(const ghoul::Dictionary& dictionary);
~RenderablePlanet();
RenderablePlanet(const ghoul::Dictionary& dictionary);
bool initialize() override;
bool deinitialize() override;
@@ -79,6 +80,8 @@ public:
void render(const RenderData& data) override;
void update(const UpdateData& data) override;
static documentation::Documentation Documentation();
protected:
void loadTexture();
private:
@@ -96,14 +99,11 @@ private:
std::unique_ptr<planetgeometry::PlanetGeometry> _geometry;
properties::BoolProperty _performShading;
properties::IntProperty _rotation;
float _alpha;
std::vector< ShadowConf > _shadowConfArray;
float _planetRadius;
glm::dmat3 _stateMatrix;
std::string _frame;
std::string _target;
bool _hasNightTexture;
bool _hasHeightTexture;
bool _shadowEnabled;

View File

@@ -29,6 +29,7 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scene/scene.h>
#include <ghoul/filesystem/filesystem>
#include <ghoul/io/texture/texturereader.h>

View File

@@ -31,6 +31,8 @@
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <ghoul/opengl/ghoul_gl.h>
namespace ghoul {
namespace filesystem { class File; }
namespace opengl {
@@ -40,7 +42,8 @@ namespace opengl {
} // namespace ghoul
namespace openspace {
namespace documentation { struct Documentation; }
namespace documentation { struct Documentation; }
class RenderableStars : public Renderable {
public:

View File

@@ -25,6 +25,7 @@
#include <modules/space/rendering/simplespheregeometry.h>
#include <openspace/util/powerscaledsphere.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/rendering/renderable.h>
namespace {
const std::string _loggerCat = "SimpleSphereGeometry";

View File

@@ -82,9 +82,12 @@ void SpaceModule::internalInitialize() {
std::vector<documentation::Documentation> SpaceModule::documentations() const {
return {
RenderableConstellationBounds::Documentation(),
RenderablePlanet::Documentation(),
RenderableRings::Documentation(),
RenderableStars::Documentation(),
SpiceRotation::Documentation(),
SpiceTranslation::Documentation(),
RenderableRings::Documentation(),
planetgeometry::PlanetGeometry::Documentation()
};
}

View File

@@ -41,8 +41,8 @@ namespace ghoul {
namespace openspace {
class RenderData;
class RaycastData;
struct RenderData;
struct RaycastData;
class ToyVolumeRaycaster : public VolumeRaycaster {
public:

View File

@@ -63,30 +63,13 @@ return {
},
CapabilitiesVerbosity = "Full"
},
LuaDocumentation = {
Type = "html",
File = "${DOCUMENTATION}/LuaScripting.html"
},
PropertyDocumentation = {
Type = "html",
File = "${DOCUMENTATION}/Properties.html"
},
ScriptLog = {
Type = "text",
File = "${BASE_PATH}/ScriptLog.txt"
},
KeyboardShortcuts = {
Type = "html",
File = "${DOCUMENTATION}/KeyboardMapping.html"
},
Documentation = {
Type = "html",
File = "${DOCUMENTATION}/Documentation.html"
},
FactoryDocumentation = {
Type = "html",
File = "${DOCUMENTATION}/FactoryDocumentation.html"
},
LuaDocumentation = "${DOCUMENTATION}/LuaScripting.html",
PropertyDocumentation = "${DOCUMENTATION}/Properties.html",
ScriptLog = "${BASE_PATH}/ScriptLog.txt",
KeyboardShortcuts = "${DOCUMENTATION}/KeyboardMapping.html",
Documentation = "${DOCUMENTATION}/Documentation.html",
FactoryDocumentation = "${DOCUMENTATION}/FactoryDocumentation.html",
ShutdownCountdown = 3,
-- OnScreenTextScaling = "framebuffer",
-- PerSceneCache = true,

View File

@@ -27,6 +27,7 @@ set(OPENSPACE_SOURCE
${OPENSPACE_BASE_DIR}/src/documentation/core_registration.cpp
${OPENSPACE_BASE_DIR}/src/documentation/documentation.cpp
${OPENSPACE_BASE_DIR}/src/documentation/documentationengine.cpp
${OPENSPACE_BASE_DIR}/src/documentation/documentationgenerator.cpp
${OPENSPACE_BASE_DIR}/src/documentation/verifier.cpp
${OPENSPACE_BASE_DIR}/src/engine/configurationmanager.cpp
${OPENSPACE_BASE_DIR}/src/engine/configurationmanager_doc.inl
@@ -167,6 +168,7 @@ set(OPENSPACE_HEADER
${OPENSPACE_BASE_DIR}/include/openspace/documentation/core_registration.h
${OPENSPACE_BASE_DIR}/include/openspace/documentation/documentation.h
${OPENSPACE_BASE_DIR}/include/openspace/documentation/documentationengine.h
${OPENSPACE_BASE_DIR}/include/openspace/documentation/documentationgenerator.h
${OPENSPACE_BASE_DIR}/include/openspace/documentation/verifier.h
${OPENSPACE_BASE_DIR}/include/openspace/documentation/verifier.inl
${OPENSPACE_BASE_DIR}/include/openspace/engine/configurationmanager.h

View File

@@ -38,13 +38,11 @@
#include <fmt/format.h>
namespace {
const std::string MainTemplateFilename = "${OPENSPACE_DATA}/web/documentation/main.hbs";
const std::string DocumentationTemplateFilename = "${OPENSPACE_DATA}/web/documentation/documentation.hbs";
const std::string HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js";
const std::string JsFilename = "${OPENSPACE_DATA}/web/documentation/script.js";
const std::string BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css";
const std::string CssFilename = "${OPENSPACE_DATA}/web/common/style.css";
}
const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/documentation/main.hbs";
const char* DocumentationTemplateFilename =
"${OPENSPACE_DATA}/web/documentation/documentation.hbs";
const char* JsFilename = "${OPENSPACE_DATA}/web/documentation/script.js";
} // namespace
namespace openspace {
namespace documentation {
@@ -61,6 +59,19 @@ DocumentationEngine::DuplicateDocumentationException::DuplicateDocumentationExce
, documentation(std::move(documentation))
{}
DocumentationEngine::DocumentationEngine()
: DocumentationGenerator(
"Documentation",
"documentation",
{
{ "mainTemplate", MainTemplateFilename },
{ "documentationTemplate", DocumentationTemplateFilename }
},
JsFilename
)
{}
DocumentationEngine& DocumentationEngine::ref() {
if (_instance == nullptr) {
_instance = new DocumentationEngine;
@@ -113,7 +124,10 @@ std::string generateTextDocumentation(const Documentation& d, int& indentLevel)
} else if (tv) {
// We have a TableVerifier, so we need to recurse
++indentLevel;
result += generateTextDocumentation({ "", "", tv->documentations }, indentLevel);
result += generateTextDocumentation(
{ "", "", tv->documentations },
indentLevel
);
result = result.substr(0, result.size() - 2);
--indentLevel;
}
@@ -256,124 +270,30 @@ std::string generateHtmlDocumentation(const Documentation& d) {
return html.str();
}
void DocumentationEngine::writeDocumentation(const std::string& f, const std::string& t) {
if (t == "text") {
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(f);
std::string DocumentationEngine::generateJson() const {
std::stringstream json;
json << "[";
for (const Documentation& d : _documentations) {
int indent = 0;
file << documentation::generateTextDocumentation(d, indent) << "\n\n";
for (const Documentation& d : _documentations) {
json << generateJsonDocumentation(d);
if (&d != &_documentations.back()) {
json << ", ";
}
}
else if (t == "html") {
std::ifstream handlebarsInput(absPath(HandlebarsFilename));
std::ifstream jsInput(absPath(JsFilename));
std::string jsContent;
std::back_insert_iterator<std::string> jsInserter(jsContent);
json << "]";
std::copy(std::istreambuf_iterator<char>{handlebarsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::copy(std::istreambuf_iterator<char>{jsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::ifstream bootstrapInput(absPath(BootstrapFilename));
std::ifstream cssInput(absPath(CssFilename));
std::string cssContent;
std::back_insert_iterator<std::string> cssInserter(cssContent);
std::copy(std::istreambuf_iterator<char>{bootstrapInput}, std::istreambuf_iterator<char>(), cssInserter);
std::copy(std::istreambuf_iterator<char>{cssInput}, std::istreambuf_iterator<char>(), cssInserter);
std::ifstream mainTemplateInput(absPath(MainTemplateFilename));
std::string mainTemplateContent{ std::istreambuf_iterator<char>{mainTemplateInput},
std::istreambuf_iterator<char>{}};
std::ifstream documentationTemplateInput(absPath(DocumentationTemplateFilename));
std::string documentationTemplateContent{ std::istreambuf_iterator<char>{documentationTemplateInput},
std::istreambuf_iterator<char>{} };
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(f);
std::stringstream json;
json << "[";
for (const Documentation& d : _documentations) {
json << generateJsonDocumentation(d);
if (&d != &_documentations.back()) {
json << ", ";
}
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
}
json << "]";
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
} else {
jsonString += c;
}
else {
jsonString += c;
}
std::stringstream html;
html << "<!DOCTYPE html>\n"
<< "<html>\n"
<< "\t<head>\n"
<< "\t\t<script id=\"mainTemplate\" type=\"text/x-handlebars-template\">\n"
<< mainTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t\t<script id=\"documentationTemplate\" type=\"text/x-handlebars-template\">\n"
<< documentationTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t<script>\n"
<< "var documentation = JSON.parse('" << jsonString << "');\n"
<< "var version = [" << OPENSPACE_VERSION_MAJOR << ", " << OPENSPACE_VERSION_MINOR << ", " << OPENSPACE_VERSION_PATCH << "];\n"
<< jsContent << "\n"
<< "\t</script>\n"
<< "\t<style type=\"text/css\">\n"
<< cssContent << "\n"
<< "\t</style>\n"
<< "\t\t<title>Documentation</title>\n"
<< "\t</head>\n"
<< "\t<body>\n"
<< "\t<body>\n"
<< "</html>\n";
file << html.str();
/*
Use this for generating documentation in raw html:
html << "<table>\n"
<< "\t<caption>Documentation</caption>\n\n"
<< "\t<thead>\n"
<< "\t\t<tr>\n"
<< "\t\t\t<th rowspan=2>Name</th>\n"
<< "\t\t</tr>\n"
<< "\t\t<tr>\n"
<< "\t\t\t<th>Key</th>\n"
<< "\t\t\t<th>Optional</th>\n"
<< "\t\t\t<th>Type</th>\n"
<< "\t\t\t<th>Restrictions</th>\n"
<< "\t\t\t<th>Documentation</th>\n"
<< "\t\t</tr>\n"
<< "\t</thead>\n"
<< "\t<tbody>\n";
for (const Documentation& d : _documentations) {
html << generateHtmlDocumentation(d);
html << "\t<tr><td style=\"line-height: 50px;\" colspan=6></br></td></tr>\n";
}
html << "\t</tbody>\n"
<< "</table>\n";
*/
}
return jsonString;
}
void DocumentationEngine::addDocumentation(Documentation doc) {

View File

@@ -0,0 +1,152 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* 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/documentation/documentationgenerator.h>
#include <openspace/openspace.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/misc/invariants.h>
#include <fstream>
namespace {
const char* HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js";
const char* BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css";
const char* CssFilename = "${OPENSPACE_DATA}/web/common/style.css";
} // namespace
namespace openspace {
DocumentationGenerator::DocumentationGenerator(std::string name,
std::string jsonName,
std::vector<HandlebarTemplate> handlebarTemplates,
std::string javascriptFilename)
: _name(std::move(name))
, _jsonName(std::move(jsonName))
, _handlebarTemplates(std::move(handlebarTemplates))
, _javascriptFile(std::move(javascriptFilename))
{
ghoul_precondition(!_name.empty(), "name must not be empty");
ghoul_precondition(!_jsonName.empty(), "jsonName must not be empty");
for (const HandlebarTemplate& t : _handlebarTemplates) {
ghoul_precondition(!t.name.empty(), "name must not be empty");
ghoul_precondition(!t.filename.empty(), "filename must not be empty");
}
ghoul_precondition(!_javascriptFile.empty(), "javascriptFilename must not be empty");
}
void DocumentationGenerator::writeDocumentation(const std::string& filename) {
std::ifstream handlebarsInput;
handlebarsInput.exceptions(~std::ofstream::goodbit);
handlebarsInput.open(absPath(HandlebarsFilename));
const std::string handlebarsContent = std::string(
std::istreambuf_iterator<char>(handlebarsInput),
std::istreambuf_iterator<char>()
);
std::ifstream jsInput;
jsInput.exceptions(~std::ofstream::goodbit);
jsInput.open(absPath(_javascriptFile));
const std::string jsContent = std::string(
std::istreambuf_iterator<char>(jsInput),
std::istreambuf_iterator<char>()
);
std::ifstream bootstrapInput;
bootstrapInput.exceptions(~std::ofstream::goodbit);
bootstrapInput.open(absPath(BootstrapFilename));
const std::string bootstrapContent = std::string(
std::istreambuf_iterator<char>(bootstrapInput),
std::istreambuf_iterator<char>()
);
std::ifstream cssInput;
cssInput.exceptions(~std::ofstream::goodbit);
cssInput.open(absPath(CssFilename));
const std::string cssContent = std::string(
std::istreambuf_iterator<char>(cssInput),
std::istreambuf_iterator<char>()
);
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
std::string json = generateJson();
// We probably should escape backslashes here?
file << "<!DOCTYPE html>" << '\n'
<< "<html>" << '\n'
<< "\t" << "<head>" << '\n';
for (const HandlebarTemplate& t : _handlebarTemplates) {
const char* Type = "text/x-handlebars-template";
file << "\t\t"
<< "<script id=\"" << t.name << "\" type=\"" << Type << "\">" << '\n';
std::ifstream templateFilename(absPath(t.filename));
std::string templateContent(
std::istreambuf_iterator<char>{templateFilename},
std::istreambuf_iterator<char>{}
);
file << templateContent << '\n';
file << "\t"
<< "</script>" << '\n';
}
const std::string Version =
"[" +
std::to_string(OPENSPACE_VERSION_MAJOR) + "," +
std::to_string(OPENSPACE_VERSION_MINOR) + "," +
std::to_string(OPENSPACE_VERSION_PATCH) +
"]";
std::string generationTime;
try {
generationTime = Time::now().ISO8601();
}
catch (...) {}
file
<< "\t" << "<script>" << '\n'
<< "\t\t" << "var " << _jsonName << " = JSON.parse('" << json << "');" << '\n'
<< "\t\t" << "var version = " << Version << ";" << '\n'
<< "\t\t" << "var generationTime = '" << generationTime << "';" << '\n'
<< "\t\t" << handlebarsContent << '\n'
<< "\t\t" << jsContent << '\n'
<< "\t" << "</script>" << '\n'
<< "\t" << "<style type=\"text/css\">" << '\n'
<< "\t\t" << cssContent << '\n'
<< "\t\t" << bootstrapContent << '\n'
<< "\t" << "</style>" << '\n'
<< "\t\t" << "<title>" << _name << "</title>" << '\n'
<< "\t" << "</head>" << '\n'
<< "\t" << "<body>" << '\n'
<< "\t" << "</body>" << '\n'
<< "</html>" << '\n';
}
} // namespace openspace

View File

@@ -141,143 +141,49 @@ documentation::Documentation ConfigurationManager::Documentation() {
},
{
ConfigurationManager::KeyLuaDocumentation,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List from ScriptEngine::writeDocumentation
{ "text", "html" }
),
"The type of documentation that will be written."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The filename that will be created on startup containing the "
"documentation of available Lua functions. Any existing file "
"will be silently overwritten."
}
}),
"Descriptions of whether and where to create a documentation file that "
"describes the available Lua functions that can be executed in scene "
"files or per console.",
new StringVerifier,
"The filename that will be created on startup containing the documentation "
"of available Lua functions that can be executed in scene files or per "
"console. Any existing file will be silently overwritten.",
Optional::Yes
},
{
ConfigurationManager::KeyPropertyDocumentation,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List taken from Scene::writePropertyDocumentation
{ "text", "html" }
),
"The type of property documentation file that is created."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The file that will be created on startup containing a list of "
"all properties in the scene. Any existing file will be silently "
"overwritten."
}
}),
"Descriptions of whether and where to create a list of all properties "
"that were created in the current scene.",
new StringVerifier,
"The file that will be created on startup containing a list of all "
"properties in the scene. Any existing file will be silently overwritten.",
Optional::Yes
},
{
ConfigurationManager::KeyScriptLog,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List taken from ScriptEngine::writeLog
{ "text" }
),
"The type of logfile that will be created."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The file that will be created on startup containing the log of "
"all Lua scripts that are executed. Any existing file (including "
"the results from previous runs) will be silently overwritten."
}
}),
"Contains a log of all Lua scripts that were executed in the last "
"session.",
new StringVerifier,
"The file that will be created on startup containing the log of all Lua "
"scripts that are executed in the last session. Any existing file (including "
"the results from previous runs) will be silently overwritten.",
Optional::Yes
},
{
ConfigurationManager::KeyKeyboardShortcuts,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List from InteractionHandler::writeKeyboardDocumentation
{ "text", "html" }
),
"The type of keyboard binding documentation that should be "
"written."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The file that will be created on startup containing the list of "
"all keyboard bindings with their respective Lua scripts. Any "
"previous file in this location will be silently overritten."
}
}),
"Contains the collection of all keyboard shortcuts that were collected "
"during startup. For each key, it mentions which scripts will be "
"executed in the current session.",
new StringVerifier,
"The file that will be created on startup containing the list of all "
"keyboard bindings with their respective Lua scripts. For each key, it "
"mentions which scripts will be executed in the current session.",
Optional::Yes
},
{
ConfigurationManager::KeyDocumentation,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List from DocumentationEngine::writeDocumentation
{ "text", "html" }
),
"The type of documentation that should be written."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The file that will be created on startup containing this "
"documentation. Any previous file in this location will be silently "
"overritten."
}
}),
"This defines the location and type of this documentation file.",
new StringVerifier,
"The file that will be created on startup containing this documentation. Any "
"previous file in this location will be silently overwritten.",
Optional::Yes
},
{
ConfigurationManager::KeyFactoryDocumentation,
new TableVerifier({
{
ConfigurationManager::PartType,
new StringInListVerifier(
// List from FactoryManager::writeDocumentation
{ "text", "html" }
),
"The type of documentation that should be written."
},
{
ConfigurationManager::PartFile,
new StringVerifier,
"The file that will be created on startup containing the factory "
"documentation. Any previous file in this location will be silently "
"overritten."
}
}),
"This defines the location and type of the factory documentation file, which "
"shows the different types of objects that can be created in the current "
"application configuration.",
new StringVerifier,
"The file that will be created on startup containing the factory "
"documentation which shows the different types of objects that can be "
"created in the current application configuration. Any previous file in this "
"location will be silently overritten.",
Optional::Yes
},
{

View File

@@ -589,43 +589,21 @@ void OpenSpaceEngine::loadScene(const std::string& scenePath) {
}
// Write keyboard documentation.
{
const std::string KeyboardShortcutsType =
ConfigurationManager::KeyKeyboardShortcuts + "." +
ConfigurationManager::PartType;
const std::string KeyboardShortcutsFile =
ConfigurationManager::KeyKeyboardShortcuts + "." +
ConfigurationManager::PartFile;
std::string type, file;
const bool hasType = configurationManager().getValue(KeyboardShortcutsType, type);
const bool hasFile = configurationManager().getValue(KeyboardShortcutsFile, file);
if (hasType && hasFile) {
file = absPath(file);
interactionHandler().writeKeyboardDocumentation(type, file);
}
if (configurationManager().hasKey(ConfigurationManager::KeyKeyboardShortcuts)) {
interactionHandler().writeDocumentation(
absPath(configurationManager().value<std::string>(
ConfigurationManager::KeyKeyboardShortcuts
))
);
}
// If a PropertyDocumentationFile was specified, generate it now.
{
const std::string KeyPropertyDocumentationType =
ConfigurationManager::KeyPropertyDocumentation + '.' +
ConfigurationManager::PartType;
const std::string KeyPropertyDocumentationFile =
ConfigurationManager::KeyPropertyDocumentation + '.' +
ConfigurationManager::PartFile;
std::string type, file;
const bool hasType = configurationManager().getValue(KeyPropertyDocumentationType, type);
const bool hasFile = configurationManager().getValue(KeyPropertyDocumentationFile, file);
if (hasType && hasFile) {
file = absPath(file);
scene->writePropertyDocumentation(file, type, scenePath);
}
if (configurationManager().hasKey(ConfigurationManager::KeyPropertyDocumentation)) {
scene->writeDocumentation(
absPath(configurationManager().value<std::string>(
ConfigurationManager::KeyPropertyDocumentation
))
);
}
_syncEngine->addSyncables(Time::ref().getSyncables());
@@ -646,72 +624,30 @@ void OpenSpaceEngine::deinitialize() {
void OpenSpaceEngine::writeDocumentation() {
// If a LuaDocumentationFile was specified, generate it now
const std::string LuaDocumentationType =
ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartType;
const std::string LuaDocumentationFile =
ConfigurationManager::KeyLuaDocumentation + "." + ConfigurationManager::PartFile;
const bool hasLuaDocType = configurationManager().hasKey(LuaDocumentationType);
const bool hasLuaDocFile = configurationManager().hasKey(LuaDocumentationFile);
if (hasLuaDocType && hasLuaDocFile) {
std::string luaDocumentationType = configurationManager().value<std::string>(
LuaDocumentationType
);
std::string luaDocumentationFile = configurationManager().value<std::string>(
LuaDocumentationFile
);
if (configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentation)) {
_scriptEngine->writeDocumentation(
absPath(luaDocumentationFile),
luaDocumentationType
absPath(configurationManager().value<std::string>(
ConfigurationManager::KeyLuaDocumentation
))
);
}
// If a general documentation was specified, generate it now
const std::string DocumentationType =
ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartType;
const std::string DocumentationFile =
ConfigurationManager::KeyDocumentation + '.' + ConfigurationManager::PartFile;
const bool hasDocumentationType = configurationManager().hasKey(DocumentationType);
const bool hasDocumentationFile = configurationManager().hasKey(DocumentationFile);
if (hasDocumentationType && hasDocumentationFile) {
std::string documentationType = configurationManager().value<std::string>(
DocumentationType
);
std::string documentationFile = configurationManager().value<std::string>(
DocumentationFile
);
if (configurationManager().hasKey(ConfigurationManager::KeyDocumentation)) {
DocEng.writeDocumentation(
absPath(documentationFile),
documentationType
absPath(configurationManager().value<std::string>(
ConfigurationManager::KeyDocumentation
))
);
}
const std::string FactoryDocumentationType =
ConfigurationManager::KeyFactoryDocumentation + '.' +
ConfigurationManager::PartType;
const std::string FactoryDocumentationFile =
ConfigurationManager::KeyFactoryDocumentation + '.' +
ConfigurationManager::PartFile;
bool hasFactoryDocumentationType = configurationManager().hasKey(
FactoryDocumentationType
);
bool hasFactoryDocumentationFile = configurationManager().hasKey(
FactoryDocumentationFile
);
if (hasFactoryDocumentationType && hasFactoryDocumentationFile) {
std::string type = configurationManager().value<std::string>(
FactoryDocumentationType
// If a factory documentation was specified, generate it now
if (configurationManager().hasKey(ConfigurationManager::KeyFactoryDocumentation)) {
FactoryManager::ref().writeDocumentation(
absPath(configurationManager().value<std::string>(
ConfigurationManager::KeyFactoryDocumentation
))
);
std::string file = configurationManager().value<std::string>(
FactoryDocumentationFile
);
FactoryManager::ref().writeDocumentation(absPath(file), type);
}
}

View File

@@ -59,10 +59,7 @@ namespace {
const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/main.hbs";
const char* KeybindingTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/keybinding.hbs";
const char* HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js";
const char* JsFilename = "${OPENSPACE_DATA}/web/keybindings/script.js";
const char* BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css";
const char* CssFilename = "${OPENSPACE_DATA}/web/common/style.css";
} // namespace
#include "interactionhandler_lua.inl"
@@ -73,6 +70,15 @@ namespace interaction {
// InteractionHandler
InteractionHandler::InteractionHandler()
: properties::PropertyOwner("Interaction")
, DocumentationGenerator(
"Documentation",
"keybindings",
{
{ "keybindingTemplate", KeybindingTemplateFilename },
{ "mainTemplate", MainTemplateFilename }
},
JsFilename
)
, _origin("origin", "Origin", "")
, _rotationalFriction("rotationalFriction", "Rotational Friction", true)
, _horizontalFriction("horizontalFriction", "Horizontal Friction", true)
@@ -433,133 +439,36 @@ void InteractionHandler::bindKey(Key key, KeyModifier modifier,
}
void InteractionHandler::writeKeyboardDocumentation(const std::string& type,
const std::string& file)
{
if (type == "text") {
std::ofstream f;
f.exceptions(~std::ofstream::goodbit);
f.open(absPath(file));
for (const auto& p : _keyLua) {
std::string remoteScriptingInfo;
bool remoteScripting = p.second.synchronization;
if (!remoteScripting) {
remoteScriptingInfo = " (LOCAL)";
}
f << std::to_string(p.first) << ": "
<< p.second.command << remoteScriptingInfo << '\n'
<< p.second.documentation << '\n';
std::string InteractionHandler::generateJson() const {
std::stringstream json;
json << "[";
bool first = true;
for (const auto& p : _keyLua) {
if (!first) {
json << ",";
}
first = false;
json << "{";
json << "\"key\": \"" << std::to_string(p.first) << "\",";
json << "\"script\": \"" << p.second.command << "\",";
json << "\"remoteScripting\": " << (p.second.synchronization ? "true," : "false,");
json << "\"documentation\": \"" << p.second.documentation << "\"";
json << "}";
}
json << "]";
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
} else {
jsonString += c;
}
}
else if (type == "html") {
std::ofstream f;
f.exceptions(~std::ofstream::goodbit);
f.open(absPath(file));
std::ifstream handlebarsInput(absPath(HandlebarsFilename));
std::ifstream jsInput(absPath(JsFilename));
std::string jsContent;
std::back_insert_iterator<std::string> jsInserter(jsContent);
std::copy(std::istreambuf_iterator<char>{handlebarsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::copy(std::istreambuf_iterator<char>{jsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::ifstream bootstrapInput(absPath(BootstrapFilename));
std::ifstream cssInput(absPath(CssFilename));
std::string cssContent;
std::back_insert_iterator<std::string> cssInserter(cssContent);
std::copy(std::istreambuf_iterator<char>{bootstrapInput}, std::istreambuf_iterator<char>(), cssInserter);
std::copy(std::istreambuf_iterator<char>{cssInput}, std::istreambuf_iterator<char>(), cssInserter);
std::ifstream mainTemplateInput(absPath(MainTemplateFilename));
std::string mainTemplateContent{ std::istreambuf_iterator<char>{mainTemplateInput},
std::istreambuf_iterator<char>{} };
std::ifstream keybindingTemplateInput(absPath(KeybindingTemplateFilename));
std::string keybindingTemplateContent{ std::istreambuf_iterator<char>{keybindingTemplateInput},
std::istreambuf_iterator<char>{} };
std::stringstream json;
json << "[";
bool first = true;
for (const auto& p : _keyLua) {
if (!first) {
json << ",";
}
first = false;
json << "{";
json << "\"key\": \"" << std::to_string(p.first) << "\",";
json << "\"script\": \"" << p.second.command << "\",";
json << "\"remoteScripting\": " << (p.second.synchronization ? "true," : "false,");
json << "\"documentation\": \"" << p.second.documentation << "\"";
json << "}";
}
json << "]";
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
} else {
jsonString += c;
}
}
std::string generationTime;
try {
generationTime = Time::now().ISO8601();
}
catch (...) {}
std::stringstream html;
html << "<!DOCTYPE html>\n"
<< "<html>\n"
<< "\t<head>\n"
<< "\t\t<script id=\"mainTemplate\" type=\"text/x-handlebars-template\">\n"
<< mainTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t\t<script id=\"keybindingTemplate\" type=\"text/x-handlebars-template\">\n"
<< keybindingTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t<script>\n"
<< "var keybindings = JSON.parse('" << jsonString << "');\n"
<< "var version = [" << OPENSPACE_VERSION_MAJOR << ", " << OPENSPACE_VERSION_MINOR << ", " << OPENSPACE_VERSION_PATCH << "];\n"
<< "var generationTime = '" << generationTime << "';\n"
<< jsContent << "\n"
<< "\t</script>\n"
<< "\t<style type=\"text/css\">\n"
<< cssContent << "\n"
<< "\t</style>\n"
<< "\t\t<title>Documentation</title>\n"
<< "\t</head>\n"
<< "\t<body>\n"
<< "\t<body>\n"
<< "</html>\n";
f << html.str();
/*
for (const auto& p : _keyLua) {
html << "\t\t<tr>\n"
<< "\t\t\t<td>" << std::to_string(p.first) << "</td>\n"
<< "\t\t\t<td>" << p.second.first << "</td>\n"
<< "\t\t\t<td>" << (p.second.second ? "Yes" : "No") << "</td>\n"
<< "\t\t</tr>\n";
}*/
}
else {
throw ghoul::RuntimeError(
"Unsupported keyboard documentation type '" + type + "'",
"InteractionHandler"
);
}
return jsonString;
}
scripting::LuaLibrary InteractionHandler::luaLibrary() {
return{

View File

@@ -29,6 +29,7 @@
#include <openspace/query/query.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scene/scene.h>
#include <openspace/util/time.h>
#include <openspace/util/keys.h>

View File

@@ -137,19 +137,19 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dict) {
}
}
const std::string & MissionPhase::name() const {
std::string MissionPhase::name() const {
return _name;
}
const TimeRange & MissionPhase::timeRange() const {
TimeRange MissionPhase::timeRange() const {
return _timeRange;
}
const std::string & MissionPhase::description() const {
std::string MissionPhase::description() const {
return _description;
}
const std::vector<MissionPhase>& MissionPhase::phases() const {
std::vector<MissionPhase> MissionPhase::phases() const {
return _subphases;
}
@@ -163,6 +163,8 @@ MissionPhase::Trace MissionPhase::phaseTrace(double time, int maxDepth) const {
}
void MissionPhase::phaseTrace(double time, Trace& trace, int maxDepth) const {
ghoul_assert(maxDepth >= 0, "maxDepth must not be negative");
if (maxDepth == 0) {
return;
}
@@ -180,7 +182,7 @@ void MissionPhase::phaseTrace(double time, Trace& trace, int maxDepth) const {
}
}
Mission missionFromFile(std::string filename) {
Mission missionFromFile(const std::string& filename) {
ghoul_assert(!filename.empty(), "filename must not be empty");
ghoul_assert(!FileSys.containsToken(filename), "filename must not contain tokens");
ghoul_assert(FileSys.fileExists(filename), "filename must exist");

View File

@@ -31,6 +31,9 @@
#include <ghoul/misc/sharedmemory.h>
#include <ghoul/misc/onscopeexit.h>
#include <algorithm>
#include <cstring>
namespace {
const std::string _loggerCat = "PerformanceManager";

File diff suppressed because it is too large Load Diff

View File

@@ -31,7 +31,7 @@
#include <openspace/rendering/renderengine.h>
#include <openspace/util/camera.h>
#include <openspace/util/factorymanager.h>
#include <openspace/scripting/scriptengine.h>
#ifdef WIN32
#define _USE_MATH_DEFINES

View File

@@ -74,18 +74,27 @@ namespace {
const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/properties/main.hbs";
const char* PropertyOwnerTemplateFilename = "${OPENSPACE_DATA}/web/properties/propertyowner.hbs";
const char* PropertyTemplateFilename = "${OPENSPACE_DATA}/web/properties/property.hbs";
const char* HandlebarsFilename = "${OPENSPACE_DATA}/web/common/handlebars-v4.0.5.js";
const char* JsFilename = "${OPENSPACE_DATA}/web/properties/script.js";
const char* BootstrapFilename = "${OPENSPACE_DATA}/web/common/bootstrap.min.css";
const char* CssFilename = "${OPENSPACE_DATA}/web/common/style.css";
} // namespace
namespace openspace {
Scene::Scene() {}
Scene::~Scene() {}
Scene::Scene()
: DocumentationGenerator(
"Documented",
"propertyOwners",
{
{ "mainTemplate", MainTemplateFilename },
{ "propertyOwnerTemplate", PropertyOwnerTemplateFilename },
{ "propertyTemplate", PropertyTemplateFilename }
},
JsFilename
)
{}
Scene::~Scene(){
}
void Scene::setRoot(std::unique_ptr<SceneGraphNode> root) {
if (_root) {
removeNode(_root.get());
@@ -266,165 +275,71 @@ const std::vector<SceneGraphNode*>& Scene::allSceneGraphNodes() const {
return _topologicallySortedNodes;
}
void Scene::writePropertyDocumentation(const std::string& filename, const std::string& type, const std::string& sceneFilename) {
LDEBUG("Writing documentation for properties");
if (type == "text") {
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
using properties::Property;
for (SceneGraphNode* node : allSceneGraphNodes()) {
std::vector<Property*> properties = node->propertiesRecursive();
if (!properties.empty()) {
file << node->name() << std::endl;
for (Property* p : properties) {
file << p->fullyQualifiedIdentifier() << ": " <<
p->guiName() << std::endl;
}
file << std::endl;
}
}
}
else if (type == "html") {
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
std::ifstream handlebarsInput(absPath(HandlebarsFilename));
std::ifstream jsInput(absPath(JsFilename));
std::string jsContent;
std::back_insert_iterator<std::string> jsInserter(jsContent);
std::copy(std::istreambuf_iterator<char>{handlebarsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::copy(std::istreambuf_iterator<char>{jsInput}, std::istreambuf_iterator<char>(), jsInserter);
std::ifstream bootstrapInput(absPath(BootstrapFilename));
std::ifstream cssInput(absPath(CssFilename));
std::string cssContent;
std::back_insert_iterator<std::string> cssInserter(cssContent);
std::copy(std::istreambuf_iterator<char>{bootstrapInput}, std::istreambuf_iterator<char>(), cssInserter);
std::copy(std::istreambuf_iterator<char>{cssInput}, std::istreambuf_iterator<char>(), cssInserter);
std::ifstream mainTemplateInput(absPath(MainTemplateFilename));
std::string mainTemplateContent{ std::istreambuf_iterator<char>{mainTemplateInput},
std::istreambuf_iterator<char>{} };
std::ifstream propertyOwnerTemplateInput(absPath(PropertyOwnerTemplateFilename));
std::string propertyOwnerTemplateContent{ std::istreambuf_iterator<char>{propertyOwnerTemplateInput},
std::istreambuf_iterator<char>{} };
std::ifstream propertyTemplateInput(absPath(PropertyTemplateFilename));
std::string propertyTemplateContent{ std::istreambuf_iterator<char>{propertyTemplateInput},
std::istreambuf_iterator<char>{} };
// Create JSON
std::function<std::string(properties::PropertyOwner*)> createJson =
[&createJson](properties::PropertyOwner* owner) -> std::string
{
std::stringstream json;
json << "{";
json << "\"name\": \"" << owner->name() << "\",";
json << "\"properties\": [";
auto properties = owner->properties();
for (properties::Property* p : properties) {
json << "{";
json << "\"id\": \"" << p->identifier() << "\",";
json << "\"type\": \"" << p->className() << "\",";
json << "\"fullyQualifiedId\": \"" << p->fullyQualifiedIdentifier() << "\",";
json << "\"guiName\": \"" << p->guiName() << "\"";
json << "}";
if (p != properties.back()) {
json << ",";
}
}
json << "],";
json << "\"propertyOwners\": [";
auto propertyOwners = owner->propertySubOwners();
for (properties::PropertyOwner* o : propertyOwners) {
json << createJson(o);
if (o != propertyOwners.back()) {
json << ",";
}
}
json << "]";
json << "}";
return json.str();
};
std::string Scene::generateJson() const {
std::function<std::string(properties::PropertyOwner*)> createJson =
[&createJson](properties::PropertyOwner* owner) -> std::string
{
std::stringstream json;
json << "[";
std::vector<SceneGraphNode*> nodes = allSceneGraphNodes();
if (!nodes.empty()) {
json << std::accumulate(
std::next(nodes.begin()),
nodes.end(),
createJson(*nodes.begin()),
[createJson](std::string a, SceneGraphNode* n) {
return a + "," + createJson(n);
}
);
}
json << "{";
json << "\"name\": \"" << owner->name() << "\",";
json << "]";
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
} else {
jsonString += c;
json << "\"properties\": [";
auto properties = owner->properties();
for (properties::Property* p : properties) {
json << "{";
json << "\"id\": \"" << p->identifier() << "\",";
json << "\"type\": \"" << p->className() << "\",";
json << "\"fullyQualifiedId\": \"" << p->fullyQualifiedIdentifier() << "\",";
json << "\"guiName\": \"" << p->guiName() << "\"";
json << "}";
if (p != properties.back()) {
json << ",";
}
}
json << "],";
std::string generationTime;
try {
generationTime = Time::now().ISO8601();
json << "\"propertyOwners\": [";
auto propertyOwners = owner->propertySubOwners();
for (properties::PropertyOwner* o : propertyOwners) {
json << createJson(o);
if (o != propertyOwners.back()) {
json << ",";
}
}
catch (...) {}
json << "]";
json << "}";
std::stringstream html;
html << "<!DOCTYPE html>\n"
<< "<html>\n"
<< "\t<head>\n"
<< "\t\t<script id=\"mainTemplate\" type=\"text/x-handlebars-template\">\n"
<< mainTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t\t<script id=\"propertyOwnerTemplate\" type=\"text/x-handlebars-template\">\n"
<< propertyOwnerTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t\t<script id=\"propertyTemplate\" type=\"text/x-handlebars-template\">\n"
<< propertyTemplateContent << "\n"
<< "\t\t</script>\n"
<< "\t<script>\n"
<< "var propertyOwners = JSON.parse('" << jsonString << "');\n"
<< "var version = [" << OPENSPACE_VERSION_MAJOR << ", " << OPENSPACE_VERSION_MINOR << ", " << OPENSPACE_VERSION_PATCH << "];\n"
<< "var sceneFilename = '" << sceneFilename << "';\n"
<< "var generationTime = '" << generationTime << "';\n"
<< jsContent << "\n"
<< "\t</script>\n"
<< "\t<style type=\"text/css\">\n"
<< cssContent << "\n"
<< "\t</style>\n"
<< "\t\t<title>Documentation</title>\n"
<< "\t</head>\n"
<< "\t<body>\n"
<< "\t<body>\n"
<< "</html>\n";
file << html.str();
return json.str();
};
std::stringstream json;
json << "[";
std::vector<SceneGraphNode*> nodes = allSceneGraphNodes();
if (!nodes.empty()) {
json << std::accumulate(
std::next(nodes.begin()),
nodes.end(),
createJson(*nodes.begin()),
[createJson](std::string a, SceneGraphNode* n) {
return a + "," + createJson(n);
}
);
}
else
LERROR("Undefined type '" << type << "' for Property documentation");
json << "]";
std::string jsonString = "";
for (const char& c : json.str()) {
if (c == '\'') {
jsonString += "\\'";
}
else {
jsonString += c;
}
}
return jsonString;
}
scripting::LuaLibrary Scene::luaLibrary() {

Some files were not shown because too many files have changed in this diff Show More