Merge branch 'develop' into solarsystem2

Conflicts:
	scripts/default_startup.lua
	src/rendering/renderablewavefrontobject.cpp
This commit is contained in:
michal
2014-10-23 11:45:24 -04:00
42 changed files with 5002 additions and 475 deletions

1
.gitignore vendored
View File

@@ -9,6 +9,7 @@ ext/SGCT
# generated glsl files
*.gglsl
*.OpenSpaceGenerated.glsl
shaders/generated/*
# CMake stuff
CMakeCache.txt

View File

@@ -39,6 +39,8 @@ set(OPENSPACE_EXT_DIR "${OPENSPACE_BASE_DIR}/ext")
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${OPENSPACE_EXT_DIR})
#include(cotire)
# Make sure a build type is set. Default is Debug.
if(NOT CMAKE_BUILD_TYPE)
set( CMAKE_BUILD_TYPE Debug CACHE STRING

3551
ext/cotire.cmake Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -49,6 +49,7 @@ public:
ABuffer();
virtual ~ABuffer();
virtual void resolve();
virtual bool reinitialize();
void addVolume(const std::string& tag,ghoul::opengl::Texture* volume);
void addTransferFunction(const std::string& tag,ghoul::opengl::Texture* transferFunction);
@@ -58,25 +59,27 @@ public:
protected:
virtual std::string settings() = 0;
virtual bool reinitializeInternal() = 0;
bool initializeABuffer();
void generateShaderSource();
bool updateShader();
std::string openspaceHeaders();
std::string openspaceSamplerCalls();
std::string openspaceSamplers();
std::string openspaceTransferFunction();
void openspaceHeaders();
void openspaceSamplerCalls();
void openspaceSamplers();
void openspaceTransferFunction();
unsigned int _width, _height, _totalPixels;
private:
void updateDimensions();
GLuint _screenQuad;
bool _validShader;
std::string _fragmentShaderPath;
ghoul::filesystem::File* _fragmentShaderFile;
ghoul::opengl::ProgramObject* _resolveShader;
std::vector<std::pair<std::string,ghoul::opengl::Texture*> > _volumes;
@@ -84,13 +87,8 @@ private:
std::vector<ghoul::filesystem::File*> _samplerFiles;
std::vector<std::string> _samplers;
// Development functionality to update shader for changes in several files
std::vector<ghoul::filesystem::File*> _shaderFiles;
float _volumeStepFactor;
}; // ABuffer
} // openspace

View File

@@ -41,6 +41,8 @@ public:
virtual void postRender();
virtual std::string settings();
protected:
virtual bool reinitializeInternal();
private:

View File

@@ -31,6 +31,7 @@ class ABuffer_I {
public:
virtual ~ABuffer_I() {};
virtual bool initialize() = 0;
virtual bool reinitialize() = 0;
virtual void clear() = 0;
virtual void preRender() = 0;

View File

@@ -41,6 +41,8 @@ public:
virtual void postRender();
virtual std::string settings();
protected:
virtual bool reinitializeInternal();
private:
@@ -51,9 +53,6 @@ private:
GLuint _fragmentBuffer;
GLuint _fragmentTexture;
}; // ABufferDynamic
} // openspace

View File

@@ -41,6 +41,8 @@ public:
virtual void postRender();
virtual std::string settings();
protected:
virtual bool reinitializeInternal();
private:

View File

@@ -29,12 +29,11 @@
// sgct header has to be included before all others due to Windows header
#define SGCT_WINDOWS_INCLUDE
#include "sgct.h"
#include <sgct.h>
#include <openspace/interaction/interactionhandler.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/engine/configurationmanager.h>
//#include <ghoul/misc/dictionary.h>
#include <ghoul/opencl/clcontext.h>
#include <ghoul/opencl/clcommandqueue.h>
@@ -46,15 +45,14 @@
#include <openspace/flare/flare.h>
#define ABUFFER_SINGLE_LINKED 1
#define ABUFFER_FIXED 2
#define ABUFFER_DYNAMIC 3
#define ABUFFER_IMPLEMENTATION ABUFFER_SINGLE_LINKED
// #define OPENSPACE_VIDEO_EXPORT
namespace openspace {
// Forward declare to minimize dependencies
class SyncBuffer;
class LuaConsole;
namespace scripting {
class ScriptEngine;
}
@@ -81,8 +79,9 @@ public:
void preSynchronization();
void postSynchronizationPreDraw();
void render();
void postDraw();
void keyboardCallback(int key, int action);
void postDraw();
void keyboardCallback(int key, int action);
void charCallback(unsigned int codepoint);
void mouseButtonCallback(int key, int action);
void mousePositionCallback(int x, int y);
void mouseScrollWheelCallback(int pos);
@@ -91,6 +90,8 @@ public:
void encode();
void decode();
void setInputCommand(bool b);
private:
OpenSpaceEngine(std::string programName);
~OpenSpaceEngine();
@@ -113,7 +114,10 @@ private:
// ScriptEngine* _scriptEngine;
ghoul::opencl::CLContext _context;
sgct::SharedVector<char> _synchronizationBuffer;
SyncBuffer* _syncBuffer;
bool _inputCommand;
LuaConsole* _console;
};
#define OsEng (openspace::OpenSpaceEngine::ref())

View File

@@ -1,3 +1,27 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef INTERACTIONHANDLER_H
#define INTERACTIONHANDLER_H
@@ -36,6 +60,8 @@ public:
void addExternalControl(ExternalControl* controller);
void setCamera(Camera *camera = nullptr);
void setOrigin(SceneGraphNode* node);
Camera * getCamera() const;
const psc getOrigin() const;
void lockControls();
@@ -45,7 +71,7 @@ public:
void orbit(const glm::quat &rotation);
void rotate(const glm::quat &rotation);
void distance(const PowerScaledScalar &distance);
void distance(const PowerScaledScalar &distance, size_t iterations = 0);
void lookAt(const glm::quat &rotation);
void setRotation(const glm::quat &rotation);
@@ -60,6 +86,15 @@ public:
void mouseScrollWheelCallback(int pos);
void addKeyCallback(int key, std::function<void(void)> f);
/**
* Returns the Lua library that contains all Lua functions available to affect the
* interaction. The functions contained are
* - openspace::luascriptfunctions::printScreen
* \return The Lua library that contains all Lua functions available to affect the
* interaction
*/
static scripting::ScriptEngine::LuaLibrary luaLibrary();
private:
glm::vec3 mapToTrackball(glm::vec2 mousePos);

View File

@@ -0,0 +1,60 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef LUACONSOLE_H
#define LUACONSOLE_H
#include <string>
#include <vector>
namespace openspace {
class LuaConsole {
public:
LuaConsole();
~LuaConsole();
void keyboardCallback(int key, int action);
void charCallback(unsigned int codepoint);
void render();
unsigned int commandInputButton();
unsigned int ignoreCodepoint();
private:
void addToCommand(std::string c);
std::string UnicodeToUTF8(unsigned int codepoint);
size_t _inputPosition;
std::vector<std::string> _commandsHistory;
size_t _activeCommand;
std::vector<std::string> _commands;
};
} // namespace openspace
#endif

View File

@@ -78,8 +78,8 @@ private:
GLenum _mode;
unsigned int _isize;
unsigned int _vsize;
Vertex *_varray;
int *_iarray;
Vertex* _varray;
int* _iarray;
glm::dmat3 _stateMatrix; // might need this

View File

@@ -25,18 +25,19 @@
#ifndef __RENDERENGINE_H__
#define __RENDERENGINE_H__
#include <openspace/scenegraph/scenegraph.h>
#include <openspace/scripting/scriptengine.h>
#include <memory>
#include <string>
#include <openspace/abuffer/abuffer.h>
namespace openspace {
// Forward declare to minimize dependencies
class Camera;
class SyncBuffer;
class SceneGraph;
class ABuffer;
class ScreenLog;
class RenderEngine {
public:
@@ -57,13 +58,15 @@ public:
void render();
void postDraw();
void serialize(std::vector<char>& dataStream, size_t& offset);
void deserialize(const std::vector<char>& dataStream, size_t& offset);
void takeScreenshot();
void serialize(SyncBuffer* syncBuffer);
void deserialize(SyncBuffer* syncBuffer);
/**
* Returns the Lua library that contains all Lua functions available to affect the
* rendering. The functions contained are
* - openspace::luascriptfunctions::printScreen
* - openspace::luascriptfunctions::printImage
* \return The Lua library that contains all Lua functions available to affect the
* rendering
*/
@@ -74,6 +77,11 @@ private:
Camera* _mainCamera;
SceneGraph* _sceneGraph;
ABuffer* _abuffer;
ScreenLog* _log;
bool _showInfo;
bool _showScreenLog;
bool _takeScreenshot;
void generateGlslConfig();
};

View File

@@ -111,7 +111,8 @@ public:
void setCameraDirection(glm::vec3 cameraDirection);
glm::vec3 cameraDirection() const;
glm::mat4 viewRotationMatrix() const;
void setViewRotationMatrix(glm::mat4 m);
const glm::mat4& viewRotationMatrix() const;
void compileViewRotationMatrix();
void rotate(const glm::quat& rotation);
@@ -119,7 +120,7 @@ public:
// const glm::quat& rotation() const;
void setRotation(glm::mat4 rotation);
const glm::vec3& viewDirection() const;
const glm::vec3& viewDirection() const;
const float& maxFov() const;
const float& sinMaxFov() const;
@@ -128,7 +129,7 @@ public:
const glm::vec2& scaling() const;
void setLookUpVector(glm::vec3 lookUp);
const glm::vec3 lookUpVector() const;
const glm::vec3& lookUpVector() const;
private:
float _maxFov;

View File

@@ -30,6 +30,12 @@
namespace openspace {
namespace constants {
namespace fonts {
const std::string keySGCT = "SGCTFont";
const std::string keyMono = "UbuntuMono";
const std::string keyLight = "UbuntuLight";
} // namespace fonts
namespace configurationmanager {
const std::string keyPaths = "Paths";
const std::string keyConfigSgct = "SGCTConfig";

View File

@@ -60,7 +60,7 @@ public:
enum class FieldlineEnd {
NORTH,
SOUTH,
OUT
FAROUT
};
KameleonWrapper(const std::string& filename, Model model);

View File

@@ -0,0 +1,67 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <ghoul/logging/log.h>
#include <vector>
#include <tuple>
#include <utility> // pair
namespace openspace {
class ScreenLog : public ghoul::logging::Log {
public:
//typedef std::tuple<ghoul::logging::LogManager::LogLevel, std::string, std::string> LogEntry;
struct LogEntry {
LogEntry(ghoul::logging::LogManager::LogLevel l, double t, std::string ts, std::string c, std::string m) : level(l), timeStamp(t), timeString(ts), category(c), message(m) {};
ghoul::logging::LogManager::LogLevel level;
double timeStamp;
std::string timeString;
std::string category;
std::string message;
};
typedef std::vector<LogEntry>::iterator iterator;
typedef std::vector<LogEntry>::const_iterator const_iterator;
typedef std::vector<LogEntry>::reverse_iterator reverse_iterator;
typedef std::vector<LogEntry>::const_reverse_iterator const_reverse_iterator;
typedef std::pair<reverse_iterator, reverse_iterator> range;
typedef std::pair<const_reverse_iterator, const_reverse_iterator> const_range;
const size_t MaximumSize = 1000;
ScreenLog();
virtual void log(ghoul::logging::LogManager::LogLevel level, const std::string& category,
const std::string& message);
const_range last(size_t n = 10);
private:
std::vector<LogEntry> _entries;
};
}

View File

@@ -0,0 +1,80 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef SYNCBUFFER_H
#define SYNCBUFFER_H
#include <vector>
#include <sgct.h>
namespace openspace {
class SyncBuffer {
public:
SyncBuffer(size_t n);
template<typename T>
void encode(const T& v) {
const size_t size = sizeof(T);
assert(_encodeOffset + size < _n);
memcpy(_dataStream.data() + _encodeOffset, &v, size);
_encodeOffset += size;
}
template<typename T>
T decode() {
const size_t size = sizeof(T);
assert(_decodeOffset + size < _n);
T value;
memcpy(&value, _dataStream.data() + _decodeOffset, size);
_decodeOffset += size;
return value;
}
template<typename T>
void decode(T& value) {
const size_t size = sizeof(T);
assert(_decodeOffset + size < _n);
memcpy(&value, _dataStream.data() + _decodeOffset, size);
_decodeOffset += size;
}
void write();
void read();
private:
size_t _n;
size_t _encodeOffset;
size_t _decodeOffset;
std::vector<char> _dataStream;
sgct::SharedVector<char> _synchronizationBuffer;
};
} // namespace openspace
#endif // SYNCBUFFER_H

View File

@@ -1,14 +1,15 @@
return {
Paths = {
BASE_PATH = "C:/Users/michal/Documents/openspace3",
SGCT = "${BASE_PATH}/config/sgct",
SCRIPTS = "${BASE_PATH}/scripts",
SHADERS = "${BASE_PATH}/shaders",
SHADERS_GENERATED = "${SHADERS}/generated",
OPENSPACE_DATA = "${BASE_PATH}/openspace-data",
TESTDIR = "${BASE_PATH}/src/tests",
CONFIG = "${BASE_PATH}/config",
CACHE = "${BASE_PATH}/cache",
TEMPORARY = "${BASE_PATH}/tmp"
TEMPORARY = "${BASE_PATH}/tmp",
FONTS = "${OPENSPACE_DATA}/fonts"
},
SpiceKernel = {
Time = "${OPENSPACE_DATA}/spice/naif0010.tls",

View File

@@ -22,7 +22,7 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <${SHADERS}/ABuffer/constants.hglsl>
#include <${SHADERS_GENERATED}/constants.hglsl>
#if ABUFFER_IMPLEMENTATION == ABUFFER_SINGLE_LINKED
layout (binding = 0, r32ui) uniform uimage2D anchorPointerTexture;
@@ -34,9 +34,9 @@ layout (binding = 0, offset = 0) uniform atomic_uint atomicCounterBuffer;
layout (binding = 0, r32ui) uniform uimage2D anchorPointerTexture;
layout (binding = 1, rgba32ui) uniform uimageBuffer fragmentTexture;
#define _MAX_LAYERS_ 64
#define _SCREEN_WIDTH_ 1280
#define _SCREEN_HEIGHT_ 720
#define _MAX_LAYERS_ MAX_LAYERS
#define _SCREEN_WIDTH_ SCREEN_WIDTH
#define _SCREEN_HEIGHT_ SCREEN_HEIGHT
#endif
ABufferStruct_t createGeometryFragment(vec4 fragColor, vec4 position, float z = gl_FragCoord.z) {

View File

@@ -24,10 +24,13 @@
#version 430
// ================================================================================
// Settings
// ================================================================================
#pragma openspace insert SETTINGS
//#pragma openspace insert SETTINGS
#include <${SHADERS_GENERATED}/ABufferSettings.hglsl>:notrack
// Select type of depth calculations
#define PSCDEPTH 1
@@ -79,7 +82,8 @@ out vec4 out_color;
// Headers,
// volume and transferfunctions uniforms
// ================================================================================
#pragma openspace insert HEADERS
//#pragma openspace insert HEADERS
#include <${SHADERS_GENERATED}/ABufferHeaders.hglsl>:notrack
// ================================================================================
// The ABuffer specific includes and definitions
@@ -221,7 +225,11 @@ vec4 calculate_final_color(uint frag_count) {
vec4 color = vec4(0);
for(int k = 0; k < max_iterations && final_color.a < ALPHA_LIMIT && k < LOOP_LIMIT; ++k) {
#pragma openspace insert SAMPLERCALLS
// #pragma openspace insert SAMPLERCALLS
#include <${SHADERS_GENERATED}/ABufferSamplerCalls.hglsl>:notrack
}
@@ -253,9 +261,13 @@ vec4 calculate_final_color(uint frag_count) {
// Transferfunction visualizer
// ================================================================================
#ifdef VISUALIZE_TRANSFERFUNCTIONS
#pragma openspace insert TRANSFERFUNC
// #pragma openspace insert TRANSFERFUNC
#include <${SHADERS_GENERATED}/ABufferTransferFunctionVisualizer.hglsl>:notrack
#endif
// if(frag_count == 0) {
// final_color = vec4(0.5,0.5,0.5,1.0);
// } else if(frag_count == 1) {
@@ -300,7 +312,8 @@ void main() {
// ================================================================================
// The samplers implementations
// ================================================================================
#pragma openspace insert SAMPLERS
//#pragma openspace insert SAMPLERS
#include <${SHADERS_GENERATED}/ABufferSamplers.hglsl>:notrack

View File

@@ -31,7 +31,6 @@
// #define ABUFFER_DYNAMIC 3
// #define ABUFFER_IMPLEMENTATION ABUFFER_SINGLE_LINKED
//========================================================================================
// ABufferStruct_t declaration
//========================================================================================

View File

@@ -148,6 +148,8 @@ include_directories("${HEADER_ROOT_DIR}")
add_executable(OpenSpace ${SOURCE_ROOT_DIR}/main.cpp ${OPENSPACE_HEADER} ${OPENSPACE_SOURCE})
target_link_libraries(OpenSpace ${DEPENDENT_LIBS})
# cotire(OpenSpace)
if (WIN32)
if (CMAKE_CL_64)
set(OPENSPACE_DLL_LIBS ${OPENSPACE_DLL_LIBS} ${GHOUL_ROOT_DIR}/ext/il/lib/win64/DevIL.dll)

View File

@@ -34,66 +34,51 @@
#include <string>
namespace {
std::string _loggerCat = "ABuffer";
std::string padGeneratedString(const std::string& content) {
std::string _content_ = "// GENERATED CONTENT\n" + content + "\n// END GENERATED CONTENT";
return _content_;
}
const std::string generatedSettingsPath = "${SHADERS_GENERATED}/ABufferSettings.hglsl";
const std::string generatedHeadersPath = "${SHADERS_GENERATED}/ABufferHeaders.hglsl";
const std::string generatedSamplerCallsPath = "${SHADERS_GENERATED}/ABufferSamplerCalls.hglsl";
const std::string generatedTransferFunctionVisualizerPath = "${SHADERS_GENERATED}/ABufferTransferFunctionVisualizer.hglsl";
const std::string generatedSamplersPath = "${SHADERS_GENERATED}/ABufferSamplers.hglsl";
const std::string _loggerCat = "ABuffer";
}
namespace openspace {
ABuffer::ABuffer() : _validShader(false), _resolveShader(nullptr) {
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
_width = xSize;
_height = ySize;
_totalPixels = _width * _height;
const std::string fragmentShaderSourcePath = absPath("${SHADERS}/ABuffer/abufferResolveFragment.glsl");
_fragmentShaderFile = new ghoul::filesystem::File(fragmentShaderSourcePath, true);
_fragmentShaderPath = fragmentShaderSourcePath.substr(0, fragmentShaderSourcePath.length()-4) + "gglsl";
updateDimensions();
}
ABuffer::~ABuffer() {
if(_fragmentShaderFile)
delete _fragmentShaderFile;
if(_resolveShader)
delete _resolveShader;
for(auto file: _samplerFiles) {
delete file;
}
for(auto file: _shaderFiles) {
delete file;
}
}
bool ABuffer::initializeABuffer() {
// ============================
// SHADERS
// ============================
auto shaderCallback = [this](const ghoul::filesystem::File& file) {
_validShader = false;
};
_fragmentShaderFile->setCallback(shaderCallback);
// Development functionality to update shader for changes in several files
auto addFunc = [this, shaderCallback](const std::string& path) {
ghoul::filesystem::File* f = new ghoul::filesystem::File(path, false);
f->setCallback(shaderCallback);
_shaderFiles.push_back(f);
auto shaderCallback = [this](ghoul::opengl::ProgramObject* program) {
// Error for visibility in log
_validShader = false;
};
addFunc("${SHADERS}/ABuffer/constants.hglsl");
addFunc("${SHADERS}/ABuffer/abufferSort.hglsl");
addFunc("${SHADERS}/ABuffer/abufferAddToBuffer.hglsl");
addFunc("${SHADERS}/ABuffer/abufferStruct.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScaling_fs.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScaling_fs.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScaling_vs.hglsl");
addFunc("${SHADERS}/PowerScaling/powerScalingMath.hglsl");
generateShaderSource();
_resolveShader = ghoul::opengl::ProgramObject::Build(
"ABufferResolve",
"${SHADERS}/ABuffer/abufferResolveVertex.glsl",
"${SHADERS}/ABuffer/abufferResolveFragment.glsl",
shaderCallback);
if (!_resolveShader)
return false;
// ============================
// GEOMETRY (quad)
@@ -120,40 +105,48 @@ bool ABuffer::initializeABuffer() {
return true;
}
bool ABuffer::reinitialize() {
// set the total resolution for all viewports
updateDimensions();
return reinitializeInternal();
}
void ABuffer::resolve() {
if( ! _validShader) {
_validShader = true;
generateShaderSource();
updateShader();
_validShader = true;
}
if(_resolveShader) {
_resolveShader->activate();
int startAt = 0;
for(int i = 0; i < _volumes.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + i);
_volumes.at(i).second->bind();
startAt = i + 1;
}
for(int i = 0; i < _transferFunctions.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + startAt + i);
_transferFunctions.at(i).second->bind();
}
if (!_resolveShader)
return;
// Decrease stepsize in volumes if right click is pressed
// TODO: Let the interactionhandler handle this
int val = sgct::Engine::getMouseButton(0, SGCT_MOUSE_BUTTON_RIGHT);
float volumeStepFactor = (val) ? 0.2: 1.0;
if(volumeStepFactor != _volumeStepFactor) {
_volumeStepFactor = volumeStepFactor;
_resolveShader->setUniform("volumeStepFactor", _volumeStepFactor);
}
glBindVertexArray(_screenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
_resolveShader->deactivate();
_resolveShader->activate();
int startAt = 0;
for(int i = 0; i < _volumes.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + i);
_volumes.at(i).second->bind();
startAt = i + 1;
}
for(int i = 0; i < _transferFunctions.size(); ++i) {
glActiveTexture(GL_TEXTURE0 + startAt + i);
_transferFunctions.at(i).second->bind();
}
// Decrease stepsize in volumes if right click is pressed
// TODO: Let the interactionhandler handle this
int val = sgct::Engine::getMouseButton(0, SGCT_MOUSE_BUTTON_RIGHT);
float volumeStepFactor = (val) ? 0.2: 1.0;
if(volumeStepFactor != _volumeStepFactor) {
_volumeStepFactor = volumeStepFactor;
_resolveShader->setUniform("volumeStepFactor", _volumeStepFactor);
}
glBindVertexArray(_screenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
_resolveShader->deactivate();
}
void ABuffer::addVolume(const std::string& tag,ghoul::opengl::Texture* volume) {
@@ -182,33 +175,22 @@ int ABuffer::addSamplerfile(const std::string& filename) {
}
bool ABuffer::updateShader() {
using ghoul::opengl::ShaderObject;
using ghoul::opengl::ProgramObject;
ProgramObject* resolveShader = ProgramObject::Build("ABuffer resolve",
"${SHADERS}/ABuffer/abufferResolveVertex.glsl",
_fragmentShaderPath);
if( ! resolveShader) {
LERROR("Resolve shader not updated");
return false;
}
int startAt = 0;
for(int i = 0; i < _volumes.size(); ++i) {
resolveShader->setUniform(_volumes.at(i).first, i);
startAt = i + 1;
bool s = _resolveShader->rebuildFromFile();
if (s) {
int startAt = 0;
for (int i = 0; i < _volumes.size(); ++i) {
_resolveShader->setUniform(_volumes.at(i).first, i);
startAt = i + 1;
}
for (int i = 0; i < _transferFunctions.size(); ++i) {
_resolveShader->setUniform(_transferFunctions.at(i).first, startAt + i);
}
LINFO("Successfully updated ABuffer resolve shader!");
}
for(int i = 0; i < _transferFunctions.size(); ++i) {
resolveShader->setUniform(_transferFunctions.at(i).first, startAt + i);
else {
LWARNING("Couldn't update ABuffer resolve shader");
}
if(_resolveShader)
delete _resolveShader;
_resolveShader = resolveShader;
LDEBUG("Successfully updated shader!");
return true;
return s;
}
void ABuffer::generateShaderSource() {
@@ -225,158 +207,131 @@ void ABuffer::generateShaderSource() {
_samplers.at(i) = source;
}
std::string line, source = "";
std::ifstream fragmentShaderFile(_fragmentShaderFile->path());
if(fragmentShaderFile.is_open()) {
while(std::getline(fragmentShaderFile, line)) {
if(line == "#pragma openspace insert HEADERS") {
line = padGeneratedString(openspaceHeaders());
} else if(line == "#pragma openspace insert SAMPLERCALLS") {
line = padGeneratedString(openspaceSamplerCalls());
} else if(line == "#pragma openspace insert SAMPLERS") {
line = padGeneratedString(openspaceSamplers());
} else if(line == "#pragma openspace insert SETTINGS") {
line = padGeneratedString(settings());
} else if(line == "#pragma openspace insert TRANSFERFUNC") {
line = padGeneratedString(openspaceTransferFunction());
}
source += line + "\n";
}
}
fragmentShaderFile.close();
std::ofstream fragmentShaderOut(_fragmentShaderPath);
fragmentShaderOut << source;
fragmentShaderOut.close();
LDEBUG("Generating shader includes");
openspaceHeaders();
openspaceSamplerCalls();
openspaceSamplers();
settings();
openspaceTransferFunction();
}
std::string ABuffer::openspaceHeaders() {
std::string headers;
headers += "#define MAX_VOLUMES " + std::to_string(_samplers.size()) + "\n";
headers += "#define MAX_TF " + std::to_string(_transferFunctions.size()) + "\n";
void ABuffer::openspaceHeaders() {
std::ofstream f(absPath(generatedHeadersPath));
f << "#define MAX_VOLUMES " << std::to_string(_samplers.size()) << "\n"
<< "#define MAX_TF " << _transferFunctions.size() << "\n";
for (int i = 0; i < _volumes.size(); ++i) {
headers += "uniform sampler3D " + _volumes.at(i).first + ";\n";
f << "uniform sampler3D " << _volumes.at(i).first << ";\n";
}
for (int i = 0; i < _transferFunctions.size(); ++i) {
headers += "uniform sampler1D " + _transferFunctions.at(i).first + ";\n";
f << "uniform sampler1D " << _transferFunctions.at(i).first << ";\n";
}
for (int i = 0; i < _samplers.size(); ++i) {
auto found = _samplers.at(i).find_first_of('{');
if(found!=std::string::npos) {
headers += _samplers.at(i).substr(0, found) + ";\n";
if (found != std::string::npos) {
f << _samplers.at(i).substr(0, found) << ";\n";
}
}
if(_volumes.size() < 1)
return headers;
if (_volumes.size() < 1) {
f.close();
return;
}
size_t maxLoop = 0;
headers += "const vec3 volume_dim[] = {\n";
f << "const vec3 volume_dim[] = {\n";
for (int i = 0; i < _volumes.size(); ++i) {
glm::size3_t size = _volumes.at(i).second->dimensions();
for(int k = 0; k < 3; ++k)
for (int k = 0; k < 3; ++k)
maxLoop = glm::max(maxLoop, size[k]);
headers += " vec3(" + std::to_string(size[0]) + ".0," + std::to_string(size[1]) + ".0,"
+ std::to_string(size[2]) + ".0),\n";
f << " vec3(" << std::to_string(size[0]) << ".0," + std::to_string(size[1]) << ".0,"
<< std::to_string(size[2]) + ".0),\n";
}
headers += "};\n";
f << "};\n";
headers += "#define LOOP_LIMIT " + std::to_string(maxLoop) + "\n";
f << "#define LOOP_LIMIT " << maxLoop << "\n";
headers += "float volumeStepSize[] = {\n";
f << "float volumeStepSize[] = {\n";
for (int i = 0; i < _volumes.size(); ++i) {
glm::size3_t size = _volumes.at(i).second->dimensions();
headers += " stepSize,\n";
f << " stepSize,\n";
}
headers += "};\n";
f << "};\n";
headers += "float volumeStepSizeOriginal[] = {\n";
f << "float volumeStepSizeOriginal[] = {\n";
for (int i = 0; i < _volumes.size(); ++i) {
glm::size3_t size = _volumes.at(i).second->dimensions();
headers += " stepSize,\n";
f << " stepSize,\n";
}
headers += "};\n";
f << "};\n";
return headers;
f.close();
}
std::string ABuffer::openspaceSamplerCalls() {
std::string samplercalls;
void ABuffer::openspaceSamplerCalls() {
std::ofstream f(absPath(generatedSamplerCallsPath));
for (int i = 0; i < _samplers.size(); ++i) {
auto found1 = _samplers.at(i).find_first_not_of("vec4 ");
auto found2 = _samplers.at(i).find_first_of("(",found1);
if(found1 != std::string::npos && found2 != std::string::npos) {
auto found2 = _samplers.at(i).find_first_of("(", found1);
if (found1 != std::string::npos && found2 != std::string::npos) {
std::string functionName = _samplers.at(i).substr(found1, found2 - found1);
samplercalls += "#ifndef SKIP_VOLUME_"+std::to_string(i)+"\n";
samplercalls += "if((currentVolumeBitmask & (1 << " + std::to_string(i) + ")) == "+std::to_string(1 << i)+") {\n";
samplercalls += " vec4 c = " + functionName + "(final_color,volume_position[" + std::to_string(i) + "]);\n";
// samplercalls += " if(c.a < 0.1) { \n";
// samplercalls += " if( volumeStepSize[" + std::to_string(i) + "] < 16.0*volumeStepSizeOriginal[" + std::to_string(i) + "]) \n";
// samplercalls += " volumeStepSize[" + std::to_string(i) + "] *= 2.0; \n";
// samplercalls += " } else {\n";
// samplercalls += " //volume_position[" + std::to_string(i) + "] -= volume_direction[" + std::to_string(i) + "]*volumeStepSize[" + std::to_string(i) + "];\n";
// samplercalls += " volumeStepSize[" + std::to_string(i) + "] = volumeStepSizeOriginal[" + std::to_string(i) + "]; \n";
// samplercalls += " //c = " + functionName + "(final_color,volume_position[" + std::to_string(i) + "]);\n";
// samplercalls += " } \n";
// samplercalls += " if(c.a > EPSILON)\n";
samplercalls += " blendStep(final_color, c, volumeStepSize[" + std::to_string(i) + "]);\n";
// samplercalls += " blendStep(final_color, c, stepSize);\n";
// samplercalls += " float aaa = volume_length[i]/myMaxSteps;\n";
samplercalls += " volume_position[" + std::to_string(i) + "] += volume_direction[" + std::to_string(i) + "]*volumeStepSize[" + std::to_string(i) + "];\n";
// float aaa = ray[v].w/myMaxSteps;
// pos[v] += vec4(ray[v].xyz*vec3(aaa),aaa);
// samplercalls += " volume_position[" + std::to_string(i) + "] += volume_direction[" + std::to_string(i) + "]*volumeStepSize[" + std::to_string(i) + "];\n";
samplercalls += "}\n";
samplercalls += "#endif\n";
f << "#ifndef SKIP_VOLUME_" << i << "\n"
<< "if((currentVolumeBitmask & (1 << " << i << ")) == " << std::to_string(1 << i) << ") {\n"
<< " vec4 c = " << functionName << "(final_color,volume_position[" << i << "]);\n"
<< " blendStep(final_color, c, volumeStepSize[" << i << "]);\n"
<< " volume_position[" << i << "] += volume_direction[" << i << "]*volumeStepSize[" << i << "];\n"
<< "}\n"
<< "#endif\n";
}
}
return samplercalls;
f.close();
}
std::string ABuffer::openspaceSamplers() {
std::string samplers;
for (int i = 0; i < _samplers.size(); ++i) {
samplers += _samplers.at(i) + "\n";
void ABuffer::openspaceSamplers() {
std::ofstream f(absPath(generatedSamplersPath));
for (auto sampler : _samplers) {
f << sampler << std::endl;
}
return samplers;
f.close();
}
std::string ABuffer::openspaceTransferFunction() {
std::string tf;
tf += "float showfunc_size = 20.0;\n";
tf += "float SCREEN_HEIGHTf = float(SCREEN_HEIGHT);\n";
tf += "float SCREEN_WIDTHf = float(SCREEN_WIDTH);\n";
for(int i = 0; i < _transferFunctions.size(); ++i) {
tf += "if( gl_FragCoord.y > SCREEN_HEIGHTf-showfunc_size*"+std::to_string(i+1)+
" && gl_FragCoord.y < SCREEN_HEIGHTf-showfunc_size*"+std::to_string(i)+") {\n";
tf += " float normalizedIntensity = gl_FragCoord.x / (SCREEN_WIDTHf-1) ;\n";
tf += " vec4 tfc = texture("+ _transferFunctions.at(i).first +", normalizedIntensity);\n";
tf += " final_color = tfc;\n";
tf += " float cmpf = SCREEN_HEIGHTf-showfunc_size*"+std::to_string(i+1)+" + tfc.a*showfunc_size;\n";
tf += " if(gl_FragCoord.y > cmpf) {\n";
tf += " final_color = vec4(0,0,0,0);\n";
tf += " } else {\n";
tf += " final_color.a = 1.0;\n";
tf += " }\n";
tf += "} else if(ceil(gl_FragCoord.y) == SCREEN_HEIGHTf - showfunc_size*"+std::to_string(i+1)+") {\n";
tf += " const float intensity = 0.4;\n";
tf += " final_color = vec4(intensity,intensity,intensity,1.0);\n";
tf += "}\n";
void ABuffer::openspaceTransferFunction() {
std::ofstream f(absPath(generatedTransferFunctionVisualizerPath));
f << "float showfunc_size = 20.0;\n"
<< "float SCREEN_HEIGHTf = float(SCREEN_HEIGHT);\n"
<< "float SCREEN_WIDTHf = float(SCREEN_WIDTH);\n";
for (int i = 0; i < _transferFunctions.size(); ++i) {
f << "if( gl_FragCoord.y > SCREEN_HEIGHTf-showfunc_size*" << i + 1
<< " && gl_FragCoord.y < SCREEN_HEIGHTf-showfunc_size*" << std::to_string(i) << ") {\n"
<< " float normalizedIntensity = gl_FragCoord.x / (SCREEN_WIDTHf-1) ;\n"
<< " vec4 tfc = texture(" << _transferFunctions.at(i).first << ", normalizedIntensity);\n"
<< " final_color = tfc;\n"
<< " float cmpf = SCREEN_HEIGHTf-showfunc_size*" << i + 1 << " + tfc.a*showfunc_size;\n"
<< " if(gl_FragCoord.y > cmpf) {\n"
<< " final_color = vec4(0,0,0,0);\n"
<< " } else {\n"
<< " final_color.a = 1.0;\n"
<< " }\n"
<< "} else if(ceil(gl_FragCoord.y) == SCREEN_HEIGHTf - showfunc_size*" << i + 1 << ") {\n"
<< " const float intensity = 0.4;\n"
<< " final_color = vec4(intensity,intensity,intensity,1.0);\n"
<< "}\n";
}
return tf;
f.close();
}
void ABuffer::invalidateABuffer() {
LDEBUG("Shader invalidated");
_validShader = false;
}
void ABuffer::updateDimensions() {
_width = sgct::Engine::instance()->getActiveWindowPtr()->getXFramebufferResolution();
_height = sgct::Engine::instance()->getActiveWindowPtr()->getYFramebufferResolution();
_totalPixels = _width * _height;
}
} // openspace

View File

@@ -59,10 +59,22 @@ bool ABufferSingleLinked::initialize() {
// BUFFERS
// ============================
glGenTextures(1, &_anchorPointerTexture);
glGenBuffers(1, &_anchorPointerTextureInitializer);
glGenBuffers(1, &_atomicCounterBuffer);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, _atomicCounterBuffer);
glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), NULL, GL_DYNAMIC_COPY);
glGenBuffers(1, &_fragmentBuffer);
glGenTextures(1, &_fragmentTexture);
reinitialize();
return initializeABuffer();
}
bool ABufferSingleLinked::reinitializeInternal() {
glBindTexture(GL_TEXTURE_2D, _anchorPointerTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, _width, _height, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, NULL);
glGenBuffers(1, &_anchorPointerTextureInitializer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _anchorPointerTextureInitializer);
glBufferData(GL_PIXEL_UNPACK_BUFFER, _totalPixels * sizeof(GLuint), NULL, GL_STATIC_DRAW);
@@ -71,22 +83,16 @@ bool ABufferSingleLinked::initialize() {
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glGenBuffers(1, &_atomicCounterBuffer);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, _atomicCounterBuffer);
glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), NULL, GL_DYNAMIC_COPY);
glGenBuffers(1, &_fragmentBuffer);
glBindBuffer(GL_TEXTURE_BUFFER, _fragmentBuffer);
glBufferData(GL_TEXTURE_BUFFER, MAX_LAYERS*_totalPixels*sizeof(GLfloat)*4, NULL, GL_DYNAMIC_COPY);
glBufferData(GL_TEXTURE_BUFFER, MAX_LAYERS*_totalPixels*sizeof(GLfloat) * 4, NULL, GL_DYNAMIC_COPY);
glGenTextures(1, &_fragmentTexture);
glBindTexture(GL_TEXTURE_BUFFER, _fragmentTexture);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32UI, _fragmentBuffer);
glBindTexture(GL_TEXTURE_BUFFER, 0);
glBindTexture(GL_TEXTURE_BUFFER, _fragmentTexture);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32UI, _fragmentBuffer);
glBindTexture(GL_TEXTURE_BUFFER, 0);
glBindImageTexture(1, _fragmentTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32UI);
glBindImageTexture(1, _fragmentTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32UI);
return initializeABuffer();
return true;
}
void ABufferSingleLinked::clear() {

View File

@@ -89,6 +89,10 @@ bool ABufferDynamic::initialize() {
return initializeABuffer();
}
bool ABufferDynamic::reinitializeInternal() {
return false;
}
void ABufferDynamic::clear() {
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _anchorPointerTextureInitializer);
glBindTexture(GL_TEXTURE_2D, _anchorPointerTexture);

View File

@@ -97,6 +97,10 @@ bool ABufferFixed::initialize() {
return initializeABuffer();
}
bool ABufferFixed::reinitializeInternal() {
return false;
}
void ABufferFixed::clear() {
// Bind texture initializer

View File

@@ -26,6 +26,7 @@
#include <openspace/interaction/deviceidentifier.h>
#include <openspace/interaction/interactionhandler.h>
#include <openspace/interaction/luaconsole.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/util/time.h>
@@ -33,6 +34,7 @@
#include <openspace/util/factorymanager.h>
#include <openspace/util/constants.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/syncbuffer.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
@@ -42,6 +44,10 @@
#include <ghoul/lua/lua_helper.h>
#include <ghoul/cmdparser/commandlineparser.h>
#include <ghoul/cmdparser/singlecommand.h>
#include <ghoul/filesystem/cachemanager.h>
#include <iostream>
#include <fstream>
using namespace ghoul::filesystem;
using namespace ghoul::logging;
@@ -68,11 +74,16 @@ OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr;
OpenSpaceEngine::OpenSpaceEngine(std::string programName)
: _commandlineParser(programName, true)
, _inputCommand(false)
, _console(nullptr)
, _syncBuffer(nullptr)
{
}
OpenSpaceEngine::~OpenSpaceEngine()
{
OpenSpaceEngine::~OpenSpaceEngine() {
if (_console)
delete _console;
SpiceManager::deinitialize();
Time::deinitialize();
DeviceIdentifier::deinit();
@@ -80,14 +91,12 @@ OpenSpaceEngine::~OpenSpaceEngine()
LogManager::deinitialize();
}
OpenSpaceEngine& OpenSpaceEngine::ref()
{
OpenSpaceEngine& OpenSpaceEngine::ref() {
assert(_engine);
return *_engine;
}
bool OpenSpaceEngine::gatherCommandlineArguments()
{
bool OpenSpaceEngine::gatherCommandlineArguments() {
// TODO: Get commandline arguments from all modules
CommandlineCommand* configurationFileCommand = new SingleCommand<std::string>(
@@ -98,8 +107,7 @@ bool OpenSpaceEngine::gatherCommandlineArguments()
return true;
}
bool OpenSpaceEngine::findConfiguration(std::string& filename)
{
bool OpenSpaceEngine::findConfiguration(std::string& filename) {
using ghoul::filesystem::Directory;
Directory directory = FileSys.currentDirectory();
@@ -184,7 +192,27 @@ bool OpenSpaceEngine::create(int argc, char** argv,
LERROR("Loading of configuration file '" << configurationFilePath << "' failed");
return false;
}
// make sure cache is registered, false since we don't want to override
FileSys.registerPathToken("${CACHE}", "${BASE_PATH}/cache", false);
// Create directories that doesn't exsist
auto tokens = FileSys.tokens();
for (auto token : tokens) {
if (!FileSys.directoryExists(token)) {
std::string p = absPath(token);
LDEBUG("Directory '" << p <<"' does not exsist, creating.");
if(FileSys.createDirectory(p, true))
LERROR("Directory '" << p <<"' could not be created");
}
}
// Create the cachemanager
FileSys.createCacheManager("${CACHE}");
_engine->_console = new LuaConsole();
_engine->_syncBuffer = new SyncBuffer(1024);
// Determining SGCT configuration file
LDEBUG("Determining SGCT configuration file");
std::string sgctConfigurationPath = _sgctDefaultConfigFile;
@@ -200,18 +228,15 @@ bool OpenSpaceEngine::create(int argc, char** argv,
return true;
}
void OpenSpaceEngine::destroy()
{
void OpenSpaceEngine::destroy() {
delete _engine;
}
bool OpenSpaceEngine::isInitialized()
{
bool OpenSpaceEngine::isInitialized() {
return _engine != nullptr;
}
bool OpenSpaceEngine::initialize()
{
bool OpenSpaceEngine::initialize() {
// clear the screen so the user don't have to see old buffer contents from the
// graphics card
glClearColor(0, 0, 0, 0);
@@ -229,7 +254,7 @@ bool OpenSpaceEngine::initialize()
// Detect and log OpenCL and OpenGL versions and available devices
ghoul::systemcapabilities::SystemCapabilities::initialize();
SysCap.addComponent(new ghoul::systemcapabilities::CPUCapabilitiesComponent);
SysCap.addComponent(new ghoul::systemcapabilities::OpenCLCapabilitiesComponent);
//SysCap.addComponent(new ghoul::systemcapabilities::OpenCLCapabilitiesComponent);
SysCap.addComponent(new ghoul::systemcapabilities::OpenGLCapabilitiesComponent);
SysCap.detectCapabilities();
SysCap.logCapabilities();
@@ -238,10 +263,10 @@ bool OpenSpaceEngine::initialize()
SpiceManager::initialize();
Time::initialize();
// Load SPICE time kernel
using constants::configurationmanager::keySpiceTimeKernel;
std::string timeKernel;
bool success = OsEng.configurationManager().getValue(keySpiceTimeKernel, timeKernel);
bool success = configurationManager().getValue(keySpiceTimeKernel, timeKernel);
if (!success) {
LERROR("Configuration file does not contain a '" << keySpiceTimeKernel << "'");
return false;
@@ -253,11 +278,12 @@ bool OpenSpaceEngine::initialize()
return false;
}
// Load SPICE leap second kernel
using constants::configurationmanager::keySpiceLeapsecondKernel;
std::string leapSecondKernel;
success = OsEng.configurationManager().getValue(keySpiceLeapsecondKernel, leapSecondKernel);
success = configurationManager().getValue(keySpiceLeapsecondKernel, leapSecondKernel);
if (!success) {
LERROR("Configuration file does not contain a '" << keySpiceLeapsecondKernel << "'");
LERROR("Configuration file does not have a '" << keySpiceLeapsecondKernel << "'");
return false;
}
id = SpiceManager::ref().loadKernel(std::move(leapSecondKernel));
@@ -266,32 +292,26 @@ bool OpenSpaceEngine::initialize()
return false;
}
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/de413.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/jup260.bsp")
//// metakernel loading doesnt seem to work... it should. to tired to even
//// CK
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ck/merged_nhpc_2006_v011.bc");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ck/merged_nhpc_2007_v006.bc");
//// FK
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/fk/nh_v200.tf");
//// IK
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ik/nh_lorri_v100.ti");
//// LSK already loaded
////PCK
////SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/pck/pck00008.tpc");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/pck/new_horizons_413.tsc");
////SPK
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/de413.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/jup260.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_nep_ura_000.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_recon_e2j_v1.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_recon_j2sep07_prelimv1.bsp");
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/sb_2002jf56_2.bsp");
// metakernel loading doesnt seem to work... it should. to tired to even
// CK
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ck/merged_nhpc_2006_v011.bc");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ck/merged_nhpc_2007_v006.bc");
// FK
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/fk/nh_v200.tf");
// IK
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/ik/nh_lorri_v100.ti");
// LSK already loaded
//PCK
//SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/pck/pck00008.tpc");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/pck/new_horizons_413.tsc");
//SPK
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/de413.bsp");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/jup260.bsp");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_nep_ura_000.bsp");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_recon_e2j_v1.bsp");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/nh_recon_j2sep07_prelimv1.bsp");
SpiceManager::ref().loadKernel("${OPENSPACE_DATA}/spice/JupiterNhKernels/spk/sb_2002jf56_2.bsp");
FactoryManager::initialize();
scriptEngine().initialize();
@@ -301,38 +321,30 @@ bool OpenSpaceEngine::initialize()
scriptEngine().addLibrary(RenderEngine::luaLibrary());
scriptEngine().addLibrary(SceneGraph::luaLibrary());
scriptEngine().addLibrary(Time::luaLibrary());
scriptEngine().addLibrary(InteractionHandler::luaLibrary());
// Load scenegraph
SceneGraph* sceneGraph = new SceneGraph;
_renderEngine.setSceneGraph(sceneGraph);
// initialize the RenderEngine, needs ${SCENEPATH} to be set
_renderEngine.initialize();
sceneGraph->initialize();
std::string sceneDescriptionPath;
success = OsEng.configurationManager().getValue(
success = configurationManager().getValue(
constants::configurationmanager::keyConfigScene, sceneDescriptionPath);
if (success)
sceneGraph->scheduleLoadSceneFile(sceneDescriptionPath);
//_renderEngine.setSceneGraph(sceneGraph);
#ifdef FLARE_ONLY
_flare = new Flare();
_flare->initialize();
#endif
// Initialize OpenSpace input devices
DeviceIdentifier::init();
DeviceIdentifier::ref().scanDevices();
_engine->_interactionHandler.connectDevices();
_interactionHandler.connectDevices();
// Run start up scripts
ghoul::Dictionary scripts;
success = _engine->configurationManager().getValue(
success = configurationManager().getValue(
constants::configurationmanager::keyStartupScript, scripts);
for (size_t i = 1; i <= scripts.size(); ++i) {
std::stringstream stream;
@@ -351,35 +363,33 @@ bool OpenSpaceEngine::initialize()
_engine->scriptEngine().runScriptFile(absoluteScriptPath);
}
#ifdef OPENSPACE_VIDEO_EXPORT
LINFO("OpenSpace compiled with video export; press Print Screen to start/stop recording");
#endif
// Load a light and a monospaced font
//sgct_text::FontManager::instance()->addFont(constants::fonts::keyMono, "ubuntu-font-family/UbuntuMono-R.ttf", absPath("${FONTS}/"));
//sgct_text::FontManager::instance()->addFont(constants::fonts::keyLight, "ubuntu-font-family/Ubuntu-L.ttf", absPath("${FONTS}/"));
sgct_text::FontManager::FontPath local = sgct_text::FontManager::FontPath::FontPath_Local;
sgct_text::FontManager::instance()->addFont(constants::fonts::keyMono, absPath("${FONTS}/Droid_Sans_Mono/DroidSansMono.ttf"), local);
sgct_text::FontManager::instance()->addFont(constants::fonts::keyLight, absPath("${FONTS}/Roboto/Roboto-Regular.ttf"), local);
return true;
}
ConfigurationManager& OpenSpaceEngine::configurationManager()
{
ConfigurationManager& OpenSpaceEngine::configurationManager() {
return _configurationManager;
}
ghoul::opencl::CLContext& OpenSpaceEngine::clContext()
{
ghoul::opencl::CLContext& OpenSpaceEngine::clContext() {
return _context;
}
InteractionHandler& OpenSpaceEngine::interactionHandler()
{
InteractionHandler& OpenSpaceEngine::interactionHandler() {
return _interactionHandler;
}
RenderEngine& OpenSpaceEngine::renderEngine()
{
RenderEngine& OpenSpaceEngine::renderEngine() {
return _renderEngine;
}
ScriptEngine& OpenSpaceEngine::scriptEngine()
{
ScriptEngine& OpenSpaceEngine::scriptEngine() {
return _scriptEngine;
}
@@ -388,8 +398,7 @@ bool OpenSpaceEngine::initializeGL()
return _renderEngine.initializeGL();
}
void OpenSpaceEngine::preSynchronization()
{
void OpenSpaceEngine::preSynchronization() {
#ifdef WIN32
// Sleeping for 0 milliseconds will trigger any pending asynchronous procedure calls
SleepEx(0, TRUE);
@@ -400,35 +409,29 @@ void OpenSpaceEngine::preSynchronization()
_interactionHandler.update(dt);
_interactionHandler.lockControls();
//Time::ref().advanceTime(dt);
Time::ref().advanceTime(dt);
}
#ifdef FLARE_ONLY
_flare->preSync();
#endif
}
void OpenSpaceEngine::postSynchronizationPreDraw()
{
void OpenSpaceEngine::postSynchronizationPreDraw() {
_renderEngine.postSynchronizationPreDraw();
#ifdef FLARE_ONLY
_flare->postSyncPreDraw();
#endif
}
void OpenSpaceEngine::render()
{
#ifdef FLARE_ONLY
_flare->render();
#else
void OpenSpaceEngine::render() {
_renderEngine.render();
#endif
// If currently writing a command, render it to screen
sgct::SGCTWindow* w = sgct::Engine::instance()->getActiveWindowPtr();
if (sgct::Engine::instance()->isMaster() && !w->isUsingFisheyeRendering() && _inputCommand) {
_console->render();
}
}
void OpenSpaceEngine::postDraw()
{
if (sgct::Engine::instance()->isMaster()) {
void OpenSpaceEngine::postDraw() {
if (sgct::Engine::instance()->isMaster())
_interactionHandler.unlockControls();
}
#ifdef OPENSPACE_VIDEO_EXPORT
float speed = 0.01;
glm::vec3 euler(0.0, speed, 0.0);
@@ -437,45 +440,47 @@ void OpenSpaceEngine::postDraw()
glm::quat rot2 = glm::quat(euler2);
_interactionHandler->orbit(rot);
_interactionHandler->rotate(rot2);
if(_doVideoExport)
sgct::Engine::instance()->takeScreenshot();
if(_doVideoExport)
_renderEngine.takeScreenshot();
#endif
_renderEngine.postDraw();
#ifdef FLARE_ONLY
_flare->postDraw();
#endif
}
void OpenSpaceEngine::keyboardCallback(int key, int action)
{
if (sgct::Engine::instance()->isMaster()) {
_interactionHandler.keyboardCallback(key, action);
}
#ifdef OPENSPACE_VIDEO_EXPORT
if(action == SGCT_PRESS && key == SGCT_KEY_PRINT_SCREEN)
_doVideoExport = !_doVideoExport;
#endif
#ifdef FLARE_ONLY
_flare->keyboard(key, action);
#endif
void OpenSpaceEngine::keyboardCallback(int key, int action) {
if (sgct::Engine::instance()->isMaster()) {
if (key == _console->commandInputButton() && (action == SGCT_PRESS || action == SGCT_REPEAT)) {
_inputCommand = !_inputCommand;
}
if (!_inputCommand) {
_interactionHandler.keyboardCallback(key, action);
}
else {
_console->keyboardCallback(key, action);
}
}
}
void OpenSpaceEngine::mouseButtonCallback(int key, int action)
{
if (sgct::Engine::instance()->isMaster()) {
void OpenSpaceEngine::charCallback(unsigned int codepoint) {
if (_inputCommand) {
_console->charCallback(codepoint);
}
}
void OpenSpaceEngine::mouseButtonCallback(int key, int action) {
if (sgct::Engine::instance()->isMaster())
_interactionHandler.mouseButtonCallback(key, action);
}
#ifdef FLARE_ONLY
_flare->mouse(key, action);
#endif
}
void OpenSpaceEngine::mousePositionCallback(int x, int y)
{
void OpenSpaceEngine::mousePositionCallback(int x, int y) {
_interactionHandler.mousePositionCallback(x, y);
}
void OpenSpaceEngine::mouseScrollWheelCallback(int pos)
{
void OpenSpaceEngine::mouseScrollWheelCallback(int pos) {
_interactionHandler.mouseScrollWheelCallback(pos);
}
@@ -493,6 +498,8 @@ void OpenSpaceEngine::encode()
// _synchronizationBuffer.setVal(dataStream);
// sgct::SharedData::instance()->writeVector(&_synchronizationBuffer);
//#endif
_renderEngine.serialize(_syncBuffer);
_syncBuffer->write();
}
void OpenSpaceEngine::decode()
@@ -507,6 +514,12 @@ void OpenSpaceEngine::decode()
// // deserialize in the same order as done in serialization
// _renderEngine->deserialize(dataStream, offset);
//#endif
_syncBuffer->read();
_renderEngine.deserialize(_syncBuffer);
}
void OpenSpaceEngine::setInputCommand(bool b) {
_inputCommand = b;
}
void OpenSpaceEngine::externalControlCallback(const char* receivedChars,

View File

@@ -1,3 +1,26 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
// open space includes
#include <ghoul/logging/logmanager.h>
@@ -19,6 +42,40 @@ std::string _loggerCat = "InteractionHandler";
namespace openspace {
namespace luascriptfunctions {
/**
* \ingroup LuaScripts
* setOrigin():
* Set the origin of the camera
*/
int setOrigin(lua_State* L) {
using ghoul::lua::luaTypeToString;
const std::string _loggerCat = "LuaInteractionHandler";
int nArguments = lua_gettop(L);
if (nArguments != 1)
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
const int type = lua_type(L, -1);
if (type != LUA_TSTRING)
return luaL_error(L, "Expected string, got %i", type);
std::string s = luaL_checkstring(L, -1);
SceneGraphNode* node = sceneGraphNode(s);
if (!node) {
LWARNING("Could not find a node in scenegraph called '" << s <<"'");
return 0;
}
OsEng.interactionHandler().setOrigin(node);
return 0;
}
} // namespace luascriptfunctions
InteractionHandler::InteractionHandler() {
// initiate pointers
camera_ = nullptr;
@@ -111,6 +168,11 @@ void InteractionHandler::setCamera(Camera *camera) {
camera_ = camera;
}
void InteractionHandler::setOrigin(SceneGraphNode* node) {
if (node)
node_ = node;
}
Camera * InteractionHandler::getCamera() const {
//assert(this_);
if (enabled_) {
@@ -177,7 +239,9 @@ void InteractionHandler::orbit(const glm::quat &rotation) {
unlockControls();
}
void InteractionHandler::distance(const PowerScaledScalar &distance) {
void InteractionHandler::distance(const PowerScaledScalar &dist, size_t iterations) {
if (iterations > 5)
return;
//assert(this_);
lockControls();
@@ -186,19 +250,28 @@ void InteractionHandler::distance(const PowerScaledScalar &distance) {
psc relative_origin_coordinate = relative - origin;
const glm::vec3 dir(relative_origin_coordinate.direction());
glm:: vec3 newdir = dir * distance[0];
glm::vec3 newdir = dir * dist[0];
relative_origin_coordinate = newdir;
relative_origin_coordinate[3] = distance[1];
relative_origin_coordinate[3] = dist[1];
relative = relative + relative_origin_coordinate;
relative_origin_coordinate = relative - origin;
newdir = relative_origin_coordinate.direction();
// update only if on the same side of the origin
if(glm::angle(newdir, dir) < 90.0f)
if (glm::angle(newdir, dir) < 90.0f) {
camera_->setPosition(relative);
unlockControls();
}
else {
unlockControls();
PowerScaledScalar d2 = dist;
d2[0] *= 0.75;
d2[1] *= 0.85;
distance(d2, iterations + 1);
}
unlockControls();
}
void InteractionHandler::lookAt(const glm::quat &rotation) {
@@ -307,13 +380,12 @@ void InteractionHandler::trackballRotate(int x, int y) {
_lastTrackballPos = curTrackballPos;
}
}
double acc = 1;
void InteractionHandler::keyboardCallback(int key, int action) {
// TODO package in script
const double speed = 2.75;
const double dt = getDt();
if(action == SGCT_PRESS || action == SGCT_REPEAT) {
if (action == SGCT_PRESS || action == SGCT_REPEAT) {
if (key == SGCT_KEY_S) {
glm::vec3 euler(speed * dt, 0.0, 0.0);
glm::quat rot = glm::quat(euler);
@@ -358,28 +430,35 @@ void InteractionHandler::keyboardCallback(int key, int action) {
rotate(rot);
}
if (key == SGCT_KEY_R) {
PowerScaledScalar dist(-speed * dt, 0.0);
PowerScaledScalar dist(-speed * dt, 5.0);
distance(dist);
}
if (key == SGCT_KEY_F) {
PowerScaledScalar dist(speed * dt, 0.0);
PowerScaledScalar dist(speed * dt, 5.0);
distance(dist);
}
if (key == SGCT_KEY_T) {
PowerScaledScalar dist(-speed * pow(10, 11) * dt, 0.0);
PowerScaledScalar dist(-speed * dt, 10.0);
distance(dist);
}
if (key == SGCT_KEY_G) {
acc += 0.001;
PowerScaledScalar dist(speed * pow(10, 8 * acc) * dt, 0.0);
PowerScaledScalar dist(speed * dt, 10.0);
distance(dist);
}
if (key == SGCT_KEY_Y) {
PowerScaledScalar dist(-speed * 100.0 * dt, 6.0);
PowerScaledScalar dist(-speed * dt, 11.5);
distance(dist);
}
if (key == SGCT_KEY_H) {
PowerScaledScalar dist(speed * 100.0 * dt, 6.0);
PowerScaledScalar dist(speed * dt, 11.5);
distance(dist);
}
if (key == SGCT_KEY_U) {
PowerScaledScalar dist(-speed * dt, 13.0);
distance(dist);
}
if (key == SGCT_KEY_J) {
PowerScaledScalar dist(speed * dt, 13.0);
distance(dist);
}
@@ -394,6 +473,13 @@ void InteractionHandler::keyboardCallback(int key, int action) {
OsEng.renderEngine().camera()->setScaling(s);
}
}
// Screenshot
if (action == SGCT_PRESS && key == SGCT_KEY_PRINT_SCREEN) {
OsEng.renderEngine().takeScreenshot();
}
/*
if (key == '1') {
SceneGraphNode* node = getSceneGraphNode("sun");
@@ -472,4 +558,18 @@ void InteractionHandler::addKeyCallback(int key, std::function<void(void)> f) {
_keyCallbacks.insert(std::make_pair(key, f));
}
scripting::ScriptEngine::LuaLibrary InteractionHandler::luaLibrary() {
return{
"",
{
{
"setOrigin",
&luascriptfunctions::setOrigin,
"setOrigin(): set the camera origin node by name"
}
}
};
}
} // namespace openspace

View File

@@ -0,0 +1,391 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/interaction/luaconsole.h>
#include <openspace/util/constants.h>
#include <openspace/engine/openspaceengine.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <string>
#include <sgct.h>
namespace {
const std::string _loggerCat = "LuaConsole";
const std::string _filename = "${TEMPORARY}/history";
#if !defined(WIN32)
// Dangerus as fuck (if malicious input)
bool exec(const std::string& cmd, std::string& value)
{
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
return false;
const int buffer_size = 1024;
char buffer[buffer_size];
value = "";
while (!feof(pipe))
{
if (fgets(buffer, buffer_size, pipe) != NULL)
{
value += buffer;
}
}
pclose(pipe);
return true;
}
#endif
// TODO: Put this functio nsomewhere appropriate
// get text from clipboard
std::string getClipboardText() {
#if defined(WIN32)
// Try opening the clipboard
if (!OpenClipboard(nullptr))
return "";
// Get handle of clipboard object for ANSI text
HANDLE hData = GetClipboardData(CF_TEXT);
if (hData == nullptr)
return "";
// Lock the handle to get the actual text pointer
char * pszText = static_cast<char*>(GlobalLock(hData));
if (pszText == nullptr)
return "";
// Save text in a string class instance
std::string text(pszText);
// Release the lock
GlobalUnlock(hData);
// Release the clipboard
CloseClipboard();
text.erase(std::remove(text.begin(), text.end(), '\r'), text.end());
return text;
#elif defined(__APPLE__)
std::string text;
if (exec("pbpaste", text))
return text.substr(0, text.length() - 1);
return ""; // remove a line ending
#else
std::string text;
if (exec("xclip -o -sel c -f", text))
return text.substr(0, text.length() - 1);
return ""; // remove a line ending
#endif
}
// TODO: Put this function somewhere appropriate
// set text to clipboard
bool setClipboardText(std::string text)
{
#if defined(WIN32)
char *ptrData = nullptr;
HANDLE hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, text.length() + 1);
ptrData = (char*)GlobalLock(hData);
memcpy(ptrData, text.c_str(), text.length() + 1);
GlobalUnlock(hData);
if (!OpenClipboard(nullptr))
return false;
if (!EmptyClipboard())
return false;
SetClipboardData(CF_TEXT, hData);
CloseClipboard();
return true;
#elif defined(__APPLE__)
std::stringstream cmd;
cmd << "echo \"" << text << "\" | pbcopy";
std::string buf;
return exec(cmd.str(), buf);
#else
std::stringstream cmd;
cmd << "echo \"" << text << "\" | xclip -i -sel c -f";
std::string buf;
return exec(cmd.str(), buf);
#endif
}
}
namespace openspace {
LuaConsole::LuaConsole()
: _inputPosition(0)
, _activeCommand(0)
{
FILE* file = fopen(absPath(_filename).c_str(), "rb");
if (file) {
size_t n;
fread(&n, sizeof(size_t), 1, file);
for (size_t i = 0; i < n; ++i) {
size_t length;
fread(&length, sizeof(size_t), 1, file);
char* tmp = new char[length + 1];
fread(tmp, sizeof(char), length, file);
tmp[length] = '\0';
_commandsHistory.emplace_back(tmp);
delete[] tmp;
}
fclose(file);
_commands = _commandsHistory;
}
_commands.push_back("");
_activeCommand = _commands.size() - 1;
}
LuaConsole::~LuaConsole() {
FILE* file = fopen(absPath(_filename).c_str(), "wb");
if (file) {
size_t n = _commandsHistory.size();
fwrite(&n, sizeof(size_t), 1, file);
for (auto s : _commandsHistory) {
size_t length = s.length();
fwrite(&length, sizeof(size_t), 1, file);
fwrite(s.c_str(), sizeof(char), length, file);
}
fclose(file);
}
}
void LuaConsole::keyboardCallback(int key, int action) {
if (action == SGCT_PRESS || action == SGCT_REPEAT) {
const size_t windowIndex = sgct::Engine::instance()->getFocusedWindowIndex();
const bool mod_CONTROL = sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_LEFT_CONTROL) ||
sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_RIGHT_CONTROL);
const bool mod_SHIFT = sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_LEFT_SHIFT) ||
sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_RIGHT_SHIFT);
// Paste from clipboard
if (key == SGCT_KEY_V) {
if (mod_CONTROL) {
addToCommand(getClipboardText());
}
}
// Copy to clipboard
if (key == SGCT_KEY_C) {
if (mod_CONTROL) {
setClipboardText(_commands.at(_activeCommand));
}
}
// Go to the previous character
if (key == SGCT_KEY_LEFT) {
if (_inputPosition > 0)
_inputPosition -= 1;
}
// Go to the next character
if (key == SGCT_KEY_RIGHT) {
if (_inputPosition < _commands.at(_activeCommand).length())
++_inputPosition;
}
// Go to previous command
if (key == SGCT_KEY_UP) {
if (_activeCommand > 0)
--_activeCommand;
_inputPosition = _commands.at(_activeCommand).length();
}
// Go to next command (the last is empty)
if (key == SGCT_KEY_DOWN) {
if (_activeCommand < _commands.size() - 1)
++_activeCommand;
_inputPosition = _commands.at(_activeCommand).length();
}
// Remove character before _inputPosition
if (key == SGCT_KEY_BACKSPACE) {
if (_inputPosition > 0) {
_commands.at(_activeCommand).erase(_inputPosition - 1, 1);
--_inputPosition;
}
}
// Remove character after _inputPosition
if (key == SGCT_KEY_DELETE) {
if (_inputPosition <= _commands.at(_activeCommand).size()) {
_commands.at(_activeCommand).erase(_inputPosition, 1);
}
}
// Go to the beginning of command string
if (key == SGCT_KEY_HOME) {
_inputPosition = 0;
}
// Go to the end of command string
if (key == SGCT_KEY_END) {
_inputPosition = _commands.at(_activeCommand).size();
}
if (key == SGCT_KEY_ENTER) {
// SHIFT+ENTER == new line
if (mod_SHIFT) {
addToCommand("\n");
}
// CTRL+ENTER == Debug print the command
else if (mod_CONTROL) {
LDEBUG("Active command from next line:\n" << _commands.at(_activeCommand));
}
// ENTER == run lua script
else {
if (_commands.at(_activeCommand) != "") {
OsEng.scriptEngine().runScript(_commands.at(_activeCommand));
_commandsHistory.push_back(_commands.at(_activeCommand));
_commands = _commandsHistory;
_commands.push_back("");
_activeCommand = _commands.size() - 1;
_inputPosition = 0;
}
else {
_commands = _commandsHistory;
_commands.push_back("");
OsEng.setInputCommand(false);
}
}
}
}
}
void LuaConsole::charCallback(unsigned int codepoint) {
if (codepoint == ignoreCodepoint())
return;
#ifndef WIN32
const size_t windowIndex = sgct::Engine::instance()->getFocusedWindowIndex();
const bool mod_CONTROL = sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_LEFT_CONTROL) ||
sgct::Engine::instance()->getKey(windowIndex, SGCT_KEY_RIGHT_CONTROL);
const int codepoint_C = 99;
const int codepoint_V = 118;
if (mod_CONTROL && (codepoint == codepoint_C || codepoint == codepoint_V)) {
return;
}
#endif
addToCommand(UnicodeToUTF8(codepoint));
}
void LuaConsole::render() {
const int font_size = 10;
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
int startY = ySize - 2 * font_size;
startY = startY - font_size * 10 * 2;
const int font_with = font_size*0.7;
const glm::vec4 red(1, 0, 0, 1);
const glm::vec4 green(0, 1, 0, 1);
const glm::vec4 white(1, 1, 1, 1);
const sgct_text::Font* font = sgct_text::FontManager::instance()->getFont(constants::fonts::keyMono, font_size);
Freetype::print(font, 10, startY, red, "$");
Freetype::print(font, 10 + font_size, startY, white, "%s", _commands.at(_activeCommand).c_str());
size_t n = std::count(_commands.at(_activeCommand).begin(), _commands.at(_activeCommand).begin() + _inputPosition, '\n');
size_t p = _commands.at(_activeCommand).find_last_of('\n', _inputPosition);
size_t linepos = _inputPosition;
if (n>0) {
if (p == _inputPosition) {
p = _commands.at(_activeCommand).find_last_of('\n', _inputPosition - 1);
if (p != std::string::npos) {
linepos -= p + 1;
}
else {
linepos = _inputPosition - 1;
}
}
else{
linepos -= p + 1;
}
}
char buffer[10];
sprintf(buffer, "%%%lus", linepos + 1);
Freetype::print(font, 10 + static_cast<float>(font_size)*0.5, startY - (font_size)*(n + 1)*3.0 / 2.0, green, buffer, "^");
}
unsigned int LuaConsole::commandInputButton(){
// Button left of 1 and abobe TAB
#ifdef WIN32
return SGCT_KEY_BACKSLASH;
#else
return SGCT_KEY_GRAVE_ACCENT;
#endif
}
unsigned int LuaConsole::ignoreCodepoint() {
// Correesponding codepoint for commandInputButton()
return 167;
}
void LuaConsole::addToCommand(std::string c) {
size_t length = c.length();
_commands.at(_activeCommand).insert(_inputPosition, c);
_inputPosition += length;
}
std::string LuaConsole::UnicodeToUTF8(unsigned int codepoint) {
std::string out;
if (codepoint <= 0x7f)
out.append(1, static_cast<char>(codepoint));
else if (codepoint <= 0x7ff)
{
out.append(1, static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f)));
out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
}
else if (codepoint <= 0xffff)
{
out.append(1, static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f)));
out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
}
else
{
out.append(1, static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07)));
out.append(1, static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));
out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
}
return out;
}
} // namespace openspace

View File

@@ -37,6 +37,7 @@ void mainPostSyncPreDrawFunc();
void mainRenderFunc();
void mainPostDrawFunc();
void mainKeyboardCallback(int key, int action);
void mainCharCallback(unsigned int codepoint);
void mainMouseButtonCallback(int key, int action);
void mainMousePosCallback(double x, double y);
void mainMouseScrollCallback(double posX, double posY);
@@ -77,8 +78,9 @@ int main(int argc, char** argv)
_sgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback);
_sgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback);
_sgctEngine->setMousePosCallbackFunction(mainMousePosCallback);
_sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback);
_sgctEngine->setExternalControlCallback(mainExternalControlCallback);
_sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback);
_sgctEngine->setExternalControlCallback(mainExternalControlCallback);
_sgctEngine->setCharCallbackFunction(mainCharCallback);
// set encode and decode functions
// NOTE: starts synchronizing before init functions
@@ -177,6 +179,12 @@ void mainMouseScrollCallback(double posX, double posY)
OsEng.mouseScrollWheelCallback(static_cast<int>(posY));
}
void mainCharCallback(unsigned int codepoint) {
if (_sgctEngine->isMaster())
OsEng.charCallback(codepoint);
}
void mainEncodeFun()
{
OsEng.encode();

View File

@@ -110,7 +110,6 @@ void Renderable::setPscUniforms(ghoul::opengl::ProgramObject* program, const Cam
program->setUniform("campos", camera->position().vec4());
program->setUniform("objpos", position.vec4());
program->setUniform("camrot", camera->viewRotationMatrix());
//const glm::vec2 scaletmp(1, 1);
program->setUniform("scaling", camera->scaling());
}

View File

@@ -31,6 +31,7 @@
// ghoul includes
#include <ghoul/opengl/texturereader.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/cachemanager.h>
#include <iostream>
#include <iomanip>
@@ -148,8 +149,10 @@ ghoul::opengl::Texture* RenderableVolume::loadVolume(
std::stringstream ss;
ss << "." << dimensions[0] << "x" << dimensions[1] << "x" << dimensions[2] << "." << modelString << "." << variableCacheString << ".cache";
std::string cachepath = filepath + ss.str();
if( cache && FileSys.fileExists(cachepath)) {
std::string cachepath; // = filepath + ss.str();
FileSys.cacheManager()->getCachedFile(filepath, ss.str(), cachepath, true);
if (cache && FileSys.fileExists(cachepath)) {
FILE* file = fopen (cachepath.c_str(), "rb");

View File

@@ -26,6 +26,7 @@
#include <openspace/engine/openspaceengine.h>
#include <openspace/util/powerscaledcoordinate.h>
#include <openspace/util/kameleonwrapper.h>
#include <openspace/abuffer/abuffer.h>
#include <ghoul/opengl/texturereader.h>
#include <ghoul/opencl/clworksize.h>

View File

@@ -54,6 +54,10 @@ RenderableWavefrontObject::RenderableWavefrontObject(const ghoul::Dictionary& di
, _fovProgram(nullptr)
, _texture(nullptr)
, _mode(GL_TRIANGLES)
, _isize(0)
, _vsize(0)
, _varray(nullptr)
, _iarray(nullptr)
{
std::string name;
assert(dictionary.getValue(constants::scenegraphnode::keyName, name));
@@ -106,6 +110,7 @@ void RenderableWavefrontObject::loadObj(const char *filename){
fi = fopen(filename, "r");
if (fi == NULL) {
LERROR("Null Object\n");
}
while (fgets(line, 150, fi) != NULL)
{
@@ -254,6 +259,9 @@ RenderableWavefrontObject::~RenderableWavefrontObject(){
bool RenderableWavefrontObject::initialize()
{
if(_isize == 0)
return false;
bool completeSuccess = true;
if (_programObject == nullptr)
completeSuccess

View File

@@ -30,8 +30,10 @@
#include <openspace/util/time.h>
// We need to decide where this is set
#include <openspace/util/constants.h>
#include <openspace/util/time.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/syncbuffer.h>
#include "sgct.h"
#include <ghoul/filesystem/filesystem.h>
@@ -40,9 +42,12 @@
#include <array>
#include <fstream>
#include <openspace/scenegraph/scenegraph.h>
#include <openspace/abuffer/abuffer.h>
#include <openspace/abuffer/abufferSingleLinked.h>
#include <openspace/abuffer/abufferfixed.h>
#include <openspace/abuffer/abufferdynamic.h>
#include <openspace/util/screenlog.h>
namespace {
const std::string _loggerCat = "RenderEngine";
@@ -72,6 +77,10 @@ RenderEngine::RenderEngine()
: _mainCamera(nullptr)
, _sceneGraph(nullptr)
, _abuffer(nullptr)
, _takeScreenshot(false)
, _log(nullptr)
, _showInfo(true)
, _showScreenLog(true)
{
}
@@ -133,7 +142,8 @@ bool RenderEngine::initializeGL()
// set the tilted view and the FOV
_mainCamera->setCameraDirection(glm::vec3(viewdir[0], viewdir[1], viewdir[2]));
_mainCamera->setMaxFov(wPtr->getFisheyeFOV());
_mainCamera->setMaxFov(wPtr->getFisheyeFOV());
_mainCamera->setLookUpVector(glm::vec3(0.0, 1.0, 0.0));
} else {
// get corner positions, calculating the forth to easily calculate center
glm::vec3 corners[4];
@@ -177,6 +187,9 @@ bool RenderEngine::initializeGL()
_abuffer->initialize();
_log = new ScreenLog();
ghoul::logging::LogManager::ref().addLog(_log);
// successful init
return true;
}
@@ -184,15 +197,17 @@ bool RenderEngine::initializeGL()
void RenderEngine::postSynchronizationPreDraw()
{
sgct_core::SGCTNode * thisNode = sgct_core::ClusterManager::instance()->getThisNodePtr();
for (unsigned int i = 0; i < thisNode->getNumberOfWindows(); i++)
if (sgct::Engine::instance()->getWindowPtr(i)->isWindowResized())
generateGlslConfig();
// Move time forward.
//_runtimeData->advanceTimeBy(1, DAY);
//_runtimeData->advanceTimeBy(1, HOUR);
//_runtimeData->advanceTimeBy(30, MINUTE);
//_runtimeData->advanceTimeBy(1, MILLISECOND);
bool updateAbuffer = false;
for (unsigned int i = 0; i < thisNode->getNumberOfWindows(); i++) {
if (sgct::Engine::instance()->getWindowPtr(i)->isWindowResized()) {
updateAbuffer = true;
break;
}
}
if (updateAbuffer) {
generateGlslConfig();
_abuffer->reinitialize();
}
// converts the quaternion used to rotation matrices
_mainCamera->compileViewRotationMatrix();
@@ -203,13 +218,14 @@ void RenderEngine::postSynchronizationPreDraw()
_sceneGraph->update(a);
_mainCamera->setCameraDirection(glm::vec3(0, 0, -1));
_sceneGraph->evaluate(_mainCamera);
// clear the abuffer before rendering the scene
_abuffer->clear();
}
void RenderEngine::render()
{
// SGCT resets certain settings
//glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
@@ -234,7 +250,6 @@ void RenderEngine::render()
// render the scene starting from the root node
_abuffer->clear();
_abuffer->preRender();
_sceneGraph->render({*_mainCamera, psc()});
_abuffer->postRender();
@@ -244,67 +259,125 @@ void RenderEngine::render()
_abuffer->resolve();
glDisable(GL_BLEND);
#ifndef OPENSPACE_VIDEO_EXPORT
// Print some useful information on the master viewport
if (sgct::Engine::instance()->isMaster()) {
// Apple usually has retina screens
#ifdef __APPLE__
#define FONT_SIZE 18
#else
#define FONT_SIZE 10
#endif
const glm::vec2 scaling = _mainCamera->scaling();
const glm::vec3 viewdirection = _mainCamera->viewDirection();
const psc position = _mainCamera->position();
const psc origin = OsEng.interactionHandler().getOrigin();
const PowerScaledScalar pssl = (position - origin).length();
/* GUI PRINT */
std::string&& time = Time::ref().currentTimeUTC().c_str();
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 18, "Date: %s", time.c_str()
);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 16, "Avg. Frametime: %.10f", sgct::Engine::instance()->getAvgDt()
);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 14, "Drawtime: %.10f", sgct::Engine::instance()->getDrawTime()
);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 12, "Frametime: %.10f", sgct::Engine::instance()->getDt()
);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 10, "Origin: (%.5f, %.5f, %.5f, %.5f)", origin[0],
origin[1], origin[2], origin[3]);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 8, "Camera position: (%.5f, %.5f, %.5f, %.5f)",
position[0], position[1], position[2], position[3]);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 6, "Distance to origin: (%.15f, %.2f)", pssl[0],
pssl[1]);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 4, "View direction: (%.3f, %.3f, %.3f)",
viewdirection[0], viewdirection[1], viewdirection[2]);
Freetype::print(
sgct_text::FontManager::instance()->getFont("SGCTFont", FONT_SIZE),
FONT_SIZE, FONT_SIZE * 2, "Scaling: (%.10f, %.2f)", scaling[0], scaling[1]);
}
sgct::SGCTWindow* w = sgct::Engine::instance()->getActiveWindowPtr();
if (sgct::Engine::instance()->isMaster() && ! w->isUsingFisheyeRendering()) {
// TODO: Adjust font_size properly when using retina screen
const int font_size_mono = 10;
const int font_size_light = 8;
const int font_with_light = font_size_light*0.7;
const sgct_text::Font* fontLight = sgct_text::FontManager::instance()->getFont(constants::fonts::keyLight, font_size_light);
const sgct_text::Font* fontMono = sgct_text::FontManager::instance()->getFont(constants::fonts::keyMono, font_size_mono);
if (_showInfo) {
const sgct_text::Font* font = fontMono;
int x1, xSize, y1, ySize;
sgct::Engine::instance()->getActiveWindowPtr()->getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
int startY = ySize - 2 * font_size_mono;
const glm::vec2 scaling = _mainCamera->scaling();
const glm::vec3 viewdirection = _mainCamera->viewDirection();
const psc position = _mainCamera->position();
const psc origin = OsEng.interactionHandler().getOrigin();
const PowerScaledScalar pssl = (position - origin).length();
// GUI PRINT
// Using a macro to shorten line length and increase readability
#define PrintText(i, format, ...) Freetype::print(font, 10, startY - font_size_mono * i * 2, format, __VA_ARGS__);
int i = 0;
PrintText(i++, "Date: %s", Time::ref().currentTimeUTC().c_str());
PrintText(i++, "Avg. Frametime: %.5f", sgct::Engine::instance()->getAvgDt());
PrintText(i++, "Drawtime: %.5f", sgct::Engine::instance()->getDrawTime());
PrintText(i++, "Frametime: %.5f", sgct::Engine::instance()->getDt());
PrintText(i++, "Origin: (% .5f, % .5f, % .5f, % .5f)", origin[0], origin[1], origin[2], origin[3]);
PrintText(i++, "Cam pos: (% .5f, % .5f, % .5f, % .5f)", position[0], position[1], position[2], position[3]);
PrintText(i++, "View dir: (% .5f, % .5f, % .5f)", viewdirection[0], viewdirection[1], viewdirection[2]);
PrintText(i++, "Cam->origin: (% .15f, % .4f)", pssl[0], pssl[1]);
PrintText(i++, "Scaling: (% .5f, % .5f)", scaling[0], scaling[1]);
#undef PrintText
}
if (_showScreenLog)
{
const sgct_text::Font* font = fontLight;
const int max = 10;
const int category_length = 20;
const int msg_length = 140;
const double ttl = 15.0;
const double fade = 5.0;
auto entries = _log->last(max);
const glm::vec4 white(0.9, 0.9, 0.9, 1);
const glm::vec4 red(1, 0, 0, 1);
const glm::vec4 yellow(1, 1, 0, 1);
const glm::vec4 green(0, 1, 0, 1);
const glm::vec4 blue(0, 0, 1, 1);
size_t nr = 1;
for (auto it = entries.first; it != entries.second; ++it) {
const ScreenLog::LogEntry* e = &(*it);
const double t = sgct::Engine::instance()->getTime();
double diff = t - e->timeStamp;
// Since all log entries are ordered, once one is exceeding TTL, all have
if (diff > ttl)
break;
float alpha = 1;
float ttf = ttl - fade;
if (diff > ttf) {
diff = diff - ttf;
float p = 0.8 - diff / fade;
alpha = (p <= 0.0) ? 0.0 : pow(p, 0.3);
}
// Since all log entries are ordered, once one exceeds alpha, all have
if (alpha <= 0.0)
break;
std::string lvl = "(" + ghoul::logging::LogManager::stringFromLevel(e->level) + ")";
Freetype::print(font, 10, font_size_light * nr * 2, white*alpha,
"%-14s %s%s", // Format
e->timeString.c_str(), // Time string
e->category.substr(0, category_length).c_str(), // Category string (up to category_length)
e->category.length() > 20 ? "..." : ""); // Pad category with "..." if exceeds category_length
glm::vec4 color = white;
if (e->level == ghoul::logging::LogManager::LogLevel::Debug)
color = green;
if (e->level == ghoul::logging::LogManager::LogLevel::Warning)
color = yellow;
if (e->level == ghoul::logging::LogManager::LogLevel::Error)
color = red;
if (e->level == ghoul::logging::LogManager::LogLevel::Fatal)
color = blue;
Freetype::print(font, 10 + 39 * font_with_light, font_size_light * nr * 2, color*alpha, "%s", lvl.c_str());
Freetype::print(font, 10 + 53 * font_with_light, font_size_light * nr * 2, white*alpha, "%s", e->message.substr(0, msg_length).c_str());
++nr;
}
}
#endif
}
}
void RenderEngine::postDraw() {
if (_takeScreenshot) {
sgct::Engine::instance()->takeScreenshot();
_takeScreenshot = false;
}
}
void RenderEngine::takeScreenshot() {
_takeScreenshot = true;
}
SceneGraph* RenderEngine::sceneGraph()
{
// TODO custom assert (ticket #5)
@@ -317,7 +390,7 @@ void RenderEngine::setSceneGraph(SceneGraph* sceneGraph)
_sceneGraph = sceneGraph;
}
void RenderEngine::serialize(std::vector<char>& dataStream, size_t& offset) {
void RenderEngine::serialize(SyncBuffer* syncBuffer) {
// TODO: This has to be redone properly (ab) [new class providing methods to serialize
// variables]
@@ -327,6 +400,12 @@ void RenderEngine::serialize(std::vector<char>& dataStream, size_t& offset) {
// camera->viewRotationMatrix
// camera->scaling
syncBuffer->encode(_mainCamera->scaling());
syncBuffer->encode(_mainCamera->position());
syncBuffer->encode(_mainCamera->viewRotationMatrix());
//syncBuffer->encode(_mainCamera->lookUpVector());
//syncBuffer->encode(_mainCamera->rotation());
//const glm::vec2 scaling = _mainCamera->scaling();
//const psc position = _mainCamera->position();
@@ -406,8 +485,23 @@ void RenderEngine::serialize(std::vector<char>& dataStream, size_t& offset) {
//dataStream[offset++] = s.representation[3];
}
void RenderEngine::deserialize(const std::vector<char>& dataStream, size_t& offset) {
void RenderEngine::deserialize(SyncBuffer* syncBuffer) {
// TODO: This has to be redone properly (ab)
glm::vec2 scaling;
psc position;
glm::mat4 viewRotation;
//glm::vec3 lookUpVector;
syncBuffer->decode(scaling);
syncBuffer->decode(position);
syncBuffer->decode(viewRotation);
_mainCamera->setScaling(scaling);
_mainCamera->setPosition(position);
_mainCamera->setViewRotationMatrix(viewRotation);
//_mainCamera->setLookUpVector(lookUpVector);
//_mainCamera->compileViewRotationMatrix();
// union storage {
// float value;
@@ -498,15 +592,13 @@ ABuffer* RenderEngine::abuffer() const {
void RenderEngine::generateGlslConfig() {
LDEBUG("Generating GLSLS config, expect shader recompilation");
int x1, xSize, y1, ySize;
sgct::Engine::instance()->
getActiveWindowPtr()->
getCurrentViewportPixelCoords(x1, y1, xSize, ySize);
int xSize = sgct::Engine::instance()->getActiveWindowPtr()->getXFramebufferResolution();;
int ySize = sgct::Engine::instance()->getActiveWindowPtr()->getYFramebufferResolution();;
// TODO: Make this file creation dynamic and better in every way
// TODO: If the screen size changes it is enough if this file is regenerated to
// recompile all necessary files
std::ofstream os(absPath("${SHADERS}/ABuffer/constants.hglsl"));
std::ofstream os(absPath("${SHADERS_GENERATED}/constants.hglsl"));
os << "#define SCREEN_WIDTH " << xSize << "\n"
<< "#define SCREEN_HEIGHT " << ySize << "\n"
<< "#define MAX_LAYERS " << ABuffer::MAX_LAYERS << "\n"

View File

@@ -292,6 +292,10 @@ bool RenderableStars::deinitialize(){
//#define TMAT
void RenderableStars::render(const RenderData& data){
if(!_haloProgram)
return;
if(!_texture)
return;
assert(_haloProgram);
//printOpenGLError();
// activate shader

View File

@@ -31,6 +31,7 @@
#include <openspace/util/constants.h>
#include <openspace/query/query.h>
#include <openspace/util/time.h>
#include <openspace/abuffer/abuffer.h>
// ghoul includes
#include "ghoul/opengl/programobject.h"

View File

@@ -100,9 +100,13 @@ glm::vec3 Camera::cameraDirection() const
return _cameraDirection;
}
glm::mat4 Camera::viewRotationMatrix() const
void Camera::setViewRotationMatrix(glm::mat4 m) {
_viewRotationMatrix = m;
}
const glm::mat4& Camera::viewRotationMatrix() const
{
return glm::mat4(_viewRotationMatrix);
return _viewRotationMatrix;
}
void Camera::compileViewRotationMatrix()
@@ -176,7 +180,7 @@ void Camera::setLookUpVector(glm::vec3 lookUp)
_lookUp = std::move(lookUp);
}
const glm::vec3 Camera::lookUpVector() const
const glm::vec3& Camera::lookUpVector() const
{
return _lookUp;
}

View File

@@ -467,7 +467,7 @@ std::vector<glm::vec3> KameleonWrapper::traceCartesianFieldline(
else if (pos.z < 0.0 && (pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < 1.0))
end = FieldlineEnd::SOUTH;
else
end = FieldlineEnd::OUT;
end = FieldlineEnd::FAROUT;
return line;
}
@@ -610,15 +610,15 @@ glm::vec4 KameleonWrapper::classifyFieldline(FieldlineEnd fEnd, FieldlineEnd bEn
&& (bEnd == FieldlineEnd::NORTH || bEnd == FieldlineEnd::SOUTH)) {
// closed
color = glm::vec4(1.0, 0.0, 0.0, 1.0);
} else if ((fEnd == FieldlineEnd::OUT && bEnd == FieldlineEnd::NORTH)
|| (bEnd == FieldlineEnd::OUT && fEnd == FieldlineEnd::NORTH)) {
} else if ((fEnd == FieldlineEnd::FAROUT && bEnd == FieldlineEnd::NORTH)
|| (bEnd == FieldlineEnd::FAROUT && fEnd == FieldlineEnd::NORTH)) {
// north
color = glm::vec4(1.0, 1.0, 0.0, 1.0);
} else if ((fEnd == FieldlineEnd::OUT && bEnd == FieldlineEnd::SOUTH)
|| (bEnd == FieldlineEnd::OUT && fEnd == FieldlineEnd::SOUTH)) {
} else if ((fEnd == FieldlineEnd::FAROUT && bEnd == FieldlineEnd::SOUTH)
|| (bEnd == FieldlineEnd::FAROUT && fEnd == FieldlineEnd::SOUTH)) {
// south
color = glm::vec4(0.0, 1.0, 0.0, 1.0);
} else if (fEnd == FieldlineEnd::OUT && bEnd == FieldlineEnd::OUT) {
} else if (fEnd == FieldlineEnd::FAROUT && bEnd == FieldlineEnd::FAROUT) {
// solar wind
color = glm::vec4(0.0, 0.0, 1.0, 1.0);
}

51
src/util/screenlog.cpp Normal file
View File

@@ -0,0 +1,51 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/util/screenlog.h>
#include <sgct.h> // sgct::Engine::instance()->getTime()
namespace openspace {
ScreenLog::ScreenLog() {}
void ScreenLog::log(ghoul::logging::LogManager::LogLevel level, const std::string& category, const std::string& message) {
if (level >= ghoul::logging::LogManager::LogLevel::Info)
_entries.emplace_back(level, sgct::Engine::instance()->getTime(), Log::getTimeString(), category, message);
// Once reaching maximum size, reduce to half
if (_entries.size() > MaximumSize) {
_entries.erase(_entries.begin(), _entries.begin() + MaximumSize / 2);
}
}
ScreenLog::const_range ScreenLog::last(size_t n) {
if (_entries.size() > n) {
return std::make_pair(_entries.rbegin(), _entries.rbegin() + n);
} else {
return std::make_pair(_entries.rbegin(), _entries.rend());
}
}
}

51
src/util/syncbuffer.cpp Normal file
View File

@@ -0,0 +1,51 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/util/syncbuffer.h>
namespace openspace {
SyncBuffer::SyncBuffer(size_t n)
: _n(n)
, _encodeOffset(0)
, _decodeOffset(0)
{
_dataStream.resize(_n);
}
void SyncBuffer::write() {
_synchronizationBuffer.setVal(_dataStream);
sgct::SharedData::instance()->writeVector(&_synchronizationBuffer);
_encodeOffset = 0;
_decodeOffset = 0;
}
void SyncBuffer::read() {
sgct::SharedData::instance()->readVector(&_synchronizationBuffer);
_dataStream = std::move(_synchronizationBuffer.getVal());
_encodeOffset = 0;
_decodeOffset = 0;
}
} // namespace openspace