Merge branch 'develop' of github.com:OpenSpace/OpenSpace into feature/parallelconnection

Conflicts:
	include/openspace/engine/openspaceengine.h
	src/engine/openspaceengine.cpp
	src/interaction/interactionhandler.cpp
	src/network/parallelconnection.cpp
	src/scripting/scriptengine.cpp
This commit is contained in:
Emil Axelsson
2016-09-22 19:33:05 +02:00
311 changed files with 12363 additions and 4144 deletions

View File

@@ -27,6 +27,7 @@
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/lua/lua_helper.h>
#include <ghoul/misc/exception.h>
#include <openspace/engine/configurationmanager.h>
#include <openspace/engine/openspaceengine.h>
@@ -51,7 +52,6 @@ namespace {
//const lua_CFunction _printFunctionReplacement = luascriptfunctions::printInfo;
const int _setTableOffset = -3; // -1 (top) -1 (first argument) -1 (second argument)
}
void ScriptEngine::initialize() {
@@ -479,41 +479,36 @@ std::vector<std::string> ScriptEngine::allLuaFunctions() const {
return result;
}
bool ScriptEngine::writeDocumentation(const std::string& filename, const std::string& type) const {
if (type == "text") {
// The additional space between the longest function name and the descriptions
LDEBUG("Writing Lua documentation of type '" << type <<
"' to file '" << filename << "'");
std::ofstream file(filename);
if (!file.good()) {
LERROR("Could not open file '" << filename << "' for writing documentation");
return false;
void ScriptEngine::writeDocumentation(const std::string& filename, const std::string& type) const {
auto concatenate = [](std::string library, std::string function) {
std::string total = "openspace.";
if (!library.empty()) {
total += std::move(library) + ".";
}
total += std::move(function);
return total;
};
auto concatenate = [](std::string library, std::string function) {
std::string total = "openspace.";
if (!library.empty())
total += std::move(library) + ".";
total += std::move(function);
return total;
};
LDEBUG("Writing Lua documentation of type '" << type <<
"' to file '" << filename << "'");
if (type == "text") {
// Settings
const unsigned int lineWidth = 80;
static const std::string whitespace = " \t";
static const std::string padding = " ";
const bool commandListArguments = true;
// The additional space between the longest function name and the descriptions
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
file << "Available commands:\n";
// Now write out the functions
for (const LuaLibrary& library : _registeredLibraries) {
for (const LuaLibrary::Function& function : library.functions) {
std::string functionName = concatenate(library.name, function.name);
file << padding << functionName;
if (commandListArguments)
file << "(" << function.argumentText << ")";
file << std::endl;
for (const LuaLibrary& l : _registeredLibraries) {
for (const LuaLibrary::Function& f : l.functions) {
std::string name = concatenate(l.name, f.name);
file << padding << name << "(" << f.argumentText << ")" << std::endl;
}
}
file << std::endl;
@@ -521,24 +516,32 @@ bool ScriptEngine::writeDocumentation(const std::string& filename, const std::st
// Now write out the functions definitions
for (const LuaLibrary& library : _registeredLibraries) {
for (const LuaLibrary::Function& function : library.functions) {
std::string functionName = concatenate(library.name, function.name);
file << functionName << "(" << function.argumentText << "):" << std::endl;
std::string name = concatenate(library.name, function.name);
file << name << "(" << function.argumentText << "):" << std::endl;
std::string remainingHelptext = function.helpText;
// @CLEANUP This needs to become a bit prettier ---abock
while (!remainingHelptext.empty()) {
const auto length = remainingHelptext.length();
const auto paddingLength = padding.length();
const size_t length = remainingHelptext.length();
const size_t paddingLength = padding.length();
if ((length + paddingLength) > lineWidth) {
auto lastSpace = remainingHelptext.find_last_of(whitespace, lineWidth - 1 - paddingLength);
if (lastSpace == remainingHelptext.npos)
size_t lastSpace = remainingHelptext.find_last_of(
whitespace,
lineWidth - 1 - paddingLength
);
if (lastSpace == remainingHelptext.npos) {
lastSpace = lineWidth;
file << padding << remainingHelptext.substr(0, lastSpace) << std::endl;
auto firstNotSpace = remainingHelptext.find_first_not_of(whitespace, lastSpace);
if (firstNotSpace == remainingHelptext.npos)
}
file << padding << remainingHelptext.substr(0, lastSpace) << '\n';
size_t firstNotSpace = remainingHelptext.find_first_not_of(
whitespace,
lastSpace
);
if (firstNotSpace == remainingHelptext.npos) {
firstNotSpace = lastSpace;
}
remainingHelptext = remainingHelptext.substr(firstNotSpace);
}
else {
@@ -549,27 +552,115 @@ bool ScriptEngine::writeDocumentation(const std::string& filename, const std::st
file << std::endl;
}
}
return true;
}
else if (type == "html") {
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
#ifdef JSON
// Create JSON
std::stringstream json;
json << "[";
for (const LuaLibrary& l : _registeredLibraries) {
json << "{";
json << "\"library\": \"" << l.name << "\",";
json << "\"functions\": [";
for (const LuaLibrary::Function& f : l.functions) {
json << "{";
json << "\"name\": \"" << f.name << "\", ";
json << "\"arguments\": \"" << f.argumentText << "\", ";
json << "\"help\": \"" << f.helpText << "\"";
json << "},";
}
json << "]},";
}
json << "]";
std::string jsonText = json.str();
#else
std::stringstream html;
html << "<html>\n"
<< "\t<head>\n"
<< "\t\t<title>Script Log</title>\n"
<< "\t</head>\n"
<< "<body>\n"
<< "<table cellpadding=3 cellspacing=0 border=1>\n"
<< "\t<caption>Script Log</caption>\n\n"
<< "\t<thead>\n"
<< "\t\t<tr>\n"
<< "\t\t\t<th rowspan=2>Library</th>\n"
<< "\t\t\t<th colspan=3>Functions</th>\n"
<< "\t\t</tr>\n"
<< "\t\t<tr>\n"
<< "\t\t\t<th>Name</th>\n"
<< "\t\t\t<th>Arguments</th>\n"
<< "\t\t\t<th>Help</th>\n"
<< "\t\t</tr>\n"
<< "\t</thead>\n"
<< "\t<tbody>\n";
for (const LuaLibrary& l : _registeredLibraries) {
html << "\t<tr>\n";
if (l.name.empty()) {
html << "\t\t<td>openspace</td>\n";
}
else {
html << "\t\t<td>openspace." << l.name << "</td>\n";
}
html << "\t\t<td></td><td></td><td></td>\n"
<< "\t\</tr>";
for (const LuaLibrary::Function& f : l.functions) {
html << "\t<tr>\n"
<< "\t\t<td></td>\n"
<< "\t\t<td>" << f.name << "</td>\n"
<< "\t\t<td>" << f.argumentText << "</td>\n"
<< "\t\t<td>" << f.helpText << "</td>\n"
<< "\t</tr>\n";
}
html << "\t<tr><td style=\"line-height: 10px;\" colspan=4></td></tr>\n";
}
html << "\t</tbody>\n"
<< "</table>\n"
<< "</html>";
file << html.str();
#endif
}
else {
LERROR("Undefined type '" << type << "' for Lua documentation");
return false;
throw ghoul::RuntimeError("Undefined type '" + type + "' for Lua documentation");
}
}
bool ScriptEngine::writeLog(const std::string& script) {
const std::string KeyScriptLogType =
ConfigurationManager::KeyScriptLog + '.' + ConfigurationManager::PartType;
const std::string KeyScriptLogFile =
ConfigurationManager::KeyScriptLog + '.' + ConfigurationManager::PartFile;
// Check that logging is enabled and initialize if necessary
if (!_logFileExists) {
// If a ScriptLogFile was specified, generate it now
const bool hasType = OsEng.configurationManager()
.hasKey(ConfigurationManager::KeyScriptLogType);
.hasKey(KeyScriptLogType);
const bool hasFile = OsEng.configurationManager()
.hasKey(ConfigurationManager::KeyScriptLogFile);
.hasKey(KeyScriptLogFile);
if (hasType && hasFile) {
OsEng.configurationManager()
.getValue(ConfigurationManager::KeyScriptLogType, _logType);
.getValue(KeyScriptLogType, _logType);
OsEng.configurationManager()
.getValue(ConfigurationManager::KeyScriptLogFile, _logFilename);
.getValue(KeyScriptLogFile, _logFilename);
_logFilename = absPath(_logFilename);
_logFileExists = true;
@@ -588,8 +679,8 @@ bool ScriptEngine::writeLog(const std::string& script) {
}
} else {
LDEBUG("No script log specified in 'openspace.cfg.' To log, set '"
<< ConfigurationManager::KeyScriptLogType << " and "
<< ConfigurationManager::KeyScriptLogFile
<< KeyScriptLogType << " and "
<< KeyScriptLogFile
<< " in configuration table.");
_logScripts = false;
return false;
@@ -616,51 +707,16 @@ bool ScriptEngine::writeLog(const std::string& script) {
return true;
}
void ScriptEngine::serialize(SyncBuffer* syncBuffer){
syncBuffer->encode(_currentSyncedScript);
_currentSyncedScript.clear();
}
void ScriptEngine::deserialize(SyncBuffer* syncBuffer){
syncBuffer->decode(_currentSyncedScript);
if (!_currentSyncedScript.empty()){
_mutex.lock();
_receivedScripts.push_back(_currentSyncedScript);
_mutex.unlock();
}
}
void ScriptEngine::postSynchronizationPreDraw() {
std::vector<std::string> scripts;
void ScriptEngine::presync(bool isMaster) {
if (!isMaster) return;
_mutex.lock();
scripts.assign(_receivedScripts.begin(), _receivedScripts.end());
_receivedScripts.clear();
_mutex.unlock();
while (!scripts.empty()) {
try {
runScript(scripts.back());
}
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
scripts.pop_back();
}
}
void ScriptEngine::preSynchronization() {
_mutex.lock();
if (!_queuedScripts.empty()){
if (!_queuedScripts.empty()) {
_currentSyncedScript = _queuedScripts.back().first;
bool remoteScripting = _queuedScripts.back().second;
//Not really a received script but the master also needs to run the script...
_receivedScripts.push_back(_currentSyncedScript);
_queuedScripts.pop_back();
@@ -670,8 +726,43 @@ void ScriptEngine::preSynchronization() {
}
}
_mutex.unlock();
}
void ScriptEngine::encode(SyncBuffer* syncBuffer) {
syncBuffer->encode(_currentSyncedScript);
_currentSyncedScript.clear();
}
void ScriptEngine::decode(SyncBuffer* syncBuffer) {
syncBuffer->decode(_currentSyncedScript);
if (!_currentSyncedScript.empty()) {
_mutex.lock();
_receivedScripts.push_back(_currentSyncedScript);
_mutex.unlock();
}
}
void ScriptEngine::postsync(bool isMaster) {
std::vector<std::string> scripts;
_mutex.lock();
scripts.assign(_receivedScripts.begin(), _receivedScripts.end());
_receivedScripts.clear();
_mutex.unlock();
while (!scripts.empty()) {
try {
runScript(scripts.back());
}
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
scripts.pop_back();
}
}
void ScriptEngine::queueScript(const std::string &script, ScriptEngine::RemoteScripting remoteScripting){

View File

@@ -0,0 +1,197 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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/scripting/scriptscheduler.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/scripting/scriptengine.h>
#include <openspace/util/spicemanager.h> // parse time
#include <ghoul/logging/logmanager.h>
#include <ghoul/filesystem/filesystem>
namespace openspace {
namespace scripting {
namespace {
const std::string _loggerCat = "ScriptScheduler";
const std::string KEY_TIME = "Time";
const std::string KEY_FORWARD_SCRIPT = "ReversibleLuaScript.Forward";
const std::string KEY_BACKWARD_SCRIPT = "ReversibleLuaScript.Backward";
}
ScheduledScript::ScheduledScript(const ghoul::Dictionary& dict)
: ScheduledScript() // default init first
{
std::string timeStr;
if (dict.getValue(KEY_TIME, timeStr)) {
time = SpiceManager::ref().ephemerisTimeFromDate(timeStr);
if (!dict.getValue(KEY_FORWARD_SCRIPT, script.forwardScript)) {
LERROR("Unable to read " << KEY_FORWARD_SCRIPT);
}
if (!dict.getValue(KEY_BACKWARD_SCRIPT, script.backwardScript)) {
LERROR("Unable to read " << KEY_BACKWARD_SCRIPT);
}
}
else {
LERROR("Unable to read " << KEY_TIME);
}
}
bool ScheduledScript::CompareByTime(const ScheduledScript& s1, const ScheduledScript& s2){
return s1.time < s2.time;
}
void ScriptScheduler::loadScripts(const std::string& filepath, lua_State* L) {
ghoul::Dictionary timedScriptsDict;
try {
ghoul::lua::loadDictionaryFromFile(absPath(filepath), timedScriptsDict, L);
}
catch (const ghoul::RuntimeError& e) {
LERROR(e.what());
return;
}
loadScripts(timedScriptsDict);
}
void ScriptScheduler::loadScripts(const ghoul::Dictionary& dict) {
for (size_t i = 0; i < dict.size(); ++i) {
std::string id = std::to_string(i + 1);
const ghoul::Dictionary& timedScriptDict = dict.value<ghoul::Dictionary>(id);
_scheduledScripts.push_back(ScheduledScript(timedScriptDict));
}
// Sort scripts by time
std::stable_sort(_scheduledScripts.begin(), _scheduledScripts.end(), &ScheduledScript::CompareByTime);
// Ensure _currentIndex and _currentTime is accurate after new scripts was added
double lastTime = _currentTime;
rewind();
progressTo(lastTime);
}
void ScriptScheduler::rewind() {
_currentIndex = 0;
_currentTime = -DBL_MAX;
}
void ScriptScheduler::clearSchedule() {
rewind();
_scheduledScripts.clear();
}
std::queue<std::string> ScriptScheduler::progressTo(double newTime) {
std::queue<std::string> triggeredScripts;
if (newTime > _currentTime) {
while(_currentIndex < _scheduledScripts.size() && _scheduledScripts[_currentIndex].time <= newTime){
triggeredScripts.push(_scheduledScripts[_currentIndex].script.forwardScript);
_currentIndex++;
}
}
else {
while (0 < _currentIndex && _scheduledScripts[_currentIndex - 1].time > newTime) {
triggeredScripts.push(_scheduledScripts[_currentIndex - 1].script.backwardScript);
_currentIndex--;
}
}
_currentTime = newTime;
return triggeredScripts;
}
std::queue<std::string> ScriptScheduler::progressTo(const std::string& timeStr) {
return std::move(progressTo(SpiceManager::ref().ephemerisTimeFromDate(timeStr)));
}
double ScriptScheduler::currentTime() const {
return _currentTime;
};
const std::vector<ScheduledScript>& ScriptScheduler::allScripts() const {
return _scheduledScripts;
};
/////////////////////////////////////////////////////////////////////
// Lua library functions //
/////////////////////////////////////////////////////////////////////
namespace luascriptfunctions {
int loadTimedScripts(lua_State* L) {
using ghoul::lua::luaTypeToString;
int nArguments = lua_gettop(L);
if (nArguments != 1)
return luaL_error(L, "Expected %i arguments, got %i", 1, nArguments);
std::string missionFileName = luaL_checkstring(L, -1);
if (missionFileName.empty()) {
return luaL_error(L, "filepath string is empty");
}
OsEng.scriptScheduler().loadScripts(missionFileName, L);
}
int clear(lua_State* L) {
using ghoul::lua::luaTypeToString;
int nArguments = lua_gettop(L);
if (nArguments != 0)
return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments);
OsEng.scriptScheduler().clearSchedule();
}
} // namespace luascriptfunction
LuaLibrary ScriptScheduler::luaLibrary() {
return {
"scriptScheduler",
{
{
"load",
&luascriptfunctions::loadTimedScripts,
"string",
"Load timed scripts from file"
},
{
"clear",
&luascriptfunctions::clear,
"",
"clears all scheduled scripts"
},
}
};
}
} // namespace scripting
} // namespace openspace