text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "webkit/glue/plugins/test/plugin_client.h"
#include "webkit/glue/plugins/test/plugin_arguments_test.h"
#include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h"
#include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h"
#include "webkit/glue/plugins/test/plugin_geturl_test.h"
#include "webkit/glue/plugins/test/plugin_javascript_open_popup.h"
#include "webkit/glue/plugins/test/plugin_new_fails_test.h"
#include "webkit/glue/plugins/test/plugin_private_test.h"
#include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h"
#include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h"
#include "webkit/glue/plugins/test/plugin_window_size_test.h"
#if defined(OS_WIN)
#include "webkit/glue/plugins/test/plugin_windowed_test.h"
#endif
#include "webkit/glue/plugins/test/plugin_windowless_test.h"
#include "third_party/npapi/bindings/npapi.h"
#include "third_party/npapi/bindings/npruntime.h"
namespace NPAPIClient {
NPNetscapeFuncs* PluginClient::host_functions_;
NPError PluginClient::GetEntryPoints(NPPluginFuncs* pFuncs) {
if (pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if (pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = reinterpret_cast<JRIGlobalRef>(NPP_GetJavaClass);
return NPERR_NO_ERROR;
}
NPError PluginClient::Initialize(NPNetscapeFuncs* pFuncs) {
if (pFuncs == NULL) {
return NPERR_INVALID_FUNCTABLE_ERROR;
}
if (static_cast<unsigned char>((pFuncs->version >> 8) & 0xff) >
NP_VERSION_MAJOR) {
return NPERR_INCOMPATIBLE_VERSION_ERROR;
}
host_functions_ = pFuncs;
return NPERR_NO_ERROR;
}
NPError PluginClient::Shutdown() {
return NPERR_NO_ERROR;
}
} // namespace NPAPIClient
extern "C" {
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode,
int16 argc, char* argn[], char* argv[], NPSavedData* saved) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// We look at the test name requested via the plugin arguments. We match
// that against a given test and try to instantiate it.
// lookup the name parameter
std::string test_name;
for (int name_index = 0; name_index < argc; name_index++)
if (base::strcasecmp(argn[name_index], "name") == 0) {
test_name = argv[name_index];
break;
}
if (test_name.empty())
return NPERR_GENERIC_ERROR; // no name found
NPError ret = NPERR_GENERIC_ERROR;
bool windowless_plugin = false;
NPAPIClient::PluginTest *new_test = NULL;
if (test_name == "arguments") {
new_test = new NPAPIClient::PluginArgumentsTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "geturl") {
new_test = new NPAPIClient::PluginGetURLTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_proxy") {
new_test = new NPAPIClient::NPObjectProxyTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_windowless_test.*.
} else if (test_name == "execute_script_delete_in_paint" ||
test_name == "execute_script_delete_in_mouse_move" ||
test_name == "delete_frame_test" ||
test_name == "multiple_instances_sync_calls") {
new_test = new NPAPIClient::WindowlessPluginTest(instance,
NPAPIClient::PluginClient::HostFunctions(), test_name);
windowless_plugin = true;
#endif
} else if (test_name == "getjavascripturl") {
new_test = new NPAPIClient::ExecuteGetJavascriptUrlTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_window_size_test.*.
} else if (test_name == "checkwindowrect") {
new_test = new NPAPIClient::PluginWindowSizeTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else if (test_name == "self_delete_plugin_stream") {
new_test = new NPAPIClient::DeletePluginInStreamTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_npobject_lifetime_test.*.
} else if (test_name == "npobject_lifetime_test") {
new_test = new NPAPIClient::NPObjectLifetimeTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_lifetime_test_second_instance") {
new_test = new NPAPIClient::NPObjectLifetimeTestInstance2(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "new_fails") {
new_test = new NPAPIClient::NewFailsTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_delete_plugin_in_evaluate") {
new_test = new NPAPIClient::NPObjectDeletePluginInNPN_Evaluate(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else if (test_name == "plugin_javascript_open_popup_with_plugin") {
new_test = new NPAPIClient::ExecuteJavascriptOpenPopupWithPluginTest(
instance, NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "plugin_popup_with_plugin_target") {
new_test = new NPAPIClient::ExecuteJavascriptPopupWindowTargetPluginTest(
instance, NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "private") {
new_test = new NPAPIClient::PrivateTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_windowed_test.*.
} else if (test_name == "hidden_plugin" ||
test_name == "create_instance_in_paint" ||
test_name == "alert_in_window_message") {
new_test = new NPAPIClient::WindowedPluginTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else {
// If we don't have a test case for this, create a
// generic one which basically never fails.
LOG(WARNING) << "Unknown test name '" << test_name
<< "'; using default test.";
new_test = new NPAPIClient::PluginTest(instance,
NPAPIClient::PluginClient::HostFunctions());
}
if (new_test) {
ret = new_test->New(mode, argc, (const char**)argn,
(const char**)argv, saved);
if ((ret == NPERR_NO_ERROR) && windowless_plugin) {
NPAPIClient::PluginClient::HostFunctions()->setvalue(
instance, NPPVpluginWindowBool, NULL);
}
}
return ret;
}
NPError NPP_Destroy(NPP instance, NPSavedData** save) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
delete plugin;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* pNPWindow) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
if (pNPWindow->window == NULL) {
return NPERR_NO_ERROR;
}
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->SetWindow(pNPWindow);
}
NPError NPP_NewStream(NPP instance, NPMIMEType type,
NPStream* stream, NPBool seekable, uint16* stype) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->NewStream(type, stream, seekable, stype);
}
int32 NPP_WriteReady(NPP instance, NPStream *stream) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->WriteReady(stream);
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset,
int32 len, void *buffer) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->Write(stream, offset, len, buffer);
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->DestroyStream(stream, reason);
}
void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
if (instance == NULL)
return;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->StreamAsFile(stream, fname);
}
void NPP_Print(NPP instance, NPPrint* printInfo) {
if (instance == NULL)
return;
// XXXMB - do work here.
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
void* notifyData) {
if (instance == NULL)
return;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->URLNotify(url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
int16 NPP_HandleEvent(NPP instance, void* event) {
if (instance == NULL)
return 0;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->HandleEvent(event);
}
void* NPP_GetJavaClass(void) {
// XXXMB - do work here.
return NULL;
}
} // extern "C"
<commit_msg>Disable NPAPIIncognitoTester.PrivateEnabled test because it's flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "webkit/glue/plugins/test/plugin_client.h"
#include "webkit/glue/plugins/test/plugin_arguments_test.h"
#include "webkit/glue/plugins/test/plugin_delete_plugin_in_stream_test.h"
#include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h"
#include "webkit/glue/plugins/test/plugin_geturl_test.h"
#include "webkit/glue/plugins/test/plugin_javascript_open_popup.h"
#include "webkit/glue/plugins/test/plugin_new_fails_test.h"
#include "webkit/glue/plugins/test/plugin_private_test.h"
#include "webkit/glue/plugins/test/plugin_npobject_lifetime_test.h"
#include "webkit/glue/plugins/test/plugin_npobject_proxy_test.h"
#include "webkit/glue/plugins/test/plugin_window_size_test.h"
#if defined(OS_WIN)
#include "webkit/glue/plugins/test/plugin_windowed_test.h"
#endif
#include "webkit/glue/plugins/test/plugin_windowless_test.h"
#include "third_party/npapi/bindings/npapi.h"
#include "third_party/npapi/bindings/npruntime.h"
namespace NPAPIClient {
NPNetscapeFuncs* PluginClient::host_functions_;
NPError PluginClient::GetEntryPoints(NPPluginFuncs* pFuncs) {
if (pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if (pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = reinterpret_cast<JRIGlobalRef>(NPP_GetJavaClass);
return NPERR_NO_ERROR;
}
NPError PluginClient::Initialize(NPNetscapeFuncs* pFuncs) {
if (pFuncs == NULL) {
return NPERR_INVALID_FUNCTABLE_ERROR;
}
if (static_cast<unsigned char>((pFuncs->version >> 8) & 0xff) >
NP_VERSION_MAJOR) {
return NPERR_INCOMPATIBLE_VERSION_ERROR;
}
host_functions_ = pFuncs;
return NPERR_NO_ERROR;
}
NPError PluginClient::Shutdown() {
return NPERR_NO_ERROR;
}
} // namespace NPAPIClient
extern "C" {
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode,
int16 argc, char* argn[], char* argv[], NPSavedData* saved) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// We look at the test name requested via the plugin arguments. We match
// that against a given test and try to instantiate it.
// lookup the name parameter
std::string test_name;
for (int name_index = 0; name_index < argc; name_index++)
if (base::strcasecmp(argn[name_index], "name") == 0) {
test_name = argv[name_index];
break;
}
if (test_name.empty())
return NPERR_GENERIC_ERROR; // no name found
NPError ret = NPERR_GENERIC_ERROR;
bool windowless_plugin = false;
NPAPIClient::PluginTest *new_test = NULL;
if (test_name == "arguments") {
new_test = new NPAPIClient::PluginArgumentsTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "geturl") {
new_test = new NPAPIClient::PluginGetURLTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_proxy") {
new_test = new NPAPIClient::NPObjectProxyTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_windowless_test.*.
} else if (test_name == "execute_script_delete_in_paint" ||
test_name == "execute_script_delete_in_mouse_move" ||
test_name == "delete_frame_test" ||
test_name == "multiple_instances_sync_calls") {
new_test = new NPAPIClient::WindowlessPluginTest(instance,
NPAPIClient::PluginClient::HostFunctions(), test_name);
windowless_plugin = true;
#endif
} else if (test_name == "getjavascripturl") {
new_test = new NPAPIClient::ExecuteGetJavascriptUrlTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_window_size_test.*.
} else if (test_name == "checkwindowrect") {
new_test = new NPAPIClient::PluginWindowSizeTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else if (test_name == "self_delete_plugin_stream") {
new_test = new NPAPIClient::DeletePluginInStreamTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#if defined(OS_WIN)
// TODO(port): plugin_npobject_lifetime_test.*.
} else if (test_name == "npobject_lifetime_test") {
new_test = new NPAPIClient::NPObjectLifetimeTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_lifetime_test_second_instance") {
new_test = new NPAPIClient::NPObjectLifetimeTestInstance2(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "new_fails") {
new_test = new NPAPIClient::NewFailsTest(instance,
NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "npobject_delete_plugin_in_evaluate") {
new_test = new NPAPIClient::NPObjectDeletePluginInNPN_Evaluate(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else if (test_name == "plugin_javascript_open_popup_with_plugin") {
new_test = new NPAPIClient::ExecuteJavascriptOpenPopupWithPluginTest(
instance, NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "plugin_popup_with_plugin_target") {
new_test = new NPAPIClient::ExecuteJavascriptPopupWindowTargetPluginTest(
instance, NPAPIClient::PluginClient::HostFunctions());
} else if (test_name == "private") {
// http://code.google.com/p/chromium/issues/detail?id=16149
#if 0
new_test = new NPAPIClient::PrivateTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
#if defined(OS_WIN)
// TODO(port): plugin_windowed_test.*.
} else if (test_name == "hidden_plugin" ||
test_name == "create_instance_in_paint" ||
test_name == "alert_in_window_message") {
new_test = new NPAPIClient::WindowedPluginTest(instance,
NPAPIClient::PluginClient::HostFunctions());
#endif
} else {
// If we don't have a test case for this, create a
// generic one which basically never fails.
LOG(WARNING) << "Unknown test name '" << test_name
<< "'; using default test.";
new_test = new NPAPIClient::PluginTest(instance,
NPAPIClient::PluginClient::HostFunctions());
}
if (new_test) {
ret = new_test->New(mode, argc, (const char**)argn,
(const char**)argv, saved);
if ((ret == NPERR_NO_ERROR) && windowless_plugin) {
NPAPIClient::PluginClient::HostFunctions()->setvalue(
instance, NPPVpluginWindowBool, NULL);
}
}
return ret;
}
NPError NPP_Destroy(NPP instance, NPSavedData** save) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
delete plugin;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* pNPWindow) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
if (pNPWindow->window == NULL) {
return NPERR_NO_ERROR;
}
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->SetWindow(pNPWindow);
}
NPError NPP_NewStream(NPP instance, NPMIMEType type,
NPStream* stream, NPBool seekable, uint16* stype) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->NewStream(type, stream, seekable, stype);
}
int32 NPP_WriteReady(NPP instance, NPStream *stream) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->WriteReady(stream);
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset,
int32 len, void *buffer) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->Write(stream, offset, len, buffer);
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->DestroyStream(stream, reason);
}
void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
if (instance == NULL)
return;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->StreamAsFile(stream, fname);
}
void NPP_Print(NPP instance, NPPrint* printInfo) {
if (instance == NULL)
return;
// XXXMB - do work here.
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
void* notifyData) {
if (instance == NULL)
return;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->URLNotify(url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
// XXXMB - do work here.
return NPERR_GENERIC_ERROR;
}
int16 NPP_HandleEvent(NPP instance, void* event) {
if (instance == NULL)
return 0;
NPAPIClient::PluginTest *plugin =
(NPAPIClient::PluginTest*)instance->pdata;
return plugin->HandleEvent(event);
}
void* NPP_GetJavaClass(void) {
// XXXMB - do work here.
return NULL;
}
} // extern "C"
<|endoftext|> |
<commit_before>
#include "interlecto.h"
using namespace web;
int web::main(enviro&Enviro) {
content Content(Enviro);
format Page(Enviro);
string request(Enviro.value("request"));
request.trim("\\/");
Page.set_title(request);
Page.load(Content);
cout << Enviro.headers();
cout << Page.html();
return Enviro.status();
}
htmlcode* web::make_content(content&Content) {
NEWPTR(html::block,cp)("div","content");
info*Env = Content["enviro"];
cp->append(Content.value("page:title"),"h1");
info*Serv = Env->at("server");
NEWPTR(html::table,tab);
for(auto x: *Serv) {
NEWPTR(html::tr_comp,tr1);
tr1->append(new html::td_comp(x.first));
tr1->append(new html::td_comp(x.second->value() ));
tab->append(tr1);
}
cp->append(tab);
return cp;
}
<commit_msg>Update: 2017-01-31 16:12:34 GMT-05:00<commit_after>
#include "interlecto.h"
using namespace web;
int web::main(enviro&Enviro) {
content Content(Enviro);
format Page(Enviro);
string request(Enviro.value("request"));
size_t n = request.find('?');
if(npos!=n) request = request.substr(0,n);
request.trim("\\/");
Page.set_title(request);
Page.load(Content);
cout << Enviro.headers();
cout << Page.html();
return Enviro.status();
}
htmlcode* web::make_content(content&Content) {
NEWPTR(html::block,cp)("div","content");
info*Env = Content["enviro"];
cp->append(Content.value("page:title"),"h1");
info*Serv = Env->at("server");
NEWPTR(html::table,tab);
for(auto x: *Serv) {
NEWPTR(html::tr_comp,tr1);
tr1->append(new html::td_comp(x.first));
tr1->append(new html::td_comp(x.second->value() ));
tab->append(tr1);
}
cp->append(tab);
return cp;
}
<|endoftext|> |
<commit_before>//
// Created by haohanwang on 1/24/16.
//
#include "ProximalGradientDescent.hpp"
#include <Eigen/Dense>
#include <iostream>
#include <map>
using namespace Eigen;
using namespace std;
ProximalGradientDescent::ProximalGradientDescent(const map<string, string>& options) {
try {
setLearningRate(stof(options.find("learningRate")->second));
} catch (exception& e) {}
try {
setTolerance(stof(options.find("tolerance")->second));
} catch (exception& e) {}
}
void ProximalGradientDescent::setTolerance(float tol) {
tolerance = tol;
}
void ProximalGradientDescent::setLearningRate2(float d) {
learningRate2 = d;
}
void ProximalGradientDescent::setPrevResidule(float d) {
prev_residue = d;
}
void ProximalGradientDescent::setInnerStep1(long d) {
innerStep1 = d;
}
void ProximalGradientDescent::setInnerStep2(long d) {
innerStep2 =d;
}
void ProximalGradientDescent::run(Model *model) {
cerr << "The algorithm for this specific model is not implemented, runs on basic model"<<endl;
int epoch = 0;
double residue = model->cost();
VectorXd grad;
VectorXd in;
while (epoch < maxIteration && residue > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
grad = model->proximal_derivative();
in = model->getBeta() - learningRate * grad;
model->updateBeta(model->proximal_operator(in, learningRate));
residue = model->cost();
}
}
void ProximalGradientDescent::run(LinearRegression *model) {
int epoch = 0;
double residue = model->cost();
VectorXd grad;
VectorXd in;
while (epoch < maxIteration && residue > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
grad = model->proximal_derivative();
in = model->getBeta() - learningRate * grad;
model->updateBeta(model->proximal_operator(in, learningRate));
residue = model->cost();
}
}
void ProximalGradientDescent::setLearningRate(float lr) {
learningRate = lr;
}
ProximalGradientDescent::ProximalGradientDescent() {
learningRate = 0.001;
learningRate2 = 0.001;
tolerance = 0.000001;
prev_residue = numeric_limits<double>::max();
innerStep1 = 10;
innerStep2 = 10;
}
void ProximalGradientDescent::run(TreeLasso * model) {
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getBeta(); //bx
MatrixXd beta_curr = model->getBeta(); //bx_new
MatrixXd beta = model->getBeta(); //bw
MatrixXd best_beta = model->getBeta();
MatrixXd in;
MatrixXd grad;
model->initGradientUpdate();
double diff = tolerance*2;
while (epoch < maxIteration && diff > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
}
model->updateBeta(best_beta);
}
void ProximalGradientDescent::run(MultiPopLasso * model) {
model->initTraining();
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getFormattedBeta(); //bx
MatrixXd beta_curr = model->getFormattedBeta(); //bx_new
MatrixXd beta = model->getFormattedBeta(); //bw
MatrixXd best_beta = model->getFormattedBeta();
MatrixXd in;
MatrixXd grad;
double diff = tolerance*2;
while (epoch < maxIteration && diff > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
}
model->updateBeta(best_beta);
}
void ProximalGradientDescent::run(AdaMultiLasso *model) {
// this is not just proximal gradient descent, also including iteratively updating beta and w, v
model->initTraining();
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getFormattedBeta(); //bx
MatrixXd beta_curr = model->getFormattedBeta(); //bx_new
MatrixXd beta = model->getFormattedBeta(); //bw
MatrixXd best_beta = model->getFormattedBeta();
MatrixXd beta_prev2 = model->getFormattedBeta();
MatrixXd in;
MatrixXd grad;
double diff = tolerance*2;
double lr2 = 0;
long i1 = 0;
long i2 = 0;
VectorXd w_update = model->getW();
VectorXd v_update = model->getV();
VectorXd w_prev = model->getW();
VectorXd v_prev = model->getV();
VectorXd w_grad = model->getW();
VectorXd v_grad = model->getV();
while (epoch < maxIteration && diff > tolerance) {
i1 = 0;
i2 = 0;
epoch++;
while (i1 < innerStep1){
i1 ++ ;
beta_prev2 = model->getFormattedBeta();
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
// if (checkVectorConvergence(beta, beta_prev2, 0.01)){
// break;
// }
}
while (i2 < innerStep2){
i2 ++ ;
lr2 = learningRate2 / sqrt(i2);
w_prev = model->getW();
v_prev = model->getV();
w_grad = model->gradient_w();
// cout << "------w_grad------"<<endl;
// cout << w_grad << endl;
v_grad = model->gradient_v();
w_update = w_prev - lr2*w_grad;
v_update = v_prev - lr2*v_grad;
// cout << "------w_update------"<<endl;
// cout << w_update << endl;
w_update = model->projection(w_update);
v_update = model->projection(v_update);
// cout << "------w_proj------"<<endl;
// cout << w_update << endl;
model->updateW(w_update);
model->updateV(v_update);
model->updateTheta_Rho();
// if (checkVectorConvergence(w_prev, w_update, 0.01) && checkVectorConvergence(v_prev, v_update, 0.01)){
// break;
// }
}
// cout << "----beta----" << endl;
// cout << model->getFormattedBeta().transpose() << endl;
// cout << "----W----" << endl;
// cout << w_update.transpose() << endl;
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
cout << "epoch: " << epoch << "\t" << "residue: " << residue << endl;
}
model->updateBeta(best_beta);
}
bool ProximalGradientDescent::checkVectorConvergence(VectorXd v1, VectorXd v2, double d) {
double r = (v1 - v2).squaredNorm();
return (r < d);
}
<commit_msg>remove useless comments<commit_after>//
// Created by haohanwang on 1/24/16.
//
#include "ProximalGradientDescent.hpp"
#include <Eigen/Dense>
#include <iostream>
#include <map>
using namespace Eigen;
using namespace std;
ProximalGradientDescent::ProximalGradientDescent(const map<string, string>& options) {
try {
setLearningRate(stof(options.find("learningRate")->second));
} catch (exception& e) {}
try {
setTolerance(stof(options.find("tolerance")->second));
} catch (exception& e) {}
}
void ProximalGradientDescent::setTolerance(float tol) {
tolerance = tol;
}
void ProximalGradientDescent::setLearningRate2(float d) {
learningRate2 = d;
}
void ProximalGradientDescent::setPrevResidule(float d) {
prev_residue = d;
}
void ProximalGradientDescent::setInnerStep1(long d) {
innerStep1 = d;
}
void ProximalGradientDescent::setInnerStep2(long d) {
innerStep2 =d;
}
void ProximalGradientDescent::run(Model *model) {
cerr << "The algorithm for this specific model is not implemented, runs on basic model"<<endl;
int epoch = 0;
double residue = model->cost();
VectorXd grad;
VectorXd in;
while (epoch < maxIteration && residue > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
grad = model->proximal_derivative();
in = model->getBeta() - learningRate * grad;
model->updateBeta(model->proximal_operator(in, learningRate));
residue = model->cost();
}
}
void ProximalGradientDescent::run(LinearRegression *model) {
int epoch = 0;
double residue = model->cost();
VectorXd grad;
VectorXd in;
while (epoch < maxIteration && residue > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
grad = model->proximal_derivative();
in = model->getBeta() - learningRate * grad;
model->updateBeta(model->proximal_operator(in, learningRate));
residue = model->cost();
}
}
void ProximalGradientDescent::setLearningRate(float lr) {
learningRate = lr;
}
ProximalGradientDescent::ProximalGradientDescent() {
learningRate = 0.001;
learningRate2 = 0.001;
tolerance = 0.000001;
prev_residue = numeric_limits<double>::max();
innerStep1 = 10;
innerStep2 = 10;
}
void ProximalGradientDescent::run(TreeLasso * model) {
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getBeta(); //bx
MatrixXd beta_curr = model->getBeta(); //bx_new
MatrixXd beta = model->getBeta(); //bw
MatrixXd best_beta = model->getBeta();
MatrixXd in;
MatrixXd grad;
model->initGradientUpdate();
double diff = tolerance*2;
while (epoch < maxIteration && diff > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
}
model->updateBeta(best_beta);
}
void ProximalGradientDescent::run(MultiPopLasso * model) {
model->initTraining();
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getFormattedBeta(); //bx
MatrixXd beta_curr = model->getFormattedBeta(); //bx_new
MatrixXd beta = model->getFormattedBeta(); //bw
MatrixXd best_beta = model->getFormattedBeta();
MatrixXd in;
MatrixXd grad;
double diff = tolerance*2;
while (epoch < maxIteration && diff > tolerance) {
epoch++;
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
}
model->updateBeta(best_beta);
}
void ProximalGradientDescent::run(AdaMultiLasso *model) {
// this is not just proximal gradient descent, also including iteratively updating beta and w, v
model->initTraining();
int epoch = 0;
double residue = model->cost();
double theta = 1;
double theta_new = 0;
MatrixXd beta_prev = model->getFormattedBeta(); //bx
MatrixXd beta_curr = model->getFormattedBeta(); //bx_new
MatrixXd beta = model->getFormattedBeta(); //bw
MatrixXd best_beta = model->getFormattedBeta();
MatrixXd beta_prev2 = model->getFormattedBeta();
MatrixXd in;
MatrixXd grad;
double diff = tolerance*2;
double lr2 = 0;
long i1 = 0;
long i2 = 0;
VectorXd w_update = model->getW();
VectorXd v_update = model->getV();
VectorXd w_prev = model->getW();
VectorXd v_prev = model->getV();
VectorXd w_grad = model->getW();
VectorXd v_grad = model->getV();
while (epoch < maxIteration && diff > tolerance) {
i1 = 0;
i2 = 0;
epoch++;
while (i1 < innerStep1){
i1 ++ ;
beta_prev2 = model->getFormattedBeta();
progress = float(epoch) / maxIteration;
theta_new = 2.0/(epoch+2);
grad = model->proximal_derivative();
in = beta - 1/model->getL() * grad;
beta_curr = model->proximal_operator(in, learningRate);
beta = beta_curr + (1-theta)/theta * theta_new * (beta_curr-beta_prev);
beta_prev = beta_curr;
theta = theta_new;
model->updateBeta(beta);
}
while (i2 < innerStep2){
i2 ++ ;
lr2 = learningRate2 / sqrt(i2);
w_prev = model->getW();
v_prev = model->getV();
w_grad = model->gradient_w();
v_grad = model->gradient_v();
w_update = w_prev - lr2*w_grad;
v_update = v_prev - lr2*v_grad;
w_update = model->projection(w_update);
v_update = model->projection(v_update);
model->updateW(w_update);
model->updateV(v_update);
model->updateTheta_Rho();
}
residue = model->cost();
if (residue < prev_residue){
best_beta = beta;
}
diff = abs(prev_residue - residue);
cout << "epoch: " << epoch << "\t" << "residue: " << residue << endl;
}
model->updateBeta(best_beta);
}
bool ProximalGradientDescent::checkVectorConvergence(VectorXd v1, VectorXd v2, double d) {
double r = (v1 - v2).squaredNorm();
return (r < d);
}
<|endoftext|> |
<commit_before>#include "decafs_barista.h"
#define MIN_ARGS 5
#define STRIPE_SIZE 1
#define CHUNK_SIZE 2
#define METADATA 3
#define ESPRESSO 4
int main (int argc, char *argv[]) {
process_arguments (argc, argv);
// TODO: Change to proper logging
printf ("Barista is initialized.\n");
printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
get_chunk_size());
struct ip_address ip;
struct client default_client = {ip, 1, 1};
int count, fd = open ("new_file.txt", O_RDWR, default_client);
char buf[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
char *read_buf = (char *)malloc (1000);
memset (read_buf, '\0', 1000);
printf ("\n\n ------------------------------FIRST WRITE------------------------------\n");
count = write (fd, buf, strlen (buf), default_client);
printf ("(\n(BARISTA) wrote %d bytes.\n", count);
close (fd, default_client);
fd = open ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------FIRST READ--------------------------------\n");
count = read (fd, read_buf, strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);
close (fd, default_client);
fd = open ("new_file.txt", O_RDWR | O_APPEND, default_client);
printf ("\n\n ------------------------------SECOND WRITE------------------------------\n");
write (fd, buf, strlen (buf), default_client);
close (fd, default_client);
fd = open ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------SECOND READ--------------------------------\n");
count = read (fd, read_buf, 2*strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);
return 0;
}
void process_arguments (int argc, char *argv[]) {
int ret;
if (argc < MIN_ARGS) {
exit_failure (USAGE_ERROR);
}
ret = set_stripe_size (atoi(argv[STRIPE_SIZE]));
if (ret < 0) {
exit_failure (get_size_error_message ("stripe", argv[STRIPE_SIZE]));
}
ret = set_chunk_size (atoi(argv[CHUNK_SIZE]));
if (ret < 0) {
exit_failure (get_size_error_message ("chunk", argv[CHUNK_SIZE]));
}
// TODO: Recreate metadata from file
// path to metadata file is in argv[METADATA]
// Add all espresso nodes to volatile_metadata
// TODO: retry connections to espresso nodes on failure
// TODO: 3 times with increased wait each time
for (int i = ESPRESSO; i < argc; i++) {
int res = network_add_client(argv[i]);
if (res >= 0) {
add_node(argv[i], res);
}
else {
fprintf(stderr, "Failed to connect to espresso node: %sn", argv[i]);
}
}
}
const char *get_size_error_message (const char *type, const char *value) {
std::string msg = "Invalid size ";
msg += value;
msg += " for ";
msg += type;
return msg.c_str();
}
void exit_failure (const char *message) {
fprintf (stderr, "%s\n", message);
exit (EXIT_FAILURE);
}
<commit_msg>Same probs.<commit_after>#include "decafs_barista.h"
#define MIN_ARGS 5
#define STRIPE_SIZE 1
#define CHUNK_SIZE 2
#define METADATA 3
#define ESPRESSO 4
int main (int argc, char *argv[]) {
process_arguments (argc, argv);
// TODO: Change to proper logging
printf ("Barista is initialized.\n");
printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
get_chunk_size());
struct ip_address ip;
struct client default_client = {ip, 1, 1};
int count, fd = open_file ("new_file.txt", O_RDWR, default_client);
char buf[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
char *read_buf = (char *)malloc (1000);
memset (read_buf, '\0', 1000);
printf ("\n\n ------------------------------FIRST WRITE------------------------------\n");
count = write_file (fd, buf, strlen (buf), default_client);
printf ("(\n(BARISTA) wrote %d bytes.\n", count);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------FIRST READ--------------------------------\n");
count = read_file (fd, read_buf, strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDWR | O_APPEND, default_client);
printf ("\n\n ------------------------------SECOND WRITE------------------------------\n");
write_file (fd, buf, strlen (buf), default_client);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------SECOND READ--------------------------------\n");
count = read_file (fd, read_buf, 2*strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);
return 0;
}
void process_arguments (int argc, char *argv[]) {
int ret;
if (argc < MIN_ARGS) {
exit_failure (USAGE_ERROR);
}
ret = set_stripe_size (atoi(argv[STRIPE_SIZE]));
if (ret < 0) {
exit_failure (get_size_error_message ("stripe", argv[STRIPE_SIZE]));
}
ret = set_chunk_size (atoi(argv[CHUNK_SIZE]));
if (ret < 0) {
exit_failure (get_size_error_message ("chunk", argv[CHUNK_SIZE]));
}
// TODO: Recreate metadata from file
// path to metadata file is in argv[METADATA]
// Add all espresso nodes to volatile_metadata
// TODO: retry connections to espresso nodes on failure
// TODO: 3 times with increased wait each time
for (int i = ESPRESSO; i < argc; i++) {
int res = network_add_client(argv[i]);
if (res >= 0) {
add_node(argv[i], res);
}
else {
fprintf(stderr, "Failed to connect to espresso node: %sn", argv[i]);
}
}
}
const char *get_size_error_message (const char *type, const char *value) {
std::string msg = "Invalid size ";
msg += value;
msg += " for ";
msg += type;
return msg.c_str();
}
void exit_failure (const char *message) {
fprintf (stderr, "%s\n", message);
exit (EXIT_FAILURE);
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 20158 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @author David Sidrane <david_s5@nscdgg.com>
*/
#pragma once
#if defined(UAVCAN_KINETIS_NUTTX)
# include <uavcan_kinetis/uavcan_kinetis.hpp>
#elif defined(UAVCAN_STM32_NUTTX)
# include <uavcan_stm32/uavcan_stm32.hpp>
#else
# error "Unsupported driver"
#endif
<commit_msg>uavcan:Fix date in copyright<commit_after>/****************************************************************************
*
* Copyright (C) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @author David Sidrane <david_s5@nscdg.com>
*/
#pragma once
#if defined(UAVCAN_KINETIS_NUTTX)
# include <uavcan_kinetis/uavcan_kinetis.hpp>
#elif defined(UAVCAN_STM32_NUTTX)
# include <uavcan_stm32/uavcan_stm32.hpp>
#else
# error "Unsupported driver"
#endif
<|endoftext|> |
<commit_before>// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "lib/jxl/modular/encoding/dec_ma.h"
#include "lib/jxl/dec_ans.h"
#include "lib/jxl/modular/encoding/ma_common.h"
#include "lib/jxl/modular/modular_image.h"
namespace jxl {
namespace {
Status ValidateTree(
const Tree &tree,
const std::vector<std::pair<pixel_type, pixel_type>> &prop_bounds,
size_t root) {
if (tree[root].property == -1) return true;
size_t p = tree[root].property;
int val = tree[root].splitval;
if (prop_bounds[p].first > val) return JXL_FAILURE("Invalid tree");
// Splitting at max value makes no sense: left range will be exactly same
// as parent, right range will be invalid (min > max).
if (prop_bounds[p].second <= val) return JXL_FAILURE("Invalid tree");
auto new_bounds = prop_bounds;
new_bounds[p].first = val + 1;
JXL_RETURN_IF_ERROR(ValidateTree(tree, new_bounds, tree[root].lchild));
new_bounds[p] = prop_bounds[p];
new_bounds[p].second = val;
return ValidateTree(tree, new_bounds, tree[root].rchild);
}
Status DecodeTree(BitReader *br, ANSSymbolReader *reader,
const std::vector<uint8_t> &context_map, Tree *tree,
size_t tree_size_limit) {
size_t leaf_id = 0;
size_t to_decode = 1;
tree->clear();
while (to_decode > 0) {
JXL_RETURN_IF_ERROR(br->AllReadsWithinBounds());
if (tree->size() > tree_size_limit) {
return JXL_FAILURE("Tree is too large");
}
to_decode--;
int property = static_cast<int>(reader->ReadHybridUint(kPropertyContext, br,
context_map)) -
1;
if (property < -1 || property >= 256) {
return JXL_FAILURE("Invalid tree property value");
}
if (property == -1) {
size_t predictor =
reader->ReadHybridUint(kPredictorContext, br, context_map);
if (predictor >= kNumModularPredictors) {
return JXL_FAILURE("Invalid predictor");
}
int64_t predictor_offset =
UnpackSigned(reader->ReadHybridUint(kOffsetContext, br, context_map));
uint32_t mul_log =
reader->ReadHybridUint(kMultiplierLogContext, br, context_map);
if (mul_log >= 31) {
return JXL_FAILURE("Invalid multiplier logarithm");
}
uint32_t mul_bits =
reader->ReadHybridUint(kMultiplierBitsContext, br, context_map);
if (mul_bits + 1 >= 1u << (31u - mul_log)) {
return JXL_FAILURE("Invalid multiplier");
}
uint32_t multiplier = (mul_bits + 1U) << mul_log;
tree->emplace_back(-1, 0, leaf_id++, 0, static_cast<Predictor>(predictor),
predictor_offset, multiplier);
continue;
}
int splitval =
UnpackSigned(reader->ReadHybridUint(kSplitValContext, br, context_map));
tree->emplace_back(property, splitval, tree->size() + to_decode + 1,
tree->size() + to_decode + 2, Predictor::Zero, 0, 1);
to_decode += 2;
}
std::vector<std::pair<pixel_type, pixel_type>> prop_bounds;
prop_bounds.resize(256, {std::numeric_limits<pixel_type>::min(),
std::numeric_limits<pixel_type>::max()});
return ValidateTree(*tree, prop_bounds, 0);
}
} // namespace
Status DecodeTree(BitReader *br, Tree *tree, size_t tree_size_limit) {
std::vector<uint8_t> tree_context_map;
ANSCode tree_code;
JXL_RETURN_IF_ERROR(
DecodeHistograms(br, kNumTreeContexts, &tree_code, &tree_context_map));
// TODO(eustas): investigate more infinite tree cases.
if (tree_code.degenerate_symbols[tree_context_map[kPropertyContext]] > 0) {
return JXL_FAILURE("Infinite tree");
}
ANSSymbolReader reader(&tree_code, br);
JXL_RETURN_IF_ERROR(DecodeTree(br, &reader, tree_context_map, tree,
std::min(tree_size_limit, kMaxTreeSize)));
if (!reader.CheckANSFinalState()) {
return JXL_FAILURE("ANS decode final state failed");
}
return true;
}
} // namespace jxl
<commit_msg>fuzzer: integer overflow in MA decoding (#618)<commit_after>// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "lib/jxl/modular/encoding/dec_ma.h"
#include "lib/jxl/dec_ans.h"
#include "lib/jxl/modular/encoding/ma_common.h"
#include "lib/jxl/modular/modular_image.h"
namespace jxl {
namespace {
Status ValidateTree(
const Tree &tree,
const std::vector<std::pair<pixel_type, pixel_type>> &prop_bounds,
size_t root) {
if (tree[root].property == -1) return true;
size_t p = tree[root].property;
int val = tree[root].splitval;
if (prop_bounds[p].first > val) return JXL_FAILURE("Invalid tree");
// Splitting at max value makes no sense: left range will be exactly same
// as parent, right range will be invalid (min > max).
if (prop_bounds[p].second <= val) return JXL_FAILURE("Invalid tree");
auto new_bounds = prop_bounds;
new_bounds[p].first = val + 1;
JXL_RETURN_IF_ERROR(ValidateTree(tree, new_bounds, tree[root].lchild));
new_bounds[p] = prop_bounds[p];
new_bounds[p].second = val;
return ValidateTree(tree, new_bounds, tree[root].rchild);
}
Status DecodeTree(BitReader *br, ANSSymbolReader *reader,
const std::vector<uint8_t> &context_map, Tree *tree,
size_t tree_size_limit) {
size_t leaf_id = 0;
size_t to_decode = 1;
tree->clear();
while (to_decode > 0) {
JXL_RETURN_IF_ERROR(br->AllReadsWithinBounds());
if (tree->size() > tree_size_limit) {
return JXL_FAILURE("Tree is too large");
}
to_decode--;
uint32_t prop1 = reader->ReadHybridUint(kPropertyContext, br, context_map);
if (prop1 > 256) return JXL_FAILURE("Invalid tree property value");
int property = prop1 - 1;
if (property == -1) {
size_t predictor =
reader->ReadHybridUint(kPredictorContext, br, context_map);
if (predictor >= kNumModularPredictors) {
return JXL_FAILURE("Invalid predictor");
}
int64_t predictor_offset =
UnpackSigned(reader->ReadHybridUint(kOffsetContext, br, context_map));
uint32_t mul_log =
reader->ReadHybridUint(kMultiplierLogContext, br, context_map);
if (mul_log >= 31) {
return JXL_FAILURE("Invalid multiplier logarithm");
}
uint32_t mul_bits =
reader->ReadHybridUint(kMultiplierBitsContext, br, context_map);
if (mul_bits + 1 >= 1u << (31u - mul_log)) {
return JXL_FAILURE("Invalid multiplier");
}
uint32_t multiplier = (mul_bits + 1U) << mul_log;
tree->emplace_back(-1, 0, leaf_id++, 0, static_cast<Predictor>(predictor),
predictor_offset, multiplier);
continue;
}
int splitval =
UnpackSigned(reader->ReadHybridUint(kSplitValContext, br, context_map));
tree->emplace_back(property, splitval, tree->size() + to_decode + 1,
tree->size() + to_decode + 2, Predictor::Zero, 0, 1);
to_decode += 2;
}
std::vector<std::pair<pixel_type, pixel_type>> prop_bounds;
prop_bounds.resize(256, {std::numeric_limits<pixel_type>::min(),
std::numeric_limits<pixel_type>::max()});
return ValidateTree(*tree, prop_bounds, 0);
}
} // namespace
Status DecodeTree(BitReader *br, Tree *tree, size_t tree_size_limit) {
std::vector<uint8_t> tree_context_map;
ANSCode tree_code;
JXL_RETURN_IF_ERROR(
DecodeHistograms(br, kNumTreeContexts, &tree_code, &tree_context_map));
// TODO(eustas): investigate more infinite tree cases.
if (tree_code.degenerate_symbols[tree_context_map[kPropertyContext]] > 0) {
return JXL_FAILURE("Infinite tree");
}
ANSSymbolReader reader(&tree_code, br);
JXL_RETURN_IF_ERROR(DecodeTree(br, &reader, tree_context_map, tree,
std::min(tree_size_limit, kMaxTreeSize)));
if (!reader.CheckANSFinalState()) {
return JXL_FAILURE("ANS decode final state failed");
}
return true;
}
} // namespace jxl
<|endoftext|> |
<commit_before>#include "SCD.h"
#if (__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/Analysis/PostDominators.h>
#include "llvm/Analysis/IteratedDominanceFrontier.h"
#if (__clang__)
#pragma clang diagnostic pop // ignore -Wunused-parameter
#else
#pragma GCC diagnostic pop
#endif
#include "dg/ADT/Queue.h"
#include "dg/util/debug.h"
using namespace std;
namespace dg {
namespace llvmdg {
void SCD::computePostDominators(llvm::Function& F) {
DBG_SECTION_BEGIN(cda, "Computing post dominators for function "
<< F.getName().str());
using namespace llvm;
PostDominatorTree *pdtree = nullptr;
DBG(cda, "Computing post dominator tree");
#if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 9))
pdtree = new PostDominatorTree();
// compute post-dominator tree for this function
pdtree->runOnFunction(F);
#else
PostDominatorTreeWrapperPass wrapper;
wrapper.runOnFunction(F);
pdtree = &wrapper.getPostDomTree();
#ifndef NDEBUG
wrapper.verifyAnalysis();
#endif
#endif
DBG(cda, "Computing post dominator frontiers and adding CD");
llvm::ReverseIDFCalculator PDF(*pdtree);
for (auto& B : F) {
llvm::SmallPtrSet<llvm::BasicBlock *, 1> blocks;
blocks.insert(&B);
PDF.setDefiningBlocks(blocks);
SmallVector<BasicBlock *, 8> pdfrontiers;
PDF.calculate(pdfrontiers);
// FIXME: reserve the memory
for (auto *pdf : pdfrontiers) {
dependencies[&B].insert(pdf);
dependentBlocks[pdf].insert(&B);
}
}
#if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 9))
delete pdtree;
#endif
DBG_SECTION_END(cda, "Done computing post dominators for function " << F.getName().str());
}
} // namespace llvmdg
} // namespace dg
<commit_msg>Fix build on LLVM 3.8<commit_after>#include "SCD.h"
#if (__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/Analysis/PostDominators.h>
#include "llvm/Analysis/IteratedDominanceFrontier.h"
#if (__clang__)
#pragma clang diagnostic pop // ignore -Wunused-parameter
#else
#pragma GCC diagnostic pop
#endif
#include "dg/ADT/Queue.h"
#include "dg/util/debug.h"
using namespace std;
namespace dg {
namespace llvmdg {
void SCD::computePostDominators(llvm::Function& F) {
DBG_SECTION_BEGIN(cda, "Computing post dominators for function "
<< F.getName().str());
using namespace llvm;
PostDominatorTree *pdtree = nullptr;
DBG(cda, "Computing post dominator tree");
#if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 9))
pdtree = new PostDominatorTree();
// compute post-dominator tree for this function
pdtree->runOnFunction(F);
using ReverseIDFCalculator = llvm::IDFCalculator<llvm::Inverse<llvm::BasicBlock *>>;
#else
PostDominatorTreeWrapperPass wrapper;
wrapper.runOnFunction(F);
pdtree = &wrapper.getPostDomTree();
using llvm::ReverseIDFCalculator;
#ifndef NDEBUG
wrapper.verifyAnalysis();
#endif
#endif
DBG(cda, "Computing post dominator frontiers and adding CD");
ReverseIDFCalculator PDF(*pdtree);
for (auto& B : F) {
llvm::SmallPtrSet<llvm::BasicBlock *, 1> blocks;
blocks.insert(&B);
PDF.setDefiningBlocks(blocks);
SmallVector<BasicBlock *, 8> pdfrontiers;
PDF.calculate(pdfrontiers);
// FIXME: reserve the memory
for (auto *pdf : pdfrontiers) {
dependencies[&B].insert(pdf);
dependentBlocks[pdf].insert(&B);
}
}
#if ((LLVM_VERSION_MAJOR == 3) && (LLVM_VERSION_MINOR < 9))
delete pdtree;
#endif
DBG_SECTION_END(cda, "Done computing post dominators for function " << F.getName().str());
}
} // namespace llvmdg
} // namespace dg
<|endoftext|> |
<commit_before>/*------------ant.cpp---------------------------------------------------------//
*
* ants -- We have them
*
* Purpose: Figure out ant pathing to food. I want food.
*
*-----------------------------------------------------------------------------*/
#include <array>
#include <iostream>
#include <vector>
#include <random>
#include <fstream>
/*----------------------------------------------------------------------------//
* STRUCTS
*-----------------------------------------------------------------------------*/
// grid size
const int n = 5;
// structs for ant movement
struct coord{
int x, y;
};
// Template for 2d boolean arrays
template <typename T, size_t rows, size_t cols>
using array2d = std::array<std::array<T, cols>, rows>;
// defines operators for definitions above
inline bool operator==(const coord& lhs, const coord& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const coord& lhs, const coord& rhs) {
return !(lhs == rhs);
}
struct ant{
array2d<bool, n, n> phetus;
coord pos;
std::vector<coord> phepath, antpath;
int stepnum, phenum, pernum;
};
struct grid{
array2d<bool, n, n> wall;
coord prize;
};
// Functions for ant movement
// Chooses step
ant step(ant curr, grid landscape, int gen_flag);
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate);
// Changes template ant
ant plate_toss(ant winner);
// Moves simulation every timestep
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output);
/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/
int main(){
// defining output file
std::ofstream output("out.dat", std::ofstream::out);
// defining initial ant vector and grid
std::vector<ant> ants;
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
// defining spawn point
coord spawn;
spawn.x = n;
spawn.y = 0;
// defining misc characters
int final_time = 10;
int pernum = 10;
move(ants, landscape, spawn, pernum, final_time, output);
//output.close();
}
/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/
// Chooses step
ant step(ant curr, grid landscape, int gen_flag){
coord next_step[4];
coord up, down, left, right, next;
int pcount = 0;
std::cout << curr.pos.x << '\t' << curr.pos.y << '\n' << '\n';
up.x = curr.pos.x; up.y = curr.pos.y + 1;
down.x = curr.pos.x; down.y = curr.pos.y - 1;
left.x = curr.pos.x - 1; left.y = curr.pos.y;
right.x = curr.pos.x + 1; right.y = curr.pos.y;
//std::cout << up.x << '\t' << up.y << '\n';
coord last;
if (curr.stepnum == 0){
last.x = -1;
last.y = -1;
}
else{
last = curr.antpath.back();
}
// determine possible movement
// up case
if (last != up) {
if (landscape.wall[up.x][up.y] == 0 && up.y <= n){
next_step[pcount] = up;
pcount++;
}
}
// down case
if (last != down) {
if (landscape.wall[down.x][down.y] == 0 && down.y >= 0){
next_step[pcount] = up;
pcount++;
}
}
if (last != left) {
if (landscape.wall[left.x][left.y] == 0 && left.x >= 0){
next_step[pcount] = up;
pcount++;
}
}
// right case
if (last != right) {
if (landscape.wall[right.x][right.y] == 0 && right.x <= n){
next_step[pcount] = up;
pcount++;
}
}
static std::random_device rd;
auto seed = rd();
static std::mt19937 gen(seed);
if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){
std::uniform_int_distribution<int> ant_distribution(0,pcount);
next = next_step[ant_distribution(gen)];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
else{
double prob = curr.pernum / curr.phenum, aprob[4], rn, psum = 0;
int choice = -1, cthulu;
std::uniform_real_distribution<double> ant_distribution(0,1);
// search through phepath to find ant's curr location
for (size_t q = 0; q < curr.phepath.size(); q++){
if (curr.pos.x == curr.phepath[q].x &&
curr.pos.y == curr.phepath[q].y){
cthulu = q;
}
}
std::uniform_real_distribution<double> ant_ddist(0,1);
rn = ant_ddist(gen);
for (size_t q = 0; q < pcount; q++){
if (next_step[q].x == curr.phepath[cthulu +1].x &&
next_step[q].y == curr.phepath[cthulu +1].y){
aprob[q] = prob;
}
else{
aprob[q] = (1 - prob) / (pcount - 1);
}
psum += aprob[q];
if (rn < psum && choice < 0){
choice = q;
}
}
next = next_step[choice];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
curr.stepnum++;
return curr;
}
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate){
ant curr;
curr = plate;
ants.push_back(curr);
return ants;
}
// Changes template ant
ant plate_toss(ant winner){
ant plate = winner;
plate.phenum = winner.stepnum;
plate.stepnum = 0;
// generate a new phetus
plate.phetus = {};
for (size_t i = 0; i < winner.antpath.size(); i++){
plate.phetus[winner.antpath[i].x][winner.antpath[i].y] = 1;
}
plate.antpath = {};
return plate;
}
// Moves simulation every timestep
// step 1: create ants
// step 2: move ants
// step 3: profit?
// redefine all paths = to shortest path
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output){
std::vector<int> killlist;
// setting template for first generate
ant plate;
plate.pos.x = spawn.x;
plate.pos.y = spawn.y;
plate.stepnum = 0;
plate.phenum = n*n;
plate.phetus = {};
// to be defined later
plate.pernum = pernum;
/*
// define walls and prize at random spot
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
*/
for (size_t i = 0; i < final_time; i++){
std::cout << i << '\n';
int flag = 0;
// step 1: generate ant
ants = gen_ants(ants, plate);
// step 2: Move ants
for (size_t j = 0; j < ants.size(); j++){
ants[j] = step(ants[j], landscape, flag);
if (ants[j].stepnum > ants[j].phenum){
killlist.push_back(j);
}
if (ants[j].pos.x == landscape.prize.x &&
ants[j].pos.y == landscape.prize.y){
plate = plate_toss(ants[j]);
}
}
for (size_t k = 0; k < killlist.size(); k++){
ants.erase(ants.begin() + killlist[k]);
}
for (size_t l = 0; l < ants[0].phepath.size(); l++){
output << ants[0].phepath[l].x << '\t'
<< ants[0].phepath[l].y << '\n';
}
output << '\n' << '\n';
}
return ants;
}
<commit_msg>seems to be working.<commit_after>/*------------ant.cpp---------------------------------------------------------//
*
* ants -- We have them
*
* Purpose: Figure out ant pathing to food. I want food.
*
*-----------------------------------------------------------------------------*/
#include <array>
#include <iostream>
#include <vector>
#include <random>
#include <fstream>
/*----------------------------------------------------------------------------//
* STRUCTS
*-----------------------------------------------------------------------------*/
// grid size
const int n = 5;
// structs for ant movement
struct coord{
int x, y;
};
// Template for 2d boolean arrays
template <typename T, size_t rows, size_t cols>
using array2d = std::array<std::array<T, cols>, rows>;
// defines operators for definitions above
inline bool operator==(const coord& lhs, const coord& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const coord& lhs, const coord& rhs) {
return !(lhs == rhs);
}
struct ant{
array2d<bool, n, n> phetus;
coord pos;
std::vector<coord> phepath, antpath;
int stepnum, phenum, pernum;
};
struct grid{
array2d<bool, n, n> wall;
coord prize;
};
// Functions for ant movement
// Chooses step
ant step(ant curr, grid landscape, int gen_flag);
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate);
// Changes template ant
ant plate_toss(ant winner);
// Moves simulation every timestep
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output);
/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/
int main(){
// defining output file
std::ofstream output("out.dat", std::ofstream::out);
// defining initial ant vector and grid
std::vector<ant> ants;
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
// defining spawn point
coord spawn;
spawn.x = n - 1;
spawn.y = 0;
// defining misc characters
int final_time = 10;
int pernum = 10;
move(ants, landscape, spawn, pernum, final_time, output);
//output.close();
}
/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/
// Chooses step
ant step(ant curr, grid landscape, int gen_flag){
coord next_step[4];
coord up, down, left, right, next;
int pcount = 0;
std::cout << curr.pos.x << '\t' << curr.pos.y << '\n' << '\n';
up.x = curr.pos.x; up.y = curr.pos.y + 1;
down.x = curr.pos.x; down.y = curr.pos.y - 1;
left.x = curr.pos.x - 1; left.y = curr.pos.y;
right.x = curr.pos.x + 1; right.y = curr.pos.y;
//std::cout << up.x << '\t' << up.y << '\n';
coord last;
if (curr.stepnum == 0){
last.x = -1;
last.y = -1;
}
else{
last = curr.antpath.back();
}
// determine possible movement
// up case
if (last != up) {
if (landscape.wall[up.x][up.y] == 0 && up.y < n){
next_step[pcount] = up;
pcount++;
}
}
// down case
if (last != down) {
if (landscape.wall[down.x][down.y] == 0 && down.y > 0){
next_step[pcount] = up;
pcount++;
}
}
if (last != left) {
if (landscape.wall[left.x][left.y] == 0 && left.x > 0){
next_step[pcount] = up;
pcount++;
}
}
// right case
if (last != right) {
if (landscape.wall[right.x][right.y] == 0 && right.x < n){
next_step[pcount] = up;
pcount++;
}
}
static std::random_device rd;
auto seed = rd();
static std::mt19937 gen(seed);
if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){
std::uniform_int_distribution<int> ant_distribution(0,pcount - 1);
next = next_step[ant_distribution(gen)];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
else{
double prob = curr.pernum / curr.phenum, aprob[4], rn, psum = 0;
int choice = -1, cthulu;
std::uniform_real_distribution<double> ant_distribution(0,1);
// search through phepath to find ant's curr location
for (size_t q = 0; q < curr.phepath.size(); q++){
if (curr.pos.x == curr.phepath[q].x &&
curr.pos.y == curr.phepath[q].y){
cthulu = q;
}
}
std::uniform_real_distribution<double> ant_ddist(0,1);
rn = ant_ddist(gen);
for (size_t q = 0; q < pcount; q++){
if (next_step[q].x == curr.phepath[cthulu +1].x &&
next_step[q].y == curr.phepath[cthulu +1].y){
aprob[q] = prob;
}
else{
aprob[q] = (1 - prob) / (pcount - 1);
}
psum += aprob[q];
if (rn < psum && choice < 0){
choice = q;
}
}
next = next_step[choice];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
curr.stepnum++;
return curr;
}
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate){
ant curr;
curr = plate;
ants.push_back(curr);
return ants;
}
// Changes template ant
ant plate_toss(ant winner){
ant plate = winner;
plate.phenum = winner.stepnum;
plate.stepnum = 0;
// generate a new phetus
plate.phetus = {};
for (size_t i = 0; i < winner.antpath.size(); i++){
plate.phetus[winner.antpath[i].x][winner.antpath[i].y] = 1;
}
plate.antpath = {};
return plate;
}
// Moves simulation every timestep
// step 1: create ants
// step 2: move ants
// step 3: profit?
// redefine all paths = to shortest path
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output){
std::vector<int> killlist;
// setting template for first generate
ant plate;
plate.pos.x = spawn.x;
plate.pos.y = spawn.y;
plate.stepnum = 0;
plate.phenum = n*n;
plate.phetus = {};
// to be defined later
plate.pernum = pernum;
/*
// define walls and prize at random spot
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
*/
for (size_t i = 0; i < final_time; i++){
std::cout << i << '\n';
int flag = 0;
// step 1: generate ant
ants = gen_ants(ants, plate);
// step 2: Move ants
for (size_t j = 0; j < ants.size(); j++){
ants[j] = step(ants[j], landscape, flag);
if (ants[j].stepnum > ants[j].phenum){
killlist.push_back(j);
}
if (ants[j].pos.x == landscape.prize.x &&
ants[j].pos.y == landscape.prize.y){
plate = plate_toss(ants[j]);
}
}
for (size_t k = 0; k < killlist.size(); k++){
ants.erase(ants.begin() + killlist[k]);
}
for (size_t l = 0; l < ants[0].phepath.size(); l++){
output << ants[0].phepath[l].x << '\t'
<< ants[0].phepath[l].y << '\n';
}
output << '\n' << '\n';
}
return ants;
}
<|endoftext|> |
<commit_before>/*
* File: AlarmClockSpeedTest.cpp
* Author: Amanda Carbonari
* Created: January 6, 2015 9:00am
*
* WARNING: This only measures CPU time
*/
#include <ctime>
#include <iostream>
#include <AlarmClock.h>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
typedef std::chrono::microseconds microseconds;
typedef std::chrono::milliseconds milliseconds;
typedef std::chrono::seconds seconds;
template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) {
while(!alerter.Expired());
}
int main(int, const char**) {
unsigned int us = 389;
cout << "Creating Alarm Clock" << endl;
AlarmClock<microseconds> alerter(us);
cout << "Sleeping to allow countdown to start"
// Give some time for the countdown to start
this_thread::sleep_for(microseconds(100));
cout << "Starting clock and resetting" << endl;
high_resolution_clock::time_point start = high_resolution_clock::now();
alerter.Reset();
high_resolution_clock::time_point end = high_resolution_clock::now();
auto reset_time = duration_cast<microseconds>(end - start).count();
cout << "Waiting for the clock to expire" << endl;
WaitForAlarmClockToExpire(alerter);
cout << "Time: " << reset_time << " us" << endl;
}<commit_msg>Added missing semicolon<commit_after>/*
* File: AlarmClockSpeedTest.cpp
* Author: Amanda Carbonari
* Created: January 6, 2015 9:00am
*
* WARNING: This only measures CPU time
*/
#include <ctime>
#include <iostream>
#include <AlarmClock.h>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
typedef std::chrono::microseconds microseconds;
typedef std::chrono::milliseconds milliseconds;
typedef std::chrono::seconds seconds;
template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) {
while(!alerter.Expired());
}
int main(int, const char**) {
unsigned int us = 389;
cout << "Creating Alarm Clock" << endl;
AlarmClock<microseconds> alerter(us);
cout << "Sleeping to allow countdown to start" << endl;
// Give some time for the countdown to start
this_thread::sleep_for(microseconds(100));
cout << "Starting clock and resetting" << endl;
high_resolution_clock::time_point start = high_resolution_clock::now();
alerter.Reset();
high_resolution_clock::time_point end = high_resolution_clock::now();
auto reset_time = duration_cast<microseconds>(end - start).count();
cout << "Waiting for the clock to expire" << endl;
WaitForAlarmClockToExpire(alerter);
cout << "Time: " << reset_time << " us" << endl;
}<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
/*
* polygon_intersects_cube()
* by Don Hatch
* January 1994
*
* Algorithm:
* 1. If any edge intersects the cube, return true.
* Testing whether a line segment intersects the cube
* is equivalent to testing whether the origin is contained
* in the rhombic dodecahedron obtained by dragging
* a unit cube from (being centered at) one segment endpoint
* to the other.
* 2. If the polygon interior intersects the cube, return true.
* Since we know no vertex or edge intersects the cube,
* this amounts to testing whether any of the four cube diagonals
* intersects the interior of the polygon. (Same as voorhies's test).
* 3. Return false.
*/
#include "polygon_cube_intersection.h"
#include "vec.h"
namespace sofa
{
namespace helper
{
namespace polygon_cube_intersection
{
#define FOR(i,n) for ((i) = 0; (i) < (n); ++(i))
#define MAXDIM2(v) ((v)[0] > (v)[1] ? 0 : 1)
#define MAXDIM3(v) ((v)[0] > (v)[2] ? MAXDIM2(v) : MAXDIM2((v)+1)+1)
#define ABS(x) ((x)<0 ? -(x) : (x))
#define SQR(x) ((x)*(x))
#define SIGN_NONZERO(x) ((x) < 0 ? -1 : 1)
/* note a and b can be in the reverse order and it still works! */
#define IN_CLOSED_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) <= 0)
#define IN_OPEN_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) < 0)
#define seg_contains_point(a,b,x) (((b)>(x)) - ((a)>(x)))
/*
* Tells whether a given polygon with nonzero area
* contains a point which is assumed to lie in the plane of the polygon.
* Actually returns the multiplicity of containment.
* This will always be 1 or 0 for non-self-intersecting planar
* polygons with the normal in the standard direction
* (towards the eye when looking at the polygon so that it's CCW).
*/
extern int
polygon_contains_point_3d(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
float point[3])
{
float abspolynormal[3];
int zaxis, xaxis, yaxis, i, count;
int xdirection;
const float *v, *w;
/*
* Determine which axis to ignore
* (the one in which the polygon normal is largest)
*/
FOR(i,3)
abspolynormal[i] = ABS(polynormal[i]);
zaxis = MAXDIM3(abspolynormal);
if (polynormal[zaxis] < 0)
{
xaxis = (zaxis+2)%3;
yaxis = (zaxis+1)%3;
}
else
{
xaxis = (zaxis+1)%3;
yaxis = (zaxis+2)%3;
}
count = 0;
FOR(i,nverts)
{
v = verts[i];
w = verts[(i+1)%nverts];
if ((xdirection = seg_contains_point(v[xaxis], w[xaxis], point[xaxis])))
{
if (seg_contains_point(v[yaxis], w[yaxis], point[yaxis]))
{
if (xdirection * (point[xaxis]-v[xaxis])*(w[yaxis]-v[yaxis]) <=
xdirection * (point[yaxis]-v[yaxis])*(w[xaxis]-v[xaxis]))
count += xdirection;
}
else
{
if (v[yaxis] <= point[yaxis])
count += xdirection;
}
}
}
return count;
}
/*
* A segment intersects the unit cube centered at the origin
* iff the origin is contained in the solid obtained
* by dragging a unit cube from one segment endpoint to the other.
* (This solid is a warped rhombic dodecahedron.)
* This amounts to 12 sidedness tests.
* Also, this test works even if one or both of the segment endpoints is
* inside the cube.
*/
extern int
segment_intersects_cube(const float v0[3], const float v1[3])
{
int i, iplus1, iplus2, edgevec_signs[3];
float edgevec[3];
VMV3(edgevec, v1, v0);
FOR(i,3)
edgevec_signs[i] = SIGN_NONZERO(edgevec[i]);
/*
* Test the three cube faces on the v1-ward side of the cube--
* if v0 is outside any of their planes then there is no intersection.
* Also test the three cube faces on the v0-ward side of the cube--
* if v1 is outside any of their planes then there is no intersection.
*/
FOR(i,3)
{
if (v0[i] * edgevec_signs[i] > .5) return 0;
if (v1[i] * edgevec_signs[i] < -.5) return 0;
}
/*
* Okay, that's the six easy faces of the rhombic dodecahedron
* out of the way. Six more to go.
* The remaining six planes bound an infinite hexagonal prism
* joining the petrie polygons (skew hexagons) of the two cubes
* centered at the endpoints.
*/
FOR(i,3)
{
float rhomb_normal_dot_v0, rhomb_normal_dot_cubedge;
iplus1 = (i+1)%3;
iplus2 = (i+2)%3;
#ifdef THE_EASY_TO_UNDERSTAND_WAY
{
float rhomb_normal[3], cubedge_midpoint[3];
/*
* rhomb_normal = VXV3(edgevec, unit vector in direction i),
* being cavalier about which direction it's facing
*/
rhomb_normal[i] = 0;
rhomb_normal[iplus1] = edgevec[iplus2];
rhomb_normal[iplus2] = -edgevec[iplus1];
/*
* We now are describing a plane parallel to
* both segment and the cube edge in question.
* if |DOT3(rhomb_normal, an arbitrary point on the segment)| >
* |DOT3(rhomb_normal, an arbitrary point on the cube edge in question|
* then the origin is outside this pair of opposite faces.
* (This is equivalent to saying that the line
* containing the segment is "outside" (i.e. further away from the
* origin than) the line containing the cube edge.
*/
cubedge_midpoint[i] = 0;
cubedge_midpoint[iplus1] = edgevec_signs[iplus1]*.5;
cubedge_midpoint[iplus2] = -edgevec_signs[iplus2]*.5;
rhomb_normal_dot_v0 = DOT3(rhomb_normal, v0);
rhomb_normal_dot_cubedge = DOT3(rhomb_normal,cubedge_midpoint);
}
#else /* the efficient way */
rhomb_normal_dot_v0 = edgevec[iplus2] * v0[iplus1]
- edgevec[iplus1] * v0[iplus2];
rhomb_normal_dot_cubedge = .5f *
(edgevec[iplus2] * edgevec_signs[iplus1] +
edgevec[iplus1] * edgevec_signs[iplus2]);
#endif /* the efficient way */
if (SQR(rhomb_normal_dot_v0) > SQR(rhomb_normal_dot_cubedge))
return 0; /* origin is outside this pair of opposite planes */
}
return 1;
}
/*
* Tells whether a given polygon intersects the cube of edge length 1
* centered at the origin.
* Always returns 1 if a polygon edge intersects the cube;
* returns the multiplicity of containment otherwise.
* (See explanation of polygon_contains_point_3d() above).
*/
extern int
polygon_intersects_cube(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
int ,/* already_know_vertices_are_outside_cube unused*/
int already_know_edges_are_outside_cube)
{
int i, best_diagonal[3];
float p[3], t;
/*
* If any edge intersects the cube, return 1.
*/
if (!already_know_edges_are_outside_cube)
FOR(i,nverts)
if (segment_intersects_cube(verts[i], verts[(i+1)%nverts]))
return 1;
/*
* If the polygon normal is zero and none of its edges intersect the
* cube, then it doesn't intersect the cube
*/
if (ISZEROVEC3(polynormal))
return 0;
/*
* Now that we know that none of the polygon's edges intersects the cube,
* deciding whether the polygon intersects the cube amounts
* to testing whether any of the four cube diagonals intersects
* the interior of the polygon.
*
* Notice that we only need to consider the cube diagonal that comes
* closest to being perpendicular to the plane of the polygon.
* If the polygon intersects any of the cube diagonals,
* it will intersect that one.
*/
FOR(i,3)
best_diagonal[i] = SIGN_NONZERO(polynormal[i]);
/*
* Okay, we have the diagonal of interest.
* The plane containing the polygon is the set of all points p satisfying
* DOT3(polynormal, p) == DOT3(polynormal, verts[0])
* So find the point p on the cube diagonal of interest
* that satisfies this equation.
* The line containing the cube diagonal is described parametrically by
* t * best_diagonal
* so plug this into the previous equation and solve for t.
* DOT3(polynormal, t * best_diagonal) == DOT3(polynormal, verts[0])
* i.e.
* t = DOT3(polynormal, verts[0]) / DOT3(polynormal, best_diagonal)
*
* (Note that the denominator is guaranteed to be nonzero, since
* polynormal is nonzero and best_diagonal was chosen to have the largest
* magnitude dot-product with polynormal)
*/
t = DOT3(polynormal, verts[0])
/ DOT3(polynormal, best_diagonal);
if (!IN_CLOSED_INTERVAL(-.5, t, .5))
return 0; /* intersection point is not in cube */
SXV3(p, t, best_diagonal); /* p = t * best_diagonal */
return polygon_contains_point_3d(nverts, verts, polynormal, p);
}
extern float *
get_polygon_normal(float normal[3],
int nverts, const float verts[/* nverts */][3])
{
int i;
float tothis[3], toprev[3], cross[3];
/*
* Triangulate the polygon and sum up the nverts-2 triangle normals.
*/
ZEROVEC3(normal);
VMV3(toprev, verts[1], verts[0]); /* 3 subtracts */
for (i = 2; i <= nverts-1; ++i) /* n-2 times... */
{
VMV3(tothis, verts[i], verts[0]); /* 3 subtracts */
VXV3(cross, toprev, tothis); /* 3 subtracts, 6 multiplies */
VPV3(normal, normal, cross); /* 3 adds */
SET3(toprev, tothis);
}
return normal;
}
}
}
}
<commit_msg>FIX: variables scope<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
/*
* polygon_intersects_cube()
* by Don Hatch
* January 1994
*
* Algorithm:
* 1. If any edge intersects the cube, return true.
* Testing whether a line segment intersects the cube
* is equivalent to testing whether the origin is contained
* in the rhombic dodecahedron obtained by dragging
* a unit cube from (being centered at) one segment endpoint
* to the other.
* 2. If the polygon interior intersects the cube, return true.
* Since we know no vertex or edge intersects the cube,
* this amounts to testing whether any of the four cube diagonals
* intersects the interior of the polygon. (Same as voorhies's test).
* 3. Return false.
*/
#include "polygon_cube_intersection.h"
#include "vec.h"
namespace sofa
{
namespace helper
{
namespace polygon_cube_intersection
{
#define FOR(i,n) for ((i) = 0; (i) < (n); ++(i))
#define MAXDIM2(v) ((v)[0] > (v)[1] ? 0 : 1)
#define MAXDIM3(v) ((v)[0] > (v)[2] ? MAXDIM2(v) : MAXDIM2((v)+1)+1)
#define ABS(x) ((x)<0 ? -(x) : (x))
#define SQR(x) ((x)*(x))
#define SIGN_NONZERO(x) ((x) < 0 ? -1 : 1)
/* note a and b can be in the reverse order and it still works! */
#define IN_CLOSED_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) <= 0)
#define IN_OPEN_INTERVAL(a,x,b) (((x)-(a)) * ((x)-(b)) < 0)
#define seg_contains_point(a,b,x) (((b)>(x)) - ((a)>(x)))
/*
* Tells whether a given polygon with nonzero area
* contains a point which is assumed to lie in the plane of the polygon.
* Actually returns the multiplicity of containment.
* This will always be 1 or 0 for non-self-intersecting planar
* polygons with the normal in the standard direction
* (towards the eye when looking at the polygon so that it's CCW).
*/
extern int
polygon_contains_point_3d(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
float point[3])
{
float abspolynormal[3];
int zaxis, xaxis, yaxis, i, count;
/*
* Determine which axis to ignore
* (the one in which the polygon normal is largest)
*/
FOR(i,3)
abspolynormal[i] = ABS(polynormal[i]);
zaxis = MAXDIM3(abspolynormal);
if (polynormal[zaxis] < 0)
{
xaxis = (zaxis+2)%3;
yaxis = (zaxis+1)%3;
}
else
{
xaxis = (zaxis+1)%3;
yaxis = (zaxis+2)%3;
}
count = 0;
FOR(i,nverts)
{
const float* v = verts[i];
const float* w = verts[(i+1)%nverts];
if (const int xdirection = seg_contains_point(v[xaxis], w[xaxis], point[xaxis]))
{
if (seg_contains_point(v[yaxis], w[yaxis], point[yaxis]))
{
if (xdirection * (point[xaxis]-v[xaxis])*(w[yaxis]-v[yaxis]) <=
xdirection * (point[yaxis]-v[yaxis])*(w[xaxis]-v[xaxis]))
count += xdirection;
}
else
{
if (v[yaxis] <= point[yaxis])
count += xdirection;
}
}
}
return count;
}
/*
* A segment intersects the unit cube centered at the origin
* iff the origin is contained in the solid obtained
* by dragging a unit cube from one segment endpoint to the other.
* (This solid is a warped rhombic dodecahedron.)
* This amounts to 12 sidedness tests.
* Also, this test works even if one or both of the segment endpoints is
* inside the cube.
*/
extern int
segment_intersects_cube(const float v0[3], const float v1[3])
{
float edgevec[3];
VMV3(edgevec, v1, v0);
int i = 0;
int edgevec_signs[3];
FOR(i,3)
edgevec_signs[i] = SIGN_NONZERO(edgevec[i]);
/*
* Test the three cube faces on the v1-ward side of the cube--
* if v0 is outside any of their planes then there is no intersection.
* Also test the three cube faces on the v0-ward side of the cube--
* if v1 is outside any of their planes then there is no intersection.
*/
FOR(i,3)
{
if (v0[i] * edgevec_signs[i] > .5) return 0;
if (v1[i] * edgevec_signs[i] < -.5) return 0;
}
/*
* Okay, that's the six easy faces of the rhombic dodecahedron
* out of the way. Six more to go.
* The remaining six planes bound an infinite hexagonal prism
* joining the petrie polygons (skew hexagons) of the two cubes
* centered at the endpoints.
*/
FOR(i,3)
{
float rhomb_normal_dot_v0, rhomb_normal_dot_cubedge;
const int iplus1 = (i+1)%3;
const int iplus2 = (i+2)%3;
#ifdef THE_EASY_TO_UNDERSTAND_WAY
{
float rhomb_normal[3], cubedge_midpoint[3];
/*
* rhomb_normal = VXV3(edgevec, unit vector in direction i),
* being cavalier about which direction it's facing
*/
rhomb_normal[i] = 0;
rhomb_normal[iplus1] = edgevec[iplus2];
rhomb_normal[iplus2] = -edgevec[iplus1];
/*
* We now are describing a plane parallel to
* both segment and the cube edge in question.
* if |DOT3(rhomb_normal, an arbitrary point on the segment)| >
* |DOT3(rhomb_normal, an arbitrary point on the cube edge in question|
* then the origin is outside this pair of opposite faces.
* (This is equivalent to saying that the line
* containing the segment is "outside" (i.e. further away from the
* origin than) the line containing the cube edge.
*/
cubedge_midpoint[i] = 0;
cubedge_midpoint[iplus1] = edgevec_signs[iplus1]*.5;
cubedge_midpoint[iplus2] = -edgevec_signs[iplus2]*.5;
rhomb_normal_dot_v0 = DOT3(rhomb_normal, v0);
rhomb_normal_dot_cubedge = DOT3(rhomb_normal,cubedge_midpoint);
}
#else /* the efficient way */
rhomb_normal_dot_v0 = edgevec[iplus2] * v0[iplus1]
- edgevec[iplus1] * v0[iplus2];
rhomb_normal_dot_cubedge = .5f *
(edgevec[iplus2] * edgevec_signs[iplus1] +
edgevec[iplus1] * edgevec_signs[iplus2]);
#endif /* the efficient way */
if (SQR(rhomb_normal_dot_v0) > SQR(rhomb_normal_dot_cubedge))
return 0; /* origin is outside this pair of opposite planes */
}
return 1;
}
/*
* Tells whether a given polygon intersects the cube of edge length 1
* centered at the origin.
* Always returns 1 if a polygon edge intersects the cube;
* returns the multiplicity of containment otherwise.
* (See explanation of polygon_contains_point_3d() above).
*/
extern int
polygon_intersects_cube(int nverts, const float verts[/* nverts */][3],
const float polynormal[3],
int ,/* already_know_vertices_are_outside_cube unused*/
int already_know_edges_are_outside_cube)
{
int i, best_diagonal[3];
float p[3], t;
/*
* If any edge intersects the cube, return 1.
*/
if (!already_know_edges_are_outside_cube)
FOR(i,nverts)
if (segment_intersects_cube(verts[i], verts[(i+1)%nverts]))
return 1;
/*
* If the polygon normal is zero and none of its edges intersect the
* cube, then it doesn't intersect the cube
*/
if (ISZEROVEC3(polynormal))
return 0;
/*
* Now that we know that none of the polygon's edges intersects the cube,
* deciding whether the polygon intersects the cube amounts
* to testing whether any of the four cube diagonals intersects
* the interior of the polygon.
*
* Notice that we only need to consider the cube diagonal that comes
* closest to being perpendicular to the plane of the polygon.
* If the polygon intersects any of the cube diagonals,
* it will intersect that one.
*/
FOR(i,3)
best_diagonal[i] = SIGN_NONZERO(polynormal[i]);
/*
* Okay, we have the diagonal of interest.
* The plane containing the polygon is the set of all points p satisfying
* DOT3(polynormal, p) == DOT3(polynormal, verts[0])
* So find the point p on the cube diagonal of interest
* that satisfies this equation.
* The line containing the cube diagonal is described parametrically by
* t * best_diagonal
* so plug this into the previous equation and solve for t.
* DOT3(polynormal, t * best_diagonal) == DOT3(polynormal, verts[0])
* i.e.
* t = DOT3(polynormal, verts[0]) / DOT3(polynormal, best_diagonal)
*
* (Note that the denominator is guaranteed to be nonzero, since
* polynormal is nonzero and best_diagonal was chosen to have the largest
* magnitude dot-product with polynormal)
*/
t = DOT3(polynormal, verts[0])
/ DOT3(polynormal, best_diagonal);
if (!IN_CLOSED_INTERVAL(-.5, t, .5))
return 0; /* intersection point is not in cube */
SXV3(p, t, best_diagonal); /* p = t * best_diagonal */
return polygon_contains_point_3d(nverts, verts, polynormal, p);
}
extern float *
get_polygon_normal(float normal[3],
int nverts, const float verts[/* nverts */][3])
{
int i;
float tothis[3], toprev[3], cross[3];
/*
* Triangulate the polygon and sum up the nverts-2 triangle normals.
*/
ZEROVEC3(normal);
VMV3(toprev, verts[1], verts[0]); /* 3 subtracts */
for (i = 2; i <= nverts-1; ++i) /* n-2 times... */
{
VMV3(tothis, verts[i], verts[0]); /* 3 subtracts */
VXV3(cross, toprev, tothis); /* 3 subtracts, 6 multiplies */
VPV3(normal, normal, cross); /* 3 adds */
SET3(toprev, tothis);
}
return normal;
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#include <GameServer/Common/IDHolder.hpp>
#include <GameServer/Human/Key.hpp>
#include <GameServer/Human/Human.hpp>
#include <GameServer/Resource/Helpers.hpp>
#include <GameServer/Resource/Key.hpp>
#include <GameServer/Turn/Managers/TurnManager.hpp>
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
using namespace GameServer::Settlement;
using namespace GameServer::World;
namespace GameServer
{
namespace Turn
{
TurnManager::TurnManager(
IContextShrPtr const a_context,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade,
ISettlementPersistenceFacadeShrPtr a_settlement_persistence_facade
)
: m_context(a_context),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade),
m_settlement_persistence_facade(a_settlement_persistence_facade)
{
}
bool TurnManager::turn(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get lands that belong to the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Execute turn of every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = executeTurn(a_transaction, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool TurnManager::executeTurn(
ITransactionShrPtr a_transaction,
ILandShrPtr const a_land
) const
{
ISettlementMap settlements = m_settlement_persistence_facade->getSettlements(a_transaction, a_land);
for (ISettlementMap::iterator it = settlements.begin(); it != settlements.end(); ++it)
{
bool const result = executeTurnSettlement(a_transaction, it->second->getSettlementName());
if (!result)
{
return false;
}
}
m_land_persistence_facade->increaseAge(a_transaction, a_land);
return true;
}
bool TurnManager::executeTurnSettlement(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
// Correct engagement.
// TODO: Implement me!
// Get the available resources.
ResourceWithVolumeMap available_resources = m_resource_persistence_facade->getResources(a_transaction, id_holder);
// Get the cost of living.
ResourceWithVolumeMap cost_of_living = getCostOfLiving(a_transaction, a_settlement_name);
// Verify if famine happened.
if (verifyFamine(available_resources, cost_of_living))
{
bool const result = famine(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Verify if poverty happened.
if (verifyPoverty(available_resources, cost_of_living))
{
bool const result = poverty(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Expenses.
{
m_resource_persistence_facade->subtractResourcesSafely(a_transaction, id_holder, cost_of_living);
}
// Receipts.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<Configuration::IHumanKey, std::string>::const_iterator production =
HUMAN_MAP_PRODUCTION.find(it->second->getHuman()->getKey());
if (production != HUMAN_MAP_PRODUCTION.end())
{
// TODO: Define whether and how to check if volume is greater than 0.
m_resource_persistence_facade->addResource(
a_transaction,
id_holder,
production->second,
it->second->getHuman()->getProduction() * it->second->getVolume()
);
}
}
}
// Experience.
// TODO: Only if not poverty.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property experienceable.
Configuration::IHumanKey const key = it->second->getHuman()->getKey();
if (key == Human::KEY_WORKER_JOBLESS_NOVICE or key == Human::KEY_WORKER_JOBLESS_ADVANCED)
{
continue;
}
if (it->second->getHuman()->getExperience() == "advanced") // TODO: A nasty hardcode. Fixme!
{
continue;
}
// TODO: Hardcoded HUMAN_EXPERIENCE_FACTOR.
Human::Volume const experienced = it->second->getVolume() * 0.1;
if (experienced)
{
IHumanKey key_novice = it->first;
IHumanKey key_advanced;
// TODO: A nasty workaround.
if (key_novice == KEY_SOLDIER_ARCHER_NOVICE ) key_advanced = KEY_SOLDIER_ARCHER_ADVANCED;
if (key_novice == KEY_SOLDIER_HORSEMAN_NOVICE ) key_advanced = KEY_SOLDIER_HORSEMAN_ADVANCED;
if (key_novice == KEY_SOLDIER_INFANTRYMAN_NOVICE) key_advanced = KEY_SOLDIER_INFANTRYMAN_ADVANCED;
if (key_novice == KEY_SORCERER_EARTH_NOVICE ) key_advanced = KEY_SORCERER_EARTH_ADVANCED;
if (key_novice == KEY_SORCERER_FIRE_NOVICE ) key_advanced = KEY_SORCERER_FIRE_ADVANCED;
if (key_novice == KEY_SORCERER_WATER_NOVICE ) key_advanced = KEY_SORCERER_WATER_ADVANCED;
if (key_novice == KEY_SORCERER_WIND_NOVICE ) key_advanced = KEY_SORCERER_WIND_ADVANCED;
if (key_novice == KEY_SPY_AGENT_NOVICE ) key_advanced = KEY_SPY_AGENT_ADVANCED;
if (key_novice == KEY_SPY_SPY_NOVICE ) key_advanced = KEY_SPY_SPY_ADVANCED;
if (key_novice == KEY_SPY_THUG_NOVICE ) key_advanced = KEY_SPY_THUG_ADVANCED;
if (key_novice == KEY_WORKER_BLACKSMITH_NOVICE ) key_advanced = KEY_WORKER_BLACKSMITH_ADVANCED;
if (key_novice == KEY_WORKER_BREEDER_NOVICE ) key_advanced = KEY_WORKER_BREEDER_ADVANCED;
if (key_novice == KEY_WORKER_DRUID_NOVICE ) key_advanced = KEY_WORKER_DRUID_ADVANCED;
if (key_novice == KEY_WORKER_FARMER_NOVICE ) key_advanced = KEY_WORKER_FARMER_ADVANCED;
if (key_novice == KEY_WORKER_FISHERMAN_NOVICE ) key_advanced = KEY_WORKER_FISHERMAN_ADVANCED;
if (key_novice == KEY_WORKER_JOBLESS_NOVICE ) key_advanced = KEY_WORKER_JOBLESS_ADVANCED;
if (key_novice == KEY_WORKER_LUMBERJACK_NOVICE ) key_advanced = KEY_WORKER_LUMBERJACK_ADVANCED;
if (key_novice == KEY_WORKER_MERCHANT_NOVICE ) key_advanced = KEY_WORKER_MERCHANT_ADVANCED;
if (key_novice == KEY_WORKER_MINER_NOVICE ) key_advanced = KEY_WORKER_MINER_ADVANCED;
if (key_novice == KEY_WORKER_OFFICIAL_NOVICE ) key_advanced = KEY_WORKER_OFFICIAL_ADVANCED;
if (key_novice == KEY_WORKER_PRIEST_NOVICE ) key_advanced = KEY_WORKER_PRIEST_ADVANCED;
if (key_novice == KEY_WORKER_STEELWORKER_NOVICE ) key_advanced = KEY_WORKER_STEELWORKER_ADVANCED;
if (key_novice == KEY_WORKER_STONE_MASON_NOVICE ) key_advanced = KEY_WORKER_STONE_MASON_ADVANCED;
if (key_novice == KEY_WORKER_TEACHER_NOVICE ) key_advanced = KEY_WORKER_TEACHER_ADVANCED;
m_human_persistence_facade->addHuman(a_transaction, id_holder, key_advanced, experienced);
bool const result = m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
key_novice,
experienced
);
if (!result)
{
return false;
}
}
}
}
// Reproduce.
// TODO: Before experience.
// TODO: Only if not famine.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property reproduceable.
// TODO: Hardcoded HUMAN_REPRODUCE_FACTOR.
// TODO: Random choosing if reproduction happened (if the uint result of volume * HUMAN_REPRODUCE_FACTOR < 1).
Human::Volume const reproduced = it->second->getVolume() * 0.1;
if (reproduced)
{
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, reproduced);
}
}
}
return true;
}
ResourceWithVolumeMap TurnManager::getCostOfLiving(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
ResourceWithVolumeMap total_cost;
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<IResourceKey, GameServer::Resource::Volume> const & cost_map =
it->second->getHuman()->getCostsToLive();
// FIXME: Workaround to get the ResourceWithVolumeMap.
ResourceWithVolumeMap resources;
for (std::map<IResourceKey, Volume>::const_iterator itr = cost_map.begin(); itr != cost_map.end(); ++itr)
{
ResourceWithVolumeShrPtr resource(new ResourceWithVolume(m_context, itr->first, itr->second));
resources[itr->first] = resource;
}
resources = multiply(m_context, resources, it->second->getVolume());
total_cost = add(m_context, total_cost, resources);
}
return total_cost;
}
bool TurnManager::verifyFamine(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
// FIXME: Code smell - envious class.
Resource::Volume const available = a_available_resources.at(KEY_RESOURCE_FOOD)->getVolume(),
used = a_used_resources.at(KEY_RESOURCE_FOOD)->getVolume();
return (available < used) ? true : false;
}
bool TurnManager::famine(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded FAMINE_DEATH_FACTOR.
Human::Volume died = it->second->getVolume() * 0.1;
if (died)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction, id_holder, it->second->getHuman()->getKey(), died);
if (!result)
{
return false;
}
}
}
return true;
}
bool TurnManager::verifyPoverty(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
// FIXME: Code smell - envious class.
Resource::Volume const available = a_available_resources.at(KEY_RESOURCE_GOLD)->getVolume(),
used = a_used_resources.at(KEY_RESOURCE_GOLD)->getVolume();
return (available < used) ? true : false;
}
bool TurnManager::poverty(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded POVERTY_DISMISS_FACTOR.
Human::Volume dismissed = it->second->getVolume() * 0.1;
if (dismissed)
{
bool const result = m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
dismissed
);
if (!result)
{
return false;
}
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, dismissed);
}
}
return true;
}
} // namespace Turn
} // namespace GameServer
<commit_msg>Storing the information about famine and poverty.<commit_after>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#include <GameServer/Common/IDHolder.hpp>
#include <GameServer/Human/Key.hpp>
#include <GameServer/Human/Human.hpp>
#include <GameServer/Resource/Helpers.hpp>
#include <GameServer/Resource/Key.hpp>
#include <GameServer/Turn/Managers/TurnManager.hpp>
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
using namespace GameServer::Settlement;
using namespace GameServer::World;
namespace GameServer
{
namespace Turn
{
TurnManager::TurnManager(
IContextShrPtr const a_context,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade,
ISettlementPersistenceFacadeShrPtr a_settlement_persistence_facade
)
: m_context(a_context),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade),
m_settlement_persistence_facade(a_settlement_persistence_facade)
{
}
bool TurnManager::turn(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get lands that belong to the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Execute turn of every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = executeTurn(a_transaction, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool TurnManager::executeTurn(
ITransactionShrPtr a_transaction,
ILandShrPtr const a_land
) const
{
ISettlementMap settlements = m_settlement_persistence_facade->getSettlements(a_transaction, a_land);
for (ISettlementMap::iterator it = settlements.begin(); it != settlements.end(); ++it)
{
bool const result = executeTurnSettlement(a_transaction, it->second->getSettlementName());
if (!result)
{
return false;
}
}
m_land_persistence_facade->increaseAge(a_transaction, a_land);
return true;
}
bool TurnManager::executeTurnSettlement(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
// Correct engagement.
// TODO: Implement me!
// Get the available resources.
ResourceWithVolumeMap available_resources = m_resource_persistence_facade->getResources(a_transaction, id_holder);
// Get the cost of living.
ResourceWithVolumeMap cost_of_living = getCostOfLiving(a_transaction, a_settlement_name);
// Verify if famine happened.
bool const famine_happened = verifyFamine(available_resources, cost_of_living);
if (famine_happened)
{
bool const result = famine(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Verify if poverty happened.
bool const poverty_happened = verifyPoverty(available_resources, cost_of_living);
if (poverty_happened)
{
bool const result = poverty(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Expenses.
{
m_resource_persistence_facade->subtractResourcesSafely(a_transaction, id_holder, cost_of_living);
}
// Receipts.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<Configuration::IHumanKey, std::string>::const_iterator production =
HUMAN_MAP_PRODUCTION.find(it->second->getHuman()->getKey());
if (production != HUMAN_MAP_PRODUCTION.end())
{
// TODO: Define whether and how to check if volume is greater than 0.
m_resource_persistence_facade->addResource(
a_transaction,
id_holder,
production->second,
it->second->getHuman()->getProduction() * it->second->getVolume()
);
}
}
}
// Experience.
// TODO: Only if not poverty.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property experienceable.
Configuration::IHumanKey const key = it->second->getHuman()->getKey();
if (key == Human::KEY_WORKER_JOBLESS_NOVICE or key == Human::KEY_WORKER_JOBLESS_ADVANCED)
{
continue;
}
if (it->second->getHuman()->getExperience() == "advanced") // TODO: A nasty hardcode. Fixme!
{
continue;
}
// TODO: Hardcoded HUMAN_EXPERIENCE_FACTOR.
Human::Volume const experienced = it->second->getVolume() * 0.1;
if (experienced)
{
IHumanKey key_novice = it->first;
IHumanKey key_advanced;
// TODO: A nasty workaround.
if (key_novice == KEY_SOLDIER_ARCHER_NOVICE ) key_advanced = KEY_SOLDIER_ARCHER_ADVANCED;
if (key_novice == KEY_SOLDIER_HORSEMAN_NOVICE ) key_advanced = KEY_SOLDIER_HORSEMAN_ADVANCED;
if (key_novice == KEY_SOLDIER_INFANTRYMAN_NOVICE) key_advanced = KEY_SOLDIER_INFANTRYMAN_ADVANCED;
if (key_novice == KEY_SORCERER_EARTH_NOVICE ) key_advanced = KEY_SORCERER_EARTH_ADVANCED;
if (key_novice == KEY_SORCERER_FIRE_NOVICE ) key_advanced = KEY_SORCERER_FIRE_ADVANCED;
if (key_novice == KEY_SORCERER_WATER_NOVICE ) key_advanced = KEY_SORCERER_WATER_ADVANCED;
if (key_novice == KEY_SORCERER_WIND_NOVICE ) key_advanced = KEY_SORCERER_WIND_ADVANCED;
if (key_novice == KEY_SPY_AGENT_NOVICE ) key_advanced = KEY_SPY_AGENT_ADVANCED;
if (key_novice == KEY_SPY_SPY_NOVICE ) key_advanced = KEY_SPY_SPY_ADVANCED;
if (key_novice == KEY_SPY_THUG_NOVICE ) key_advanced = KEY_SPY_THUG_ADVANCED;
if (key_novice == KEY_WORKER_BLACKSMITH_NOVICE ) key_advanced = KEY_WORKER_BLACKSMITH_ADVANCED;
if (key_novice == KEY_WORKER_BREEDER_NOVICE ) key_advanced = KEY_WORKER_BREEDER_ADVANCED;
if (key_novice == KEY_WORKER_DRUID_NOVICE ) key_advanced = KEY_WORKER_DRUID_ADVANCED;
if (key_novice == KEY_WORKER_FARMER_NOVICE ) key_advanced = KEY_WORKER_FARMER_ADVANCED;
if (key_novice == KEY_WORKER_FISHERMAN_NOVICE ) key_advanced = KEY_WORKER_FISHERMAN_ADVANCED;
if (key_novice == KEY_WORKER_JOBLESS_NOVICE ) key_advanced = KEY_WORKER_JOBLESS_ADVANCED;
if (key_novice == KEY_WORKER_LUMBERJACK_NOVICE ) key_advanced = KEY_WORKER_LUMBERJACK_ADVANCED;
if (key_novice == KEY_WORKER_MERCHANT_NOVICE ) key_advanced = KEY_WORKER_MERCHANT_ADVANCED;
if (key_novice == KEY_WORKER_MINER_NOVICE ) key_advanced = KEY_WORKER_MINER_ADVANCED;
if (key_novice == KEY_WORKER_OFFICIAL_NOVICE ) key_advanced = KEY_WORKER_OFFICIAL_ADVANCED;
if (key_novice == KEY_WORKER_PRIEST_NOVICE ) key_advanced = KEY_WORKER_PRIEST_ADVANCED;
if (key_novice == KEY_WORKER_STEELWORKER_NOVICE ) key_advanced = KEY_WORKER_STEELWORKER_ADVANCED;
if (key_novice == KEY_WORKER_STONE_MASON_NOVICE ) key_advanced = KEY_WORKER_STONE_MASON_ADVANCED;
if (key_novice == KEY_WORKER_TEACHER_NOVICE ) key_advanced = KEY_WORKER_TEACHER_ADVANCED;
m_human_persistence_facade->addHuman(a_transaction, id_holder, key_advanced, experienced);
bool const result = m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
key_novice,
experienced
);
if (!result)
{
return false;
}
}
}
}
// Reproduce.
// TODO: Before experience.
// TODO: Only if not famine.
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property reproduceable.
// TODO: Hardcoded HUMAN_REPRODUCE_FACTOR.
// TODO: Random choosing if reproduction happened (if the uint result of volume * HUMAN_REPRODUCE_FACTOR < 1).
Human::Volume const reproduced = it->second->getVolume() * 0.1;
if (reproduced)
{
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, reproduced);
}
}
}
return true;
}
ResourceWithVolumeMap TurnManager::getCostOfLiving(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
ResourceWithVolumeMap total_cost;
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<IResourceKey, GameServer::Resource::Volume> const & cost_map =
it->second->getHuman()->getCostsToLive();
// FIXME: Workaround to get the ResourceWithVolumeMap.
ResourceWithVolumeMap resources;
for (std::map<IResourceKey, Volume>::const_iterator itr = cost_map.begin(); itr != cost_map.end(); ++itr)
{
ResourceWithVolumeShrPtr resource(new ResourceWithVolume(m_context, itr->first, itr->second));
resources[itr->first] = resource;
}
resources = multiply(m_context, resources, it->second->getVolume());
total_cost = add(m_context, total_cost, resources);
}
return total_cost;
}
bool TurnManager::verifyFamine(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
// FIXME: Code smell - envious class.
Resource::Volume const available = a_available_resources.at(KEY_RESOURCE_FOOD)->getVolume(),
used = a_used_resources.at(KEY_RESOURCE_FOOD)->getVolume();
return (available < used) ? true : false;
}
bool TurnManager::famine(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded FAMINE_DEATH_FACTOR.
Human::Volume died = it->second->getVolume() * 0.1;
if (died)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
died
);
if (!result)
{
return false;
}
}
}
return true;
}
bool TurnManager::verifyPoverty(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
// FIXME: Code smell - envious class.
Resource::Volume const available = a_available_resources.at(KEY_RESOURCE_GOLD)->getVolume(),
used = a_used_resources.at(KEY_RESOURCE_GOLD)->getVolume();
return (available < used) ? true : false;
}
bool TurnManager::poverty(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded POVERTY_DISMISS_FACTOR.
Human::Volume dismissed = it->second->getVolume() * 0.1;
if (dismissed)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
dismissed
);
if (!result)
{
return false;
}
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, dismissed);
}
}
return true;
}
} // namespace Turn
} // namespace GameServer
<|endoftext|> |
<commit_before>#include "mysql.hpp"
#include "CQuery.hpp"
#include "CConnection.hpp"
#include "CDispatcher.hpp"
#include "COptions.hpp"
#include "CLog.hpp"
CConnection::CConnection(const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG,
"CConnection::CConnection(this={}, host='{}', user='{}', passw='****', db='{}', options={})",
static_cast<const void *>(this),
host ? host : "(nullptr)",
user ? user : "(nullptr)",
db ? db : "(nullptr)",
static_cast<const void *>(options));
assert(options != nullptr);
//initialize
m_Connection = mysql_init(nullptr);
if (m_Connection == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - MySQL initialization failed (not enough memory available)");
return;
}
if (options->GetOption<bool>(COptions::Type::SSL_ENABLE))
{
string
key = options->GetOption<string>(COptions::Type::SSL_KEY_FILE),
cert = options->GetOption<string>(COptions::Type::SSL_CERT_FILE),
ca = options->GetOption<string>(COptions::Type::SSL_CA_FILE),
capath = options->GetOption<string>(COptions::Type::SSL_CA_PATH),
cipher = options->GetOption<string>(COptions::Type::SSL_CIPHER);
mysql_ssl_set(m_Connection,
key.empty() ? nullptr : key.c_str(),
cert.empty() ? nullptr : cert.c_str(),
ca.empty() ? nullptr : ca.c_str(),
capath.empty() ? nullptr : capath.c_str(),
cipher.empty() ? nullptr : cipher.c_str());
}
//prepare connection flags through passed options
unsigned long connect_flags = 0;
if (options->GetOption<bool>(COptions::Type::MULTI_STATEMENTS) == true)
connect_flags |= CLIENT_MULTI_STATEMENTS;
//connect
auto *result = mysql_real_connect(m_Connection, host, user, passw, db,
options->GetOption<unsigned int>(COptions::Type::SERVER_PORT),
nullptr, connect_flags);
if (result == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - establishing connection to MySQL database failed: #{} '{}'",
mysql_errno(m_Connection), mysql_error(m_Connection));
return;
}
m_IsConnected = true;
//set additional connection options
my_bool reconnect = options->GetOption<bool>(COptions::Type::AUTO_RECONNECT);
mysql_options(m_Connection, MYSQL_OPT_RECONNECT, &reconnect);
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::CConnection - new connection = {}",
static_cast<const void *>(m_Connection));
}
CConnection::~CConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::~CConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
if (IsConnected())
mysql_close(m_Connection);
}
bool CConnection::EscapeString(const char *src, StringEscapeResult_t &dest)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::EscapeString(src='{}', this={}, connection={})",
src ? src : "(nullptr)",
static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
if (IsConnected() == false || src == nullptr)
return false;
const size_t src_len = strlen(src);
auto &dest_ptr = std::get<0>(dest);
dest_ptr.reset(new char[src_len * 2 + 1]);
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
std::get<1>(dest) = mysql_real_escape_string(m_Connection, dest_ptr.get(), src, src_len);
return true;
}
bool CConnection::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::SetCharset(charset='{}', this={}, connection={})",
charset, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || charset.empty())
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
int error = mysql_set_character_set(m_Connection, charset.c_str());
if (error != 0)
return false;
return true;
}
bool CConnection::GetCharset(string &charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetCharset(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
charset = mysql_character_set_name(m_Connection);
return true;
}
bool CConnection::Execute(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::Execute(query={}, this={}, connection={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
return IsConnected() && query->Execute(m_Connection);
}
bool CConnection::GetError(unsigned int &id, string &msg)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetError(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (m_Connection == nullptr)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
id = mysql_errno(m_Connection);
msg = mysql_error(m_Connection);
return true;
}
bool CConnection::GetStatus(string &stat)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetStatus(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
const char *stat_raw = mysql_stat(m_Connection);
if (stat_raw == nullptr)
return false;
stat = stat_raw;
return true;
}
CThreadedConnection::CThreadedConnection(
const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
:
m_Connection(host, user, passw, db, options),
m_UnprocessedQueries(0),
m_WorkerThreadActive(true),
m_WorkerThread(std::bind(&CThreadedConnection::WorkerFunc, this))
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
}
void CThreadedConnection::WorkerFunc()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::WorkerFunc(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
mysql_thread_init();
while (m_WorkerThreadActive)
{
Query_t query;
while (m_Queue.pop(query))
{
DispatchFunction_t func;
if (m_Connection.Execute(query))
{
func = std::bind(&CQuery::CallCallback, query);
}
else
{
unsigned int errorid = 0;
string error;
m_Connection.GetError(errorid, error);
func = std::bind(&CQuery::CallErrorCallback, query, errorid, error);
}
--m_UnprocessedQueries;
CDispatcher::Get()->Dispatch(std::move(func));
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
}
mysql_thread_end();
}
CThreadedConnection::~CThreadedConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::~CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
while(m_Queue.empty() == false)
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
m_WorkerThreadActive = false;
m_WorkerThread.join();
}
CConnectionPool::CConnectionPool(
const size_t size, const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::CConnectionPool(size={}, this={})",
size, static_cast<const void *>(this));
assert(size != 0);
SConnectionNode
*node = m_CurrentNode = new SConnectionNode,
*old_node = nullptr;
for (size_t i = 0; i != size; ++i)
{
old_node = node;
old_node->Connection = new CThreadedConnection(host, user, passw, db, options);
old_node->Next = ((i + 1) == size) ? m_CurrentNode : (node = new SConnectionNode);
}
}
bool CConnectionPool::Queue(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::Queue(query={}, this={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
auto *connection = m_CurrentNode->Connection;
m_CurrentNode = m_CurrentNode->Next;
assert(m_CurrentNode != nullptr && connection != nullptr);
return connection->Queue(query);
}
bool CConnectionPool::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::SetCharset(charset='{}', this={})",
charset, static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
if (node->Connection->SetCharset(charset) == false)
return false;
} while ((node = node->Next) != m_CurrentNode);
return true;
}
unsigned int CConnectionPool::GetUnprocessedQueryCount()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::GetUnprocessedQueryCount(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
unsigned int count = 0;
do
{
count += node->Connection->GetUnprocessedQueryCount();
} while ((node = node->Next) != m_CurrentNode);
return count;
}
CConnectionPool::~CConnectionPool()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::~CConnectionPool(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
delete node->Connection;
auto *old_node = node;
node = node->Next;
delete old_node;
} while (node != m_CurrentNode);
}
<commit_msg>add additional log message<commit_after>#include "mysql.hpp"
#include "CQuery.hpp"
#include "CConnection.hpp"
#include "CDispatcher.hpp"
#include "COptions.hpp"
#include "CLog.hpp"
CConnection::CConnection(const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG,
"CConnection::CConnection(this={}, host='{}', user='{}', passw='****', db='{}', options={})",
static_cast<const void *>(this),
host ? host : "(nullptr)",
user ? user : "(nullptr)",
db ? db : "(nullptr)",
static_cast<const void *>(options));
assert(options != nullptr);
//initialize
m_Connection = mysql_init(nullptr);
if (m_Connection == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - MySQL initialization failed (not enough memory available)");
return;
}
if (options->GetOption<bool>(COptions::Type::SSL_ENABLE))
{
string
key = options->GetOption<string>(COptions::Type::SSL_KEY_FILE),
cert = options->GetOption<string>(COptions::Type::SSL_CERT_FILE),
ca = options->GetOption<string>(COptions::Type::SSL_CA_FILE),
capath = options->GetOption<string>(COptions::Type::SSL_CA_PATH),
cipher = options->GetOption<string>(COptions::Type::SSL_CIPHER);
mysql_ssl_set(m_Connection,
key.empty() ? nullptr : key.c_str(),
cert.empty() ? nullptr : cert.c_str(),
ca.empty() ? nullptr : ca.c_str(),
capath.empty() ? nullptr : capath.c_str(),
cipher.empty() ? nullptr : cipher.c_str());
}
//prepare connection flags through passed options
unsigned long connect_flags = 0;
if (options->GetOption<bool>(COptions::Type::MULTI_STATEMENTS) == true)
connect_flags |= CLIENT_MULTI_STATEMENTS;
//connect
auto *result = mysql_real_connect(m_Connection, host, user, passw, db,
options->GetOption<unsigned int>(COptions::Type::SERVER_PORT),
nullptr, connect_flags);
if (result == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - establishing connection to MySQL database failed: #{} '{}'",
mysql_errno(m_Connection), mysql_error(m_Connection));
return;
}
m_IsConnected = true;
//set additional connection options
my_bool reconnect = options->GetOption<bool>(COptions::Type::AUTO_RECONNECT);
mysql_options(m_Connection, MYSQL_OPT_RECONNECT, &reconnect);
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::CConnection - new connection = {}",
static_cast<const void *>(m_Connection));
}
CConnection::~CConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::~CConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
if (IsConnected())
mysql_close(m_Connection);
}
bool CConnection::EscapeString(const char *src, StringEscapeResult_t &dest)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::EscapeString(src='{}', this={}, connection={})",
src ? src : "(nullptr)",
static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
if (IsConnected() == false || src == nullptr)
return false;
const size_t src_len = strlen(src);
auto &dest_ptr = std::get<0>(dest);
dest_ptr.reset(new char[src_len * 2 + 1]);
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
std::get<1>(dest) = mysql_real_escape_string(m_Connection, dest_ptr.get(), src, src_len);
return true;
}
bool CConnection::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::SetCharset(charset='{}', this={}, connection={})",
charset, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || charset.empty())
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
int error = mysql_set_character_set(m_Connection, charset.c_str());
if (error != 0)
return false;
return true;
}
bool CConnection::GetCharset(string &charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetCharset(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
charset = mysql_character_set_name(m_Connection);
return true;
}
bool CConnection::Execute(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::Execute(query={}, this={}, connection={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
return IsConnected() && query->Execute(m_Connection);
}
bool CConnection::GetError(unsigned int &id, string &msg)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetError(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (m_Connection == nullptr)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
id = mysql_errno(m_Connection);
msg = mysql_error(m_Connection);
return true;
}
bool CConnection::GetStatus(string &stat)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetStatus(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
const char *stat_raw = mysql_stat(m_Connection);
if (stat_raw == nullptr)
return false;
stat = stat_raw;
return true;
}
CThreadedConnection::CThreadedConnection(
const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
:
m_Connection(host, user, passw, db, options),
m_UnprocessedQueries(0),
m_WorkerThreadActive(true),
m_WorkerThread(std::bind(&CThreadedConnection::WorkerFunc, this))
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
}
void CThreadedConnection::WorkerFunc()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::WorkerFunc(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
mysql_thread_init();
while (m_WorkerThreadActive)
{
Query_t query;
while (m_Queue.pop(query))
{
DispatchFunction_t func;
if (m_Connection.Execute(query))
{
func = std::bind(&CQuery::CallCallback, query);
}
else
{
unsigned int errorid = 0;
string error;
m_Connection.GetError(errorid, error);
func = std::bind(&CQuery::CallErrorCallback, query, errorid, error);
}
--m_UnprocessedQueries;
CDispatcher::Get()->Dispatch(std::move(func));
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
}
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::WorkerFunc(this={}, connection={}) - shutting down",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
mysql_thread_end();
}
CThreadedConnection::~CThreadedConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::~CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
while(m_Queue.empty() == false)
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
m_WorkerThreadActive = false;
m_WorkerThread.join();
}
CConnectionPool::CConnectionPool(
const size_t size, const char *host, const char *user, const char *passw, const char *db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::CConnectionPool(size={}, this={})",
size, static_cast<const void *>(this));
assert(size != 0);
SConnectionNode
*node = m_CurrentNode = new SConnectionNode,
*old_node = nullptr;
for (size_t i = 0; i != size; ++i)
{
old_node = node;
old_node->Connection = new CThreadedConnection(host, user, passw, db, options);
old_node->Next = ((i + 1) == size) ? m_CurrentNode : (node = new SConnectionNode);
}
}
bool CConnectionPool::Queue(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::Queue(query={}, this={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
auto *connection = m_CurrentNode->Connection;
m_CurrentNode = m_CurrentNode->Next;
assert(m_CurrentNode != nullptr && connection != nullptr);
return connection->Queue(query);
}
bool CConnectionPool::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::SetCharset(charset='{}', this={})",
charset, static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
if (node->Connection->SetCharset(charset) == false)
return false;
} while ((node = node->Next) != m_CurrentNode);
return true;
}
unsigned int CConnectionPool::GetUnprocessedQueryCount()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::GetUnprocessedQueryCount(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
unsigned int count = 0;
do
{
count += node->Connection->GetUnprocessedQueryCount();
} while ((node = node->Next) != m_CurrentNode);
return count;
}
CConnectionPool::~CConnectionPool()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::~CConnectionPool(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
delete node->Connection;
auto *old_node = node;
node = node->Next;
delete old_node;
} while (node != m_CurrentNode);
}
<|endoftext|> |
<commit_before>#include "crunch/concurrency/meta_scheduler.hpp"
#include "crunch/base/assert.hpp"
#include "crunch/base/stack_alloc.hpp"
#include "crunch/concurrency/event.hpp"
#include <algorithm>
#if defined (CRUNCH_PLATFORM_WIN32)
# include <windows.h>
#endif
namespace Crunch { namespace Concurrency {
class MetaScheduler::Context : Waiter
{
public:
Context(MetaScheduler& owner)
: mOwner(owner)
#if defined (CRUNCH_PLATFORM_WIN32)
, mEvent(CreateEvent(NULL, TRUE, FALSE, NULL))
#endif
{
#if defined (CRUNCH_PLATFORM_WIN32)
CRUNCH_ASSERT_ALWAYS(mEvent != NULL);
#endif
}
~Context()
{
#if defined (CRUNCH_PLATFORM_WIN32)
CloseHandle(mEvent);
#endif
}
void WaitFor(IWaitable& waitable)
{
// TODO: Let active scheduler handle the wait if it can
// TODO: Keep in mind if active scheduler is a fiber scheduler we might come back on a different system thread.. (and this thread might be used for other things.. i.e. waiter must be stack local)
#if defined (CRUNCH_PLATFORM_WIN32)
ResetEvent(mEvent);
#endif
waitable.AddWaiter(this);
#if defined (CRUNCH_PLATFORM_WIN32)
WaitForSingleObject(mEvent, INFINITE);
#endif
}
virtual void Wakeup()
{
#if defined (CRUNCH_PLATFORM_WIN32)
SetEvent(mEvent);
#endif
}
private:
MetaScheduler& mOwner;
#if defined (CRUNCH_PLATFORM_WIN32)
HANDLE mEvent;
#endif
};
void MetaScheduler::WaitForAll(IWaitable** waitables, std::size_t count, WaitMode waitMode)
{
IWaitable** unordered = CRUNCH_STACK_ALLOC_T(IWaitable*, count);
IWaitable** ordered = CRUNCH_STACK_ALLOC_T(IWaitable*, count);
std::size_t orderedCount = 0;
std::size_t unorderedCount = 0;
for (std::size_t i = 0; i < count; ++i)
{
if (waitables[i]->IsOrderDependent())
ordered[orderedCount++] = waitables[i];
else
unordered[unorderedCount++] = waitables[i];
}
Context& context = *tCurrentContext;
if (orderedCount != 0)
{
std::sort(ordered, ordered + orderedCount);
for (std::size_t i = 0; i < orderedCount; ++i)
{
// Order dependent doesn't imply fair, so we need to wait for one at a time
context.WaitFor(*ordered[i]);
}
}
// TODO: could add all waiters in one go and do only one wait
for (std::size_t i = 0; i < unorderedCount; ++i)
{
context.WaitFor(*unordered[i]);
}
}
void MetaScheduler::WaitForAny(IWaitable** waitables, std::size_t count, WaitMode waitMode)
{
struct WaiterHelper : Waiter
{
virtual void Wakeup()
{
event->Set();
}
Event* event;
};
WaiterHelper* waiters = CRUNCH_STACK_ALLOC_T(WaiterHelper, count);
Event event(false);
for (std::size_t i = 0; i < count; ++i)
{
waiters[i].event = &event;
waitables[i]->AddWaiter(&waiters[i]);
}
tCurrentContext->WaitFor(event);
for (std::size_t i = 0; i < count; ++i)
{
waitables[i]->RemoveWaiter(&waiters[i]);
}
}
CRUNCH_THREAD_LOCAL MetaScheduler::Context* MetaScheduler::tCurrentContext = NULL;
struct ContextRunState : Waiter
{
ISchedulerContext* context;
virtual void Wakeup()
{
// Add to active set
// Wake up scheduler if sleeping
}
};
MetaScheduler::MetaScheduler(const SchedulerList& schedulers)
: mSchedulers(schedulers)
{}
MetaScheduler::~MetaScheduler()
{}
void MetaScheduler::Join(ThreadConfig const& config)
{
CRUNCH_ASSERT_ALWAYS(tCurrentContext == nullptr);
// Set up thread specific data
ContextPtr context(new Context(*this));
tCurrentContext = context.get();
mContexts.push_back(std::move(context));
}
void MetaScheduler::Leave()
{
CRUNCH_ASSERT_ALWAYS(tCurrentContext != nullptr);
tCurrentContext = NULL;
}
void MetaScheduler::Run(IWaitable& until)
{
}
/*
void MetaScheduler::Run()
{
typedef std::vector<ContextRunState> ContextList;
ContextList runStates;
{
const boost::mutex::scoped_lock lock(mSchedulersLock);
BOOST_FOREACH(const SchedulerPtr& scheduler, mSchedulers)
{
ContextRunState runState;
runState.context = &scheduler->GetContext();
runStates.push_back(runState);
}
}
// Check if scheduler master list has changed
// - Add / Remove schedulers as needed
// - Should probably also hold copy of scheduler ptr as long as we use context
for (;;)
{
for (ContextList::iterator it = runStates.begin();
it != runStates.end();)
{
ISchedulerContext& context = *it->context;
const ISchedulerContext::State state = context.RunOne();
if (state == ISchedulerContext::STATE_IDLE)
{
it = runStates.erase(it);
// idleRunStates.push_back(&context);
context.GetHasWorkCondition().AddWaiter(&*it);
}
else
{
++it;
}
}
// If active list empty, go idle
}
}
}*/
}}
<commit_msg>crunch_concurrency - Removed commented out code<commit_after>#include "crunch/concurrency/meta_scheduler.hpp"
#include "crunch/base/assert.hpp"
#include "crunch/base/stack_alloc.hpp"
#include "crunch/concurrency/event.hpp"
#include <algorithm>
#if defined (CRUNCH_PLATFORM_WIN32)
# include <windows.h>
#endif
namespace Crunch { namespace Concurrency {
class MetaScheduler::Context : Waiter
{
public:
Context(MetaScheduler& owner)
: mOwner(owner)
#if defined (CRUNCH_PLATFORM_WIN32)
, mEvent(CreateEvent(NULL, TRUE, FALSE, NULL))
#endif
{
#if defined (CRUNCH_PLATFORM_WIN32)
CRUNCH_ASSERT_ALWAYS(mEvent != NULL);
#endif
}
~Context()
{
#if defined (CRUNCH_PLATFORM_WIN32)
CloseHandle(mEvent);
#endif
}
void WaitFor(IWaitable& waitable)
{
// TODO: Let active scheduler handle the wait if it can
// TODO: Keep in mind if active scheduler is a fiber scheduler we might come back on a different system thread.. (and this thread might be used for other things.. i.e. waiter must be stack local)
#if defined (CRUNCH_PLATFORM_WIN32)
ResetEvent(mEvent);
#endif
waitable.AddWaiter(this);
#if defined (CRUNCH_PLATFORM_WIN32)
WaitForSingleObject(mEvent, INFINITE);
#endif
}
virtual void Wakeup()
{
#if defined (CRUNCH_PLATFORM_WIN32)
SetEvent(mEvent);
#endif
}
private:
MetaScheduler& mOwner;
#if defined (CRUNCH_PLATFORM_WIN32)
HANDLE mEvent;
#endif
};
void MetaScheduler::WaitForAll(IWaitable** waitables, std::size_t count, WaitMode waitMode)
{
IWaitable** unordered = CRUNCH_STACK_ALLOC_T(IWaitable*, count);
IWaitable** ordered = CRUNCH_STACK_ALLOC_T(IWaitable*, count);
std::size_t orderedCount = 0;
std::size_t unorderedCount = 0;
for (std::size_t i = 0; i < count; ++i)
{
if (waitables[i]->IsOrderDependent())
ordered[orderedCount++] = waitables[i];
else
unordered[unorderedCount++] = waitables[i];
}
Context& context = *tCurrentContext;
if (orderedCount != 0)
{
std::sort(ordered, ordered + orderedCount);
for (std::size_t i = 0; i < orderedCount; ++i)
{
// Order dependent doesn't imply fair, so we need to wait for one at a time
context.WaitFor(*ordered[i]);
}
}
// TODO: could add all waiters in one go and do only one wait
for (std::size_t i = 0; i < unorderedCount; ++i)
{
context.WaitFor(*unordered[i]);
}
}
void MetaScheduler::WaitForAny(IWaitable** waitables, std::size_t count, WaitMode waitMode)
{
struct WaiterHelper : Waiter
{
virtual void Wakeup()
{
event->Set();
}
Event* event;
};
WaiterHelper* waiters = CRUNCH_STACK_ALLOC_T(WaiterHelper, count);
Event event(false);
for (std::size_t i = 0; i < count; ++i)
{
waiters[i].event = &event;
waitables[i]->AddWaiter(&waiters[i]);
}
tCurrentContext->WaitFor(event);
for (std::size_t i = 0; i < count; ++i)
{
waitables[i]->RemoveWaiter(&waiters[i]);
}
}
CRUNCH_THREAD_LOCAL MetaScheduler::Context* MetaScheduler::tCurrentContext = NULL;
struct ContextRunState : Waiter
{
ISchedulerContext* context;
virtual void Wakeup()
{
// Add to active set
// Wake up scheduler if sleeping
}
};
MetaScheduler::MetaScheduler(const SchedulerList& schedulers)
: mSchedulers(schedulers)
{}
MetaScheduler::~MetaScheduler()
{}
void MetaScheduler::Join(ThreadConfig const& config)
{
CRUNCH_ASSERT_ALWAYS(tCurrentContext == nullptr);
// Set up thread specific data
ContextPtr context(new Context(*this));
tCurrentContext = context.get();
mContexts.push_back(std::move(context));
}
void MetaScheduler::Leave()
{
CRUNCH_ASSERT_ALWAYS(tCurrentContext != nullptr);
tCurrentContext = NULL;
}
void MetaScheduler::Run(IWaitable& until)
{
}
}}
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#ifdef OS_OSX
#include <Cocoa/Cocoa.h>
#endif
#if defined(OS_WIN32)
# include "base.h"
# include <windows.h>
#else
# include <dirent.h>
#endif
#include <errno.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include "kroll.h"
#include <Poco/DirectoryIterator.h>
#include <Poco/File.h>
namespace kroll
{
Host::Host(int argc, const char *argv[])
{
char *ti_home = getenv("KR_HOME");
char *ti_runtime = getenv("KR_RUNTIME");
#ifdef DEBUG
std::cout << ">>> KR_HOME=" << ti_home << std::endl;
std::cout << ">>> KR_RUNTIME=" << ti_runtime << std::endl;
#endif
if (ti_home == NULL)
{
std::cerr << "KR_HOME not defined, aborting." << std::endl;
exit(1);
}
if (ti_runtime == NULL)
{
std::cerr << "KR_RUNTIME not defined, aborting." << std::endl;
exit(1);
}
#ifdef OS_WIN32
#define BUFSIZE 8024
char paths[BUFSIZE];
int bufsize = BUFSIZE;
bufsize = GetEnvironmentVariable("KR_MODULES",(char*)&paths,bufsize);
if (bufsize > 0)
{
paths[bufsize]='\0';
}
else
{
std::cerr << "KR_MODULES not defined, aborting." << std::endl;
exit(1);
}
#else
char *paths = getenv("KR_MODULES");
if (!paths)
{
std::cerr << "KR_MODULES not defined, aborting." << std::endl;
exit(1);
}
#endif
FileUtils::Tokenize(paths, this->module_paths, KR_LIB_SEP);
this->running = false;
this->exitCode = 0;
this->appDirectory = std::string(ti_home);
this->runtimeDirectory = std::string(ti_runtime);
this->global_object = new StaticBoundObject();
// link the name of our global variable to ourself so
// we can reference from global scope directly to get it
this->global_object->SetObject(GLOBAL_NS_VARNAME, this->global_object);
#if defined(OS_WIN32)
this->module_suffix = "module.dll";
#elif defined(OS_OSX)
this->module_suffix = "module.dylib";
#elif defined(OS_LINUX)
this->module_suffix = "module.so";
#endif
this->autoScan = false;
// Sometimes libraries parsing argc and argv will
// modify them, so we want to keep our own copy here
for (int i = 0; i < argc; i++)
{
this->args.push_back(std::string(argv[i]));
}
}
Host::~Host()
{
}
const int Host::GetCommandLineArgCount()
{
return this->args.size();
}
const char* Host::GetCommandLineArg(int index)
{
if ((int) this->args.size() > index)
{
return this->args.at(index).c_str();
}
else
{
return NULL;
}
}
void Host::AddModuleProvider(ModuleProvider *provider)
{
ScopedLock lock(&moduleMutex);
module_providers.push_back(provider);
if (autoScan)
{
this->ScanInvalidModuleFiles();
}
}
ModuleProvider* Host::FindModuleProvider(std::string& filename)
{
ScopedLock lock(&moduleMutex);
std::vector<ModuleProvider*>::iterator iter;
for (iter = module_providers.begin();
iter != module_providers.end();
iter++)
{
ModuleProvider *provider = (*iter);
if (provider != NULL && provider->IsModule(filename)) {
return provider;
}
}
return NULL;
}
void Host::RemoveModuleProvider(ModuleProvider *provider)
{
ScopedLock lock(&moduleMutex);
std::vector<ModuleProvider*>::iterator iter =
std::find(module_providers.begin(),
module_providers.end(), provider);
if (iter != module_providers.end()) {
module_providers.erase(iter);
}
}
void Host::UnloadModuleProviders()
{
while (module_providers.size() > 0)
{
ModuleProvider* provider = module_providers.at(0);
this->RemoveModuleProvider(provider);
}
}
bool Host::IsModule(std::string& filename)
{
bool isModule = (filename.length() > module_suffix.length() && filename.substr(
filename.length() - this->module_suffix.length()) == this->module_suffix);
return isModule;
}
SharedPtr<Module> Host::LoadModule(std::string& path, ModuleProvider *provider)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
SharedPtr<Module> module = NULL;
try
{
module = provider->CreateModule(path);
module->SetProvider(provider); // set the provider
std::cout << "Module loaded " << module->GetName()
<< " from " << path << std::endl;
// Call module Load lifecycle event
module->Initialize();
// Store module
this->modules[path] = module;
this->loaded_modules.push_back(module);
}
catch (kroll::ValueException& e)
{
SharedString s = e.GetValue()->DisplayString();
std::cerr << "Error generated loading module ("
<< path << "): " << *s << std::endl;
}
catch(...)
{
std::cerr << "Error generated loading module: " << path << std::endl;
}
return module;
}
void Host::UnloadModules()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
// Stop all modules
while (this->loaded_modules.size() > 0)
{
this->UnregisterModule(this->loaded_modules.at(0));
}
}
void Host::LoadModules()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
/* Scan module paths for modules which can be
* loaded by the basic shared-object provider */
std::vector<std::string>::iterator iter;
iter = this->module_paths.begin();
while (iter != this->module_paths.end())
{
this->FindBasicModules((*iter++));
}
/* All modules are now loaded,
* so start them all */
this->StartModules(this->loaded_modules);
/* Try to load files that weren't modules
* using newly available module providers */
this->ScanInvalidModuleFiles();
/* From now on, adding a module provider will trigger
* a rescan of all invalid module files */
this->autoScan = true;
}
void Host::FindBasicModules(std::string& dir)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
Poco::DirectoryIterator iter = Poco::DirectoryIterator(dir);
Poco::DirectoryIterator end;
while (iter != end)
{
Poco::File f = *iter;
if (!f.isDirectory() && !f.isHidden())
{
std::string fpath = iter.path().absolute().toString();
if (IsModule(fpath))
{
this->LoadModule(fpath, this);
}
else
{
this->AddInvalidModuleFile(fpath);
}
}
iter++;
}
}
void Host::AddInvalidModuleFile(std::string path)
{
// Don't add module twice
std::vector<std::string>& invalid = this->invalid_module_files;
if (std::find(invalid.begin(), invalid.end(), path) == invalid.end())
{
this->invalid_module_files.push_back(path);
}
}
void Host::ScanInvalidModuleFiles()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
this->autoScan = false; // Do not recursively scan
ModuleList modulesLoaded; // Track loaded modules
std::vector<std::string>::iterator iter;
iter = this->invalid_module_files.begin();
while (iter != this->invalid_module_files.end())
{
std::string path = *iter;
ModuleProvider *provider = FindModuleProvider(path);
if (provider != NULL)
{
SharedPtr<Module> m = this->LoadModule(path, provider);
// Module was loaded successfully
if (!m.isNull())
modulesLoaded.push_back(m);
// Erase path, even on failure
invalid_module_files.erase(iter);
}
iter++;
}
if (modulesLoaded.size() > 0)
{
this->StartModules(modulesLoaded);
/* If any of the invalid module files added
* a ModuleProvider, let them load their modules */
this->ScanInvalidModuleFiles();
}
this->autoScan = true;
}
void Host::StartModules(ModuleList to_init)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
ModuleList::iterator iter = to_init.begin();
while (iter != to_init.end())
{
(*iter)->Start();
*iter++;
}
}
SharedPtr<Module> Host::GetModule(std::string& name)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
ModuleMap::iterator iter = this->modules.find(name);
if (this->modules.end() == iter) {
return SharedPtr<Module>(NULL);
}
return iter->second;
}
bool Host::HasModule(std::string name)
{
ScopedLock lock(&moduleMutex);
ModuleMap::iterator iter = this->modules.find(name);
return (this->modules.end() != iter);
}
void Host::UnregisterModule(Module* module)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
std::cout << "Unregistering " << module->GetName() << std::endl;
// Remove from the module map
ModuleMap::iterator i = this->modules.begin();
while (i != this->modules.end())
{
if (module == (i->second).get())
break;
i++;
}
// Remove from the list of loaded modules
ModuleList::iterator j = this->loaded_modules.begin();
while (j != this->loaded_modules.end())
{
if (module == (*j).get())
break;
j++;
}
module->Stop(); // Call Stop() lifecycle event
if (i != this->modules.end())
this->modules.erase(i);
if (j != this->loaded_modules.end())
this->loaded_modules.erase(j);
}
SharedPtr<StaticBoundObject> Host::GetGlobalObject() {
return this->global_object;
}
bool Host::Start()
{
KR_DUMP_LOCATION
return true;
}
void Host::Stop ()
{
KR_DUMP_LOCATION
}
int Host::Run()
{
KR_DUMP_LOCATION
{
ScopedLock lock(&moduleMutex);
this->AddModuleProvider(this);
this->LoadModules();
}
// allow start to immediately end
this->running = this->Start();
while (this->running)
{
ScopedLock lock(&moduleMutex);
if (!this->RunLoop())
{
break;
}
}
ScopedLock lock(&moduleMutex);
this->Stop();
this->UnloadModuleProviders();
this->UnloadModules();
// Clear the global object, being sure to remove the recursion, so
// that the memory will be cleared
this->global_object->Set(GLOBAL_NS_VARNAME, Value::Undefined);
this->global_object = NULL;
return this->exitCode;
}
void Host::Exit(int exitcode)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
running = false;
this->exitCode = exitcode;
}
}
<commit_msg>fix win32 compile errors<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#ifdef OS_OSX
#include <Cocoa/Cocoa.h>
#endif
#if defined(OS_WIN32)
#include "base.h"
#include <windows.h>
#else
# include <dirent.h>
#endif
#include <errno.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include "kroll.h"
#include <Poco/DirectoryIterator.h>
#include <Poco/File.h>
namespace kroll
{
Host::Host(int argc, const char *argv[])
{
char *ti_home = getenv("KR_HOME");
char *ti_runtime = getenv("KR_RUNTIME");
#ifdef DEBUG
std::cout << ">>> KR_HOME=" << ti_home << std::endl;
std::cout << ">>> KR_RUNTIME=" << ti_runtime << std::endl;
#endif
if (ti_home == NULL)
{
std::cerr << "KR_HOME not defined, aborting." << std::endl;
exit(1);
}
if (ti_runtime == NULL)
{
std::cerr << "KR_RUNTIME not defined, aborting." << std::endl;
exit(1);
}
char *paths = getenv("KR_MODULES");
if (!paths)
{
std::cerr << "KR_MODULES not defined, aborting." << std::endl;
exit(1);
}
FileUtils::Tokenize(paths, this->module_paths, KR_LIB_SEP);
this->running = false;
this->exitCode = 0;
this->appDirectory = std::string(ti_home);
this->runtimeDirectory = std::string(ti_runtime);
this->global_object = new StaticBoundObject();
// link the name of our global variable to ourself so
// we can reference from global scope directly to get it
this->global_object->SetObject(GLOBAL_NS_VARNAME, this->global_object);
#if defined(OS_WIN32)
this->module_suffix = "module.dll";
#elif defined(OS_OSX)
this->module_suffix = "module.dylib";
#elif defined(OS_LINUX)
this->module_suffix = "module.so";
#endif
this->autoScan = false;
// Sometimes libraries parsing argc and argv will
// modify them, so we want to keep our own copy here
for (int i = 0; i < argc; i++)
{
this->args.push_back(std::string(argv[i]));
}
}
Host::~Host()
{
}
const int Host::GetCommandLineArgCount()
{
return this->args.size();
}
const char* Host::GetCommandLineArg(int index)
{
if ((int) this->args.size() > index)
{
return this->args.at(index).c_str();
}
else
{
return NULL;
}
}
void Host::AddModuleProvider(ModuleProvider *provider)
{
ScopedLock lock(&moduleMutex);
module_providers.push_back(provider);
if (autoScan)
{
this->ScanInvalidModuleFiles();
}
}
ModuleProvider* Host::FindModuleProvider(std::string& filename)
{
ScopedLock lock(&moduleMutex);
std::vector<ModuleProvider*>::iterator iter;
for (iter = module_providers.begin();
iter != module_providers.end();
iter++)
{
ModuleProvider *provider = (*iter);
if (provider != NULL && provider->IsModule(filename)) {
return provider;
}
}
return NULL;
}
void Host::RemoveModuleProvider(ModuleProvider *provider)
{
ScopedLock lock(&moduleMutex);
std::vector<ModuleProvider*>::iterator iter =
std::find(module_providers.begin(),
module_providers.end(), provider);
if (iter != module_providers.end()) {
module_providers.erase(iter);
}
}
void Host::UnloadModuleProviders()
{
while (module_providers.size() > 0)
{
ModuleProvider* provider = module_providers.at(0);
this->RemoveModuleProvider(provider);
}
}
bool Host::IsModule(std::string& filename)
{
bool isModule = (filename.length() > module_suffix.length() && filename.substr(
filename.length() - this->module_suffix.length()) == this->module_suffix);
return isModule;
}
SharedPtr<Module> Host::LoadModule(std::string& path, ModuleProvider *provider)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
SharedPtr<Module> module = NULL;
try
{
module = provider->CreateModule(path);
module->SetProvider(provider); // set the provider
std::cout << "Module loaded " << module->GetName()
<< " from " << path << std::endl;
// Call module Load lifecycle event
module->Initialize();
// Store module
this->modules[path] = module;
this->loaded_modules.push_back(module);
}
catch (kroll::ValueException& e)
{
SharedString s = e.GetValue()->DisplayString();
std::cerr << "Error generated loading module ("
<< path << "): " << *s << std::endl;
}
catch(...)
{
std::cerr << "Error generated loading module: " << path << std::endl;
}
return module;
}
void Host::UnloadModules()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
// Stop all modules
while (this->loaded_modules.size() > 0)
{
this->UnregisterModule(this->loaded_modules.at(0));
}
}
void Host::LoadModules()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
/* Scan module paths for modules which can be
* loaded by the basic shared-object provider */
std::vector<std::string>::iterator iter;
iter = this->module_paths.begin();
while (iter != this->module_paths.end())
{
this->FindBasicModules((*iter++));
}
/* All modules are now loaded,
* so start them all */
this->StartModules(this->loaded_modules);
/* Try to load files that weren't modules
* using newly available module providers */
this->ScanInvalidModuleFiles();
/* From now on, adding a module provider will trigger
* a rescan of all invalid module files */
this->autoScan = true;
}
void Host::FindBasicModules(std::string& dir)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
Poco::DirectoryIterator iter = Poco::DirectoryIterator(dir);
Poco::DirectoryIterator end;
while (iter != end)
{
Poco::File f = *iter;
if (!f.isDirectory() && !f.isHidden())
{
std::string fpath = iter.path().absolute().toString();
if (IsModule(fpath))
{
this->LoadModule(fpath, this);
}
else
{
this->AddInvalidModuleFile(fpath);
}
}
iter++;
}
}
void Host::AddInvalidModuleFile(std::string path)
{
// Don't add module twice
std::vector<std::string>& invalid = this->invalid_module_files;
if (std::find(invalid.begin(), invalid.end(), path) == invalid.end())
{
this->invalid_module_files.push_back(path);
}
}
void Host::ScanInvalidModuleFiles()
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
this->autoScan = false; // Do not recursively scan
ModuleList modulesLoaded; // Track loaded modules
std::vector<std::string>::iterator iter;
iter = this->invalid_module_files.begin();
while (iter != this->invalid_module_files.end())
{
std::string path = *iter;
ModuleProvider *provider = FindModuleProvider(path);
if (provider != NULL)
{
SharedPtr<Module> m = this->LoadModule(path, provider);
// Module was loaded successfully
if (!m.isNull())
modulesLoaded.push_back(m);
// Erase path, even on failure
invalid_module_files.erase(iter);
}
iter++;
}
if (modulesLoaded.size() > 0)
{
this->StartModules(modulesLoaded);
/* If any of the invalid module files added
* a ModuleProvider, let them load their modules */
this->ScanInvalidModuleFiles();
}
this->autoScan = true;
}
void Host::StartModules(ModuleList to_init)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
ModuleList::iterator iter = to_init.begin();
while (iter != to_init.end())
{
(*iter)->Start();
*iter++;
}
}
SharedPtr<Module> Host::GetModule(std::string& name)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
ModuleMap::iterator iter = this->modules.find(name);
if (this->modules.end() == iter) {
return SharedPtr<Module>(NULL);
}
return iter->second;
}
bool Host::HasModule(std::string name)
{
ScopedLock lock(&moduleMutex);
ModuleMap::iterator iter = this->modules.find(name);
return (this->modules.end() != iter);
}
void Host::UnregisterModule(Module* module)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
std::cout << "Unregistering " << module->GetName() << std::endl;
// Remove from the module map
ModuleMap::iterator i = this->modules.begin();
while (i != this->modules.end())
{
if (module == (i->second).get())
break;
i++;
}
// Remove from the list of loaded modules
ModuleList::iterator j = this->loaded_modules.begin();
while (j != this->loaded_modules.end())
{
if (module == (*j).get())
break;
j++;
}
module->Stop(); // Call Stop() lifecycle event
if (i != this->modules.end())
this->modules.erase(i);
if (j != this->loaded_modules.end())
this->loaded_modules.erase(j);
}
SharedPtr<StaticBoundObject> Host::GetGlobalObject() {
return this->global_object;
}
bool Host::Start()
{
KR_DUMP_LOCATION
return true;
}
void Host::Stop ()
{
KR_DUMP_LOCATION
}
int Host::Run()
{
KR_DUMP_LOCATION
{
ScopedLock lock(&moduleMutex);
this->AddModuleProvider(this);
this->LoadModules();
}
// allow start to immediately end
this->running = this->Start();
while (this->running)
{
ScopedLock lock(&moduleMutex);
if (!this->RunLoop())
{
break;
}
}
ScopedLock lock(&moduleMutex);
this->Stop();
this->UnloadModuleProviders();
this->UnloadModules();
// Clear the global object, being sure to remove the recursion, so
// that the memory will be cleared
this->global_object->Set(GLOBAL_NS_VARNAME, Value::Undefined);
this->global_object = NULL;
return this->exitCode;
}
void Host::Exit(int exitcode)
{
KR_DUMP_LOCATION
ScopedLock lock(&moduleMutex);
running = false;
this->exitCode = exitcode;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRibbonFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkMath.h"
#include "vtkRibbonFilter.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
#include "vtkPolyLine.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkRibbonFilter* vtkRibbonFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkRibbonFilter");
if(ret)
{
return (vtkRibbonFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkRibbonFilter;
}
// Construct ribbon so that width is 0.1, the width does
// not vary with scalar values, and the width factor is 2.0.
vtkRibbonFilter::vtkRibbonFilter()
{
this->Width = 0.5;
this->Angle = 0.0;
this->VaryWidth = 0;
this->WidthFactor = 2.0;
this->DefaultNormal[0] = this->DefaultNormal[1] = 0.0;
this->DefaultNormal[2] = 1.0;
this->UseDefaultNormal = 0;
}
void vtkRibbonFilter::Execute()
{
int i, j;
vtkPoints *inPts;
vtkNormals *inNormals;
vtkPointData *pd, *outPD;
vtkCellArray *inLines;
int numPts = 0;
int numNewPts = 0;
vtkPoints *newPts;
vtkNormals *newNormals;
vtkCellArray *newStrips;
int npts, *pts;
float p[3], pNext[3];
float *n;
float s[3], sNext[3], sPrev[3], w[3];
double BevelAngle;
int deleteNormals=0, ptId;
vtkPolyData *input= this->GetInput();
vtkPolyData *output= this->GetOutput();
vtkScalars *inScalars=NULL;
float sFactor=1.0, range[2];
int ptOffset=0;
//
// Initialize
//
vtkDebugMacro(<<"Creating ribbon");
inPts=input->GetPoints();
inLines = input->GetLines();
if ( !inPts ||
(numNewPts=inPts->GetNumberOfPoints()*2) < 1 ||
!inLines || inLines->GetNumberOfCells() < 1 )
{
vtkErrorMacro(<< "No input data!");
return;
}
numPts = inPts->GetNumberOfPoints();
// copy scalars, vectors, tcoords. Normals may be computed here.
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyNormalsOff();
outPD->CopyAllocate(pd,numNewPts);
output->GetPointData()->CopyAllocate(pd,numNewPts);
if ( !(inNormals=pd->GetNormals()) || this->UseDefaultNormal )
{
vtkPolyLine *lineNormalGenerator = vtkPolyLine::New();
deleteNormals = 1;
inNormals = vtkNormals::New();
((vtkNormals *)inNormals)->Allocate(numPts);
if ( this->UseDefaultNormal )
{
for ( i=0; i < numPts; i++)
{
inNormals->SetNormal(i,this->DefaultNormal);
}
}
else
{
if ( !lineNormalGenerator->GenerateSlidingNormals(inPts,inLines,(vtkNormals*)inNormals) )
{
vtkErrorMacro(<< "No normals for line!\n");
inNormals->Delete();
return;
}
}
lineNormalGenerator->Delete();
}
//
// If varying width, get appropriate info.
//
if ( this->VaryWidth && (inScalars=pd->GetScalars()) )
{
inScalars->GetRange(range);
}
newPts = vtkPoints::New();
newPts->Allocate(numNewPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numNewPts);
newStrips = vtkCellArray::New();
newStrips->Allocate(newStrips->EstimateSize(1,numNewPts));
//
// Create pairs of points along the line that are later connected into a
// triangle strip.
//
for (inLines->InitTraversal(); inLines->GetNextCell(npts,pts); )
{
//
// Use "averaged" segment to create beveled effect. Watch out for first and
// last points.
//
for (j=0; j < npts; j++)
{
if ( j == 0 ) //first point
{
inPts->GetPoint(pts[0],p);
inPts->GetPoint(pts[1],pNext);
for (i=0; i<3; i++)
{
sNext[i] = pNext[i] - p[i];
sPrev[i] = sNext[i];
}
}
else if ( j == (npts-1) ) //last point
{
for (i=0; i<3; i++)
{
sPrev[i] = sNext[i];
p[i] = pNext[i];
}
}
else
{
for (i=0; i<3; i++)
{
p[i] = pNext[i];
}
inPts->GetPoint(pts[j+1],pNext);
for (i=0; i<3; i++)
{
sPrev[i] = sNext[i];
sNext[i] = pNext[i] - p[i];
}
}
n = inNormals->GetNormal(pts[j]);
if ( vtkMath::Normalize(sNext) == 0.0 )
{
vtkErrorMacro(<<"Coincident points!");
return;
}
for (i=0; i<3; i++)
{
s[i] = (sPrev[i] + sNext[i]) / 2.0; //average vector
}
vtkMath::Normalize(s);
if ( (BevelAngle = vtkMath::Dot(sNext,sPrev)) > 1.0 )
{
BevelAngle = 1.0;
}
if ( BevelAngle < -1.0 )
{
BevelAngle = -1.0;
}
BevelAngle = acos((double)BevelAngle) / 2.0; //(0->90 degrees)
if ( (BevelAngle = cos(BevelAngle)) == 0.0 )
{
BevelAngle = 1.0;
}
BevelAngle = this->Width / BevelAngle;
vtkMath::Cross(s,n,w);
if ( vtkMath::Normalize(w) == 0.0)
{
vtkErrorMacro(<<"Bad normal!");
return;
}
if ( inScalars )
{
sFactor = 1.0 + ((this->WidthFactor - 1.0) *
(inScalars->GetScalar(pts[j]) - range[0]) / (range[1]-range[0]));
}
for (i=0; i<3; i++)
{
s[i] = p[i] + w[i] * BevelAngle * sFactor;
}
ptId = newPts->InsertNextPoint(s);
newNormals->InsertNormal(ptId,n);
outPD->CopyData(pd,pts[j],ptId);
for (i=0; i<3; i++)
{
s[i] = p[i] - w[i] * BevelAngle * sFactor;
}
ptId = newPts->InsertNextPoint(s);
newNormals->InsertNormal(ptId,n);
outPD->CopyData(pd,pts[j],ptId);
}
//
// Generate the strip topology
//
newStrips->InsertNextCell(npts*2);
for (i=0; i < npts; i++)
{//order important for consistent normals
newStrips->InsertCellPoint(ptOffset+2*i+1);
newStrips->InsertCellPoint(ptOffset+2*i);
}
ptOffset += npts*2;
} //for this line
//
// Update ourselves
//
if ( deleteNormals )
{
inNormals->Delete();
}
output->SetPoints(newPts);
newPts->Delete();
output->SetStrips(newStrips);
newStrips->Delete();
outPD->SetNormals(newNormals);
newNormals->Delete();
output->Squeeze();
}
void vtkRibbonFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Width: " << this->Width << "\n";
os << indent << "Angle: " << this->Angle << "\n";
os << indent << "VaryWidth: " << (this->VaryWidth ? "On\n" : "Off\n");
os << indent << "Width Factor: " << this->WidthFactor << "\n";
os << indent << "Use Default Normal: " << this->UseDefaultNormal << "\n";
os << indent << "Default Normal: " << "( " <<
this->DefaultNormal[0] << ", " <<
this->DefaultNormal[1] << ", " <<
this->DefaultNormal[2] << " )\n";
}
<commit_msg>Copies cell data now<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRibbonFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkMath.h"
#include "vtkRibbonFilter.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
#include "vtkPolyLine.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkRibbonFilter* vtkRibbonFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkRibbonFilter");
if(ret)
{
return (vtkRibbonFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkRibbonFilter;
}
// Construct ribbon so that width is 0.1, the width does
// not vary with scalar values, and the width factor is 2.0.
vtkRibbonFilter::vtkRibbonFilter()
{
this->Width = 0.5;
this->Angle = 0.0;
this->VaryWidth = 0;
this->WidthFactor = 2.0;
this->DefaultNormal[0] = this->DefaultNormal[1] = 0.0;
this->DefaultNormal[2] = 1.0;
this->UseDefaultNormal = 0;
}
void vtkRibbonFilter::Execute()
{
int i, j;
vtkPoints *inPts;
vtkNormals *inNormals;
vtkPointData *pd, *outPD;
vtkCellData *cd, *outCD;
vtkCellArray *inLines;
int numPts = 0;
int numNewPts = 0;
vtkPoints *newPts;
vtkNormals *newNormals;
vtkCellArray *newStrips;
int npts, *pts;
float p[3], pNext[3];
float *n;
float s[3], sNext[3], sPrev[3], w[3];
double BevelAngle;
int deleteNormals=0, ptId;
vtkPolyData *input= this->GetInput();
vtkPolyData *output= this->GetOutput();
vtkScalars *inScalars=NULL;
float sFactor=1.0, range[2];
int ptOffset=0;
//
// Initialize
//
vtkDebugMacro(<<"Creating ribbon");
inPts=input->GetPoints();
inLines = input->GetLines();
if ( !inPts ||
(numNewPts=inPts->GetNumberOfPoints()*2) < 1 ||
!inLines || inLines->GetNumberOfCells() < 1 )
{
vtkErrorMacro(<< "No input data!");
return;
}
numPts = inPts->GetNumberOfPoints();
// copy point scalars, vectors, tcoords. Normals may be computed here.
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyNormalsOff();
outPD->CopyAllocate(pd,numNewPts);
// copy point scalars, vectors, tcoords.
cd = input->GetCellData();
outCD = output->GetCellData();
outCD->CopyNormalsOff();
outCD->CopyAllocate(cd, inLines->GetNumberOfCells());
int inCellId, outCellId;
if ( !(inNormals=pd->GetNormals()) || this->UseDefaultNormal )
{
vtkPolyLine *lineNormalGenerator = vtkPolyLine::New();
deleteNormals = 1;
inNormals = vtkNormals::New();
((vtkNormals *)inNormals)->Allocate(numPts);
if ( this->UseDefaultNormal )
{
for ( i=0; i < numPts; i++)
{
inNormals->SetNormal(i,this->DefaultNormal);
}
}
else
{
if ( !lineNormalGenerator->GenerateSlidingNormals(inPts,inLines,(vtkNormals*)inNormals) )
{
vtkErrorMacro(<< "No normals for line!\n");
inNormals->Delete();
return;
}
}
lineNormalGenerator->Delete();
}
//
// If varying width, get appropriate info.
//
if ( this->VaryWidth && (inScalars=pd->GetScalars()) )
{
inScalars->GetRange(range);
}
newPts = vtkPoints::New();
newPts->Allocate(numNewPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numNewPts);
newStrips = vtkCellArray::New();
newStrips->Allocate(newStrips->EstimateSize(1,numNewPts));
//
// Create pairs of points along the line that are later connected into a
// triangle strip.
//
inCellId = 0;
for (inLines->InitTraversal(); inLines->GetNextCell(npts,pts); ++inCellId)
{
//
// Use "averaged" segment to create beveled effect. Watch out for first and
// last points.
//
for (j=0; j < npts; j++)
{
if ( j == 0 ) //first point
{
inPts->GetPoint(pts[0],p);
inPts->GetPoint(pts[1],pNext);
for (i=0; i<3; i++)
{
sNext[i] = pNext[i] - p[i];
sPrev[i] = sNext[i];
}
}
else if ( j == (npts-1) ) //last point
{
for (i=0; i<3; i++)
{
sPrev[i] = sNext[i];
p[i] = pNext[i];
}
}
else
{
for (i=0; i<3; i++)
{
p[i] = pNext[i];
}
inPts->GetPoint(pts[j+1],pNext);
for (i=0; i<3; i++)
{
sPrev[i] = sNext[i];
sNext[i] = pNext[i] - p[i];
}
}
n = inNormals->GetNormal(pts[j]);
if ( vtkMath::Normalize(sNext) == 0.0 )
{
vtkErrorMacro(<<"Coincident points!");
return;
}
for (i=0; i<3; i++)
{
s[i] = (sPrev[i] + sNext[i]) / 2.0; //average vector
}
vtkMath::Normalize(s);
if ( (BevelAngle = vtkMath::Dot(sNext,sPrev)) > 1.0 )
{
BevelAngle = 1.0;
}
if ( BevelAngle < -1.0 )
{
BevelAngle = -1.0;
}
BevelAngle = acos((double)BevelAngle) / 2.0; //(0->90 degrees)
if ( (BevelAngle = cos(BevelAngle)) == 0.0 )
{
BevelAngle = 1.0;
}
BevelAngle = this->Width / BevelAngle;
vtkMath::Cross(s,n,w);
if ( vtkMath::Normalize(w) == 0.0)
{
vtkErrorMacro(<<"Bad normal!");
return;
}
if ( inScalars )
{
sFactor = 1.0 + ((this->WidthFactor - 1.0) *
(inScalars->GetScalar(pts[j]) - range[0]) / (range[1]-range[0]));
}
for (i=0; i<3; i++)
{
s[i] = p[i] + w[i] * BevelAngle * sFactor;
}
ptId = newPts->InsertNextPoint(s);
newNormals->InsertNormal(ptId,n);
outPD->CopyData(pd,pts[j],ptId);
for (i=0; i<3; i++)
{
s[i] = p[i] - w[i] * BevelAngle * sFactor;
}
ptId = newPts->InsertNextPoint(s);
newNormals->InsertNormal(ptId,n);
outPD->CopyData(pd,pts[j],ptId);
}
//
// Generate the strip topology
//
outCellId = newStrips->InsertNextCell(npts*2);
for (i=0; i < npts; i++)
{//order important for consistent normals
newStrips->InsertCellPoint(ptOffset+2*i+1);
newStrips->InsertCellPoint(ptOffset+2*i);
}
outCD->CopyData(cd,inCellId,outCellId);
ptOffset += npts*2;
} //for this line
//
// Update ourselves
//
if ( deleteNormals )
{
inNormals->Delete();
}
output->SetPoints(newPts);
newPts->Delete();
output->SetStrips(newStrips);
newStrips->Delete();
outPD->SetNormals(newNormals);
newNormals->Delete();
output->Squeeze();
}
void vtkRibbonFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Width: " << this->Width << "\n";
os << indent << "Angle: " << this->Angle << "\n";
os << indent << "VaryWidth: " << (this->VaryWidth ? "On\n" : "Off\n");
os << indent << "Width Factor: " << this->WidthFactor << "\n";
os << indent << "Use Default Normal: " << this->UseDefaultNormal << "\n";
os << indent << "Default Normal: " << "( " <<
this->DefaultNormal[0] << ", " <<
this->DefaultNormal[1] << ", " <<
this->DefaultNormal[2] << " )\n";
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Program: Wake Forest University - Virginia Tech CTC Software
Id: $Id$
Language: C++
*******************************************************************************/
// command line app to subtract tagged stool from images
#include <iostream>
#include <cstdlib>
using namespace std;
// ITK includes
#include <itkImageSeriesWriter.h>
#include <itkNumericSeriesFileNames.h>
#include <itksys/SystemTools.hxx>
#include <itkGDCMImageIO.h>
#include <itkImageRegionIterator.h>
#include <itkImageRegionConstIterator.h>
#include <itkMetaDataObject.h>
#include <itkMetaDataDictionary.h>
// CTC includes
#include "ctcConfigure.h"
#include "ctcCTCImage.h"
#include "ctcCTCImageReader.h"
#include "ctcSegmentColonWithContrastFilter.h"
#include "vul_arg.h"
int main(int argc, char ** argv)
{
// parse args
vul_arg<char const*> infile(0, "Input DICOM directory");
vul_arg<char const*> outfile(0, "Output DICOM directory");
vul_arg<int> replaceval("-r",
"Replacement HU value for tagged regions (default -900)",
-900);
vul_arg_parse(argc, argv);
// test if outfile exists, if so bail out
if(itksys::SystemTools::FileExists(outfile()))
{
if(itksys::SystemTools::FileIsDirectory(outfile()))
{
cerr << "Error: directory " << outfile() << " exists. Halting." << endl;
}
else
{
cerr << "Error: file " << outfile() << " exists. Halting." << endl;
}
return EXIT_FAILURE;
}
// read in the DICOM series
ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New();
reader->SetDirectory(string(infile()));
try
{
reader->Update();
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
// segment air + constrast
clog << "Starting Segment";
ctc::SegmentColonWithContrastFilter::Pointer filter =
ctc::SegmentColonWithContrastFilter::New();
filter->SetInput( reader->GetOutput() );
filter->Update();
clog << " Done Segmenting." << endl;
// loop through the voxels, testing for threshold and lumen test
// replace image values with air
clog << "Starting Mask";
int replace = replaceval();
typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType;
typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType;
InputIteratorType it1(reader->GetOutput(),
reader->GetOutput()->GetRequestedRegion());
BinaryIteratorType it2(filter->GetOutput(),
filter->GetOutput()->GetRequestedRegion());
for( it1.GoToBegin(), it2.GoToBegin();
!it1.IsAtEnd() || !it2.IsAtEnd();
++it1, ++it2)
{
if( (it2.Get() == 255) && (it1.Get() > -800) )
{
it1.Set(replace);
}
}
clog << " Done Masking" << endl;
// write out modified image
typedef itk::Image< short, 2 > Image2DType;
typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( reader->GetOutput() );
// modify series number
ctc::CTCImageReader::DictionaryArrayRawPointer dictarray =
reader->GetMetaDataDictionaryArray();
std::string SeriesNumberTag = "0020|0011";
std::string SeriesNumberValue;
for(int slice = 0;
slice < dictarray->size();
slice++)
{
ctc::CTCImageReader::DictionaryRawPointer dict =
(*(reader->GetMetaDataDictionaryArray()))[slice];
itk::ExposeMetaData<std::string>(*dict,
SeriesNumberTag,
SeriesNumberValue);
SeriesNumberValue = "90";
itk::EncapsulateMetaData<std::string>(*dict,
SeriesNumberTag,
SeriesNumberValue);
}
writer->SetMetaDataDictionaryArray( dictarray );
itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New();
writer->SetImageIO( dicomIO );
typedef itk::NumericSeriesFileNames NameGeneratorType;
NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();
if( !itksys::SystemTools::MakeDirectory(outfile()) )
{
cerr << "Error: could not create output directory" << endl;
return EXIT_FAILURE;
}
std::string format = outfile();
format += "/%03d.dcm";
nameGenerator->SetSeriesFormat( format.c_str() );
ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput();
ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion();
ctc::CTCImageType::IndexType start = region.GetIndex();
ctc::CTCImageType::SizeType size = region.GetSize();
const unsigned int firstSlice = start[2];
const unsigned int lastSlice = start[2] + size[2] - 1;
nameGenerator->SetStartIndex( firstSlice );
nameGenerator->SetEndIndex( lastSlice );
nameGenerator->SetIncrementIndex( 1 );
writer->SetFileNames( nameGenerator->GetFileNames() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
cerr << "ExceptionObject caught !" << endl;
cerr << err << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Modfication to DICOM tag output for Tag Subtraction requested by Don Gage<commit_after>/*******************************************************************************
Program: Wake Forest University - Virginia Tech CTC Software
Id: $Id$
Language: C++
*******************************************************************************/
// command line app to subtract tagged stool from images
#include <iostream>
#include <cstdlib>
using namespace std;
// ITK includes
#include <itkImageSeriesWriter.h>
#include <itkNumericSeriesFileNames.h>
#include <itksys/SystemTools.hxx>
#include <itkGDCMImageIO.h>
#include <itkImageRegionIterator.h>
#include <itkImageRegionConstIterator.h>
#include <itkMetaDataObject.h>
#include <itkMetaDataDictionary.h>
// CTC includes
#include "ctcConfigure.h"
#include "ctcCTCImage.h"
#include "ctcCTCImageReader.h"
#include "ctcSegmentColonWithContrastFilter.h"
#include "vul_arg.h"
int main(int argc, char ** argv)
{
// parse args
vul_arg<char const*> infile(0, "Input DICOM directory");
vul_arg<char const*> outfile(0, "Output DICOM directory");
vul_arg<int> replaceval("-r",
"Replacement HU value for tagged regions (default -900)",
-900);
vul_arg_parse(argc, argv);
// test if outfile exists, if so bail out
if(itksys::SystemTools::FileExists(outfile()))
{
if(itksys::SystemTools::FileIsDirectory(outfile()))
{
cerr << "Error: directory " << outfile() << " exists. Halting." << endl;
}
else
{
cerr << "Error: file " << outfile() << " exists. Halting." << endl;
}
return EXIT_FAILURE;
}
// read in the DICOM series
ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New();
reader->SetDirectory(string(infile()));
try
{
reader->Update();
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
// store the orginal DICOM meta-data from first slice
std::string StudyInstanceUIDTag = "0020|000D";
std::string StudyInstanceUIDValue;
std::string SeriesInstanceUIDTag = "0020|000E";
std::string SeriesInstanceUIDValue;
ctc::CTCImageReader::DictionaryRawPointer dict0 =
(*(reader->GetMetaDataDictionaryArray()))[0];
itk::ExposeMetaData<std::string>(*dict0,
StudyInstanceUIDTag,
StudyInstanceUIDValue);
itk::ExposeMetaData<std::string>(*dict0,
SeriesInstanceUIDTag,
SeriesInstanceUIDValue);
// segment air + constrast
clog << "Starting Segment";
ctc::SegmentColonWithContrastFilter::Pointer filter =
ctc::SegmentColonWithContrastFilter::New();
filter->SetInput( reader->GetOutput() );
filter->Update();
clog << " Done Segmenting." << endl;
// loop through the voxels, testing for threshold and lumen test
// replace image values with air
clog << "Starting Mask";
int replace = replaceval();
typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType;
typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType;
InputIteratorType it1(reader->GetOutput(),
reader->GetOutput()->GetRequestedRegion());
BinaryIteratorType it2(filter->GetOutput(),
filter->GetOutput()->GetRequestedRegion());
for( it1.GoToBegin(), it2.GoToBegin();
!it1.IsAtEnd() || !it2.IsAtEnd();
++it1, ++it2)
{
if( (it2.Get() == 255) && (it1.Get() > -800) )
{
it1.Set(replace);
}
}
clog << " Done Masking" << endl;
// write out modified image
typedef itk::Image< short, 2 > Image2DType;
typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( reader->GetOutput() );
// modify series number, use old StudyInstanceUID,
// alter old SeriesInstanceUId, and add Series description
ctc::CTCImageReader::DictionaryArrayRawPointer dictarray =
reader->GetMetaDataDictionaryArray();
std::string SeriesNumberTag = "0020|0011";
std::string SeriesNumberValue = "90";
std::string SeriesDescriptionTag = "0008|103E";
std::string SeriesDescriptionValue = "Derived from SeriesInstance UID " + SeriesInstanceUIDValue;
for(int slice = 0;
slice < dictarray->size();
slice++)
{
ctc::CTCImageReader::DictionaryRawPointer dict =
(*dictarray)[slice];
itk::ExposeMetaData<std::string>(*dict,
SeriesNumberTag,
SeriesNumberValue);
itk::EncapsulateMetaData<std::string>(*dict,
SeriesNumberTag,
SeriesNumberValue);
itk::EncapsulateMetaData<std::string>(*dict,
StudyInstanceUIDTag,
StudyInstanceUIDValue);
itk::EncapsulateMetaData<std::string>(*dict,
SeriesInstanceUIDTag,
SeriesInstanceUIDValue+"1");
itk::EncapsulateMetaData<std::string>(*dict,
StudyInstanceUIDTag,
StudyInstanceUIDValue);
}
writer->SetMetaDataDictionaryArray( dictarray );
itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New();
writer->SetImageIO( dicomIO );
typedef itk::NumericSeriesFileNames NameGeneratorType;
NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();
if( !itksys::SystemTools::MakeDirectory(outfile()) )
{
cerr << "Error: could not create output directory" << endl;
return EXIT_FAILURE;
}
std::string format = outfile();
format += "/%03d.dcm";
nameGenerator->SetSeriesFormat( format.c_str() );
ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput();
ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion();
ctc::CTCImageType::IndexType start = region.GetIndex();
ctc::CTCImageType::SizeType size = region.GetSize();
const unsigned int firstSlice = start[2];
const unsigned int lastSlice = start[2] + size[2] - 1;
nameGenerator->SetStartIndex( firstSlice );
nameGenerator->SetEndIndex( lastSlice );
nameGenerator->SetIncrementIndex( 1 );
writer->SetFileNames( nameGenerator->GetFileNames() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
cerr << "ExceptionObject caught !" << endl;
cerr << err << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkProStarReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkProStarReader.h"
#include "vtkUnstructuredGrid.h"
#include "vtkErrorCode.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include <ctype.h>
#include <string.h>
#include <sstream>
#include <vtkstd/string>
#include <vtkstd/map>
#include <vtkstd/vector>
#include <vtkstd/utility>
vtkStandardNewMacro(vtkProStarReader);
// Internal Classes/Structures
struct vtkProStarReader::idMapping : public vtkstd::map<vtkIdType, vtkIdType>
{};
//----------------------------------------------------------------------------
vtkProStarReader::vtkProStarReader()
{
this->FileName = NULL;
this->ScaleFactor = 1;
this->SetNumberOfInputPorts(0);
}
//----------------------------------------------------------------------------
vtkProStarReader::~vtkProStarReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
}
//----------------------------------------------------------------------------
int vtkProStarReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
if (!this->FileName)
{
vtkErrorMacro("FileName has to be specified!");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the output
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (this->FileName)
{
idMapping mapPointId; // inverse mapping (STAR-CD pointId -> index)
if (this->ReadVrtFile(output, mapPointId))
{
this->ReadCelFile(output, mapPointId);
}
}
return 1;
}
//----------------------------------------------------------------------------
void vtkProStarReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << endl;
}
//----------------------------------------------------------------------------
int vtkProStarReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *vtkNotUsed(outputVector))
{
if (!this->FileName)
{
vtkErrorMacro("FileName has to be specified!");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
FILE* vtkProStarReader::OpenFile(const char *ext)
{
vtkstd::string fullName = this->FileName;
const char *dot = strrchr(this->FileName, '.');
if
(
dot != NULL
&& (
strcmp(dot, ".cel") == 0
|| strcmp(dot, ".vrt") == 0
|| strcmp(dot, ".inp") == 0
)
)
{
fullName.resize(dot - this->FileName);
}
fullName += ext;
FILE *in = fopen(fullName.c_str(), "r");
if (in == NULL)
{
vtkErrorMacro(<<"Error opening file: " << fullName);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
}
return in;
}
//
// read in the points from the .vrt file
/*---------------------------------------------------------------------------*\
Line 1:
PROSTAR_VERTEX [newline]
Line 2:
<version> 0 0 0 0 0 0 0 [newline]
Body:
<vertexId> <x> <y> <z> [newline]
\*---------------------------------------------------------------------------*/
bool vtkProStarReader::ReadVrtFile(vtkUnstructuredGrid *output,
idMapping& mapPointId)
{
mapPointId.clear();
FILE *in = this->OpenFile(".vrt");
if (in == NULL)
{
return false;
}
const int MAX_LINE = 1024;
char rawLine[MAX_LINE];
int lineLabel, errorCount = 0;
if (
fgets(rawLine, MAX_LINE, in) != NULL
&& strncmp(rawLine, "PROSTAR_VERTEX", 14) == 0
&& fgets(rawLine, MAX_LINE, in) != NULL
&& sscanf(rawLine, "%d", &lineLabel) == 1
&& lineLabel >= 4000
)
{
vtkDebugMacro(<<"Got PROSTAR_VERTEX header");
}
else
{
vtkErrorMacro(<<"Error reading header for PROSTAR_VERTEX file");
++errorCount;
}
vtkPoints *points = vtkPoints::New();
// don't know the number of points a priori -- just pick some number
points->Allocate(10000,20000);
int lineNr = 2;
float xyz[3];
vtkIdType nodeCount = 0;
while (!errorCount && fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
if (sscanf(rawLine, "%d %f %f %f", &lineLabel, xyz, xyz+1, xyz+2) == 4)
{
xyz[0] *= this->ScaleFactor;
xyz[1] *= this->ScaleFactor;
xyz[2] *= this->ScaleFactor;
points->InsertNextPoint(xyz);
vtkIdType nodeId = lineLabel;
mapPointId.insert(vtkstd::make_pair(nodeId, nodeCount));
++nodeCount;
}
else
{
vtkErrorMacro(<<"Error reading point at line " << lineNr);
++errorCount;
}
}
points->Squeeze();
output->SetPoints(points);
points->Delete();
vtkDebugMacro(<<"Read points: " << lineNr << " errors: " << errorCount);
fclose(in);
return errorCount == 0;
}
//
// read in the cells from the .cel file
/*---------------------------------------------------------------------------*\
Line 1:
PROSTAR_CELL [newline]
Line 2:
<version> 0 0 0 0 0 0 0 [newline]
Body:
<cellId> <shapeId> <nLabels> <cellTableId> <typeId> [newline]
<cellId> <int1> .. <int8>
<cellId> <int9> .. <int16>
with shapeId:
* 1 = point
* 2 = line
* 3 = shell
* 11 = hexa
* 12 = prism
* 13 = tetra
* 14 = pyramid
* 255 = polyhedron
with typeId
* 1 = fluid
* 2 = solid
* 3 = baffle
* 4 = shell
* 5 = line
* 6 = point
For primitive cell shapes, the number of vertices will never exceed 8 (hexa)
and corresponds to <nLabels>.
For polyhedral, <nLabels> includes an index table comprising beg/end pairs
for each cell face.
\*---------------------------------------------------------------------------*/
bool vtkProStarReader::ReadCelFile(vtkUnstructuredGrid *output,
const idMapping& mapPointId)
{
FILE *in = this->OpenFile(".cel");
if (in == NULL)
{
return false;
}
const int MAX_LINE = 1024;
char rawLine[MAX_LINE];
int lineLabel, errorCount = 0;
if (
fgets(rawLine, MAX_LINE, in) != NULL
&& strncmp(rawLine, "PROSTAR_CELL", 12) == 0
&& fgets(rawLine, MAX_LINE, in) != NULL
&& sscanf(rawLine, "%d", &lineLabel) == 1
&& lineLabel >= 4000
)
{
vtkDebugMacro(<<"Got PROSTAR_CELL header");
}
else
{
vtkErrorMacro(<<"Error reading header for PROSTAR_CELL file");
++errorCount;
}
// don't know the number of cells a priori -- just pick some number
output->Allocate(10000,20000);
// add a cellTableId array
vtkIntArray *cellTableId = vtkIntArray::New();
cellTableId->Allocate(10000,20000);
cellTableId->SetName("cellTableId");
int shapeId, nLabels, tableId, typeId;
vtkstd::vector<vtkIdType> starLabels;
starLabels.reserve(256);
// face-stream for a polyhedral cell
// [numFace0Pts, id1, id2, id3, numFace1Pts, id1, id2, id3, ...]
vtkstd::vector<vtkIdType> faceStream;
faceStream.reserve(256);
// use string buffer for easier parsing
vtkstd::istringstream strbuf;
int lineNr = 2;
while (!errorCount && fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
if (sscanf(rawLine, "%d %d %d %d %d", &lineLabel, &shapeId, &nLabels, &tableId, &typeId) == 5)
{
starLabels.clear();
starLabels.reserve(nLabels);
// read indices - max 8 per line
for (int index = 0; !errorCount && index < nLabels; ++index)
{
int vrtId;
if ((index % 8) == 0)
{
if (fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
strbuf.clear();
strbuf.str(rawLine);
strbuf >> lineLabel;
}
else
{
vtkErrorMacro(<<"Error reading PROSTAR_CELL file at line "<<lineNr);
++errorCount;
}
}
strbuf >> vrtId;
starLabels.push_back(vrtId);
}
// special treatment for polyhedra
if (shapeId == starcdPoly)
{
const vtkIdType nFaces = starLabels[0] - 1;
// build face-stream
// [numFace0Pts, id1, id2, id3, numFace1Pts, id1, id2, id3, ...]
// point Ids are global
faceStream.clear();
faceStream.reserve(nLabels);
for (vtkIdType faceI = 0; faceI < nFaces; ++faceI)
{
// traverse beg/end indices
const int beg = starLabels[faceI];
const int end = starLabels[faceI+1];
// number of points for this face
faceStream.push_back(end - beg);
for (int idxI = beg; idxI < end; ++idxI)
{
// map orig vertex id -> point label
faceStream.push_back(mapPointId.find(starLabels[idxI])->second);
}
}
output->InsertNextCell(VTK_POLYHEDRON, nFaces, &(faceStream[0]));
cellTableId->InsertNextValue(tableId);
}
else
{
// map orig vertex id -> point label
for (int i=0; i < nLabels; ++i)
{
starLabels[i] = mapPointId.find(starLabels[i])->second;
}
switch (shapeId)
{
// 0-D
case starcdPoint:
output->InsertNextCell(VTK_VERTEX, 1, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
// 1-D
case starcdLine:
output->InsertNextCell(VTK_LINE, 2, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
// 2-D
case starcdShell:
switch (nLabels)
{
case 3:
output->InsertNextCell(VTK_TRIANGLE, 3, &(starLabels[0]));
break;
case 4:
output->InsertNextCell(VTK_QUAD, 4, &(starLabels[0]));
break;
default:
output->InsertNextCell(VTK_POLYGON, nLabels, &(starLabels[0]));
break;
}
cellTableId->InsertNextValue(tableId);
break;
// 3-D
case starcdHex:
output->InsertNextCell(VTK_HEXAHEDRON, 8, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdPrism:
// the VTK definition has outwards normals for the triangles!!
vtkstd::swap(starLabels[1], starLabels[2]);
vtkstd::swap(starLabels[4], starLabels[5]);
output->InsertNextCell(VTK_WEDGE, 6, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdTet:
output->InsertNextCell(VTK_TETRA, 4, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdPyr:
output->InsertNextCell(VTK_PYRAMID, 5, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
default: break;
}
}
}
else
{
vtkErrorMacro(<<"Error reading cell at line " << lineNr);
++errorCount;
}
}
output->Squeeze();
cellTableId->Squeeze();
// now add the cellTableId array
output->GetCellData()->AddArray(cellTableId);
if (!output->GetCellData()->GetScalars())
{
output->GetCellData()->SetScalars(cellTableId);
}
cellTableId->Delete();
vtkDebugMacro(<<"Read cells: " << lineNr << " errors: " << errorCount);
fclose(in);
return errorCount == 0;
}
<commit_msg>Forgot to print out ScaleFactor ivar in PrintSelf()<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkProStarReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkProStarReader.h"
#include "vtkUnstructuredGrid.h"
#include "vtkErrorCode.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include <ctype.h>
#include <string.h>
#include <sstream>
#include <vtkstd/string>
#include <vtkstd/map>
#include <vtkstd/vector>
#include <vtkstd/utility>
vtkStandardNewMacro(vtkProStarReader);
// Internal Classes/Structures
struct vtkProStarReader::idMapping : public vtkstd::map<vtkIdType, vtkIdType>
{};
//----------------------------------------------------------------------------
vtkProStarReader::vtkProStarReader()
{
this->FileName = NULL;
this->ScaleFactor = 1;
this->SetNumberOfInputPorts(0);
}
//----------------------------------------------------------------------------
vtkProStarReader::~vtkProStarReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
}
//----------------------------------------------------------------------------
int vtkProStarReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
if (!this->FileName)
{
vtkErrorMacro("FileName has to be specified!");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the output
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (this->FileName)
{
idMapping mapPointId; // inverse mapping (STAR-CD pointId -> index)
if (this->ReadVrtFile(output, mapPointId))
{
this->ReadCelFile(output, mapPointId);
}
}
return 1;
}
//----------------------------------------------------------------------------
void vtkProStarReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << endl;
os << indent << "ScaleFactor: " << this->ScaleFactor << endl;
}
//----------------------------------------------------------------------------
int vtkProStarReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *vtkNotUsed(outputVector))
{
if (!this->FileName)
{
vtkErrorMacro("FileName has to be specified!");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
FILE* vtkProStarReader::OpenFile(const char *ext)
{
vtkstd::string fullName = this->FileName;
const char *dot = strrchr(this->FileName, '.');
if
(
dot != NULL
&& (
strcmp(dot, ".cel") == 0
|| strcmp(dot, ".vrt") == 0
|| strcmp(dot, ".inp") == 0
)
)
{
fullName.resize(dot - this->FileName);
}
fullName += ext;
FILE *in = fopen(fullName.c_str(), "r");
if (in == NULL)
{
vtkErrorMacro(<<"Error opening file: " << fullName);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
}
return in;
}
//
// read in the points from the .vrt file
/*---------------------------------------------------------------------------*\
Line 1:
PROSTAR_VERTEX [newline]
Line 2:
<version> 0 0 0 0 0 0 0 [newline]
Body:
<vertexId> <x> <y> <z> [newline]
\*---------------------------------------------------------------------------*/
bool vtkProStarReader::ReadVrtFile(vtkUnstructuredGrid *output,
idMapping& mapPointId)
{
mapPointId.clear();
FILE *in = this->OpenFile(".vrt");
if (in == NULL)
{
return false;
}
const int MAX_LINE = 1024;
char rawLine[MAX_LINE];
int lineLabel, errorCount = 0;
if (
fgets(rawLine, MAX_LINE, in) != NULL
&& strncmp(rawLine, "PROSTAR_VERTEX", 14) == 0
&& fgets(rawLine, MAX_LINE, in) != NULL
&& sscanf(rawLine, "%d", &lineLabel) == 1
&& lineLabel >= 4000
)
{
vtkDebugMacro(<<"Got PROSTAR_VERTEX header");
}
else
{
vtkErrorMacro(<<"Error reading header for PROSTAR_VERTEX file");
++errorCount;
}
vtkPoints *points = vtkPoints::New();
// don't know the number of points a priori -- just pick some number
points->Allocate(10000,20000);
int lineNr = 2;
float xyz[3];
vtkIdType nodeCount = 0;
while (!errorCount && fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
if (sscanf(rawLine, "%d %f %f %f", &lineLabel, xyz, xyz+1, xyz+2) == 4)
{
xyz[0] *= this->ScaleFactor;
xyz[1] *= this->ScaleFactor;
xyz[2] *= this->ScaleFactor;
points->InsertNextPoint(xyz);
vtkIdType nodeId = lineLabel;
mapPointId.insert(vtkstd::make_pair(nodeId, nodeCount));
++nodeCount;
}
else
{
vtkErrorMacro(<<"Error reading point at line " << lineNr);
++errorCount;
}
}
points->Squeeze();
output->SetPoints(points);
points->Delete();
vtkDebugMacro(<<"Read points: " << lineNr << " errors: " << errorCount);
fclose(in);
return errorCount == 0;
}
//
// read in the cells from the .cel file
/*---------------------------------------------------------------------------*\
Line 1:
PROSTAR_CELL [newline]
Line 2:
<version> 0 0 0 0 0 0 0 [newline]
Body:
<cellId> <shapeId> <nLabels> <cellTableId> <typeId> [newline]
<cellId> <int1> .. <int8>
<cellId> <int9> .. <int16>
with shapeId:
* 1 = point
* 2 = line
* 3 = shell
* 11 = hexa
* 12 = prism
* 13 = tetra
* 14 = pyramid
* 255 = polyhedron
with typeId
* 1 = fluid
* 2 = solid
* 3 = baffle
* 4 = shell
* 5 = line
* 6 = point
For primitive cell shapes, the number of vertices will never exceed 8 (hexa)
and corresponds to <nLabels>.
For polyhedral, <nLabels> includes an index table comprising beg/end pairs
for each cell face.
\*---------------------------------------------------------------------------*/
bool vtkProStarReader::ReadCelFile(vtkUnstructuredGrid *output,
const idMapping& mapPointId)
{
FILE *in = this->OpenFile(".cel");
if (in == NULL)
{
return false;
}
const int MAX_LINE = 1024;
char rawLine[MAX_LINE];
int lineLabel, errorCount = 0;
if (
fgets(rawLine, MAX_LINE, in) != NULL
&& strncmp(rawLine, "PROSTAR_CELL", 12) == 0
&& fgets(rawLine, MAX_LINE, in) != NULL
&& sscanf(rawLine, "%d", &lineLabel) == 1
&& lineLabel >= 4000
)
{
vtkDebugMacro(<<"Got PROSTAR_CELL header");
}
else
{
vtkErrorMacro(<<"Error reading header for PROSTAR_CELL file");
++errorCount;
}
// don't know the number of cells a priori -- just pick some number
output->Allocate(10000,20000);
// add a cellTableId array
vtkIntArray *cellTableId = vtkIntArray::New();
cellTableId->Allocate(10000,20000);
cellTableId->SetName("cellTableId");
int shapeId, nLabels, tableId, typeId;
vtkstd::vector<vtkIdType> starLabels;
starLabels.reserve(256);
// face-stream for a polyhedral cell
// [numFace0Pts, id1, id2, id3, numFace1Pts, id1, id2, id3, ...]
vtkstd::vector<vtkIdType> faceStream;
faceStream.reserve(256);
// use string buffer for easier parsing
vtkstd::istringstream strbuf;
int lineNr = 2;
while (!errorCount && fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
if (sscanf(rawLine, "%d %d %d %d %d", &lineLabel, &shapeId, &nLabels, &tableId, &typeId) == 5)
{
starLabels.clear();
starLabels.reserve(nLabels);
// read indices - max 8 per line
for (int index = 0; !errorCount && index < nLabels; ++index)
{
int vrtId;
if ((index % 8) == 0)
{
if (fgets(rawLine, MAX_LINE, in) != NULL)
{
++lineNr;
strbuf.clear();
strbuf.str(rawLine);
strbuf >> lineLabel;
}
else
{
vtkErrorMacro(<<"Error reading PROSTAR_CELL file at line "<<lineNr);
++errorCount;
}
}
strbuf >> vrtId;
starLabels.push_back(vrtId);
}
// special treatment for polyhedra
if (shapeId == starcdPoly)
{
const vtkIdType nFaces = starLabels[0] - 1;
// build face-stream
// [numFace0Pts, id1, id2, id3, numFace1Pts, id1, id2, id3, ...]
// point Ids are global
faceStream.clear();
faceStream.reserve(nLabels);
for (vtkIdType faceI = 0; faceI < nFaces; ++faceI)
{
// traverse beg/end indices
const int beg = starLabels[faceI];
const int end = starLabels[faceI+1];
// number of points for this face
faceStream.push_back(end - beg);
for (int idxI = beg; idxI < end; ++idxI)
{
// map orig vertex id -> point label
faceStream.push_back(mapPointId.find(starLabels[idxI])->second);
}
}
output->InsertNextCell(VTK_POLYHEDRON, nFaces, &(faceStream[0]));
cellTableId->InsertNextValue(tableId);
}
else
{
// map orig vertex id -> point label
for (int i=0; i < nLabels; ++i)
{
starLabels[i] = mapPointId.find(starLabels[i])->second;
}
switch (shapeId)
{
// 0-D
case starcdPoint:
output->InsertNextCell(VTK_VERTEX, 1, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
// 1-D
case starcdLine:
output->InsertNextCell(VTK_LINE, 2, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
// 2-D
case starcdShell:
switch (nLabels)
{
case 3:
output->InsertNextCell(VTK_TRIANGLE, 3, &(starLabels[0]));
break;
case 4:
output->InsertNextCell(VTK_QUAD, 4, &(starLabels[0]));
break;
default:
output->InsertNextCell(VTK_POLYGON, nLabels, &(starLabels[0]));
break;
}
cellTableId->InsertNextValue(tableId);
break;
// 3-D
case starcdHex:
output->InsertNextCell(VTK_HEXAHEDRON, 8, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdPrism:
// the VTK definition has outwards normals for the triangles!!
vtkstd::swap(starLabels[1], starLabels[2]);
vtkstd::swap(starLabels[4], starLabels[5]);
output->InsertNextCell(VTK_WEDGE, 6, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdTet:
output->InsertNextCell(VTK_TETRA, 4, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
case starcdPyr:
output->InsertNextCell(VTK_PYRAMID, 5, &(starLabels[0]));
cellTableId->InsertNextValue(tableId);
break;
default: break;
}
}
}
else
{
vtkErrorMacro(<<"Error reading cell at line " << lineNr);
++errorCount;
}
}
output->Squeeze();
cellTableId->Squeeze();
// now add the cellTableId array
output->GetCellData()->AddArray(cellTableId);
if (!output->GetCellData()->GetScalars())
{
output->GetCellData()->SetScalars(cellTableId);
}
cellTableId->Delete();
vtkDebugMacro(<<"Read cells: " << lineNr << " errors: " << errorCount);
fclose(in);
return errorCount == 0;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// ļVerFile.cpp
// ߣSong Baoming,2016
// ; resource.h *.rc ļӱ汾 CVerFile ķļ
// Licensehttps://github.com/songbaoming/IncBuildVer/blob/master/LICENSE
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "VerFile.h"
#define MAJOR 0
#define MINOR 1
#define REVISION 2
#define BUILD 3
CVerFile::CVerFile()
: m_dwOffset(0)
, m_dwCode(0)
, m_hFile(nullptr)
, m_pContent(nullptr)
{
}
CVerFile::~CVerFile()
{
if (m_pContent)
delete[] m_pContent;
if (m_hFile && m_hFile != INVALID_HANDLE_VALUE)
CloseHandle(m_hFile);
}
// ָļб汾źֵһ
bool CVerFile::IncBuildVer(LPCTSTR lpszDirPath)
{
TCHAR szFilePath[MAX_PATH];
_stprintf_s(szFilePath, TEXT("%sresource.h"), lpszDirPath);
// resource.h
if (!IncResourceVer(szFilePath))
return false;
// .rcļ·
auto pos = _tcsrchr(lpszDirPath, TEXT('\\'));
if (!pos)
return false;
while (pos != lpszDirPath && *(pos - 1) != TEXT('\\'))
--pos;
if (pos == lpszDirPath)
return false;
_stprintf_s(szFilePath, TEXT("%s%s"), lpszDirPath, pos);
szFilePath[_tcslen(szFilePath) - 1] = 0;
_tcscat_s(szFilePath, TEXT(".rc"));
// .rc
if (!IncRCFileVer(szFilePath))
return false;
return true;
}
bool CVerFile::IncResourceVer(LPCTSTR lpszFilePath)
{
static LPCTSTR pszVerSign[] = {
TEXT("MAJOR_VER_NUM"),
TEXT("MINOR_VER_NUM"),
TEXT("REVISION_VER_NUM"),
TEXT("BUILD_VER_NUM"),
NULL
};
bool bRes = true;
// ȡļ
if (!GetFileContent(lpszFilePath))
return false;
auto pszBegin = m_pContent;
for (int i = 0; pszVerSign[i]; ++i){
pszBegin = _tcsstr(m_pContent, pszVerSign[i]);
if (!pszBegin)
return false;
pszBegin += _tcslen(pszVerSign[i]);
m_dwVersion[i] = _ttoi(pszBegin);
}
// ת汾ŵλ
while (*pszBegin && !_istdigit(*pszBegin)) ++pszBegin;
if (!*pszBegin)
return false;
auto pszEnd = pszBegin;
while (*pszEnd && _istdigit(*pszEnd)) ++pszEnd;
// ݾͰ汾ż°汾ţתΪַ
//DWORD dwBuildVer = _ttoi(pszBegin);
TCHAR szNewVer[20];
_stprintf_s(szNewVer, TEXT("%u"), ++m_dwVersion[BUILD]);
// ʹð汾ǰַضλļָ
if (!SetFilePtrWithString(m_pContent, pszBegin - m_pContent))
return false;
// д°汾
if (!WriteContent(szNewVer, _tcslen(szNewVer)))
return false;
// жϰ汾ųǷһ£ֻвһʱҪд汾ź
if (pszEnd - pszBegin != _tcslen(szNewVer)){
bRes = WriteContent(pszEnd, _tcslen(pszEnd));
SetEndOfFile(m_hFile);
}
return bRes;
}
bool CVerFile::IncRCFileVer(LPCTSTR lpszFilePath)
{
static LPCTSTR pszSign[] = {
TEXT("FILEVERSION"),
TEXT("PRODUCTVERSION"),
TEXT("\"FileVersion\","),
TEXT("\"ProductVersion\","),
NULL
};
bool bRes = false;
// ȡļ
if (!GetFileContent(lpszFilePath))
return false;
auto pszBegin = m_pContent;
auto pszEnd = pszBegin;
TCHAR szText[100];
for (int i = 0; pszSign[i]; ++i){
pszEnd = _tcsstr(pszBegin, pszSign[i]);
if (!pszEnd)
return false;
pszEnd += _tcslen(pszSign[i]);
while (*pszEnd && !_istgraph(*pszEnd)) ++pszEnd;
if (!*pszEnd)
return false;
if (i == 0)
bRes = SetFilePtrWithString(pszBegin, pszEnd - pszBegin);
else
bRes = WriteContent(pszBegin, pszEnd - pszBegin);
if (!bRes)
return false;
if (!i){
_stprintf_s(szText, TEXT("%u,%u,%u,%u"), m_dwVersion[MAJOR], m_dwVersion[MINOR]
, m_dwVersion[REVISION], m_dwVersion[BUILD]);
}else if(i == 2){
_stprintf_s(szText, TEXT("\"%u.%u.%u.%u\""), m_dwVersion[MAJOR], m_dwVersion[MINOR]
, m_dwVersion[REVISION], m_dwVersion[BUILD]);
}
if (!WriteContent(szText, _tcslen(szText)))
return false;
while (*pszEnd && _istprint(*pszEnd)) ++pszEnd;
if (!*pszEnd)
return false;
pszBegin = pszEnd;
}
// дʣ
bRes = WriteContent(pszEnd, _tcslen(pszEnd));
SetEndOfFile(m_hFile);
return bRes;
}
// ȡָļݣתΪ Unicode
bool CVerFile::GetFileContent(LPCTSTR lpszFilePath)
{
// ļ
if (m_hFile)
CloseHandle(m_hFile);
m_hFile = CreateFile(lpszFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, 0, nullptr);
if (m_hFile == INVALID_HANDLE_VALUE)
return false;
LARGE_INTEGER large;
GetFileSizeEx(m_hFile, &large);
if (!large.QuadPart)
return false;
// ļӳ䲢ӳ䵽ڴҳ
HANDLE hMapping = CreateFileMapping(m_hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!hMapping)
return false;
auto pData = (char*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
CloseHandle(hMapping);
if (!pData)
return false;
// ȡļ
GetFileContentCode(pData, large.QuadPart);
// ļ뽫ļת unicode
if (m_pContent)
delete[] m_pContent;
m_pContent = FileContentToUnicode(pData + m_dwOffset, large.QuadPart - m_dwOffset);
UnmapViewOfFile(pData);
return m_pContent != nullptr;
}
// ȡļݵıʽ
bool CVerFile::GetFileContentCode(LPCSTR pData, LONGLONG llLen)
{
if (llLen > 3) {
DWORD dwBOM = MAKELONG(MAKEWORD(pData[0], pData[1]), MAKEWORD(pData[2], 0));
if (dwBOM == 0xBFBBEF) { // utf-8
m_dwCode = CP_UTF8;
m_dwOffset = 3;
}
else if (LOWORD(dwBOM) == 0xFFFE) { // utf-16 big endian
m_dwCode = CP_UTF16B;
m_dwOffset = 2;
}
else if (LOWORD(dwBOM) == 0xFEFF) { // utf-16
m_dwCode = CP_UTF16;
m_dwOffset = 2;
}
}
if(!m_dwCode) {
if (IsCodeUtf8(pData, llLen))
m_dwCode = CP_UTF8;
else
m_dwCode = IsCodeUtf16(pData, llLen);
}
return true;
}
// жϸǷΪutf-8
bool CVerFile::IsCodeUtf8(LPCSTR pString, LONGLONG llLen)
{
bool bRet = false;
auto pData = (PBYTE)pString;
for (LONGLONG i = 0; i < llLen; ++i) {
if (pData[i] > 0x80) {
int nCount = 1;
while ((pData[i] << nCount) & 0x80) ++nCount;
if (nCount > 6 || i + nCount > llLen)
return false;
for (int j = 1; j < nCount; ++j) {
if ((pData[i + j] & 0xc0) != 0x80)
return false;
}
//i += nCount;
//bRet = true;
return true;
}
//else
// ++i;
}
return bRet;
}
// жϸǷΪutf-16ʽı룬ַ룬
int CVerFile::IsCodeUtf16(LPCSTR pString, LONGLONG llLen)
{
if (llLen % 2)
return 0;
for (LONGLONG i = 0; i + 1 < llLen; ++i) {
if (!pString[i])
return CP_UTF16B;
else if (!pString[i + 1])
return CP_UTF16;
}
return 0;
}
LPTSTR CVerFile::FileContentToUnicode(LPCSTR lpszSrc, LONGLONG llLen)
{
LPTSTR pContent = nullptr;
if (m_dwCode == CP_UTF16) {
pContent = new TCHAR[llLen / sizeof(TCHAR) + 1];
if (pContent) {
memset(pContent, 0, llLen + sizeof(TCHAR));
memcpy_s(pContent, llLen + sizeof(TCHAR), lpszSrc, llLen);
}
}
else if (m_dwCode == CP_UTF16B) {
pContent = new TCHAR[llLen / sizeof(TCHAR)+1];
if (pContent) {
memset(pContent, 0, llLen + sizeof(TCHAR));
char *pDst = (char*)pContent;
const char *pSrc = lpszSrc;
for (LONGLONG i = 0; i + 1 < llLen; i += 2) {
pDst[i] = pSrc[i + 1];
pDst[i + 1] = pSrc[i];
}
}
}
else {
DWORD dwLen = MultiByteToWideChar(m_dwCode, 0, lpszSrc, llLen, nullptr, 0);
if (dwLen) {
pContent = new TCHAR[dwLen];
if (pContent)
MultiByteToWideChar(m_dwCode, 0, lpszSrc, llLen, pContent, dwLen);
}
}
return pContent;
}
// Ӹİ汾֮ǰַԭļ뷽ʽļݵƫ
// 㲢ļָλã汾֮ǰᱻĵݣ
// ںд룬 I/O Ч
bool CVerFile::SetFilePtrWithString(LPCTSTR lpszProBuildVer, DWORD dwLen)
{
LARGE_INTEGER large = { m_dwOffset };
if (m_dwCode != CP_UTF16 && m_dwCode != CP_UTF16B) {
int nLen = WideCharToMultiByte(m_dwCode, 0, lpszProBuildVer, dwLen, nullptr, 0, nullptr, nullptr);
if (!nLen)
return false;
large.QuadPart += nLen;
}
else
large.QuadPart += dwLen * sizeof(TCHAR);
return TRUE == SetFilePointerEx(m_hFile, large, nullptr, FILE_BEGIN);
}
// ݣתΪԭļʽдļ
bool CVerFile::WriteContent(LPCTSTR lpszContent, DWORD dwLen)
{
DWORD dwWriten;
if (m_dwCode == CP_UTF16) {
return WriteFile(m_hFile, lpszContent, dwLen * sizeof(TCHAR), &dwWriten, nullptr);
}
else if (m_dwCode == CP_UTF16B) {
DWORD dwBytes = dwLen * sizeof(TCHAR);
auto pDst = new char[dwBytes];
if (pDst) {
auto pSrc = (const char*)lpszContent;
for (DWORD i = 0; i + 1 < dwBytes; i += 2) {
pDst[i] = pSrc[i + 1];
pDst[i + 1] = pSrc[i];
}
auto bRes = WriteFile(m_hFile, pDst, dwBytes, &dwWriten, nullptr);
delete[] pDst;
return bRes;
}
}
else {
int nLen = WideCharToMultiByte(m_dwCode, 0, lpszContent, dwLen, nullptr, 0, nullptr, nullptr);
if (!nLen)
return false;
auto pBuff = new char[nLen];
if (pBuff) {
WideCharToMultiByte(m_dwCode, 0, lpszContent, dwLen, pBuff, nLen, nullptr, nullptr);
auto bRes = WriteFile(m_hFile, pBuff, nLen - 1, &dwWriten, nullptr);
delete[] pBuff;
return bRes;
}
}
return false;
}
<commit_msg>Fix a bug that the string without null terminator<commit_after>////////////////////////////////////////////////////////////////////////////////
// ļVerFile.cpp
// ߣSong Baoming,2016
// ; resource.h *.rc ļӱ汾 CVerFile ķļ
// Licensehttps://github.com/songbaoming/IncBuildVer/blob/master/LICENSE
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "VerFile.h"
#define MAJOR 0
#define MINOR 1
#define REVISION 2
#define BUILD 3
CVerFile::CVerFile()
: m_dwOffset(0)
, m_dwCode(0)
, m_hFile(nullptr)
, m_pContent(nullptr)
{
}
CVerFile::~CVerFile()
{
if (m_pContent)
delete[] m_pContent;
if (m_hFile && m_hFile != INVALID_HANDLE_VALUE)
CloseHandle(m_hFile);
}
// ָļб汾źֵһ
bool CVerFile::IncBuildVer(LPCTSTR lpszDirPath)
{
TCHAR szFilePath[MAX_PATH];
_stprintf_s(szFilePath, TEXT("%sresource.h"), lpszDirPath);
// resource.h
if (!IncResourceVer(szFilePath))
return false;
// .rcļ·
auto pos = _tcsrchr(lpszDirPath, TEXT('\\'));
if (!pos)
return false;
while (pos != lpszDirPath && *(pos - 1) != TEXT('\\'))
--pos;
if (pos == lpszDirPath)
return false;
_stprintf_s(szFilePath, TEXT("%s%s"), lpszDirPath, pos);
szFilePath[_tcslen(szFilePath) - 1] = 0;
_tcscat_s(szFilePath, TEXT(".rc"));
// .rc
if (!IncRCFileVer(szFilePath))
return false;
return true;
}
bool CVerFile::IncResourceVer(LPCTSTR lpszFilePath)
{
static LPCTSTR pszVerSign[] = {
TEXT("MAJOR_VER_NUM"),
TEXT("MINOR_VER_NUM"),
TEXT("REVISION_VER_NUM"),
TEXT("BUILD_VER_NUM"),
NULL
};
bool bRes = true;
// ȡļ
if (!GetFileContent(lpszFilePath))
return false;
auto pszBegin = m_pContent;
for (int i = 0; pszVerSign[i]; ++i){
pszBegin = _tcsstr(m_pContent, pszVerSign[i]);
if (!pszBegin)
return false;
pszBegin += _tcslen(pszVerSign[i]);
m_dwVersion[i] = _ttoi(pszBegin);
}
// ת汾ŵλ
while (*pszBegin && !_istdigit(*pszBegin)) ++pszBegin;
if (!*pszBegin)
return false;
auto pszEnd = pszBegin;
while (*pszEnd && _istdigit(*pszEnd)) ++pszEnd;
// ݾͰ汾ż°汾ţתΪַ
//DWORD dwBuildVer = _ttoi(pszBegin);
TCHAR szNewVer[20];
_stprintf_s(szNewVer, TEXT("%u"), ++m_dwVersion[BUILD]);
// ʹð汾ǰַضλļָ
if (!SetFilePtrWithString(m_pContent, pszBegin - m_pContent))
return false;
// д°汾
if (!WriteContent(szNewVer, _tcslen(szNewVer)))
return false;
// жϰ汾ųǷһ£ֻвһʱҪд汾ź
if (pszEnd - pszBegin != _tcslen(szNewVer)){
bRes = WriteContent(pszEnd, _tcslen(pszEnd));
SetEndOfFile(m_hFile);
}
return bRes;
}
bool CVerFile::IncRCFileVer(LPCTSTR lpszFilePath)
{
static LPCTSTR pszSign[] = {
TEXT("FILEVERSION"),
TEXT("PRODUCTVERSION"),
TEXT("\"FileVersion\","),
TEXT("\"ProductVersion\","),
NULL
};
bool bRes = false;
// ȡļ
if (!GetFileContent(lpszFilePath))
return false;
auto pszBegin = m_pContent;
auto pszEnd = pszBegin;
TCHAR szText[100];
for (int i = 0; pszSign[i]; ++i){
pszEnd = _tcsstr(pszBegin, pszSign[i]);
if (!pszEnd)
return false;
pszEnd += _tcslen(pszSign[i]);
while (*pszEnd && !_istgraph(*pszEnd)) ++pszEnd;
if (!*pszEnd)
return false;
if (i == 0)
bRes = SetFilePtrWithString(pszBegin, pszEnd - pszBegin);
else
bRes = WriteContent(pszBegin, pszEnd - pszBegin);
if (!bRes)
return false;
if (!i){
_stprintf_s(szText, TEXT("%u,%u,%u,%u"), m_dwVersion[MAJOR], m_dwVersion[MINOR]
, m_dwVersion[REVISION], m_dwVersion[BUILD]);
}else if(i == 2){
_stprintf_s(szText, TEXT("\"%u.%u.%u.%u\""), m_dwVersion[MAJOR], m_dwVersion[MINOR]
, m_dwVersion[REVISION], m_dwVersion[BUILD]);
}
if (!WriteContent(szText, _tcslen(szText)))
return false;
while (*pszEnd && _istprint(*pszEnd)) ++pszEnd;
if (!*pszEnd)
return false;
pszBegin = pszEnd;
}
// дʣ
bRes = WriteContent(pszEnd, _tcslen(pszEnd));
SetEndOfFile(m_hFile);
return bRes;
}
// ȡָļݣתΪ Unicode
bool CVerFile::GetFileContent(LPCTSTR lpszFilePath)
{
// ļ
if (m_hFile)
CloseHandle(m_hFile);
m_hFile = CreateFile(lpszFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, 0, nullptr);
if (m_hFile == INVALID_HANDLE_VALUE)
return false;
LARGE_INTEGER large;
GetFileSizeEx(m_hFile, &large);
if (!large.QuadPart)
return false;
// ļӳ䲢ӳ䵽ڴҳ
HANDLE hMapping = CreateFileMapping(m_hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!hMapping)
return false;
auto pData = (char*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
CloseHandle(hMapping);
if (!pData)
return false;
// ȡļ
GetFileContentCode(pData, large.QuadPart);
// ļ뽫ļת unicode
if (m_pContent)
delete[] m_pContent;
m_pContent = FileContentToUnicode(pData + m_dwOffset, large.QuadPart - m_dwOffset);
UnmapViewOfFile(pData);
return m_pContent != nullptr;
}
// ȡļݵıʽ
bool CVerFile::GetFileContentCode(LPCSTR pData, LONGLONG llLen)
{
if (llLen > 3) {
DWORD dwBOM = MAKELONG(MAKEWORD(pData[0], pData[1]), MAKEWORD(pData[2], 0));
if (dwBOM == 0xBFBBEF) { // utf-8
m_dwCode = CP_UTF8;
m_dwOffset = 3;
}
else if (LOWORD(dwBOM) == 0xFFFE) { // utf-16 big endian
m_dwCode = CP_UTF16B;
m_dwOffset = 2;
}
else if (LOWORD(dwBOM) == 0xFEFF) { // utf-16
m_dwCode = CP_UTF16;
m_dwOffset = 2;
}
}
if(!m_dwCode) {
if (IsCodeUtf8(pData, llLen))
m_dwCode = CP_UTF8;
else
m_dwCode = IsCodeUtf16(pData, llLen);
}
return true;
}
// жϸǷΪutf-8
bool CVerFile::IsCodeUtf8(LPCSTR pString, LONGLONG llLen)
{
bool bRet = false;
auto pData = (PBYTE)pString;
for (LONGLONG i = 0; i < llLen; ++i) {
if (pData[i] > 0x80) {
int nCount = 1;
while ((pData[i] << nCount) & 0x80) ++nCount;
if (nCount > 6 || i + nCount > llLen)
return false;
for (int j = 1; j < nCount; ++j) {
if ((pData[i + j] & 0xc0) != 0x80)
return false;
}
//i += nCount;
//bRet = true;
return true;
}
//else
// ++i;
}
return bRet;
}
// жϸǷΪutf-16ʽı룬ַ룬
int CVerFile::IsCodeUtf16(LPCSTR pString, LONGLONG llLen)
{
if (llLen % 2)
return 0;
for (LONGLONG i = 0; i + 1 < llLen; ++i) {
if (!pString[i])
return CP_UTF16B;
else if (!pString[i + 1])
return CP_UTF16;
}
return 0;
}
LPTSTR CVerFile::FileContentToUnicode(LPCSTR lpszSrc, LONGLONG llLen)
{
LPTSTR pContent = nullptr;
if (m_dwCode == CP_UTF16) {
pContent = new TCHAR[llLen / sizeof(TCHAR) + 1];
if (pContent) {
memset(pContent, 0, llLen + sizeof(TCHAR));
memcpy_s(pContent, llLen + sizeof(TCHAR), lpszSrc, llLen);
}
}
else if (m_dwCode == CP_UTF16B) {
pContent = new TCHAR[llLen / sizeof(TCHAR)+1];
if (pContent) {
memset(pContent, 0, llLen + sizeof(TCHAR));
char *pDst = (char*)pContent;
const char *pSrc = lpszSrc;
for (LONGLONG i = 0; i + 1 < llLen; i += 2) {
pDst[i] = pSrc[i + 1];
pDst[i + 1] = pSrc[i];
}
}
}
else {
DWORD dwLen = MultiByteToWideChar(m_dwCode, 0, lpszSrc, llLen, nullptr, 0);
if (dwLen) {
pContent = new TCHAR[dwLen + 1];
if (pContent){
MultiByteToWideChar(m_dwCode, 0, lpszSrc, llLen, pContent, dwLen);
pContent[dwLen] = 0;
}
}
}
return pContent;
}
// Ӹİ汾֮ǰַԭļ뷽ʽļݵƫ
// 㲢ļָλã汾֮ǰᱻĵݣ
// ںд룬 I/O Ч
bool CVerFile::SetFilePtrWithString(LPCTSTR lpszProBuildVer, DWORD dwLen)
{
LARGE_INTEGER large = { m_dwOffset };
if (m_dwCode != CP_UTF16 && m_dwCode != CP_UTF16B) {
int nLen = WideCharToMultiByte(m_dwCode, 0, lpszProBuildVer, dwLen, nullptr, 0, nullptr, nullptr);
if (!nLen)
return false;
large.QuadPart += nLen;
}
else
large.QuadPart += dwLen * sizeof(TCHAR);
return TRUE == SetFilePointerEx(m_hFile, large, nullptr, FILE_BEGIN);
}
// ݣתΪԭļʽдļ
bool CVerFile::WriteContent(LPCTSTR lpszContent, DWORD dwLen)
{
DWORD dwWriten;
if (m_dwCode == CP_UTF16) {
return WriteFile(m_hFile, lpszContent, dwLen * sizeof(TCHAR), &dwWriten, nullptr);
}
else if (m_dwCode == CP_UTF16B) {
DWORD dwBytes = dwLen * sizeof(TCHAR);
auto pDst = new char[dwBytes];
if (pDst) {
auto pSrc = (const char*)lpszContent;
for (DWORD i = 0; i + 1 < dwBytes; i += 2) {
pDst[i] = pSrc[i + 1];
pDst[i + 1] = pSrc[i];
}
auto bRes = WriteFile(m_hFile, pDst, dwBytes, &dwWriten, nullptr);
delete[] pDst;
return bRes;
}
}
else {
int nLen = WideCharToMultiByte(m_dwCode, 0, lpszContent, dwLen, nullptr, 0, nullptr, nullptr);
if (!nLen)
return false;
auto pBuff = new char[nLen];
if (pBuff) {
WideCharToMultiByte(m_dwCode, 0, lpszContent, dwLen, pBuff, nLen, nullptr, nullptr);
auto bRes = WriteFile(m_hFile, pBuff, nLen, &dwWriten, nullptr);
delete[] pBuff;
return bRes;
}
}
return false;
}
<|endoftext|> |
<commit_before>#ifndef BUW_MATERIAL_HPP
#define BUW_MATERIAL_HPP
#include <string>
#include <iostream>
#include "color.hpp"
class Material
{
public:
Material();
Material(std::string const& n, Color const& a, Color const& d, Color const& s, float const& m);
Material(std::string const& n, Color const& a, float const& m);
~Material();
std::string const& name() const;
Color const& ka() const;
Color const& kd() const;
Color const& ks() const;
float const& m() const;
friend std::ostream& operator<<(std::ostream& os, Material const& m);
bool operator==(Material const& m2) const{
return ((ka() == m2.ka()) && (kd() == m2.kd()) && (ks() == m2.ks()));
}
private:
std::string name_;
Color ka_;
Color kd_;
Color ks_;
float reflection_;
};
#endif
<commit_msg>nothing happened<commit_after>#ifndef BUW_MATERIAL_HPP
#define BUW_MATERIAL_HPP
#include <string>
#include <iostream>
#include "color.hpp"
class Material
{
public:
Material();
Material(std::string const& n, Color const& a, Color const& d, Color const& s, float const& m);
Material(std::string const& n, Color const& a, float const& m);
~Material();
std::string const& name() const;
Color const& ka() const;
Color const& kd() const;
Color const& ks() const;
float const& m() const;
friend std::ostream& operator<<(std::ostream& os, Material const& m);
bool operator==(Material const& m2) const{
return ((ka() == m2.ka()) && (kd() == m2.kd()) && (ks() == m2.ks()));
}
private:
std::string name_;
Color ka_;
Color kd_;
Color ks_;
float reflection_;
};
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test de la classe LineSpatialObjectList
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbLineSpatialObjectList.h"
#include <list>
int otbLineSpatialObjectList( int argc, char ** argv )
{
try
{
typedef otb::LineSpatialObjectList LineSpatialObjectListType;
typedef LineSpatialObjectListType::LineType LineSpatialObjecType;
typedef LineSpatialObjectListType::LineType::PointListType PointListType;
typedef LineSpatialObjectListType::const_iterator LineSpatialObjectListConstIterator;
LineSpatialObjectListType listLines;
for( int i = 0 ; i < 10 ; i++ )
{
LineSpatialObjecType::Pointer lLine = LineSpatialObjecType::New();
listLines.push_back( lLine );
}
LineSpatialObjectListConstIterator lIter;
lIter = listLines.begin();
while( lIter != listLines.end() )
{
LineSpatialObjecType::Pointer lLine = (*lIter);
PointListType lPoints = lLine->GetPoints();
lIter++;
}
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>nomsg<commit_after>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - T.Feuvrier
Language : C++
Date : 11 janvier 2005
Version :
Role : Test de la classe LineSpatialObjectList
$Id$
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbLineSpatialObjectList.h"
#include <list>
int otbLineSpatialObjectList( int argc, char ** argv )
{
try
{
/* typedef otb::LineSpatialObjectList LineSpatialObjectListType;
typedef LineSpatialObjectListType::LineType LineSpatialObjecType;
typedef LineSpatialObjectListType::LineType::PointListType PointListType;
typedef LineSpatialObjectListType::const_iterator LineSpatialObjectListConstIterator;
LineSpatialObjectListType listLines;
for( int i = 0 ; i < 10 ; i++ )
{
LineSpatialObjecType::Pointer lLine = LineSpatialObjecType::New();
listLines.push_back( lLine );
}
LineSpatialObjectListConstIterator lIter;
lIter = listLines.begin();
while( lIter != listLines.end() )
{
LineSpatialObjecType::Pointer lLine = (*lIter);
PointListType lPoints = lLine->GetPoints();
lIter++;
}
*/
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUISpinner.cpp
created: 3/2/2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/widgets/Spinner.h"
#include "CEGUI/widgets/PushButton.h"
#include "CEGUI/widgets/Editbox.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/WindowManager.h"
#include <stdio.h>
#include <sstream>
#include <iomanip>
// Start of CEGUI namespace section
namespace CEGUI
{
const String Spinner::WidgetTypeName("CEGUI/Spinner");
//////////////////////////////////////////////////////////////////////////
// event strings
const String Spinner::EventNamespace("Spinner");
const String Spinner::EventValueChanged("ValueChanged");
const String Spinner::EventStepChanged("StepChanged");
const String Spinner::EventMaximumValueChanged("MaximumValueChanged");
const String Spinner::EventMinimumValueChanged("MinimumValueChanged");
const String Spinner::EventTextInputModeChanged("TextInputModeChanged");
// Validator strings
const String Spinner::FloatValidator("-?\\d*\\.?\\d*");
const String Spinner::IntegerValidator("-?\\d*");
const String Spinner::HexValidator("[0-9a-fA-F]*");
const String Spinner::OctalValidator("[0-7]*");
// component widget name strings
const String Spinner::EditboxName( "__auto_editbox__" );
const String Spinner::IncreaseButtonName( "__auto_incbtn__" );
const String Spinner::DecreaseButtonName( "__auto_decbtn__" );
//////////////////////////////////////////////////////////////////////////
Spinner::Spinner(const String& type, const String& name) :
Window(type, name),
d_stepSize(1.0f),
d_currentValue(1.0f),
d_maxValue(32767.0f),
d_minValue(-32768.0f),
d_inputMode((TextInputMode)-1)
{
addSpinnerProperties();
}
Spinner::~Spinner(void)
{
// Nothing to do here.
}
void Spinner::initialiseComponents(void)
{
// get all the component widgets
PushButton* increaseButton = getIncreaseButton();
PushButton* decreaseButton = getDecreaseButton();
Editbox* editbox = getEditbox();
// setup component controls
increaseButton->setPointerAutoRepeatEnabled(true);
decreaseButton->setPointerAutoRepeatEnabled(true);
// perform event subscriptions.
increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this));
decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this));
editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this));
// final initialisation
setTextInputMode(Integer);
setCurrentValue(0.0f);
performChildWindowLayout();
}
double Spinner::getCurrentValue(void) const
{
return d_currentValue;
}
double Spinner::getStepSize(void) const
{
return d_stepSize;
}
double Spinner::getMaximumValue(void) const
{
return d_maxValue;
}
double Spinner::getMinimumValue(void) const
{
return d_minValue;
}
Spinner::TextInputMode Spinner::getTextInputMode(void) const
{
return d_inputMode;
}
void Spinner::setCurrentValue(double value)
{
if (value != d_currentValue)
{
// limit input value to within valid range for spinner
value = ceguimax(ceguimin(value, d_maxValue), d_minValue);
d_currentValue = value;
WindowEventArgs args(this);
onValueChanged(args);
}
}
void Spinner::setStepSize(double step)
{
if (step != d_stepSize)
{
d_stepSize = step;
WindowEventArgs args(this);
onStepChanged(args);
}
}
void Spinner::setMaximumValue(double maxValue)
{
if (maxValue != d_maxValue)
{
d_maxValue = maxValue;
WindowEventArgs args(this);
onMaximumValueChanged(args);
}
}
void Spinner::setMinimumValue(double minVaue)
{
if (minVaue != d_minValue)
{
d_minValue = minVaue;
WindowEventArgs args(this);
onMinimumValueChanged(args);
}
}
void Spinner::setTextInputMode(TextInputMode mode)
{
if (mode != d_inputMode)
{
switch (mode)
{
case FloatingPoint:
getEditbox()->setValidationString(FloatValidator);
break;
case Integer:
getEditbox()->setValidationString(IntegerValidator);
break;
case Hexadecimal:
getEditbox()->setValidationString(HexValidator);
break;
case Octal:
getEditbox()->setValidationString(OctalValidator);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was specified."));
}
d_inputMode = mode;
WindowEventArgs args(this);
onTextInputModeChanged(args);
}
}
void Spinner::addSpinnerProperties(void)
{
const String& propertyOrigin = WidgetTypeName;
CEGUI_DEFINE_PROPERTY(Spinner, double,
"CurrentValue", "Property to get/set the current value of the spinner. Value is a float.",
&Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"StepSize", "Property to get/set the step size of the spinner. Value is a float.",
&Spinner::setStepSize, &Spinner::getStepSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.",
&Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.",
&Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f
);
CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode,
"TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".",
&Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer
);
}
double Spinner::getValueFromText(void) const
{
String tmpTxt(getEditbox()->getText());
// handle empty and lone '-' or '.' cases
if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == "."))
{
return 0.0f;
}
int res, tmp;
uint utmp;
double val;
switch (d_inputMode)
{
case FloatingPoint:
res = sscanf(tmpTxt.c_str(), "%lf", &val);
break;
case Integer:
res = sscanf(tmpTxt.c_str(), "%d", &tmp);
val = static_cast<double>(tmp);
break;
case Hexadecimal:
res = sscanf(tmpTxt.c_str(), "%x", &utmp);
val = static_cast<double>(utmp);
break;
case Octal:
res = sscanf(tmpTxt.c_str(), "%o", &utmp);
val = static_cast<double>(utmp);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was encountered."));
}
if (res)
{
return val;
}
CEGUI_THROW(InvalidRequestException(
"The string '" + getEditbox()->getText() +
"' can not be converted to numerical representation."));
}
String Spinner::getTextFromValue(void) const
{
std::stringstream tmp;
switch (d_inputMode)
{
case FloatingPoint:
return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) );
break;
case Integer:
tmp << static_cast<int>(d_currentValue);
break;
case Hexadecimal:
tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue);
break;
case Octal:
tmp << std::oct << static_cast<int>(d_currentValue);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was encountered."));
}
return String(tmp.str().c_str());
}
void Spinner::onFontChanged(WindowEventArgs& e)
{
// Propagate to children
getEditbox()->setFont(getFont());
// Call base class handler
Window::onFontChanged(e);
}
void Spinner::onTextChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// update only if needed
if (editbox->getText() != getText())
{
// done before doing base class processing so event subscribers see
// 'updated' version.
editbox->setText(getText());
++e.handled;
Window::onTextChanged(e);
}
}
void Spinner::onActivated(ActivationEventArgs& e)
{
if (!isActive())
{
Window::onActivated(e);
Editbox* editbox = getEditbox();
if (!editbox->isActive())
{
editbox->activate();
}
}
}
void Spinner::onValueChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// mute to save doing unnecessary events work.
bool wasMuted = editbox->isMuted();
editbox->setMutedState(true);
// Update editbox and spinner text with new value.
// (allow empty and '-' cases to equal 0 with no text change required)
if (!(d_currentValue == 0 &&
(editbox->getText().empty() || editbox->getText() == "-")))
{
const CEGUI::String& valueString = getTextFromValue();
editbox->setText(valueString);
setText(valueString);
}
// restore previous mute state.
editbox->setMutedState(wasMuted);
fireEvent(EventValueChanged, e, EventNamespace);
}
void Spinner::onStepChanged(WindowEventArgs& e)
{
fireEvent(EventStepChanged, e, EventNamespace);
}
void Spinner::onMaximumValueChanged(WindowEventArgs& e)
{
fireEvent(EventMaximumValueChanged, e, EventNamespace);
if (d_currentValue > d_maxValue)
{
setCurrentValue(d_maxValue);
}
}
void Spinner::onMinimumValueChanged(WindowEventArgs& e)
{
fireEvent(EventMinimumValueChanged, e, EventNamespace);
if (d_currentValue < d_minValue)
{
setCurrentValue(d_minValue);
}
}
void Spinner::onTextInputModeChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// update edit box text to reflect new mode.
// mute to save doing unnecessary events work.
bool wasMuted = editbox->isMuted();
editbox->setMutedState(true);
// Update text with new value.
editbox->setText(getTextFromValue());
// restore previous mute state.
editbox->setMutedState(wasMuted);
fireEvent(EventTextInputModeChanged, e, EventNamespace);
}
bool Spinner::handleIncreaseButton(const EventArgs& e)
{
if (((const PointerEventArgs&)e).source == PS_Left)
{
setCurrentValue(d_currentValue + d_stepSize);
return true;
}
return false;
}
bool Spinner::handleDecreaseButton(const EventArgs& e)
{
if (((const PointerEventArgs&)e).source == PS_Left)
{
setCurrentValue(d_currentValue - d_stepSize);
return true;
}
return false;
}
bool Spinner::handleEditTextChange(const EventArgs&)
{
// set this windows text to match
setText(getEditbox()->getText());
// update value
setCurrentValue(getValueFromText());
return true;
}
PushButton* Spinner::getIncreaseButton() const
{
return static_cast<PushButton*>(getChild(IncreaseButtonName));
}
PushButton* Spinner::getDecreaseButton() const
{
return static_cast<PushButton*>(getChild(DecreaseButtonName));
}
Editbox* Spinner::getEditbox() const
{
return static_cast<Editbox*>(getChild(EditboxName));
}
//////////////////////////////////////////////////////////////////////////
} // End of CEGUI namespace section
<commit_msg>Backed out changeset: ebcdf16f6207<commit_after>/***********************************************************************
filename: CEGUISpinner.cpp
created: 3/2/2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/widgets/Spinner.h"
#include "CEGUI/widgets/PushButton.h"
#include "CEGUI/widgets/Editbox.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/WindowManager.h"
#include <stdio.h>
#include <sstream>
#include <iomanip>
// Start of CEGUI namespace section
namespace CEGUI
{
const String Spinner::WidgetTypeName("CEGUI/Spinner");
//////////////////////////////////////////////////////////////////////////
// event strings
const String Spinner::EventNamespace("Spinner");
const String Spinner::EventValueChanged("ValueChanged");
const String Spinner::EventStepChanged("StepChanged");
const String Spinner::EventMaximumValueChanged("MaximumValueChanged");
const String Spinner::EventMinimumValueChanged("MinimumValueChanged");
const String Spinner::EventTextInputModeChanged("TextInputModeChanged");
// Validator strings
const String Spinner::FloatValidator("-?\\d*\\.?\\d*");
const String Spinner::IntegerValidator("-?\\d*");
const String Spinner::HexValidator("[0-9a-fA-F]*");
const String Spinner::OctalValidator("[0-7]*");
// component widget name strings
const String Spinner::EditboxName( "__auto_editbox__" );
const String Spinner::IncreaseButtonName( "__auto_incbtn__" );
const String Spinner::DecreaseButtonName( "__auto_decbtn__" );
//////////////////////////////////////////////////////////////////////////
Spinner::Spinner(const String& type, const String& name) :
Window(type, name),
d_stepSize(1.0f),
d_currentValue(1.0f),
d_maxValue(32767.0f),
d_minValue(-32768.0f),
d_inputMode((TextInputMode)-1)
{
addSpinnerProperties();
}
Spinner::~Spinner(void)
{
// Nothing to do here.
}
void Spinner::initialiseComponents(void)
{
// get all the component widgets
PushButton* increaseButton = getIncreaseButton();
PushButton* decreaseButton = getDecreaseButton();
Editbox* editbox = getEditbox();
// setup component controls
increaseButton->setPointerAutoRepeatEnabled(true);
decreaseButton->setPointerAutoRepeatEnabled(true);
// perform event subscriptions.
increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this));
decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this));
editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this));
// final initialisation
setTextInputMode(Integer);
setCurrentValue(0.0f);
performChildWindowLayout();
}
double Spinner::getCurrentValue(void) const
{
return d_currentValue;
}
double Spinner::getStepSize(void) const
{
return d_stepSize;
}
double Spinner::getMaximumValue(void) const
{
return d_maxValue;
}
double Spinner::getMinimumValue(void) const
{
return d_minValue;
}
Spinner::TextInputMode Spinner::getTextInputMode(void) const
{
return d_inputMode;
}
void Spinner::setCurrentValue(double value)
{
if (value != d_currentValue)
{
// limit input value to within valid range for spinner
value = ceguimax(ceguimin(value, d_maxValue), d_minValue);
d_currentValue = value;
WindowEventArgs args(this);
onValueChanged(args);
}
}
void Spinner::setStepSize(double step)
{
if (step != d_stepSize)
{
d_stepSize = step;
WindowEventArgs args(this);
onStepChanged(args);
}
}
void Spinner::setMaximumValue(double maxValue)
{
if (maxValue != d_maxValue)
{
d_maxValue = maxValue;
WindowEventArgs args(this);
onMaximumValueChanged(args);
}
}
void Spinner::setMinimumValue(double minVaue)
{
if (minVaue != d_minValue)
{
d_minValue = minVaue;
WindowEventArgs args(this);
onMinimumValueChanged(args);
}
}
void Spinner::setTextInputMode(TextInputMode mode)
{
if (mode != d_inputMode)
{
switch (mode)
{
case FloatingPoint:
getEditbox()->setValidationString(FloatValidator);
break;
case Integer:
getEditbox()->setValidationString(IntegerValidator);
break;
case Hexadecimal:
getEditbox()->setValidationString(HexValidator);
break;
case Octal:
getEditbox()->setValidationString(OctalValidator);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was specified."));
}
d_inputMode = mode;
WindowEventArgs args(this);
onTextInputModeChanged(args);
}
}
void Spinner::addSpinnerProperties(void)
{
const String& propertyOrigin = WidgetTypeName;
CEGUI_DEFINE_PROPERTY(Spinner, double,
"CurrentValue", "Property to get/set the current value of the spinner. Value is a float.",
&Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"StepSize", "Property to get/set the step size of the spinner. Value is a float.",
&Spinner::setStepSize, &Spinner::getStepSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.",
&Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f
);
CEGUI_DEFINE_PROPERTY(Spinner, double,
"MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.",
&Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f
);
CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode,
"TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".",
&Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer
);
}
double Spinner::getValueFromText(void) const
{
String tmpTxt(getEditbox()->getText());
// handle empty and lone '-' or '.' cases
if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == "."))
{
return 0.0f;
}
int res, tmp;
uint utmp;
double val;
switch (d_inputMode)
{
case FloatingPoint:
res = sscanf(tmpTxt.c_str(), "%lf", &val);
break;
case Integer:
res = sscanf(tmpTxt.c_str(), "%d", &tmp);
val = static_cast<double>(tmp);
break;
case Hexadecimal:
res = sscanf(tmpTxt.c_str(), "%x", &utmp);
val = static_cast<double>(utmp);
break;
case Octal:
res = sscanf(tmpTxt.c_str(), "%o", &utmp);
val = static_cast<double>(utmp);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was encountered."));
}
if (res)
{
return val;
}
CEGUI_THROW(InvalidRequestException(
"The string '" + getEditbox()->getText() +
"' can not be converted to numerical representation."));
}
String Spinner::getTextFromValue(void) const
{
std::stringstream tmp;
switch (d_inputMode)
{
case FloatingPoint:
return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) );
break;
case Integer:
tmp << static_cast<int>(d_currentValue);
break;
case Hexadecimal:
tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue);
break;
case Octal:
tmp << std::oct << static_cast<int>(d_currentValue);
break;
default:
CEGUI_THROW(InvalidRequestException(
"An unknown TextInputMode was encountered."));
}
return String(tmp.str().c_str());
}
void Spinner::onFontChanged(WindowEventArgs& e)
{
// Propagate to children
getEditbox()->setFont(getFont());
// Call base class handler
Window::onFontChanged(e);
}
void Spinner::onTextChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// update only if needed
if (editbox->getText() != getText())
{
// done before doing base class processing so event subscribers see
// 'updated' version.
editbox->setText(getText());
++e.handled;
Window::onTextChanged(e);
}
}
void Spinner::onActivated(ActivationEventArgs& e)
{
if (!isActive())
{
Window::onActivated(e);
Editbox* editbox = getEditbox();
if (!editbox->isActive())
{
editbox->activate();
}
}
}
void Spinner::onValueChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// mute to save doing unnecessary events work.
bool wasMuted = editbox->isMuted();
editbox->setMutedState(true);
// Update text with new value.
// (allow empty and '-' cases to equal 0 with no text change required)
if (!(d_currentValue == 0 &&
(editbox->getText().empty() || editbox->getText() == "-")))
{
editbox->setText(getTextFromValue());
}
// restore previous mute state.
editbox->setMutedState(wasMuted);
fireEvent(EventValueChanged, e, EventNamespace);
}
void Spinner::onStepChanged(WindowEventArgs& e)
{
fireEvent(EventStepChanged, e, EventNamespace);
}
void Spinner::onMaximumValueChanged(WindowEventArgs& e)
{
fireEvent(EventMaximumValueChanged, e, EventNamespace);
if (d_currentValue > d_maxValue)
{
setCurrentValue(d_maxValue);
}
}
void Spinner::onMinimumValueChanged(WindowEventArgs& e)
{
fireEvent(EventMinimumValueChanged, e, EventNamespace);
if (d_currentValue < d_minValue)
{
setCurrentValue(d_minValue);
}
}
void Spinner::onTextInputModeChanged(WindowEventArgs& e)
{
Editbox* editbox = getEditbox();
// update edit box text to reflect new mode.
// mute to save doing unnecessary events work.
bool wasMuted = editbox->isMuted();
editbox->setMutedState(true);
// Update text with new value.
editbox->setText(getTextFromValue());
// restore previous mute state.
editbox->setMutedState(wasMuted);
fireEvent(EventTextInputModeChanged, e, EventNamespace);
}
bool Spinner::handleIncreaseButton(const EventArgs& e)
{
if (((const PointerEventArgs&)e).source == PS_Left)
{
setCurrentValue(d_currentValue + d_stepSize);
return true;
}
return false;
}
bool Spinner::handleDecreaseButton(const EventArgs& e)
{
if (((const PointerEventArgs&)e).source == PS_Left)
{
setCurrentValue(d_currentValue - d_stepSize);
return true;
}
return false;
}
bool Spinner::handleEditTextChange(const EventArgs&)
{
// set this windows text to match
setText(getEditbox()->getText());
// update value
setCurrentValue(getValueFromText());
return true;
}
PushButton* Spinner::getIncreaseButton() const
{
return static_cast<PushButton*>(getChild(IncreaseButtonName));
}
PushButton* Spinner::getDecreaseButton() const
{
return static_cast<PushButton*>(getChild(DecreaseButtonName));
}
Editbox* Spinner::getEditbox() const
{
return static_cast<Editbox*>(getChild(EditboxName));
}
//////////////////////////////////////////////////////////////////////////
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "ShaderPaths.hpp"
#include "UniformLocations.glsl"
#include <atlas/glx/Buffer.hpp>
#include <atlas/glx/Context.hpp>
#include <atlas/glx/ErrorCallback.hpp>
#include <atlas/glx/GLSL.hpp>
#include <atlas/gui/GUI.hpp>
#include <fmt/printf.h>
#include <array>
using namespace atlas;
// We need to define an error callback function for GLFW, so we do that
// here.
void errorCallback(int code, char const* message)
{
fmt::print("error ({}):{}\n", code, message);
}
int main()
{
// First, lets create all of the structs that we're going to need.
glx::WindowSettings settings;
glx::WindowCallbacks callbacks;
gui::GuiRenderData guiRenderData;
gui::GuiWindowData guiWindowData;
// Set our window settings first.
{
settings.size.width = 1280;
settings.size.height = 720;
settings.title = "Hello Triangle";
}
// Now, let's make the window callbacks.
{
auto mousePressCallback = [&guiWindowData](int button, int action,
int mode) {
gui::mousePressedCallback(guiWindowData, button, action, mode);
};
auto mouseScrollCallback = [](double xOffset, double yOffset) {
gui::mouseScrollCallback(xOffset, yOffset);
};
auto keyPressCallback = [](int key, int scancode, int action,
int mods) {
gui::keyPressCallback(key, scancode, action, mods);
};
auto charCallback = [](unsigned int codepoint) {
gui::charCallback(codepoint);
};
callbacks.mousePressCallback = mousePressCallback;
callbacks.mouseScrollCallback = mouseScrollCallback;
callbacks.keyPressCallback = keyPressCallback;
callbacks.charCallback = charCallback;
}
// We're ready to start initializing things. So start with GLFW and OpenGL.
GLFWwindow* window;
{
glx::initializeGLFW(errorCallback);
// Next comes the window.
window = createGLFWWindow(settings);
// Bind the callbacks.
glx::bindWindowCallbacks(window, callbacks);
// Now bind the context.
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// Create the OpenGL context.
glx::createGLContext(window, settings.version);
// Set the error callback.
using namespace atlas::core;
glx::initializeGLCallback(glx::ErrorSource::All, glx::ErrorType::All,
glx::ErrorSeverity::High |
glx::ErrorSeverity::Medium);
}
// We have a window and a GL context, so now initialize the GUI.
{
ImGui::CreateContext();
ImGui::StyleColorsDark();
// Initialize the GUI structs. Remember to set the window!
gui::initializeGuiWindowData(guiWindowData);
gui::initializeGuiRenderData(guiRenderData);
setGuiWindow(guiWindowData, window);
}
// We want to draw a triangle on the screen, so let's setup all of the
// OpenGL variables next. Start with the shaders.
GLuint vertexShader{0};
GLuint fragmentShader{0};
GLuint shaderProgram{0};
glx::ShaderFile vertexSource;
glx::ShaderFile fragmentSource;
std::vector<std::string> includeDirs = {ShaderPath};
{
// Let's setup our shaders first. Create the program and the shaders.
shaderProgram = glCreateProgram();
vertexShader = glCreateShader(GL_VERTEX_SHADER);
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
std::string shaderRoot{ShaderPath};
std::string vertexFilename = shaderRoot + "triangle.vs.glsl";
vertexSource = glx::readShaderSource(vertexFilename, includeDirs);
std::string fragmentFilename = shaderRoot + "triangle.fs.glsl";
fragmentSource = glx::readShaderSource(fragmentFilename, includeDirs);
// Now compile both the shaders.
if (auto res =
glx::compileShader(vertexSource.sourceString, vertexShader);
res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
if (auto res =
glx::compileShader(fragmentSource.sourceString, fragmentShader);
res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
// Attach the shaders.
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
// Now link the shaders.
if (auto res = glx::linkShaders(shaderProgram); res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
}
// Now let's setup the data and buffers for our triangle.
GLuint vbo;
GLuint vao;
{
// clang-format off
std::array<float, 18> vertices =
{
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
// clang-format on
glCreateVertexArrays(1, &vao);
glCreateBuffers(1, &vbo);
glNamedBufferStorage(vbo, glx::size<float>(vertices.size()),
vertices.data(), 0);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, FALSE, glx::stride<float>(6),
glx::bufferOffset<float>(0));
glVertexAttribPointer(1, 3, GL_FLOAT, FALSE, glx::stride<float>(6),
glx::bufferOffset<float>(3));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
}
// Now we are ready for our main loop.
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Check if we have to reload the shaders.
if (glx::shouldShaderBeReloaded(vertexSource))
{
glx::reloadShader(shaderProgram, vertexShader, vertexSource,
includeDirs);
}
if (glx::shouldShaderBeReloaded(fragmentSource))
{
glx::reloadShader(shaderProgram, fragmentShader, fragmentSource,
includeDirs);
}
glUseProgram(shaderProgram);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
// Now draw the GUI elements.
gui::newFrame(guiWindowData);
ImGui::Begin("HUD");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0f / ImGui::GetIO().Framerate,
ImGui::GetIO().Framerate);
ImGui::End();
// Render the GUI.
ImGui::Render();
gui::endFrame(guiWindowData, guiRenderData);
glfwSwapBuffers(window);
glfwPollEvents();
}
// Clean up our resources.
gui::destroyGuiRenderData(guiRenderData);
gui::destroyGuiWindow(guiWindowData);
ImGui::DestroyContext();
glx::destroyGLFWWindow(window);
glx::terminateGLFW();
return 0;
}
<commit_msg>[brief] In shader example, replaces attrib locations with macros.<commit_after>#include "ShaderPaths.hpp"
#include "UniformLocations.glsl"
#include <atlas/glx/Buffer.hpp>
#include <atlas/glx/Context.hpp>
#include <atlas/glx/ErrorCallback.hpp>
#include <atlas/glx/GLSL.hpp>
#include <atlas/gui/GUI.hpp>
#include <fmt/printf.h>
#include <array>
using namespace atlas;
// We need to define an error callback function for GLFW, so we do that
// here.
void errorCallback(int code, char const* message)
{
fmt::print("error ({}):{}\n", code, message);
}
int main()
{
// First, lets create all of the structs that we're going to need.
glx::WindowSettings settings;
glx::WindowCallbacks callbacks;
gui::GuiRenderData guiRenderData;
gui::GuiWindowData guiWindowData;
// Set our window settings first.
{
settings.size.width = 1280;
settings.size.height = 720;
settings.title = "Hello Triangle";
}
// Now, let's make the window callbacks.
{
auto mousePressCallback = [&guiWindowData](int button, int action,
int mode) {
gui::mousePressedCallback(guiWindowData, button, action, mode);
};
auto mouseScrollCallback = [](double xOffset, double yOffset) {
gui::mouseScrollCallback(xOffset, yOffset);
};
auto keyPressCallback = [](int key, int scancode, int action,
int mods) {
gui::keyPressCallback(key, scancode, action, mods);
};
auto charCallback = [](unsigned int codepoint) {
gui::charCallback(codepoint);
};
callbacks.mousePressCallback = mousePressCallback;
callbacks.mouseScrollCallback = mouseScrollCallback;
callbacks.keyPressCallback = keyPressCallback;
callbacks.charCallback = charCallback;
}
// We're ready to start initializing things. So start with GLFW and OpenGL.
GLFWwindow* window;
{
glx::initializeGLFW(errorCallback);
// Next comes the window.
window = createGLFWWindow(settings);
// Bind the callbacks.
glx::bindWindowCallbacks(window, callbacks);
// Now bind the context.
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// Create the OpenGL context.
glx::createGLContext(window, settings.version);
// Set the error callback.
using namespace atlas::core;
glx::initializeGLCallback(glx::ErrorSource::All, glx::ErrorType::All,
glx::ErrorSeverity::High |
glx::ErrorSeverity::Medium);
}
// We have a window and a GL context, so now initialize the GUI.
{
ImGui::CreateContext();
ImGui::StyleColorsDark();
// Initialize the GUI structs. Remember to set the window!
gui::initializeGuiWindowData(guiWindowData);
gui::initializeGuiRenderData(guiRenderData);
setGuiWindow(guiWindowData, window);
}
// We want to draw a triangle on the screen, so let's setup all of the
// OpenGL variables next. Start with the shaders.
GLuint vertexShader{0};
GLuint fragmentShader{0};
GLuint shaderProgram{0};
glx::ShaderFile vertexSource;
glx::ShaderFile fragmentSource;
std::vector<std::string> includeDirs = {ShaderPath};
{
// Let's setup our shaders first. Create the program and the shaders.
shaderProgram = glCreateProgram();
vertexShader = glCreateShader(GL_VERTEX_SHADER);
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
std::string shaderRoot{ShaderPath};
std::string vertexFilename = shaderRoot + "triangle.vs.glsl";
vertexSource = glx::readShaderSource(vertexFilename, includeDirs);
std::string fragmentFilename = shaderRoot + "triangle.fs.glsl";
fragmentSource = glx::readShaderSource(fragmentFilename, includeDirs);
// Now compile both the shaders.
if (auto res =
glx::compileShader(vertexSource.sourceString, vertexShader);
res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
if (auto res =
glx::compileShader(fragmentSource.sourceString, fragmentShader);
res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
// Attach the shaders.
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
// Now link the shaders.
if (auto res = glx::linkShaders(shaderProgram); res)
{
fmt::print("error: {}\n", res.value());
return 0;
}
}
// Now let's setup the data and buffers for our triangle.
GLuint vbo;
GLuint vao;
{
// clang-format off
std::array<float, 18> vertices =
{
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
// clang-format on
glCreateVertexArrays(1, &vao);
glCreateBuffers(1, &vbo);
glNamedBufferStorage(vbo, glx::size<float>(vertices.size()),
vertices.data(), 0);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(VERTEX_ATTRIB_LOCATION, 3, GL_FLOAT, FALSE,
glx::stride<float>(6),
glx::bufferOffset<float>(0));
glVertexAttribPointer(COLOUR_ATTRIB_LOCATION, 3, GL_FLOAT, FALSE,
glx::stride<float>(6),
glx::bufferOffset<float>(3));
glEnableVertexAttribArray(VERTEX_ATTRIB_LOCATION);
glEnableVertexAttribArray(COLOUR_ATTRIB_LOCATION);
}
// Now we are ready for our main loop.
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Check if we have to reload the shaders.
if (glx::shouldShaderBeReloaded(vertexSource))
{
glx::reloadShader(shaderProgram, vertexShader, vertexSource,
includeDirs);
}
if (glx::shouldShaderBeReloaded(fragmentSource))
{
glx::reloadShader(shaderProgram, fragmentShader, fragmentSource,
includeDirs);
}
glUseProgram(shaderProgram);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
// Now draw the GUI elements.
gui::newFrame(guiWindowData);
ImGui::Begin("HUD");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0f / ImGui::GetIO().Framerate,
ImGui::GetIO().Framerate);
ImGui::End();
// Render the GUI.
ImGui::Render();
gui::endFrame(guiWindowData, guiRenderData);
glfwSwapBuffers(window);
glfwPollEvents();
}
// Clean up our resources.
gui::destroyGuiRenderData(guiRenderData);
gui::destroyGuiWindow(guiWindowData);
ImGui::DestroyContext();
glx::destroyGLFWWindow(window);
glx::terminateGLFW();
return 0;
}
<|endoftext|> |
<commit_before>//
// Created by vrosca on 1/21/17.
//
#include "ArrivalsProvider.hpp"
ArrivalsProvider::ArrivalsProvider (std::string station, std::string country, Calendar calendar) {
query = "MATCH (tr:Trip)-[t:TO_STOP]->(a:Stop{name: '" + station + "'}), (tr:Trip)-[:FOR]->(r:Route)-[:STARTS_AT]->(b:Stop), (b)-[t2:TO_TRIP]->(tr), (tr)-[:HAS]->(s:Service) WHERE ";
int max_day = 3;
for (int day = 0; day < max_day; day++) {
std::string dayName = calendar.getDayName();
std::string time = std::to_string(calendar.getDayTimeUnix() + day * 60 * 60 * 24);
query += "(t.arrival >= " + time + " AND s." + dayName + " = '1') ";
if (day < max_day - 1) {
query += "OR ";
}
else {
query += "RETURN r, b, t, tr;";
}
calendar.add(-1, Calendar::DAY);
}
type = "ArrivalsProvider";
}
json ArrivalsProvider::provide (neo4j_result_stream_t * result_stream) {
neo4j_result_t *result = neo4j_fetch_next(result_stream);
json json_response;
std::vector<json> pieces;
while (result != NULL) {
json json_response_piece;
json route = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 0))["properties"];
json origin = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 1))["properties"];
json edge = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 2))["properties"];
json trip = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 3))["properties"];
json_response_piece["route"] = route;
json_response_piece["origin"] = origin;
json_response_piece["arrival"] = edge["arrival"];
json_response_piece["delay"] = trip["delay"];
json_response_piece["trip_id"] = trip["id"];
pieces.push_back(json_response_piece);
result = neo4j_fetch_next(result_stream);
}
json_response = json(pieces);
pieces.clear();
return json_response;
}<commit_msg>Find if arrival is active or not and pass it<commit_after>//
// Created by vrosca on 1/21/17.
//
#include "ArrivalsProvider.hpp"
ArrivalsProvider::ArrivalsProvider (std::string station, std::string country, Calendar calendar) {
query = "MATCH (tr:Trip)-[t:TO_STOP]->(a:Stop{name: '" + station + "'}), (tr:Trip)-[:FOR]->(r:Route)-[:STARTS_AT]->(b:Stop), (b)-[t2:TO_TRIP]->(tr), (tr)-[:HAS]->(s:Service) WHERE ";
std::string case_when;
int max_day = 3;
for (int day = 0; day < max_day; day++) {
std::string dayName = calendar.getDayName();
std::string time = std::to_string(calendar.getDayTimeUnix() + day * 60 * 60 * 24);
query += "(t.arrival >= " + time + " AND s." + dayName + " = '1') ";
if (day < max_day - 1) {
query += "OR ";
case_when += "(t2.departure <= " + time + " AND s." + dayName + " = '1' AND t.arrival >= " + time + ") OR ";
}
else {
case_when += "(t.departure <= " + time + " AND s." + dayName + " = '1') then 1 else 0 end;";
query += "RETURN r, b, t, tr, case when " + case_when;
}
calendar.add(-1, Calendar::DAY);
}
type = "ArrivalsProvider";
}
json ArrivalsProvider::provide (neo4j_result_stream_t * result_stream) {
neo4j_result_t *result = neo4j_fetch_next(result_stream);
json json_response;
std::vector<json> pieces;
while (result != NULL) {
json json_response_piece;
json route = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 0))["properties"];
json origin = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 1))["properties"];
json edge = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 2))["properties"];
json trip = DatabaseUtils::GetInstance().neo4j_to_json(neo4j_result_field(result, 3))["properties"];
int is_running = (int) neo4j_int_value(neo4j_result_field(result, 4));
json_response_piece["route"] = route;
json_response_piece["origin"] = origin;
json_response_piece["arrival"] = edge["arrival"];
json_response_piece["delay"] = trip["delay"];
json_response_piece["trip_id"] = trip["id"];
json_response_piece["running"] = is_running;
pieces.push_back(json_response_piece);
result = neo4j_fetch_next(result_stream);
}
json_response = json(pieces);
pieces.clear();
return json_response;
}<|endoftext|> |
<commit_before>#include "Maze.h"
int main(int argc, char **argv){
Maze::Launch(argc, argv);
return 0;
}<commit_msg>Just add line to ignore all the annoying warnings<commit_after>#ifdef __APPLE__
#pragma GCC diagnostic ignored "-Wwarning-flag"
#endif
#include "Maze.h"
int main(int argc, char **argv){
Maze::Launch(argc, argv);
return 0;
}<|endoftext|> |
<commit_before>//===--- GuaranteedARCOpts.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-guaranteed-arc-opts"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SIL/SILVisitor.h"
#include "llvm/ADT/Statistic.h"
using namespace swift;
STATISTIC(NumInstsEliminated, "Number of instructions eliminated");
namespace {
struct GuaranteedARCOptsVisitor
: SILInstructionVisitor<GuaranteedARCOptsVisitor, bool> {
bool visitValueBase(ValueBase *V) { return false; }
bool visitDestroyAddrInst(DestroyAddrInst *DAI);
bool visitStrongReleaseInst(StrongReleaseInst *SRI);
bool visitDestroyValueInst(DestroyValueInst *DVI);
bool visitReleaseValueInst(ReleaseValueInst *RVI);
};
} // end anonymous namespace
static SILBasicBlock::reverse_iterator
getPrevReverseIterator(SILInstruction *I) {
return std::next(I->getIterator().getReverse());
}
bool GuaranteedARCOptsVisitor::visitDestroyAddrInst(DestroyAddrInst *DAI) {
SILValue Operand = DAI->getOperand();
for (auto II = getPrevReverseIterator(DAI), IE = DAI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) {
if (CA->getSrc() == Operand && !CA->isTakeOfSrc()) {
CA->setIsTakeOfSrc(IsTake);
DAI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
}
// destroy_addrs commonly exist in a block of dealloc_stack's, which don't
// affect take-ability.
if (isa<DeallocStackInst>(Inst))
continue;
// This code doesn't try to prove tricky validity constraints about whether
// it is safe to push the destroy_addr past interesting instructions.
if (Inst->mayHaveSideEffects())
break;
}
// If we didn't find a copy_addr to fold this into, emit the destroy_addr.
return false;
}
static bool couldReduceStrongRefcount(SILInstruction *Inst) {
// Simple memory accesses cannot reduce refcounts.
if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) ||
isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) ||
isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) ||
isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst))
return false;
// Assign and copyaddr of trivial types cannot drop refcounts, and 'inits'
// never can either. Nontrivial ones can though, because the overwritten
// value drops a retain. We would have to do more alias analysis to be able
// to safely ignore one of those.
if (auto *AI = dyn_cast<AssignInst>(Inst)) {
SILType StoredType = AI->getOperand(0)->getType();
if (StoredType.isTrivial(Inst->getModule()) ||
StoredType.is<ReferenceStorageType>())
return false;
}
if (auto *CAI = dyn_cast<CopyAddrInst>(Inst)) {
// Initializations can only increase refcounts.
if (CAI->isInitializationOfDest())
return false;
SILType StoredType = CAI->getOperand(0)->getType().getObjectType();
if (StoredType.isTrivial(Inst->getModule()) ||
StoredType.is<ReferenceStorageType>())
return false;
}
// This code doesn't try to prove tricky validity constraints about whether
// it is safe to push the release past interesting instructions.
return Inst->mayHaveSideEffects();
}
bool GuaranteedARCOptsVisitor::visitStrongReleaseInst(StrongReleaseInst *SRI) {
SILValue Operand = SRI->getOperand();
// Release on a functionref is a noop.
if (isa<FunctionRefInst>(Operand)) {
SRI->eraseFromParent();
++NumInstsEliminated;
return true;
}
// Check to see if the instruction immediately before the insertion point is a
// strong_retain of the specified operand. If so, we can zap the pair.
for (auto II = getPrevReverseIterator(SRI), IE = SRI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *SRA = dyn_cast<StrongRetainInst>(Inst)) {
if (SRA->getOperand() == Operand) {
SRA->eraseFromParent();
SRI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce strong refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
// If we didn't find a retain to fold this into, return false.
return false;
}
bool GuaranteedARCOptsVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
SILValue Operand = DVI->getOperand();
for (auto II = getPrevReverseIterator(DVI), IE = DVI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *CVI = dyn_cast<CopyValueInst>(Inst)) {
if (SILValue(CVI) == Operand || CVI->getOperand() == Operand) {
CVI->replaceAllUsesWith(CVI->getOperand());
CVI->eraseFromParent();
DVI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
return false;
}
bool GuaranteedARCOptsVisitor::visitReleaseValueInst(ReleaseValueInst *RVI) {
SILValue Operand = RVI->getOperand();
for (auto II = getPrevReverseIterator(RVI), IE = RVI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *SRA = dyn_cast<RetainValueInst>(Inst)) {
if (SRA->getOperand() == Operand) {
SRA->eraseFromParent();
RVI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
// If we didn't find a retain to fold this into, emit the release.
return false;
}
//===----------------------------------------------------------------------===//
// Top Level Entrypoint
//===----------------------------------------------------------------------===//
namespace {
struct GuaranteedARCOpts : SILFunctionTransform {
void run() override {
GuaranteedARCOptsVisitor Visitor;
bool MadeChange = false;
SILFunction *F = getFunction();
for (auto &BB : *F) {
for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
SILInstruction *I = &*II;
++II;
MadeChange |= Visitor.visit(I);
}
}
if (MadeChange) {
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createGuaranteedARCOpts() {
return new GuaranteedARCOpts();
}
<commit_msg>Guaranteed ARC Opts: Access instructions do not reduce refcounts.<commit_after>//===--- GuaranteedARCOpts.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-guaranteed-arc-opts"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SIL/SILVisitor.h"
#include "llvm/ADT/Statistic.h"
using namespace swift;
STATISTIC(NumInstsEliminated, "Number of instructions eliminated");
namespace {
struct GuaranteedARCOptsVisitor
: SILInstructionVisitor<GuaranteedARCOptsVisitor, bool> {
bool visitValueBase(ValueBase *V) { return false; }
bool visitDestroyAddrInst(DestroyAddrInst *DAI);
bool visitStrongReleaseInst(StrongReleaseInst *SRI);
bool visitDestroyValueInst(DestroyValueInst *DVI);
bool visitReleaseValueInst(ReleaseValueInst *RVI);
};
} // end anonymous namespace
static SILBasicBlock::reverse_iterator
getPrevReverseIterator(SILInstruction *I) {
return std::next(I->getIterator().getReverse());
}
bool GuaranteedARCOptsVisitor::visitDestroyAddrInst(DestroyAddrInst *DAI) {
SILValue Operand = DAI->getOperand();
for (auto II = getPrevReverseIterator(DAI), IE = DAI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) {
if (CA->getSrc() == Operand && !CA->isTakeOfSrc()) {
CA->setIsTakeOfSrc(IsTake);
DAI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
}
// destroy_addrs commonly exist in a block of dealloc_stack's, which don't
// affect take-ability.
if (isa<DeallocStackInst>(Inst))
continue;
// This code doesn't try to prove tricky validity constraints about whether
// it is safe to push the destroy_addr past interesting instructions.
if (Inst->mayHaveSideEffects())
break;
}
// If we didn't find a copy_addr to fold this into, emit the destroy_addr.
return false;
}
static bool couldReduceStrongRefcount(SILInstruction *Inst) {
// Simple memory accesses cannot reduce refcounts.
if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) ||
isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) ||
isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) ||
isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst) ||
isa<BeginAccessInst>(Inst) || isa<EndAccessInst>(Inst) ||
isa<BeginUnpairedAccessInst>(Inst) || isa<EndUnpairedAccessInst>(Inst))
return false;
// Assign and copyaddr of trivial types cannot drop refcounts, and 'inits'
// never can either. Nontrivial ones can though, because the overwritten
// value drops a retain. We would have to do more alias analysis to be able
// to safely ignore one of those.
if (auto *AI = dyn_cast<AssignInst>(Inst)) {
SILType StoredType = AI->getOperand(0)->getType();
if (StoredType.isTrivial(Inst->getModule()) ||
StoredType.is<ReferenceStorageType>())
return false;
}
if (auto *CAI = dyn_cast<CopyAddrInst>(Inst)) {
// Initializations can only increase refcounts.
if (CAI->isInitializationOfDest())
return false;
SILType StoredType = CAI->getOperand(0)->getType().getObjectType();
if (StoredType.isTrivial(Inst->getModule()) ||
StoredType.is<ReferenceStorageType>())
return false;
}
// This code doesn't try to prove tricky validity constraints about whether
// it is safe to push the release past interesting instructions.
return Inst->mayHaveSideEffects();
}
bool GuaranteedARCOptsVisitor::visitStrongReleaseInst(StrongReleaseInst *SRI) {
SILValue Operand = SRI->getOperand();
// Release on a functionref is a noop.
if (isa<FunctionRefInst>(Operand)) {
SRI->eraseFromParent();
++NumInstsEliminated;
return true;
}
// Check to see if the instruction immediately before the insertion point is a
// strong_retain of the specified operand. If so, we can zap the pair.
for (auto II = getPrevReverseIterator(SRI), IE = SRI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *SRA = dyn_cast<StrongRetainInst>(Inst)) {
if (SRA->getOperand() == Operand) {
SRA->eraseFromParent();
SRI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce strong refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
// If we didn't find a retain to fold this into, return false.
return false;
}
bool GuaranteedARCOptsVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
SILValue Operand = DVI->getOperand();
for (auto II = getPrevReverseIterator(DVI), IE = DVI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *CVI = dyn_cast<CopyValueInst>(Inst)) {
if (SILValue(CVI) == Operand || CVI->getOperand() == Operand) {
CVI->replaceAllUsesWith(CVI->getOperand());
CVI->eraseFromParent();
DVI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
return false;
}
bool GuaranteedARCOptsVisitor::visitReleaseValueInst(ReleaseValueInst *RVI) {
SILValue Operand = RVI->getOperand();
for (auto II = getPrevReverseIterator(RVI), IE = RVI->getParent()->rend();
II != IE;) {
auto *Inst = &*II;
++II;
if (auto *SRA = dyn_cast<RetainValueInst>(Inst)) {
if (SRA->getOperand() == Operand) {
SRA->eraseFromParent();
RVI->eraseFromParent();
NumInstsEliminated += 2;
return true;
}
// Skip past unrelated retains.
continue;
}
// Scan past simple instructions that cannot reduce refcounts.
if (couldReduceStrongRefcount(Inst))
break;
}
// If we didn't find a retain to fold this into, emit the release.
return false;
}
//===----------------------------------------------------------------------===//
// Top Level Entrypoint
//===----------------------------------------------------------------------===//
namespace {
struct GuaranteedARCOpts : SILFunctionTransform {
void run() override {
GuaranteedARCOptsVisitor Visitor;
bool MadeChange = false;
SILFunction *F = getFunction();
for (auto &BB : *F) {
for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
SILInstruction *I = &*II;
++II;
MadeChange |= Visitor.visit(I);
}
}
if (MadeChange) {
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createGuaranteedARCOpts() {
return new GuaranteedARCOpts();
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief player クラス
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include "gui_test.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_slider.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_radio.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_tree.hpp"
#include "widgets/widget_filer.hpp"
#include "img_io/img_base.hpp"
img::img_base<img::rgba8> img_;
namespace app {
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void gui_test::initialize()
{
gl::IGLcore* igl = gl::get_glcore();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
if(1) { // ラジオボタンのテスト
widget::param wpr(vtx::srect(20, 20, 130, 200), 0);
widget_null::param wpr_;
widget* root = wd.add_widget<widget_null>(wpr, wpr_);
root->set_state(widget::state::POSITION_LOCK);
widget::param wp(vtx::srect(0, 0, 130, 30), root);
widget_radio::param wp_("Enable");
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wp_.check_ = true;
wd.add_widget<widget_radio>(wp, wp_);
}
if(1) { // リストのテスト
widget::param wp(vtx::srect(30, 300, 150, 40), 0);
widget_list::param wp_("List Box");
wp_.text_list_.push_back("abc");
wp_.text_list_.push_back("1234");
wp_.text_list_.push_back("qwert");
wd.add_widget<widget_list>(wp, wp_);
}
if(1) { // イメージのテスト
widget::param wp(vtx::srect(400, 20, 500, 250), 0);
img::paint pa;
pa.set_fore_color(img::rgba8(0, 255, 0));
pa.create(vtx::spos(500, 250), true);
pa.fill(img::rgba8(255, 100, 100));
pa.alpha_blend();
pa.fill_circle(vtx::spos(250), 220);
vtx::sposs ss;
ss.push_back(vtx::spos(10, 10));
ss.push_back(vtx::spos(100, 100));
ss.push_back(vtx::spos(50, 200));
pa.set_fore_color(img::rgba8(240, 40, 50));
// pa.fill_polygon(ss);
widget_image::param wp_(&pa);
wd.add_widget<widget_image>(wp, wp_);
}
if(1) { // テキストのテスト
widget::param wp(vtx::srect(400, 20, 200, 250), 0);
widget_text::param wp_;
wp_.text_param_.text_ = "日本の美しい漢字\nqwertyuiop\nzxcvbnm";
wp_.text_param_.placement_.vpt = vtx::placement::vertical::CENTER;
wd.add_widget<widget_text>(wp, wp_);
}
if(1) { // フレームのテスト
widget::param wp(vtx::srect(200, 20, 100, 80));
widget_frame::param wp_;
frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
if(1) { // ダイアログのテスト
widget::param wp(vtx::srect(300, 300, 300, 200));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::param::style::CANCEL_OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->set_text("ああああ\nうううう\nいいいい\n漢字\n日本");
}
if(1) { // ラベルのテスト
widget::param wp(vtx::srect(30, 250, 150, 40));
widget_label::param wp_("Label");
wd.add_widget<widget_label>(wp, wp_);
}
if(1) { // ボタンのテスト(ダイアログ開始ボタン)
widget::param wp(vtx::srect(30, 200, 100, 40));
widget_button::param wp_("Daialog");
dialog_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ボタンのテスト(ファイラー開始ボタン)
widget::param wp(vtx::srect(30, 150, 100, 40));
widget_button::param wp_("Filer");
filer_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // スライダーのテスト
widget::param wp(vtx::srect(30, 400, 180, 20));
widget_slider::param wp_;
slider_ = wd.add_widget<widget_slider>(wp, wp_);
}
if(1) { // ファイラーのテスト
widget::param wp(vtx::srect(10, 30, 300, 200));
widget_filer::param wp_(igl->get_current_path());
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
if(1) { // チェックボックスのテスト
widget::param wp(vtx::srect(20, 350, 130, 30));
widget_check::param wp_("Disable");
wd.add_widget<widget_check>(wp, wp_);
}
if(1) { // ツリーのテスト
{
widget::param wp(vtx::srect(400, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
tree_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
widget::param wp(vtx::srect(0), tree_frame_);
widget_tree::param wp_;
tree_core_ = wd.add_widget<widget_tree>(wp, wp_);
tree_core_->set_state(widget::state::CLIP_PARENTS);
tree_core_->set_state(widget::state::RESIZE_ROOT);
tree_core_->set_state(widget::state::MOVE_ROOT, false);
widget_tree::tree_unit& tu = tree_core_->at_tree_unit();
tu.make_directory("/root0");
tu.make_directory("/root1");
tu.set_current_path("/root0");
{
widget_tree::value v;
v.data_ = "AAA";
tu.install("sub0", v);
}
{
widget_tree::value v;
v.data_ = "BBB";
tu.install("sub1", v);
}
tu.make_directory("sub2");
tu.set_current_path("sub2");
{
widget_tree::value v;
v.data_ = "CCC";
tu.install("sub-sub", v);
}
tu.set_current_path("/root1");
{
widget_tree::value v;
v.data_ = "ASDFG";
tu.install("sub_A", v);
}
{
widget_tree::value v;
v.data_ = "ZXCVB";
tu.install("sub_B", v);
}
// tu.list("/root");
// tu.list();
}
if(1) { // ターミナルのテスト
{
widget::param wp(vtx::srect(700, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::srect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(frame_) {
frame_->load(pre);
}
if(tree_frame_) {
tree_frame_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void gui_test::update()
{
gl::IGLcore* igl = gl::get_glcore();
const vtx::spos& size = igl->get_size();
gui::widget_director& wd = director_.at().widget_director_;
if(dialog_open_) {
if(dialog_open_->get_selected()) {
if(dialog_) {
dialog_->enable();
}
}
}
if(filer_open_) {
if(filer_open_->get_selected()) {
if(filer_) {
filer_->enable();
}
}
}
if(filer_) {
if(filer_id_ != filer_->get_select_file_id()) {
filer_id_ = filer_->get_select_file_id();
std::cout << "Filer: '" << filer_->get_file() << "'" << std::endl;
}
}
if(terminal_core_) {
/// static wchar_t ch = ' ';
/// terminal_core_->output(ch);
/// ++ch;
/// if(ch >= 0x7f) ch = ' ';
}
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void gui_test::render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void gui_test::destroy()
{
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
if(tree_frame_) {
tree_frame_->save(pre);
}
if(frame_) {
frame_->save(pre);
}
}
}
<commit_msg>widget_label 文字入力のテスト<commit_after>//=====================================================================//
/*! @file
@brief player クラス
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include "gui_test.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_slider.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_radio.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_tree.hpp"
#include "widgets/widget_filer.hpp"
#include "img_io/img_base.hpp"
img::img_base<img::rgba8> img_;
namespace app {
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void gui_test::initialize()
{
gl::IGLcore* igl = gl::get_glcore();
using namespace gui;
widget_director& wd = director_.at().widget_director_;
if(1) { // ラジオボタンのテスト
widget::param wpr(vtx::srect(20, 20, 130, 200), 0);
widget_null::param wpr_;
widget* root = wd.add_widget<widget_null>(wpr, wpr_);
root->set_state(widget::state::POSITION_LOCK);
widget::param wp(vtx::srect(0, 0, 130, 30), root);
widget_radio::param wp_("Enable");
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wd.add_widget<widget_radio>(wp, wp_);
wp.rect_.org.y += 40;
wp_.check_ = true;
wd.add_widget<widget_radio>(wp, wp_);
}
if(1) { // リストのテスト
widget::param wp(vtx::srect(30, 300, 150, 40), 0);
widget_list::param wp_("List Box");
wp_.text_list_.push_back("abc");
wp_.text_list_.push_back("1234");
wp_.text_list_.push_back("qwert");
wd.add_widget<widget_list>(wp, wp_);
}
if(1) { // イメージのテスト
widget::param wp(vtx::srect(400, 20, 500, 250), 0);
img::paint pa;
pa.set_fore_color(img::rgba8(0, 255, 0));
pa.create(vtx::spos(500, 250), true);
pa.fill(img::rgba8(255, 100, 100));
pa.alpha_blend();
pa.fill_circle(vtx::spos(250), 220);
vtx::sposs ss;
ss.push_back(vtx::spos(10, 10));
ss.push_back(vtx::spos(100, 100));
ss.push_back(vtx::spos(50, 200));
pa.set_fore_color(img::rgba8(240, 40, 50));
// pa.fill_polygon(ss);
widget_image::param wp_(&pa);
wd.add_widget<widget_image>(wp, wp_);
}
if(1) { // テキストのテスト
widget::param wp(vtx::srect(400, 20, 200, 250), 0);
widget_text::param wp_;
wp_.text_param_.text_ = "日本の美しい漢字\nqwertyuiop\nzxcvbnm";
wp_.text_param_.placement_.vpt = vtx::placement::vertical::CENTER;
wd.add_widget<widget_text>(wp, wp_);
}
if(1) { // フレームのテスト
widget::param wp(vtx::srect(200, 20, 100, 80));
widget_frame::param wp_;
frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
if(1) { // ダイアログのテスト
widget::param wp(vtx::srect(300, 300, 300, 200));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::param::style::CANCEL_OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->set_text("ああああ\nうううう\nいいいい\n漢字\n日本");
}
if(1) { // ラベルのテスト
widget::param wp(vtx::srect(30, 250, 150, 40));
widget_label::param wp_("Label");
wp_.read_only_ = false;
wd.add_widget<widget_label>(wp, wp_);
}
if(1) { // ボタンのテスト(ダイアログ開始ボタン)
widget::param wp(vtx::srect(30, 200, 100, 40));
widget_button::param wp_("Daialog");
dialog_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // ボタンのテスト(ファイラー開始ボタン)
widget::param wp(vtx::srect(30, 150, 100, 40));
widget_button::param wp_("Filer");
filer_open_ = wd.add_widget<widget_button>(wp, wp_);
}
if(1) { // スライダーのテスト
widget::param wp(vtx::srect(30, 400, 180, 20));
widget_slider::param wp_;
slider_ = wd.add_widget<widget_slider>(wp, wp_);
}
if(1) { // ファイラーのテスト
widget::param wp(vtx::srect(10, 30, 300, 200));
widget_filer::param wp_(igl->get_current_path());
filer_ = wd.add_widget<widget_filer>(wp, wp_);
filer_->enable(false);
}
if(1) { // チェックボックスのテスト
widget::param wp(vtx::srect(20, 350, 130, 30));
widget_check::param wp_("Disable");
wd.add_widget<widget_check>(wp, wp_);
}
if(1) { // ツリーのテスト
{
widget::param wp(vtx::srect(400, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
tree_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
widget::param wp(vtx::srect(0), tree_frame_);
widget_tree::param wp_;
tree_core_ = wd.add_widget<widget_tree>(wp, wp_);
tree_core_->set_state(widget::state::CLIP_PARENTS);
tree_core_->set_state(widget::state::RESIZE_ROOT);
tree_core_->set_state(widget::state::MOVE_ROOT, false);
widget_tree::tree_unit& tu = tree_core_->at_tree_unit();
tu.make_directory("/root0");
tu.make_directory("/root1");
tu.set_current_path("/root0");
{
widget_tree::value v;
v.data_ = "AAA";
tu.install("sub0", v);
}
{
widget_tree::value v;
v.data_ = "BBB";
tu.install("sub1", v);
}
tu.make_directory("sub2");
tu.set_current_path("sub2");
{
widget_tree::value v;
v.data_ = "CCC";
tu.install("sub-sub", v);
}
tu.set_current_path("/root1");
{
widget_tree::value v;
v.data_ = "ASDFG";
tu.install("sub_A", v);
}
{
widget_tree::value v;
v.data_ = "ZXCVB";
tu.install("sub_B", v);
}
// tu.list("/root");
// tu.list();
}
if(1) { // ターミナルのテスト
{
widget::param wp(vtx::srect(700, 500, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(30);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::srect(0), terminal_frame_);
widget_terminal::param wp_;
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
}
}
// プリファレンスの取得
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->load(pre);
}
if(frame_) {
frame_->load(pre);
}
if(tree_frame_) {
tree_frame_->load(pre);
}
if(terminal_frame_) {
terminal_frame_->load(pre);
}
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void gui_test::update()
{
gl::IGLcore* igl = gl::get_glcore();
const vtx::spos& size = igl->get_size();
gui::widget_director& wd = director_.at().widget_director_;
if(dialog_open_) {
if(dialog_open_->get_selected()) {
if(dialog_) {
dialog_->enable();
}
}
}
if(filer_open_) {
if(filer_open_->get_selected()) {
if(filer_) {
filer_->enable();
}
}
}
if(filer_) {
if(filer_id_ != filer_->get_select_file_id()) {
filer_id_ = filer_->get_select_file_id();
std::cout << "Filer: '" << filer_->get_file() << "'" << std::endl;
}
}
/// if(terminal_core_) {
/// static wchar_t ch = ' ';
/// terminal_core_->output(ch);
/// ++ch;
/// if(ch >= 0x7f) ch = ' ';
/// }
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void gui_test::render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void gui_test::destroy()
{
sys::preference& pre = director_.at().preference_;
if(filer_) {
filer_->save(pre);
}
if(terminal_frame_) {
terminal_frame_->save(pre);
}
if(tree_frame_) {
tree_frame_->save(pre);
}
if(frame_) {
frame_->save(pre);
}
}
}
<|endoftext|> |
<commit_before>#include "binarytree.h"
#include <stdlib.h>
#include <fstream>
int main(int argc, char* argv[]) {
binarytree::BinaryTree<int> n;
for (int x = 0; x < 1000000; ++x) {
n.Add(rand() % 1000000);
}
for (auto el : n.Walk())
std::cout << el << std::endl;
}
<commit_msg>Make the C++ test case more like the Java one<commit_after>#include "binarytree.h"
#include <stdlib.h>
#include <fstream>
int main(int argc, char* argv[]) {
binarytree::BinaryTree<int> n;
for (int x = 0; x < 1000000; ++x) {
n.Add(rand());
}
}
<|endoftext|> |
<commit_before>// Time: build tree: O(n), query: O(h), modify: O(h)
// Space: O(h)
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
class SegmentTreeSumNode {
public:
int start, end;
long long sum;
SegmentTreeSumNode *left, *right;
SegmentTreeSumNode(int start, int end, long long sum) {
this->start = start;
this->end = end;
this->sum = sum;
this->left = this->right = NULL;
}
};
class Solution {
public:
/* you may need to use some attributes here */
SegmentTreeSumNode *root_;
/**
* @param A: An integer vector
*/
Solution(vector<int> A) {
root_ = build(A, 0, A.size() - 1);
}
/**
* @param start, end: Indices
* @return: The sum from start to end
*/
long long query(int start, int end) {
queryTree(root_, start, end);
}
/**
* @param index, value: modify A[index] to value.
*/
void modify(int index, int value) {
modifyTree(root_, index, value);
}
// Query Sum in given range.
long long queryTree(SegmentTreeSumNode *root, int start, int end) {
// Out of range.
if (root == nullptr || root->start > end || root->end < start) {
return 0;
}
// Current segment is totally within range [start, end]
if (root->start >= start && root->end <= end) {
return root->sum;
}
long long left = queryTree(root->left, start, end);
long long right = queryTree(root->right, start, end);
// Find sum in the children.
return left + right;
}
void modifyTree(SegmentTreeSumNode *root, int index, int value) {
// Out of range.
if (root == nullptr || root->start > index || root->end < index) {
return;
}
// Change the node's value with [index, index] to the new given value.
if (root->start == index && root->end == index) {
root->sum = value;
return;
}
modifyTree(root->left, index, value);
modifyTree(root->right, index, value);
int left_sum = root->left != nullptr? root->left->sum : 0;
int right_sum = root->right != nullptr? root->right->sum : 0;
// Update sum.
root->sum = left_sum + right_sum;
}
// Build segment tree.
SegmentTreeSumNode *build(vector<int> &A, int start, int end) {
if (start > end) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = A[start];
return root;
}
// Left child: start=A.left, end=(A.left + A.right) / 2.
root->left = build(A, start, (start + end) / 2);
// Right child: start=(A.left + A.right) / 2 + 1, end=A.right.
root->right = build(A, (start + end) / 2 + 1, end);
long long left_sum = root->left != nullptr? root->left->sum : 0;
long long right_sum = root->right != nullptr? root->right->sum : 0;
// Update sum.
root->sum = left_sum + right_sum;
return root;
}
};
<commit_msg>Update interval-sum-ii.cpp<commit_after>// Time: ctor: O(n),
// query: O(logn),
// modify: O(logn)
// Space: O(n)
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
// Segment Tree solution.
class SegmentTreeSumNode {
public:
int start, end;
long long sum;
SegmentTreeSumNode *left, *right;
SegmentTreeSumNode(int start, int end, long long sum) {
this->start = start;
this->end = end;
this->sum = sum;
this->left = this->right = NULL;
}
};
class Solution {
public:
/* you may need to use some attributes here */
SegmentTreeSumNode *root_;
/**
* @param A: An integer vector
*/
Solution(vector<int> A) {
root_ = build(A, 0, A.size() - 1);
}
/**
* @param start, end: Indices
* @return: The sum from start to end
*/
long long query(int start, int end) {
queryTree(root_, start, end);
}
/**
* @param index, value: modify A[index] to value.
*/
void modify(int index, int value) {
modifyTree(root_, index, value);
}
// Query Sum in given range.
long long queryTree(SegmentTreeSumNode *root, int start, int end) {
// Out of range.
if (root == nullptr || root->start > end || root->end < start) {
return 0;
}
// Current segment is totally within range [start, end]
if (root->start >= start && root->end <= end) {
return root->sum;
}
long long left = queryTree(root->left, start, end);
long long right = queryTree(root->right, start, end);
// Find sum in the children.
return left + right;
}
void modifyTree(SegmentTreeSumNode *root, int index, int value) {
// Out of range.
if (root == nullptr || root->start > index || root->end < index) {
return;
}
// Change the node's value with [index, index] to the new given value.
if (root->start == index && root->end == index) {
root->sum = value;
return;
}
modifyTree(root->left, index, value);
modifyTree(root->right, index, value);
int left_sum = root->left != nullptr? root->left->sum : 0;
int right_sum = root->right != nullptr? root->right->sum : 0;
// Update sum.
root->sum = left_sum + right_sum;
}
// Build segment tree.
SegmentTreeSumNode *build(vector<int> &A, int start, int end) {
if (start > end) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = A[start];
return root;
}
// Left child: start=A.left, end=(A.left + A.right) / 2.
root->left = build(A, start, (start + end) / 2);
// Right child: start=(A.left + A.right) / 2 + 1, end=A.right.
root->right = build(A, (start + end) / 2 + 1, end);
long long left_sum = root->left != nullptr? root->left->sum : 0;
long long right_sum = root->right != nullptr? root->right->sum : 0;
// Update sum.
root->sum = left_sum + right_sum;
return root;
}
};
// Time: ctor: O(nlogn),
// query: O(logn),
// modify: O(logn)
// Space: O(n)
// Binary Indexed Tree (BIT) solution.
class Solution2 {
public:
/* you may need to use some attributes here */
/**
* @param A: An integer vector
*/
Solution(vector<int> A) : nums_(A) {
bit_ = vector<int>(nums_.size() + 1);
for (int i = 0; i < nums_.size(); ++i) {
add(i, nums_[i]);
}
}
/**
* @param start, end: Indices
* @return: The sum from start to end
*/
long long query(int start, int end) {
int sum = sumRegion_bit(end);
if (start > 0) {
sum -= sumRegion_bit(start - 1);
}
return sum;
}
/**
* @param index, value: modify A[index] to value.
*/
void modify(int index, int value) {
if (value - nums_[index]) {
add(index, value - nums_[index]);
nums_[index] = value;
}
}
private:
vector<int> nums_;
vector<int> bit_;
int sumRegion_bit(int i) {
++i;
int sum = 0;
for (; i > 0; i -= lower_bit(i)) {
sum += bit_[i];
}
return sum;
}
void add(int i, int val) {
++i;
for (; i <= nums_.size(); i += lower_bit(i)) {
bit_[i] += val;
}
}
int lower_bit(int i) {
return i & -i;
}
};
<|endoftext|> |
<commit_before>
// (c) COPYRIGHT URI/MIT 1998
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)
//
// Implementation of the DODS Time class
// $Log: DODS_Time.cc,v $
// Revision 1.1 1998/12/28 19:07:33 jimg
// Initial version of the DODS_Time object
//
#include "config_dap.h"
static char rcsid[] __unused__ ="$Id: DODS_Time.cc,v 1.1 1998/12/28 19:07:33 jimg Exp $";
#ifdef __GNUG__
#pragma implementation
#endif
#include <stdio.h>
#include <assert.h>
#include <string>
#include <String.h>
#include <strstream.h>
#include <iomanip.h>
#include "BaseType.h"
#include "DODS_Time.h"
#include "debug.h"
#include "Error.h"
double DODS_Time::_eps = 1.0e-6;
static String time_syntax_string = \
"Invalid time: times must be given as hh:mm or hh:mm:ss with an optional\n\
suffix of GMT or UTC. In addition, 0 <= hh <=23, 0 <= mm <= 59 and\n\
0 <= ss <= 59.999999";
static inline double
compute_ssm(int hh, int mm, double ss)
{
return ((hh * 60 + mm) * 60) + ss;
}
static string
extract_argument(BaseType *arg)
{
if (arg->type() != dods_str_c)
throw Error(malformed_expr, "A DODS string argument is required.");
// Use String until conversion of String to string is complete. 9/3/98
// jhrg
String *sp = 0;
arg->buf2val((void **)&sp);
string s = sp->chars();
delete sp;
DBG(cerr << "s: " << s << endl);
return s;
}
bool
DODS_Time::OK()
{
return _hours >= 0 && _hours <= 23
&& _minutes >= 0 && _minutes <= 59
&& _seconds >= 0.0 && _seconds < 60.0;
}
// Public mfincs.
// Don't test this ctor with OK since a null Time is not OK for use but we
// want to be able to make one and then call set_time(). 12/16/98 jhrg
DODS_Time::DODS_Time(): _hours(-1), _minutes(-1), _seconds(-1),
_sec_since_midnight(-1), _gmt(false)
{
}
DODS_Time::DODS_Time(string time_str)
{
set_time(time_str);
}
DODS_Time::DODS_Time(BaseType *arg)
{
set_time(extract_argument(arg));
}
DODS_Time::DODS_Time(int hh, int mm, bool gmt = false):
_hours(hh), _minutes(mm), _seconds(0), _gmt(gmt)
{
_sec_since_midnight = compute_ssm(hh, mm, 0);
if (!OK())
throw Error(malformed_expr, time_syntax_string);
}
DODS_Time::DODS_Time(int hh, int mm, double ss, bool gmt = false):
_hours(hh), _minutes(mm), _seconds(ss), _gmt(gmt)
{
_sec_since_midnight = compute_ssm(hh, mm, ss);
if (!OK())
throw Error(malformed_expr, time_syntax_string);
}
void
DODS_Time::set_time(string time)
{
// Parse the date_str.
istrstream iss(time.data());
char c;
iss >> _hours;
iss >> c;
iss >> _minutes;
// If there are two colons, assume hours:minutes:seconds.
if (time.find_first_of(":") != time.find_last_of(":")) {
iss >> c;
iss >> _seconds;
}
_sec_since_midnight = compute_ssm(_hours, _minutes, _seconds);
string gmt;
iss >> gmt;
if (gmt == "GMT" || gmt == "gmt" || gmt == "UTC" || gmt == "utc")
_gmt = true;
else
_gmt = false;
if (!OK())
throw Error(malformed_expr, time_syntax_string);
}
void
DODS_Time::set_time(BaseType *arg)
{
set_time(extract_argument(arg));
}
void
DODS_Time::set_time(int hh, int mm, bool gmt = false)
{
set_time(hh, mm, 0, gmt);
}
void
DODS_Time::set_time(int hh, int mm, double ss, bool gmt = false)
{
_hours = hh;
_minutes = mm;
_seconds = ss;
_gmt = gmt;
_sec_since_midnight = compute_ssm(hh, mm, ss);
if (!OK())
throw Error(malformed_expr, time_syntax_string);
}
double
DODS_Time::get_epsilon() const
{
return _eps;
}
void
DODS_Time::set_epsilon(double eps)
{
_eps = eps;
}
int
operator==(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() + t1._eps >= t2.seconds_since_midnight()
&& t1.seconds_since_midnight() - t2._eps <= t2.seconds_since_midnight();
}
int
operator!=(DODS_Time &t1, DODS_Time &t2)
{
return !(t1 == t2);
}
// The relational ops > and < are possibly flaky. Note that the Intel machines
// and the Sparc machines *do* represent floating point numbers slightly
// differently.
int
operator>(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() > t2.seconds_since_midnight();
}
int
operator>=(DODS_Time &t1, DODS_Time &t2)
{
return t1 > t2 || t1 == t2;
}
int
operator<(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() < t2.seconds_since_midnight();
}
int
operator<=(DODS_Time &t1, DODS_Time &t2)
{
return t1 < t2 || t1 == t2;
}
double
DODS_Time::seconds_since_midnight() const
{
return _sec_since_midnight;
}
int
DODS_Time::hours() const
{
return _hours;
}
int
DODS_Time::minutes() const
{
return _minutes;
}
double
DODS_Time::seconds() const
{
return _seconds;
}
bool
DODS_Time::gmt() const
{
return _gmt;
}
string
DODS_Time::string_rep(bool gmt) const
{
ostrstream oss;
// Pad with leading zeros and use fixed fields of two chars for hours and
// minutes. Make sure that seconds < 10 have a leading zero but don't
// require their filed to have `precision' digits if they are all zero.
oss << setfill('0') << setw(2) << _hours << ":"
<< setfill('0') << setw(2) << _minutes << ":"
<< setfill('0') << setw(2) << setprecision(6) << _seconds << " ";
if (_gmt)
oss << "GMT";
oss << ends;
string time_str = oss.str();
oss.freeze(0);
return time_str;
}
<commit_msg>Define TEST to use this without the dap++ library (e.g., when testing DODS_Date_Time).<commit_after>
// (c) COPYRIGHT URI/MIT 1998
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)
//
// Implementation of the DODS Time class
// $Log: DODS_Time.cc,v $
// Revision 1.2 1998/12/30 06:38:26 jimg
// Define TEST to use this without the dap++ library (e.g., when testing
// DODS_Date_Time).
//
// Revision 1.1 1998/12/28 19:07:33 jimg
// Initial version of the DODS_Time object
//
#include "config_dap.h"
static char rcsid[] __unused__ ="$Id: DODS_Time.cc,v 1.2 1998/12/30 06:38:26 jimg Exp $";
#ifdef __GNUG__
#pragma implementation
#endif
#include <stdio.h>
#include <assert.h>
#include <string>
#include <String.h>
#include <strstream.h>
#include <iomanip.h>
#include "BaseType.h"
#include "DODS_Time.h"
#include "debug.h"
#include "Error.h"
double DODS_Time::_eps = 1.0e-6;
static String time_syntax_string = \
"Invalid time: times must be given as hh:mm or hh:mm:ss with an optional\n\
suffix of GMT or UTC. In addition, 0 <= hh <=23, 0 <= mm <= 59 and\n\
0 <= ss <= 59.999999";
static inline double
compute_ssm(int hh, int mm, double ss)
{
return ((hh * 60 + mm) * 60) + ss;
}
static string
extract_argument(BaseType *arg)
{
#ifndef TEST
if (arg->type() != dods_str_c)
throw Error(malformed_expr, "A DODS string argument is required.");
// Use String until conversion of String to string is complete. 9/3/98
// jhrg
String *sp = 0;
arg->buf2val((void **)&sp);
string s = sp->chars();
delete sp;
DBG(cerr << "s: " << s << endl);
return s;
#else
return "";
#endif
}
bool
DODS_Time::OK() const
{
return _hours >= 0 && _hours <= 23
&& _minutes >= 0 && _minutes <= 59
&& _seconds >= 0.0 && _seconds < 60.0;
}
// Public mfincs.
// Don't test this ctor with OK since a null Time is not OK for use but we
// want to be able to make one and then call set_time(). 12/16/98 jhrg
DODS_Time::DODS_Time(): _hours(-1), _minutes(-1), _seconds(-1),
_sec_since_midnight(-1), _gmt(false)
{
}
DODS_Time::DODS_Time(string time_str)
{
set_time(time_str);
}
DODS_Time::DODS_Time(BaseType *arg)
{
set_time(extract_argument(arg));
}
DODS_Time::DODS_Time(int hh, int mm, bool gmt = false):
_hours(hh), _minutes(mm), _seconds(0), _gmt(gmt)
{
_sec_since_midnight = compute_ssm(hh, mm, 0);
#ifndef TEST
if (!OK())
throw Error(malformed_expr, time_syntax_string);
#endif
}
DODS_Time::DODS_Time(int hh, int mm, double ss, bool gmt = false):
_hours(hh), _minutes(mm), _seconds(ss), _gmt(gmt)
{
_sec_since_midnight = compute_ssm(hh, mm, ss);
#ifndef TEST
if (!OK())
throw Error(malformed_expr, time_syntax_string);
#endif
}
void
DODS_Time::set_time(string time)
{
// Parse the date_str.
istrstream iss(time.data());
char c;
iss >> _hours;
iss >> c;
iss >> _minutes;
// If there are two colons, assume hours:minutes:seconds.
if (time.find(":") != time.rfind(":")) {
iss >> c;
iss >> _seconds;
}
_sec_since_midnight = compute_ssm(_hours, _minutes, _seconds);
string gmt;
iss >> gmt;
if (gmt == "GMT" || gmt == "gmt" || gmt == "UTC" || gmt == "utc")
_gmt = true;
else
_gmt = false;
#ifndef TEST
if (!OK())
throw Error(malformed_expr, time_syntax_string);
#endif
}
void
DODS_Time::set_time(BaseType *arg)
{
set_time(extract_argument(arg));
}
void
DODS_Time::set_time(int hh, int mm, bool gmt = false)
{
set_time(hh, mm, 0, gmt);
}
void
DODS_Time::set_time(int hh, int mm, double ss, bool gmt = false)
{
_hours = hh;
_minutes = mm;
_seconds = ss;
_gmt = gmt;
_sec_since_midnight = compute_ssm(hh, mm, ss);
#ifndef TEST
if (!OK())
throw Error(malformed_expr, time_syntax_string);
#endif
}
double
DODS_Time::get_epsilon() const
{
return _eps;
}
void
DODS_Time::set_epsilon(double eps)
{
_eps = eps;
}
int
operator==(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() + t1._eps >= t2.seconds_since_midnight()
&& t1.seconds_since_midnight() - t2._eps <= t2.seconds_since_midnight();
}
int
operator!=(DODS_Time &t1, DODS_Time &t2)
{
return !(t1 == t2);
}
// The relational ops > and < are possibly flaky. Note that the Intel machines
// and the Sparc machines *do* represent floating point numbers slightly
// differently.
int
operator>(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() > t2.seconds_since_midnight();
}
int
operator>=(DODS_Time &t1, DODS_Time &t2)
{
return t1 > t2 || t1 == t2;
}
int
operator<(DODS_Time &t1, DODS_Time &t2)
{
return t1.seconds_since_midnight() < t2.seconds_since_midnight();
}
int
operator<=(DODS_Time &t1, DODS_Time &t2)
{
return t1 < t2 || t1 == t2;
}
double
DODS_Time::seconds_since_midnight() const
{
return _sec_since_midnight;
}
int
DODS_Time::hours() const
{
return _hours;
}
int
DODS_Time::minutes() const
{
return _minutes;
}
double
DODS_Time::seconds() const
{
return _seconds;
}
bool
DODS_Time::gmt() const
{
return _gmt;
}
string
DODS_Time::string_rep(bool gmt) const
{
ostrstream oss;
// Pad with leading zeros and use fixed fields of two chars for hours and
// minutes. Make sure that seconds < 10 have a leading zero but don't
// require their filed to have `precision' digits if they are all zero.
oss << setfill('0') << setw(2) << _hours << ":"
<< setfill('0') << setw(2) << _minutes << ":"
<< setfill('0') << setw(2) << setprecision(6) << _seconds << " ";
if (_gmt)
oss << "GMT";
oss << ends;
string time_str = oss.str();
oss.freeze(0);
return time_str;
}
<|endoftext|> |
<commit_before>//#include <ros/ros.h>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <list>
#include <Eigen/Dense>
#include <sys/time.h>
#include <cmath>
#include <random>
#include <dynmeans/kerndynmeans.hpp>
#include "maxmatching.hpp"
using namespace std;
typedef Eigen::Vector2d V2d;
//function declarations
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings);
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev);
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double likelihoodstd, vector<V2d>& clusterData, vector<int>& trueLabels);
//random number generator
mt19937 rng;//uses the same seed every time, 5489u
class VectorGraph{
public:
std::vector<V2d> data, oldprms;
std::vector<int> oldprmlbls;
void updateData(std::vector<V2d> data){
this->data = data;
}
void updateOldParameters(std::vector<V2d> data, std::vector<int> lbls, std::vector<double> gammas, std::vector<int> prmlbls){
std::vector<V2d> updatedoldprms;
for (int i = 0; i < prmlbls.size(); i++){
//if there is no data assigned to this cluster, must be old/uninstantiated
if (find(lbls.begin(), lbls.end(), prmlbls[i]) == lbls.end()){
int oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));
updatedoldprms.push_back(oldprms[oldidx]);
//if the label is not in oldprmlbls, must be a new cluster
//furthermore, must have at least one label in lbls = prmlbls[i]
} else if (find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]) == oldprmlbls.end()) {
V2d tmpprm = V2d::Zero();
int tmpcnt = 0;
for (int j =0 ; j < lbls.size(); j++){
if (lbls[j] == prmlbls[i]){
tmpprm += data[j];
tmpcnt++;
}
}
tmpprm /= tmpcnt;
updatedoldprms.push_back(tmpprm);
//old instantiated cluster
} else {
int oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));
V2d tmpprm = gammas[i]*oldprms[oldidx];
int tmpcnt = 0;
for (int j =0 ; j < lbls.size(); j++){
if (lbls[j] == prmlbls[i]){
tmpprm += data[j];
tmpcnt++;
}
}
tmpprm /= (gammas[i]+tmpcnt);
updatedoldprms.push_back(tmpprm);
}
}
this->oldprms = updatedoldprms;
this->oldprmlbls = prmlbls;
}
double diagSelfSimDD(const int i) const{
return data[i].transpose()*data[i];
}
double offDiagSelfSimDD(const int i) const{
return 0;
}
double selfSimPP(const int i) const{
return oldprms[i].transpose()*oldprms[i];
}
double simDD(const int i, const int j) const{
return data[i].transpose()*data[j];
}
double simDP(const int i, const int j) const{
return data[i].transpose()*oldprms[j];
}
int getNodeCt(const int i) const{
return 1;
}
int getNNodes() const {
return data.size();
}
int getNOldPrms() const {
return oldprms.size();
}
};
int main(int argc, char** argv){
//generates clusters that jump around on the domain R^2
//they move stochastically with a normal distribution w/ std deviation 0.05
//they die stochastically with probability 0.05 at each step
//a cluster is created stochastically with probability 0.10 at each step in the area [0,1]x[0,1]
//note: when computing accuracy, ***proper tracking is taken into account***
//i.e. if true label 1 is matched to learned label 3, then that matching is fixed from that point forward
//later pairings that attempt to match true label 1 to something else
//or learned label 3 to something else are discarded
//constants
//play with these to change the data generation process
double birthProbability = 0.10;
double deathProbability = 0.05;
double motionStdDev = 0.05;
double clusterStdDev = 0.05;
int nDataPerClusterPerStep = 10; // datapoints generated for each cluster per timestep
int nSteps = 100;//run the experiment for nSteps steps
int initialClusters = 4; //the number of clusters to start with
//data structures for the cluster centers
vector<V2d> clusterCenters;
vector<bool> aliveClusters;
//start with some number of initial clusters
uniform_real_distribution<double> uniformDist01(0, 1);
for (int i = 0; i < initialClusters; i++){
V2d newCenter;
newCenter(0) = uniformDist01(rng);
newCenter(1) = uniformDist01(rng);
clusterCenters.push_back(newCenter);
aliveClusters.push_back(true);
}
//the Dynamic Means object
//play with lambda/Q/tau to change Dynamic Means' performance
double lambda = 10;
double T_Q = 5;
double K_tau = 1.05;
//double lambda = 0.05;
//double T_Q = 6.8;
//double K_tau = 1.01;
double Q = lambda/T_Q;
double tau = (T_Q*(K_tau-1.0)+1.0)/(T_Q-1.0);
int nRestarts = 10;
int nCoarsest = 50;
KernDynMeans<VectorGraph> kdm(lambda, Q, tau, false); //true);
VectorGraph vgr;
//run the experiment
double cumulativeAccuracy = 0;//stores the accuracy accumulated for each step
map<int, int> matchings;//stores the saved matchings from previous timesteps
//enables proper label tracking (see note at line 27)
for (int i = 0; i < nSteps; i++){
//----------------------------
//birth/death/motion processes
//----------------------------
cout << "Step " << i << ": Clusters undergoing birth/death/motion..." << endl;
birthDeathMotionProcesses(clusterCenters, aliveClusters, birthProbability, deathProbability, motionStdDev);
//------------------------------------------
//generate the data for the current timestep
//------------------------------------------
cout << "Step " << i << ": Generating data from the clusters..." << endl;
vector<V2d> clusterData;
vector<int> trueLabels;
generateData(clusterCenters, aliveClusters, nDataPerClusterPerStep, clusterStdDev, clusterData, trueLabels);
//------------------------------------------
//Take the vectors that we just created, and package them in the KD class defined above
//------------------------------------------
vgr.updateData(clusterData);
//----------------------------
//cluster using Dynamic Means
//---------------------------
vector<int> learnedLabels;
vector<double> gammas;
vector<int> prmlbls;
double tTaken, obj;
cout << "Step " << i << ": Clustering..." << endl;
kdm.cluster(vgr, nRestarts, nCoarsest, learnedLabels, obj, gammas, prmlbls, tTaken);
vgr.updateOldParameters(clusterData, learnedLabels, gammas, prmlbls);
//----------------------------------------------------
//calculate the accuracy via linear programming
//including proper cluster label tracking (see above)
//----------------------------------------------------
matchings = getMaxMatchingConsistentWithOldMatching(learnedLabels, trueLabels, matchings);
double acc = computeAccuracy(learnedLabels, trueLabels, matchings);
cout << "Step " << i << ": Accuracy = " << acc << "\%" << endl;
cumulativeAccuracy += acc;
}
cout << "Average Accuracy: " << cumulativeAccuracy/(double)nSteps << "\%" << endl;
cout << "Done!" << endl;
return 0;
}
//this function takes two label sets and a matching and outputs
//the accuracy of the labelling (assuming labels1 = learned, labels2 = true)
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings){
if (labels1.size() != labels2.size()){
cout << "Error: computeAccuracy requires labels1/labels2 to have the same size" << endl;
return -1;
}
double acc = 0;
for (int i = 0; i < labels1.size(); i++){
if (matchings[labels1[i]] == labels2[i]){
acc += 1.0;
}
}
//compute the accuracy
return 100.0*acc/(double)labels1.size();
}
//this function takes a set of cluster centers and runs them through a birth/death/motion model
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev){
//distributions
uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
uniform_real_distribution<double> uniformDist01(0, 1);
normal_distribution<double> transitionDistRadial(0, motionStdDev);
for (int j = 0; j < clusterCenters.size(); j++){
//for each cluster center, decide whether it dies
if (aliveClusters[j] && uniformDist01(rng) < deathProbability){
cout << "Cluster " << j << " died." << endl;
aliveClusters[j] = false;
} else if (aliveClusters[j]) {
//if it survived, move it stochastically
//radius sampled from normal
double steplen = transitionDistRadial(rng);
//angle sampled from uniform
double stepang = uniformDistAng(rng);
clusterCenters[j](0) += steplen*cos(stepang);
clusterCenters[j](1) += steplen*sin(stepang);
cout << "Cluster " << j << " moved to " << clusterCenters[j].transpose() << endl;
}
}
//decide whether to create a new cluster
if (uniformDist01(rng) < birthProbability || all_of(aliveClusters.begin(), aliveClusters.end(), [](bool b){return !b;}) ) {
V2d newCenter;
newCenter(0) = uniformDist01(rng);
newCenter(1) = uniformDist01(rng);
clusterCenters.push_back(newCenter);
aliveClusters.push_back(true);
cout << "Cluster " << clusterCenters.size()-1 << " was created at " << clusterCenters.back().transpose() << endl;
}
}
//this function takes a set of cluster centers and generates data from them
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double clusterStdDev, vector<V2d>& clusterData, vector<int>& trueLabels){
//distributions
uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
normal_distribution<double> likelihoodDistRadial(0, clusterStdDev);
//loop through alive centers, generate nDataPerClusterPerStep datapoints for each
for (int j = 0; j < clusterCenters.size(); j++){
if (aliveClusters[j]){
for (int k = 0; k < nDataPerClusterPerStep; k++){
V2d newData = clusterCenters[j];
double len = likelihoodDistRadial(rng);
double ang = uniformDistAng(rng);
newData(0) += len*cos(ang);
newData(1) += len*sin(ang);
clusterData.push_back(newData);
trueLabels.push_back(j);
}
}
}
}
<commit_msg>more param tweaking<commit_after>//#include <ros/ros.h>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <list>
#include <Eigen/Dense>
#include <sys/time.h>
#include <cmath>
#include <random>
#include <dynmeans/kerndynmeans.hpp>
#include "maxmatching.hpp"
using namespace std;
typedef Eigen::Vector2d V2d;
//function declarations
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings);
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev);
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double likelihoodstd, vector<V2d>& clusterData, vector<int>& trueLabels);
//random number generator
mt19937 rng;//uses the same seed every time, 5489u
class VectorGraph{
public:
std::vector<V2d> data, oldprms;
std::vector<int> oldprmlbls;
void updateData(std::vector<V2d> data){
this->data = data;
}
void updateOldParameters(std::vector<V2d> data, std::vector<int> lbls, std::vector<double> gammas, std::vector<int> prmlbls){
std::vector<V2d> updatedoldprms;
for (int i = 0; i < prmlbls.size(); i++){
//if there is no data assigned to this cluster, must be old/uninstantiated
if (find(lbls.begin(), lbls.end(), prmlbls[i]) == lbls.end()){
int oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));
updatedoldprms.push_back(oldprms[oldidx]);
//if the label is not in oldprmlbls, must be a new cluster
//furthermore, must have at least one label in lbls = prmlbls[i]
} else if (find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]) == oldprmlbls.end()) {
V2d tmpprm = V2d::Zero();
int tmpcnt = 0;
for (int j =0 ; j < lbls.size(); j++){
if (lbls[j] == prmlbls[i]){
tmpprm += data[j];
tmpcnt++;
}
}
tmpprm /= tmpcnt;
updatedoldprms.push_back(tmpprm);
//old instantiated cluster
} else {
int oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));
V2d tmpprm = gammas[i]*oldprms[oldidx];
int tmpcnt = 0;
for (int j =0 ; j < lbls.size(); j++){
if (lbls[j] == prmlbls[i]){
tmpprm += data[j];
tmpcnt++;
}
}
tmpprm /= (gammas[i]+tmpcnt);
updatedoldprms.push_back(tmpprm);
}
}
this->oldprms = updatedoldprms;
this->oldprmlbls = prmlbls;
}
double diagSelfSimDD(const int i) const{
return data[i].transpose()*data[i];
}
double offDiagSelfSimDD(const int i) const{
return 0;
}
double selfSimPP(const int i) const{
return oldprms[i].transpose()*oldprms[i];
}
double simDD(const int i, const int j) const{
return data[i].transpose()*data[j];
}
double simDP(const int i, const int j) const{
return data[i].transpose()*oldprms[j];
}
int getNodeCt(const int i) const{
return 1;
}
int getNNodes() const {
return data.size();
}
int getNOldPrms() const {
return oldprms.size();
}
};
int main(int argc, char** argv){
//generates clusters that jump around on the domain R^2
//they move stochastically with a normal distribution w/ std deviation 0.05
//they die stochastically with probability 0.05 at each step
//a cluster is created stochastically with probability 0.10 at each step in the area [0,1]x[0,1]
//note: when computing accuracy, ***proper tracking is taken into account***
//i.e. if true label 1 is matched to learned label 3, then that matching is fixed from that point forward
//later pairings that attempt to match true label 1 to something else
//or learned label 3 to something else are discarded
//constants
//play with these to change the data generation process
double birthProbability = 0.10;
double deathProbability = 0.05;
double motionStdDev = 0.05;
double clusterStdDev = 0.05;
int nDataPerClusterPerStep = 15; // datapoints generated for each cluster per timestep
int nSteps = 100;//run the experiment for nSteps steps
int initialClusters = 4; //the number of clusters to start with
//data structures for the cluster centers
vector<V2d> clusterCenters;
vector<bool> aliveClusters;
//start with some number of initial clusters
uniform_real_distribution<double> uniformDist01(0, 1);
for (int i = 0; i < initialClusters; i++){
V2d newCenter;
newCenter(0) = uniformDist01(rng);
newCenter(1) = uniformDist01(rng);
clusterCenters.push_back(newCenter);
aliveClusters.push_back(true);
}
//the Dynamic Means object
//play with lambda/Q/tau to change Dynamic Means' performance
double lambda = 0.05;
double T_Q = 6.8;
double K_tau = 1.01;
double Q = lambda/T_Q;
double tau = (T_Q*(K_tau-1.0)+1.0)/(T_Q-1.0);
int nRestarts = 10;
int nCoarsest = 50;
KernDynMeans<VectorGraph> kdm(lambda, Q, tau, false); //true);
VectorGraph vgr;
//run the experiment
double cumulativeAccuracy = 0;//stores the accuracy accumulated for each step
map<int, int> matchings;//stores the saved matchings from previous timesteps
//enables proper label tracking (see note at line 27)
for (int i = 0; i < nSteps; i++){
//----------------------------
//birth/death/motion processes
//----------------------------
cout << "Step " << i << ": Clusters undergoing birth/death/motion..." << endl;
birthDeathMotionProcesses(clusterCenters, aliveClusters, birthProbability, deathProbability, motionStdDev);
//------------------------------------------
//generate the data for the current timestep
//------------------------------------------
cout << "Step " << i << ": Generating data from the clusters..." << endl;
vector<V2d> clusterData;
vector<int> trueLabels;
generateData(clusterCenters, aliveClusters, nDataPerClusterPerStep, clusterStdDev, clusterData, trueLabels);
//------------------------------------------
//Take the vectors that we just created, and package them in the KD class defined above
//------------------------------------------
vgr.updateData(clusterData);
//----------------------------
//cluster using Dynamic Means
//---------------------------
vector<int> learnedLabels;
vector<double> gammas;
vector<int> prmlbls;
double tTaken, obj;
cout << "Step " << i << ": Clustering..." << endl;
kdm.cluster(vgr, nRestarts, nCoarsest, learnedLabels, obj, gammas, prmlbls, tTaken);
vgr.updateOldParameters(clusterData, learnedLabels, gammas, prmlbls);
//----------------------------------------------------
//calculate the accuracy via linear programming
//including proper cluster label tracking (see above)
//----------------------------------------------------
matchings = getMaxMatchingConsistentWithOldMatching(learnedLabels, trueLabels, matchings);
double acc = computeAccuracy(learnedLabels, trueLabels, matchings);
cout << "Step " << i << ": Accuracy = " << acc << "\%" << endl;
cumulativeAccuracy += acc;
}
cout << "Average Accuracy: " << cumulativeAccuracy/(double)nSteps << "\%" << endl;
cout << "Done!" << endl;
return 0;
}
//this function takes two label sets and a matching and outputs
//the accuracy of the labelling (assuming labels1 = learned, labels2 = true)
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings){
if (labels1.size() != labels2.size()){
cout << "Error: computeAccuracy requires labels1/labels2 to have the same size" << endl;
return -1;
}
double acc = 0;
for (int i = 0; i < labels1.size(); i++){
if (matchings[labels1[i]] == labels2[i]){
acc += 1.0;
}
}
//compute the accuracy
return 100.0*acc/(double)labels1.size();
}
//this function takes a set of cluster centers and runs them through a birth/death/motion model
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev){
//distributions
uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
uniform_real_distribution<double> uniformDist01(0, 1);
normal_distribution<double> transitionDistRadial(0, motionStdDev);
for (int j = 0; j < clusterCenters.size(); j++){
//for each cluster center, decide whether it dies
if (aliveClusters[j] && uniformDist01(rng) < deathProbability){
cout << "Cluster " << j << " died." << endl;
aliveClusters[j] = false;
} else if (aliveClusters[j]) {
//if it survived, move it stochastically
//radius sampled from normal
double steplen = transitionDistRadial(rng);
//angle sampled from uniform
double stepang = uniformDistAng(rng);
clusterCenters[j](0) += steplen*cos(stepang);
clusterCenters[j](1) += steplen*sin(stepang);
cout << "Cluster " << j << " moved to " << clusterCenters[j].transpose() << endl;
}
}
//decide whether to create a new cluster
if (uniformDist01(rng) < birthProbability || all_of(aliveClusters.begin(), aliveClusters.end(), [](bool b){return !b;}) ) {
V2d newCenter;
newCenter(0) = uniformDist01(rng);
newCenter(1) = uniformDist01(rng);
clusterCenters.push_back(newCenter);
aliveClusters.push_back(true);
cout << "Cluster " << clusterCenters.size()-1 << " was created at " << clusterCenters.back().transpose() << endl;
}
}
//this function takes a set of cluster centers and generates data from them
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double clusterStdDev, vector<V2d>& clusterData, vector<int>& trueLabels){
//distributions
uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
normal_distribution<double> likelihoodDistRadial(0, clusterStdDev);
//loop through alive centers, generate nDataPerClusterPerStep datapoints for each
for (int j = 0; j < clusterCenters.size(); j++){
if (aliveClusters[j]){
for (int k = 0; k < nDataPerClusterPerStep; k++){
V2d newData = clusterCenters[j];
double len = likelihoodDistRadial(rng);
double ang = uniformDistAng(rng);
newData(0) += len*cos(ang);
newData(1) += len*sin(ang);
clusterData.push_back(newData);
trueLabels.push_back(j);
}
}
}
}
<|endoftext|> |
<commit_before>#include "get_new_points.hxx"
#include "eval_weighted.hxx"
#include "poles_prefactor.hxx"
#include "power_prefactor.hxx"
#include "../sdp_solve.hxx"
#include "../ostream_set.hxx"
std::vector<El::BigFloat>
compute_optimal(const std::vector<Positive_Matrix_With_Prefactor> &matrices,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters)
{
size_t num_weights(normalization.size());
const size_t num_blocks(matrices.size());
std::vector<El::BigFloat> weights(num_weights, 0);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// Need to have a point at zero and infinity
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
const El::BigFloat min_x(0), max_x(infinity);
for(size_t block(0); block < num_blocks; ++block)
{
points.at(block).emplace(min_x);
points.at(block).emplace(0.1);
points.at(block).emplace(1);
// for(double x(min_x); x < max_x; x *= 4)
// points.at(block).emplace(x);
new_points.at(block).emplace_back(max_x);
}
bool has_new_points(true);
while(has_new_points)
{
has_new_points = false;
size_t num_constraints(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
matrices[block].polynomials.size());
if(El::mpi::Rank() == 0)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(El::mpi::Rank() == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
}
// std::cout << "matrix_dimensions: " << matrix_dimensions << "\n";
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
auto max_normalization(normalization.begin());
for(auto n(normalization.begin()); n != normalization.end(); ++n)
{
if(Abs(*n) > Abs(*max_normalization))
{
max_normalization = n;
}
}
const int64_t max_index(
std::distance(normalization.begin(), max_normalization));
for(size_t block(0); block != num_blocks; ++block)
{
const int64_t max_degree([&]() {
int64_t result(0);
for(auto &row : matrices[block].polynomials)
for(auto &column : row)
for(auto &poly : column)
{
result = std::max(result, poly.degree());
}
return result;
}());
for(auto &x : points.at(block))
{
El::BigFloat prefactor([&]() {
if(x == infinity)
{
return El::BigFloat(1);
}
return power_prefactor(matrices[block].damped_rational.base, x)
* poles_prefactor(matrices[block].damped_rational.poles,
x);
}());
const size_t dim(matrices[block].polynomials.size());
free_var_matrix.emplace_back(
dim * (dim + 1) / 2,
matrices[block].polynomials.at(0).at(0).size() - 1);
auto &free_var(free_var_matrix.back());
primal_objective_c.emplace_back();
auto &primal(primal_objective_c.back());
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
if(x == infinity)
{
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.degree()
< max_degree)
{
primal.push_back(0);
}
else
{
primal.push_back(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.coefficients.at(max_degree)
/ normalization.at(max_index));
}
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.degree()
< max_degree)
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index);
}
else
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.coefficients.at(max_degree);
}
}
}
else
{
primal.push_back(prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)(x)
/ normalization.at(max_index));
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)(x);
}
}
++flattened_matrix_row;
}
}
}
SDP sdp(objectives, normalization, primal_objective_c, free_var_matrix,
block_info, grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
for(auto &block : solver.y.blocks)
{
if(block.GlobalCol(0) == 0)
{
for(int64_t row(0); row != block.LocalHeight(); ++row)
{
int64_t global_row(block.GlobalRow(row));
const int64_t index(global_row
+ (global_row < max_index ? 0 : 1));
block.SetLocal(row, 0, weights.at(index));
}
}
}
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(reason != SDP_Solver_Terminate_Reason::PrimalDualOptimal)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization condition
// dot(norm,weights)=1
weights.at(max_index) = 1;
for(int64_t block_row(0); block_row != solver.y.blocks.at(0).Height();
++block_row)
{
const int64_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = solver.y.blocks.at(0).Get(block_row, 0);
weights.at(max_index) -= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(El::mpi::Rank() == 0)
{
std::cout.precision(10);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
for(size_t block(0); block != num_blocks; ++block)
{
// 0.01 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
// Mesh mesh(*(points.at(block).begin()), *(points.at(block).rbegin()),
Mesh mesh(*(points.at(block).begin()), El::BigFloat(100),
[&](const El::BigFloat &x) {
return eval_weighted(matrices[block], x, weights);
},
0.01);
new_points.at(block) = get_new_points(mesh);
for(auto &point : new_points.at(block))
{
has_new_points
= has_new_points || (points.at(block).count(point) == 0);
}
}
}
// if(El::mpi::Rank() == 0)
// {
// std::cout << "weights: " << weights << "\n";
// }
return weights;
}
<commit_msg>Rescale each row<commit_after>#include "get_new_points.hxx"
#include "eval_weighted.hxx"
#include "poles_prefactor.hxx"
#include "power_prefactor.hxx"
#include "../sdp_solve.hxx"
#include "../ostream_set.hxx"
std::vector<El::BigFloat>
compute_optimal(const std::vector<Positive_Matrix_With_Prefactor> &matrices,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters)
{
size_t num_weights(normalization.size());
const size_t num_blocks(matrices.size());
std::vector<El::BigFloat> weights(num_weights, 0);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// Need to have a point at zero and infinity
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
const El::BigFloat min_x(0), max_x(infinity);
for(size_t block(0); block < num_blocks; ++block)
{
points.at(block).emplace(min_x);
points.at(block).emplace(0.1);
points.at(block).emplace(1);
// for(double x(min_x); x < max_x; x *= 4)
// points.at(block).emplace(x);
new_points.at(block).emplace_back(max_x);
}
bool has_new_points(true);
while(has_new_points)
{
has_new_points = false;
size_t num_constraints(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
matrices[block].polynomials.size());
if(El::mpi::Rank() == 0)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(El::mpi::Rank() == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
}
// std::cout << "matrix_dimensions: " << matrix_dimensions << "\n";
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
auto max_normalization(normalization.begin());
for(auto n(normalization.begin()); n != normalization.end(); ++n)
{
if(Abs(*n) > Abs(*max_normalization))
{
max_normalization = n;
}
}
const int64_t max_index(
std::distance(normalization.begin(), max_normalization));
for(size_t block(0); block != num_blocks; ++block)
{
const int64_t max_degree([&]() {
int64_t result(0);
for(auto &row : matrices[block].polynomials)
for(auto &column : row)
for(auto &poly : column)
{
result = std::max(result, poly.degree());
}
return result;
}());
for(auto &x : points.at(block))
{
El::BigFloat prefactor([&]() {
if(x == infinity)
{
return El::BigFloat(1);
}
return power_prefactor(matrices[block].damped_rational.base, x)
* poles_prefactor(matrices[block].damped_rational.poles,
x);
}());
const size_t dim(matrices[block].polynomials.size());
free_var_matrix.emplace_back(
dim * (dim + 1) / 2,
matrices[block].polynomials.at(0).at(0).size() - 1);
auto &free_var(free_var_matrix.back());
primal_objective_c.emplace_back();
auto &primal(primal_objective_c.back());
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
if(x == infinity)
{
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.degree()
< max_degree)
{
primal.push_back(0);
}
else
{
primal.push_back(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.coefficients.at(max_degree)
/ normalization.at(max_index));
}
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.degree()
< max_degree)
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index);
}
else
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.coefficients.at(max_degree);
}
}
}
else
{
primal.push_back(prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)(x)
/ normalization.at(max_index));
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)(x);
}
}
++flattened_matrix_row;
}
// Rescale
const El::BigFloat scaling([&]() {
El::BigFloat max_value(0);
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
max_value = std::max(
max_value, El::Abs(primal.at(flattened_matrix_row)));
for(int64_t column(0); column != free_var.Width();
++column)
{
max_value = std::max(
max_value,
El::Abs(free_var(flattened_matrix_row, column)));
}
++flattened_matrix_row;
}
return 1 / max_value;
}());
{
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
primal.at(flattened_matrix_row) *= scaling;
for(int64_t column(0); column != free_var.Width();
++column)
{
free_var(flattened_matrix_row, column) *= scaling;
}
++flattened_matrix_row;
}
}
}
}
SDP sdp(objectives, normalization, primal_objective_c, free_var_matrix,
block_info, grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
for(auto &block : solver.y.blocks)
{
if(block.GlobalCol(0) == 0)
{
for(int64_t row(0); row != block.LocalHeight(); ++row)
{
int64_t global_row(block.GlobalRow(row));
const int64_t index(global_row
+ (global_row < max_index ? 0 : 1));
block.SetLocal(row, 0, weights.at(index));
}
}
}
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(reason != SDP_Solver_Terminate_Reason::PrimalDualOptimal)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization condition
// dot(norm,weights)=1
weights.at(max_index) = 1;
for(int64_t block_row(0); block_row != solver.y.blocks.at(0).Height();
++block_row)
{
const int64_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = solver.y.blocks.at(0).Get(block_row, 0);
weights.at(max_index) -= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(El::mpi::Rank() == 0)
{
std::cout.precision(10);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
for(size_t block(0); block != num_blocks; ++block)
{
// 0.01 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
// Mesh mesh(*(points.at(block).begin()), *(points.at(block).rbegin()),
Mesh mesh(*(points.at(block).begin()), El::BigFloat(100),
[&](const El::BigFloat &x) {
return eval_weighted(matrices[block], x, weights);
},
0.01);
new_points.at(block) = get_new_points(mesh);
for(auto &point : new_points.at(block))
{
has_new_points
= has_new_points || (points.at(block).count(point) == 0);
}
}
}
// if(El::mpi::Rank() == 0)
// {
// std::cout << "weights: " << weights << "\n";
// }
return weights;
}
<|endoftext|> |
<commit_before>/*
* Global Presence - wraps calls to set and get presence for all accounts.
*
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "global-presence.h"
#include <KTp/presence.h>
#include <QDBusPendingCall>
#include <QVariant>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountSet>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Types>
#include "types.h"
#include "ktp-debug.h"
namespace KTp
{
GlobalPresence::GlobalPresence(QObject *parent)
: QObject(parent),
m_connectionStatus(GlobalPresence::Disconnected),
m_changingPresence(false),
m_hasEnabledAccounts(false)
{
Tp::registerTypes();
m_statusHandlerInterface = new QDBusInterface(QLatin1String("org.freedesktop.Telepathy.Client.KTp.KdedIntegrationModule"),
QLatin1String("/StatusHandler"),
QString(),
QDBusConnection::sessionBus(), this);
m_requestedPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
m_currentPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
}
void GlobalPresence::setAccountManager(const Tp::AccountManagerPtr &accountManager)
{
m_accountManager = accountManager;
m_enabledAccounts = m_accountManager->enabledAccounts();
m_onlineAccounts = m_accountManager->onlineAccounts();
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
onAccountEnabledChanged(account);
}
connect(m_enabledAccounts.data(), &Tp::AccountSet::accountAdded, this, &GlobalPresence::onAccountEnabledChanged);
connect(m_enabledAccounts.data(), &Tp::AccountSet::accountRemoved, this, &GlobalPresence::onAccountEnabledChanged);
if (!m_accountManager->isReady()) {
qCWarning(KTP_COMMONINTERNALS) << "GlobalPresence used with unready account manager";
} else {
Q_EMIT accountManagerReady();
}
}
void GlobalPresence::addAccountManager(const Tp::AccountManagerPtr &accountManager)
{
connect(accountManager->becomeReady(), &Tp::PendingReady::finished, [=] (Tp::PendingOperation* op) {
if (op->isError()) {
qCDebug(KTP_COMMONINTERNALS) << op->errorName();
qCDebug(KTP_COMMONINTERNALS) << op->errorMessage();
qCDebug(KTP_COMMONINTERNALS) << "Something unexpected happened to"
<< "the core part of your Instant Messaging system and it couldn't"
<< "be initialized. Try restarting the client.";
return;
}
setAccountManager(accountManager);
});
}
Tp::AccountManagerPtr GlobalPresence::accountManager() const
{
return m_accountManager;
}
GlobalPresence::ConnectionStatus GlobalPresence::connectionStatus() const
{
return m_connectionStatus;
}
KTp::Presence GlobalPresence::currentPresence() const
{
return m_currentPresence;
}
QString GlobalPresence::currentPresenceMessage() const
{
return m_currentPresence.statusMessage();
}
QIcon GlobalPresence::currentPresenceIcon() const
{
return m_currentPresence.icon();
}
QString GlobalPresence::currentPresenceIconName() const
{
return m_currentPresence.iconName();
}
QString GlobalPresence::currentPresenceName() const
{
return m_currentPresence.displayString();
}
GlobalPresence::ConnectionPresenceType GlobalPresence::currentPresenceType() const
{
switch(m_currentPresence.type()) {
case Tp::ConnectionPresenceTypeAvailable:
return GlobalPresence::Available;
case Tp::ConnectionPresenceTypeBusy:
return GlobalPresence::Busy;
case Tp::ConnectionPresenceTypeAway:
return GlobalPresence::Away;
case Tp::ConnectionPresenceTypeExtendedAway:
return GlobalPresence::ExtendedAway;
case Tp::ConnectionPresenceTypeHidden:
return GlobalPresence::Hidden;
case Tp::ConnectionPresenceTypeOffline:
return GlobalPresence::Offline;
default:
return GlobalPresence::Unknown;
}
}
KTp::Presence GlobalPresence::requestedPresence() const
{
return m_requestedPresence;
}
QString GlobalPresence::requestedPresenceName() const
{
return m_requestedPresence.displayString();
}
bool GlobalPresence::isChangingPresence() const
{
return m_changingPresence;
}
KTp::Presence GlobalPresence::globalPresence() const
{
KTp::Presence globalPresence;
globalPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
if (m_statusHandlerInterface->property("requestedGlobalPresence").isValid()) {
globalPresence = KTp::Presence(qdbus_cast<Tp::SimplePresence>(m_statusHandlerInterface->property("requestedGlobalPresence")));
}
return globalPresence;
}
void GlobalPresence::setPresence(const KTp::Presence &presence, PresenceClass presenceClass)
{
if (m_enabledAccounts.isNull()) {
qCWarning(KTP_COMMONINTERNALS) << "Requested presence change on empty accounts set";
return;
}
if (!presence.isValid()) {
qCWarning(KTP_COMMONINTERNALS) << "Invalid requested presence";
return;
}
QDBusPendingCall call = m_statusHandlerInterface->asyncCall(QLatin1String("setRequestedGlobalPresence"), QVariant::fromValue<Tp::SimplePresence>(presence.barePresence()), QVariant::fromValue<uint>(presenceClass));
}
void GlobalPresence::setPresence(GlobalPresence::ConnectionPresenceType type, QString message, PresenceClass presenceClass)
{
KTp::Presence presence;
switch (type) {
case GlobalPresence::Available:
presence = KTp::Presence::available(message);
break;
case GlobalPresence::Busy:
presence = KTp::Presence::busy(message);
break;
case GlobalPresence::Away:
presence = KTp::Presence::away(message);
break;
case GlobalPresence::ExtendedAway:
presence = KTp::Presence::xa(message);
break;
case GlobalPresence::Hidden:
presence = KTp::Presence::hidden(message);
break;
case GlobalPresence::Offline:
presence = KTp::Presence::offline(message);
break;
case GlobalPresence::Unknown:
presence = KTp::Presence(Tp::Presence(Tp::ConnectionPresenceTypeUnknown, QLatin1String("unknown"), message));
break;
case GlobalPresence::Unset:
presence = KTp::Presence(Tp::Presence(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), message));
break;
default:
qCDebug(KTP_COMMONINTERNALS) << "You should not be here!";
}
setPresence(presence, presenceClass);
}
void GlobalPresence::onAccountEnabledChanged(const Tp::AccountPtr &account)
{
if (account->isEnabled()) {
connect(account.data(), &Tp::Account::connectionStatusChanged, this, &GlobalPresence::onConnectionStatusChanged);
connect(account.data(), &Tp::Account::changingPresence, this, &GlobalPresence::onChangingPresence);
connect(account.data(), &Tp::Account::requestedPresenceChanged, this, &GlobalPresence::onRequestedPresenceChanged);
connect(account.data(), &Tp::Account::currentPresenceChanged, this, &GlobalPresence::onCurrentPresenceChanged);
} else {
disconnect(account.data());
}
onCurrentPresenceChanged(account->currentPresence());
onRequestedPresenceChanged(account->requestedPresence());
onChangingPresence(account->isChangingPresence());
onConnectionStatusChanged(account->connectionStatus());
if (m_hasEnabledAccounts != !m_enabledAccounts.data()->accounts().isEmpty()) {
m_hasEnabledAccounts = !m_enabledAccounts.data()->accounts().isEmpty();
Q_EMIT enabledAccountsChanged(m_hasEnabledAccounts);
}
qCDebug(KTP_COMMONINTERNALS) << "Account" << account->uniqueIdentifier()
<< "enabled:" << account->isEnabled();
}
void GlobalPresence::onCurrentPresenceChanged(const Tp::Presence ¤tPresence)
{
/* basic idea of choosing global presence it to make it reflects the presence
* over all accounts, usually this is used to indicates user the whole system
* status.
*
* If there isn't any account, currentPresence should be offline, since there is nothing
* online.
* If there's only one account, then currentPresence should represent the presence
* of this account.
* If there're more than one accounts, the situation is more complicated.
* There can be some accounts is still connecting (thus it's offline), and there can be
* some accounts doesn't support the presence you're choosing. The user-chosen presence
* priority will be higher than standard presence order.
*
* Example:
* user choose to be online, 1 account online, 1 account offline, current presence
* should be online, since online priority is higher than offline.
* user chooses a presence supported by part of the account, current presence will be
* the one chosen by user, to indicate there is at least one account supports it.
* user choose a presence supported by no account, current presence will be chosen
* from all accounts based on priority, and it also indicates there is no account support
* the user-chosen presence.
*/
KTp::Presence highestCurrentPresence = KTp::Presence::offline();
if (m_currentPresence == KTp::Presence(currentPresence)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
if (KTp::Presence(account->currentPresence()) > highestCurrentPresence) {
highestCurrentPresence = KTp::Presence(account->currentPresence());
}
}
}
if (m_currentPresence != highestCurrentPresence) {
m_currentPresence = highestCurrentPresence;
Q_EMIT currentPresenceChanged(m_currentPresence);
qCDebug(KTP_COMMONINTERNALS) << "Current presence changed:"
<< m_currentPresence.status() << m_currentPresence.statusMessage();
}
}
void GlobalPresence::onRequestedPresenceChanged(const Tp::Presence &requestedPresence)
{
KTp::Presence highestRequestedPresence = KTp::Presence::offline();
if (m_requestedPresence == KTp::Presence(requestedPresence)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
if (KTp::Presence(account->requestedPresence()) > highestRequestedPresence) {
highestRequestedPresence = KTp::Presence(account->requestedPresence());
}
}
}
if (m_requestedPresence != highestRequestedPresence) {
m_requestedPresence = highestRequestedPresence;
Q_EMIT requestedPresenceChanged(m_requestedPresence);
qCDebug(KTP_COMMONINTERNALS) << "Requested presence changed:"
<< m_requestedPresence.status() << m_requestedPresence.statusMessage();
}
}
void GlobalPresence::onChangingPresence(bool isChangingPresence)
{
bool changing = false;
if (m_changingPresence == isChangingPresence) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
changing = account->isChangingPresence();
if (account->isChangingPresence()) {
break;
}
}
}
if (m_changingPresence != changing) {
m_changingPresence = changing;
Q_EMIT changingPresence(m_changingPresence);
qCDebug(KTP_COMMONINTERNALS) << "Presence changing:" << m_changingPresence;
}
}
void GlobalPresence::onConnectionStatusChanged(Tp::ConnectionStatus connectionStatus)
{
GlobalPresence::ConnectionStatus changedConnectionStatus = GlobalPresence::Disconnected;
QList<GlobalPresence::ConnectionStatus> accountConnectionStatuses;
bool hasConnectionError = false;
if (m_connectionStatus == ConnectionStatus(connectionStatus)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
accountConnectionStatuses << ConnectionStatus(account->connectionStatus());
if (!account->connectionError().isEmpty()) {
hasConnectionError = true;
}
}
}
if (accountConnectionStatuses.contains(GlobalPresence::Connecting)) {
changedConnectionStatus = GlobalPresence::Connecting;
} else if (accountConnectionStatuses.contains(GlobalPresence::Connected)) {
changedConnectionStatus = GlobalPresence::Connected;
}
m_hasConnectionError = hasConnectionError;
if (m_connectionStatus != changedConnectionStatus) {
m_connectionStatus = changedConnectionStatus;
Q_EMIT connectionStatusChanged(m_connectionStatus);
qCDebug(KTP_COMMONINTERNALS) << "Connection status changed:" << m_connectionStatus;
}
}
bool GlobalPresence::hasEnabledAccounts() const
{
return m_hasEnabledAccounts;
}
bool GlobalPresence::hasConnectionError() const
{
return m_hasConnectionError;
}
Tp::AccountSetPtr GlobalPresence::onlineAccounts() const
{
return m_onlineAccounts;
}
Tp::AccountSetPtr GlobalPresence::enabledAccounts() const
{
return m_enabledAccounts;
}
}
#include "global-presence.moc"
<commit_msg>Fix a warning about moc included for no reason<commit_after>/*
* Global Presence - wraps calls to set and get presence for all accounts.
*
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "global-presence.h"
#include <KTp/presence.h>
#include <QDBusPendingCall>
#include <QVariant>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountSet>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Types>
#include "types.h"
#include "ktp-debug.h"
namespace KTp
{
GlobalPresence::GlobalPresence(QObject *parent)
: QObject(parent),
m_connectionStatus(GlobalPresence::Disconnected),
m_changingPresence(false),
m_hasEnabledAccounts(false)
{
Tp::registerTypes();
m_statusHandlerInterface = new QDBusInterface(QLatin1String("org.freedesktop.Telepathy.Client.KTp.KdedIntegrationModule"),
QLatin1String("/StatusHandler"),
QString(),
QDBusConnection::sessionBus(), this);
m_requestedPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
m_currentPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
}
void GlobalPresence::setAccountManager(const Tp::AccountManagerPtr &accountManager)
{
m_accountManager = accountManager;
m_enabledAccounts = m_accountManager->enabledAccounts();
m_onlineAccounts = m_accountManager->onlineAccounts();
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
onAccountEnabledChanged(account);
}
connect(m_enabledAccounts.data(), &Tp::AccountSet::accountAdded, this, &GlobalPresence::onAccountEnabledChanged);
connect(m_enabledAccounts.data(), &Tp::AccountSet::accountRemoved, this, &GlobalPresence::onAccountEnabledChanged);
if (!m_accountManager->isReady()) {
qCWarning(KTP_COMMONINTERNALS) << "GlobalPresence used with unready account manager";
} else {
Q_EMIT accountManagerReady();
}
}
void GlobalPresence::addAccountManager(const Tp::AccountManagerPtr &accountManager)
{
connect(accountManager->becomeReady(), &Tp::PendingReady::finished, [=] (Tp::PendingOperation* op) {
if (op->isError()) {
qCDebug(KTP_COMMONINTERNALS) << op->errorName();
qCDebug(KTP_COMMONINTERNALS) << op->errorMessage();
qCDebug(KTP_COMMONINTERNALS) << "Something unexpected happened to"
<< "the core part of your Instant Messaging system and it couldn't"
<< "be initialized. Try restarting the client.";
return;
}
setAccountManager(accountManager);
});
}
Tp::AccountManagerPtr GlobalPresence::accountManager() const
{
return m_accountManager;
}
GlobalPresence::ConnectionStatus GlobalPresence::connectionStatus() const
{
return m_connectionStatus;
}
KTp::Presence GlobalPresence::currentPresence() const
{
return m_currentPresence;
}
QString GlobalPresence::currentPresenceMessage() const
{
return m_currentPresence.statusMessage();
}
QIcon GlobalPresence::currentPresenceIcon() const
{
return m_currentPresence.icon();
}
QString GlobalPresence::currentPresenceIconName() const
{
return m_currentPresence.iconName();
}
QString GlobalPresence::currentPresenceName() const
{
return m_currentPresence.displayString();
}
GlobalPresence::ConnectionPresenceType GlobalPresence::currentPresenceType() const
{
switch(m_currentPresence.type()) {
case Tp::ConnectionPresenceTypeAvailable:
return GlobalPresence::Available;
case Tp::ConnectionPresenceTypeBusy:
return GlobalPresence::Busy;
case Tp::ConnectionPresenceTypeAway:
return GlobalPresence::Away;
case Tp::ConnectionPresenceTypeExtendedAway:
return GlobalPresence::ExtendedAway;
case Tp::ConnectionPresenceTypeHidden:
return GlobalPresence::Hidden;
case Tp::ConnectionPresenceTypeOffline:
return GlobalPresence::Offline;
default:
return GlobalPresence::Unknown;
}
}
KTp::Presence GlobalPresence::requestedPresence() const
{
return m_requestedPresence;
}
QString GlobalPresence::requestedPresenceName() const
{
return m_requestedPresence.displayString();
}
bool GlobalPresence::isChangingPresence() const
{
return m_changingPresence;
}
KTp::Presence GlobalPresence::globalPresence() const
{
KTp::Presence globalPresence;
globalPresence.setStatus(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), QString());
if (m_statusHandlerInterface->property("requestedGlobalPresence").isValid()) {
globalPresence = KTp::Presence(qdbus_cast<Tp::SimplePresence>(m_statusHandlerInterface->property("requestedGlobalPresence")));
}
return globalPresence;
}
void GlobalPresence::setPresence(const KTp::Presence &presence, PresenceClass presenceClass)
{
if (m_enabledAccounts.isNull()) {
qCWarning(KTP_COMMONINTERNALS) << "Requested presence change on empty accounts set";
return;
}
if (!presence.isValid()) {
qCWarning(KTP_COMMONINTERNALS) << "Invalid requested presence";
return;
}
QDBusPendingCall call = m_statusHandlerInterface->asyncCall(QLatin1String("setRequestedGlobalPresence"), QVariant::fromValue<Tp::SimplePresence>(presence.barePresence()), QVariant::fromValue<uint>(presenceClass));
}
void GlobalPresence::setPresence(GlobalPresence::ConnectionPresenceType type, QString message, PresenceClass presenceClass)
{
KTp::Presence presence;
switch (type) {
case GlobalPresence::Available:
presence = KTp::Presence::available(message);
break;
case GlobalPresence::Busy:
presence = KTp::Presence::busy(message);
break;
case GlobalPresence::Away:
presence = KTp::Presence::away(message);
break;
case GlobalPresence::ExtendedAway:
presence = KTp::Presence::xa(message);
break;
case GlobalPresence::Hidden:
presence = KTp::Presence::hidden(message);
break;
case GlobalPresence::Offline:
presence = KTp::Presence::offline(message);
break;
case GlobalPresence::Unknown:
presence = KTp::Presence(Tp::Presence(Tp::ConnectionPresenceTypeUnknown, QLatin1String("unknown"), message));
break;
case GlobalPresence::Unset:
presence = KTp::Presence(Tp::Presence(Tp::ConnectionPresenceTypeUnset, QLatin1String("unset"), message));
break;
default:
qCDebug(KTP_COMMONINTERNALS) << "You should not be here!";
}
setPresence(presence, presenceClass);
}
void GlobalPresence::onAccountEnabledChanged(const Tp::AccountPtr &account)
{
if (account->isEnabled()) {
connect(account.data(), &Tp::Account::connectionStatusChanged, this, &GlobalPresence::onConnectionStatusChanged);
connect(account.data(), &Tp::Account::changingPresence, this, &GlobalPresence::onChangingPresence);
connect(account.data(), &Tp::Account::requestedPresenceChanged, this, &GlobalPresence::onRequestedPresenceChanged);
connect(account.data(), &Tp::Account::currentPresenceChanged, this, &GlobalPresence::onCurrentPresenceChanged);
} else {
disconnect(account.data());
}
onCurrentPresenceChanged(account->currentPresence());
onRequestedPresenceChanged(account->requestedPresence());
onChangingPresence(account->isChangingPresence());
onConnectionStatusChanged(account->connectionStatus());
if (m_hasEnabledAccounts != !m_enabledAccounts.data()->accounts().isEmpty()) {
m_hasEnabledAccounts = !m_enabledAccounts.data()->accounts().isEmpty();
Q_EMIT enabledAccountsChanged(m_hasEnabledAccounts);
}
qCDebug(KTP_COMMONINTERNALS) << "Account" << account->uniqueIdentifier()
<< "enabled:" << account->isEnabled();
}
void GlobalPresence::onCurrentPresenceChanged(const Tp::Presence ¤tPresence)
{
/* basic idea of choosing global presence it to make it reflects the presence
* over all accounts, usually this is used to indicates user the whole system
* status.
*
* If there isn't any account, currentPresence should be offline, since there is nothing
* online.
* If there's only one account, then currentPresence should represent the presence
* of this account.
* If there're more than one accounts, the situation is more complicated.
* There can be some accounts is still connecting (thus it's offline), and there can be
* some accounts doesn't support the presence you're choosing. The user-chosen presence
* priority will be higher than standard presence order.
*
* Example:
* user choose to be online, 1 account online, 1 account offline, current presence
* should be online, since online priority is higher than offline.
* user chooses a presence supported by part of the account, current presence will be
* the one chosen by user, to indicate there is at least one account supports it.
* user choose a presence supported by no account, current presence will be chosen
* from all accounts based on priority, and it also indicates there is no account support
* the user-chosen presence.
*/
KTp::Presence highestCurrentPresence = KTp::Presence::offline();
if (m_currentPresence == KTp::Presence(currentPresence)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
if (KTp::Presence(account->currentPresence()) > highestCurrentPresence) {
highestCurrentPresence = KTp::Presence(account->currentPresence());
}
}
}
if (m_currentPresence != highestCurrentPresence) {
m_currentPresence = highestCurrentPresence;
Q_EMIT currentPresenceChanged(m_currentPresence);
qCDebug(KTP_COMMONINTERNALS) << "Current presence changed:"
<< m_currentPresence.status() << m_currentPresence.statusMessage();
}
}
void GlobalPresence::onRequestedPresenceChanged(const Tp::Presence &requestedPresence)
{
KTp::Presence highestRequestedPresence = KTp::Presence::offline();
if (m_requestedPresence == KTp::Presence(requestedPresence)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
if (KTp::Presence(account->requestedPresence()) > highestRequestedPresence) {
highestRequestedPresence = KTp::Presence(account->requestedPresence());
}
}
}
if (m_requestedPresence != highestRequestedPresence) {
m_requestedPresence = highestRequestedPresence;
Q_EMIT requestedPresenceChanged(m_requestedPresence);
qCDebug(KTP_COMMONINTERNALS) << "Requested presence changed:"
<< m_requestedPresence.status() << m_requestedPresence.statusMessage();
}
}
void GlobalPresence::onChangingPresence(bool isChangingPresence)
{
bool changing = false;
if (m_changingPresence == isChangingPresence) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
changing = account->isChangingPresence();
if (account->isChangingPresence()) {
break;
}
}
}
if (m_changingPresence != changing) {
m_changingPresence = changing;
Q_EMIT changingPresence(m_changingPresence);
qCDebug(KTP_COMMONINTERNALS) << "Presence changing:" << m_changingPresence;
}
}
void GlobalPresence::onConnectionStatusChanged(Tp::ConnectionStatus connectionStatus)
{
GlobalPresence::ConnectionStatus changedConnectionStatus = GlobalPresence::Disconnected;
QList<GlobalPresence::ConnectionStatus> accountConnectionStatuses;
bool hasConnectionError = false;
if (m_connectionStatus == ConnectionStatus(connectionStatus)) {
return;
} else {
for (const Tp::AccountPtr &account : m_enabledAccounts->accounts()) {
accountConnectionStatuses << ConnectionStatus(account->connectionStatus());
if (!account->connectionError().isEmpty()) {
hasConnectionError = true;
}
}
}
if (accountConnectionStatuses.contains(GlobalPresence::Connecting)) {
changedConnectionStatus = GlobalPresence::Connecting;
} else if (accountConnectionStatuses.contains(GlobalPresence::Connected)) {
changedConnectionStatus = GlobalPresence::Connected;
}
m_hasConnectionError = hasConnectionError;
if (m_connectionStatus != changedConnectionStatus) {
m_connectionStatus = changedConnectionStatus;
Q_EMIT connectionStatusChanged(m_connectionStatus);
qCDebug(KTP_COMMONINTERNALS) << "Connection status changed:" << m_connectionStatus;
}
}
bool GlobalPresence::hasEnabledAccounts() const
{
return m_hasEnabledAccounts;
}
bool GlobalPresence::hasConnectionError() const
{
return m_hasConnectionError;
}
Tp::AccountSetPtr GlobalPresence::onlineAccounts() const
{
return m_onlineAccounts;
}
Tp::AccountSetPtr GlobalPresence::enabledAccounts() const
{
return m_enabledAccounts;
}
}
<|endoftext|> |
<commit_before>#include "Emulator.h"
#include "Log.h"
#include "Font.h"
#include <fstream>
namespace Chip8
{
Emulator::Emulator() : cpu(this)
{
init();
}
Emulator::~Emulator()
{
}
void Emulator::init()
{
// Load font
for (int i = 0; i < (FONT_BYTES*16); ++i)
{
memory.write(Memory::FONT_START + i, FONT[i]);
}
}
bool Emulator::open(const std::string &filename)
{
close();
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (!file.is_open())
{
Log::error() << "Could not open \"" << filename << "\"" << std::endl;
return false;
}
std::size_t size = file.tellg();
file.seekg(0);
byte_t *data = memory.get(Memory::ROM_START);
file.read(reinterpret_cast<char*>(data), size);
return true;
}
void Emulator::close()
{
memory.zeroAll();
cpu.reset();
}
void Emulator::step(float seconds)
{
cpu.step(seconds);
}
}
<commit_msg>Emulator::open now checks the size to make sure the ROM is not too large<commit_after>#include "Emulator.h"
#include "Log.h"
#include "Font.h"
#include <fstream>
namespace Chip8
{
Emulator::Emulator() : cpu(this)
{
init();
}
Emulator::~Emulator()
{
}
void Emulator::init()
{
// Load font
for (int i = 0; i < (FONT_BYTES*16); ++i)
{
memory.write(Memory::FONT_START + i, FONT[i]);
}
}
bool Emulator::open(const std::string &filename)
{
close();
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (!file.is_open())
{
Log::error() << "Could not open \"" << filename << "\"" << std::endl;
return false;
}
std::size_t size = file.tellg();
file.seekg(0);
if (size > (Memory::SIZE - Memory::ROM_START))
{
Log::error() << "ROM file is too large (maximum size " << std::dec << (Memory::SIZE - Memory::ROM_START) << " bytes)" << std::endl;
return false;
}
byte_t *data = memory.get(Memory::ROM_START);
file.read(reinterpret_cast<char*>(data), size);
return true;
}
void Emulator::close()
{
memory.zeroAll();
cpu.reset();
}
void Emulator::step(float seconds)
{
cpu.step(seconds);
}
}
<|endoftext|> |
<commit_before>/*!
@file
@author George Evmenov
@date 01/2010
*/
#include "precompiled.h"
#include "CodeGenerator.h"
#include "EditorWidgets.h"
#include "UndoManager.h"
#include "Localise.h"
namespace tools
{
// FIXME
const std::string TemplateName = "BaseLayoutCPP.xml";
CodeGenerator::CodeGenerator() :
Dialog(),
mOpenSaveFileDialog(nullptr)
{
initialiseByAttributes(this);
mOpenSaveFileDialog = new OpenSaveFileDialog();
mOpenSaveFileDialog->setDialogInfo(replaceTags("CaptionOpenFolder"), replaceTags("ButtonOpenFolder"), true);
mOpenSaveFileDialog->eventEndDialog = MyGUI::newDelegate(this, &CodeGenerator::notifyEndDialogOpenSaveFile);
mGenerateButton->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyGeneratePressed);
mCancel->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyCancel);
mBrowseHeader->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyBrowseHeader);
mBrowseSource->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyBrowseSource);
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false);
if (window != nullptr)
window->eventWindowButtonPressed += MyGUI::newDelegate(this, &CodeGenerator::notifyWindowButtonPressed);
MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("LECodeTemplate") = MyGUI::newDelegate(this, &CodeGenerator::parseTemplate);
MyGUI::ResourceManager::getInstance().load(TemplateName);
}
CodeGenerator::~CodeGenerator()
{
delete mOpenSaveFileDialog;
mOpenSaveFileDialog = nullptr;
}
void CodeGenerator::parseTemplate(MyGUI::xml::ElementPtr _node, const std::string& _file, MyGUI::Version _version)
{
mTemplateFiles.clear();
mTemplateStrings.clear();
MyGUI::xml::ElementEnumerator file = _node->getElementEnumerator();
while (file.next("File"))
{
std::string templateFile = file->findAttribute("template");
std::string outputFile = file->findAttribute("out_file");
mTemplateFiles.insert(MyGUI::PairString(templateFile, outputFile));
}
MyGUI::xml::ElementEnumerator string = _node->getElementEnumerator();
while (string.next("String"))
{
std::string key = string->findAttribute("key");
std::string value = string->findAttribute("value");
mTemplateStrings.insert(MyGUI::PairString(key, value));
}
}
std::string CodeGenerator::stringToUpperCase(const std::string& _str)
{
// replace lower case sharacters with upper case characters and add '_' between words
// words is either Word or WORD, for example TestXMLPanelName return TEST_XML_PANEL_NAME
if (_str.empty()) return "";
std::string ret;
bool previousIsLowerCase = false;
for(size_t i=0;i<_str.length();i++)
{
if ((i != 0) &&
(
(previousIsLowerCase && isupper(_str[i])) ||
(isupper(_str[i]) && (i + 1<_str.length()) && islower(_str[i+1]))
)
)
{
ret.push_back('_');
}
ret.push_back((char)toupper(_str[i]));
previousIsLowerCase = (islower(_str[i]) != 0);
}
return ret;
}
void CodeGenerator::printWidgetDeclaration(WidgetContainer* _container, std::ofstream& _stream)
{
if (!_container->name.empty() && _container->name != "_Main")
{
MyGUI::LanguageManager& lm = MyGUI::LanguageManager::getInstance();
lm.addUserTag("Widget_Name", _container->name);
lm.addUserTag("Widget_Type", _container->type);
for (MyGUI::MapString::iterator iterS = mTemplateStrings.begin(); iterS != mTemplateStrings.end(); ++iterS)
{
lm.addUserTag(iterS->first, lm.replaceTags(iterS->second));
}
std::string declaration = lm.getTag("Widget_Declaration");
while (declaration.find("\\n") != std::string::npos)
declaration.replace(declaration.find("\\n"), 2, "\n");
_stream << declaration;
}
for (std::vector<WidgetContainer*>::iterator iter = _container->childContainers.begin(); iter != _container->childContainers.end(); ++iter)
{
printWidgetDeclaration(*iter, _stream);
}
}
void CodeGenerator::notifyGeneratePressed(MyGUI::Widget* _sender)
{
MyGUI::LanguageManager& lm = MyGUI::LanguageManager::getInstance();
std::string panelName = mPanelNameEdit->getOnlyText();
std::string panelNamespace = mPanelNamespaceEdit->getOnlyText();
std::string includeDirectory = mIncludeDirectoryEdit->getOnlyText();
std::string sourceDirectory = mSourceDirectoryEdit->getOnlyText();
lm.addUserTag("Panel_Name", panelName);
lm.addUserTag("Panel_Namespace", panelNamespace);
lm.addUserTag("Layout_Name", MyGUI::LanguageManager::getInstance().getTag("CurrentFileName_Short"));
lm.addUserTag("Include_Directory", includeDirectory);
lm.addUserTag("Source_Directory", sourceDirectory);
lm.addUserTag("Uppercase_Panel_Name", stringToUpperCase(panelName));
for (MyGUI::MapString::iterator iter = mTemplateFiles.begin(); iter != mTemplateFiles.end(); ++iter)
{
std::ifstream input_file(MyGUI::DataManager::getInstance().getDataPath(iter->first).c_str());
std::ofstream output_file(lm.replaceTags(iter->second).asUTF8_c_str());
while (!input_file.eof() && !input_file.fail() && !output_file.fail())
{
char str[256];
input_file.getline(str, sizeof(str));
output_file << lm.replaceTags(str) << std::endl;
if (strstr(str, "//%LE Widget_Declaration list start") != 0)
{
EnumeratorWidgetContainer widget = EditorWidgets::getInstance().getWidgets();
while (widget.next())
printWidgetDeclaration(widget.current(), output_file);
}
}
output_file.close();
input_file.close();
}
eventEndDialog(this, true);
}
void CodeGenerator::onDoModal()
{
MyGUI::IntSize windowSize = mMainWidget->getSize();
MyGUI::IntSize parentSize = mMainWidget->getParentSize();
mMainWidget->setPosition((parentSize.width - windowSize.width) / 2, (parentSize.height - windowSize.height) / 2);
}
void CodeGenerator::onEndModal()
{
}
void CodeGenerator::notifyCancel(MyGUI::Widget* _sender)
{
eventEndDialog(this, false);
}
void CodeGenerator::notifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _name)
{
if (_name == "close")
eventEndDialog(this, false);
}
void CodeGenerator::loadTemplate()
{
SettingsSector* sector = EditorWidgets::getInstance().getSector("CodeGenaratorSettings");
mPanelNameEdit->setCaption(sector->getPropertyValue("PanelName"));
mIncludeDirectoryEdit->setCaption(sector->getPropertyValue("IncludeDirectory"));
mSourceDirectoryEdit->setCaption(sector->getPropertyValue("SourceDirectory"));
}
void CodeGenerator::saveTemplate()
{
SettingsSector* sector = EditorWidgets::getInstance().getSector("CodeGenaratorSettings");
sector->setPropertyValue("PanelName", mPanelNameEdit->getOnlyText());
sector->setPropertyValue("IncludeDirectory", mIncludeDirectoryEdit->getOnlyText());
sector->setPropertyValue("SourceDirectory", mSourceDirectoryEdit->getOnlyText());
UndoManager::getInstance().setUnsaved(true);
}
void CodeGenerator::notifyBrowseHeader(MyGUI::Widget* _sender)
{
mOpenSaveFileDialog->setCurrentFolder(mIncludeDirectoryEdit->getOnlyText());
mOpenSaveFileDialog->setMode("Header");
mOpenSaveFileDialog->doModal();
}
void CodeGenerator::notifyBrowseSource(MyGUI::Widget* _sender)
{
mOpenSaveFileDialog->setCurrentFolder(mSourceDirectoryEdit->getOnlyText());
mOpenSaveFileDialog->setMode("Source");
mOpenSaveFileDialog->doModal();
}
void CodeGenerator::notifyEndDialogOpenSaveFile(Dialog* _sender, bool _result)
{
if (_result)
{
if (mOpenSaveFileDialog->getMode() == "Header")
{
mIncludeDirectoryEdit->setCaption(mOpenSaveFileDialog->getCurrentFolder());
}
else if (mOpenSaveFileDialog->getMode() == "Source")
{
mSourceDirectoryEdit->setCaption(mOpenSaveFileDialog->getCurrentFolder());
}
}
mOpenSaveFileDialog->endModal();
}
} // namespace tools
<commit_msg>LayoutEditor CodeGenerator: check for empty panel name and source path, add Namespace<commit_after>/*!
@file
@author George Evmenov
@date 01/2010
*/
#include "precompiled.h"
#include "CodeGenerator.h"
#include "EditorWidgets.h"
#include "UndoManager.h"
#include "Localise.h"
namespace tools
{
// FIXME
const std::string TemplateName = "BaseLayoutCPP.xml";
CodeGenerator::CodeGenerator() :
Dialog(),
mOpenSaveFileDialog(nullptr)
{
initialiseByAttributes(this);
mOpenSaveFileDialog = new OpenSaveFileDialog();
mOpenSaveFileDialog->setDialogInfo(replaceTags("CaptionOpenFolder"), replaceTags("ButtonOpenFolder"), true);
mOpenSaveFileDialog->eventEndDialog = MyGUI::newDelegate(this, &CodeGenerator::notifyEndDialogOpenSaveFile);
mGenerateButton->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyGeneratePressed);
mCancel->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyCancel);
mBrowseHeader->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyBrowseHeader);
mBrowseSource->eventMouseButtonClick += MyGUI::newDelegate(this, &CodeGenerator::notifyBrowseSource);
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false);
if (window != nullptr)
window->eventWindowButtonPressed += MyGUI::newDelegate(this, &CodeGenerator::notifyWindowButtonPressed);
MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("LECodeTemplate") = MyGUI::newDelegate(this, &CodeGenerator::parseTemplate);
MyGUI::ResourceManager::getInstance().load(TemplateName);
}
CodeGenerator::~CodeGenerator()
{
delete mOpenSaveFileDialog;
mOpenSaveFileDialog = nullptr;
}
void CodeGenerator::parseTemplate(MyGUI::xml::ElementPtr _node, const std::string& _file, MyGUI::Version _version)
{
mTemplateFiles.clear();
mTemplateStrings.clear();
MyGUI::xml::ElementEnumerator file = _node->getElementEnumerator();
while (file.next("File"))
{
std::string templateFile = file->findAttribute("template");
std::string outputFile = file->findAttribute("out_file");
mTemplateFiles.insert(MyGUI::PairString(templateFile, outputFile));
}
MyGUI::xml::ElementEnumerator string = _node->getElementEnumerator();
while (string.next("String"))
{
std::string key = string->findAttribute("key");
std::string value = string->findAttribute("value");
mTemplateStrings.insert(MyGUI::PairString(key, value));
}
}
std::string CodeGenerator::stringToUpperCase(const std::string& _str)
{
// replace lower case sharacters with upper case characters and add '_' between words
// words is either Word or WORD, for example TestXMLPanelName return TEST_XML_PANEL_NAME
if (_str.empty()) return "";
std::string ret;
bool previousIsLowerCase = false;
for(size_t i=0;i<_str.length();i++)
{
if ((i != 0) &&
(
(previousIsLowerCase && isupper(_str[i])) ||
(isupper(_str[i]) && (i + 1<_str.length()) && islower(_str[i+1]))
)
)
{
ret.push_back('_');
}
ret.push_back((char)toupper(_str[i]));
previousIsLowerCase = (islower(_str[i]) != 0);
}
return ret;
}
void CodeGenerator::printWidgetDeclaration(WidgetContainer* _container, std::ofstream& _stream)
{
if (!_container->name.empty() && _container->name != "_Main")
{
MyGUI::LanguageManager& lm = MyGUI::LanguageManager::getInstance();
lm.addUserTag("Widget_Name", _container->name);
lm.addUserTag("Widget_Type", _container->type);
for (MyGUI::MapString::iterator iterS = mTemplateStrings.begin(); iterS != mTemplateStrings.end(); ++iterS)
{
lm.addUserTag(iterS->first, lm.replaceTags(iterS->second));
}
std::string declaration = lm.getTag("Widget_Declaration");
while (declaration.find("\\n") != std::string::npos)
declaration.replace(declaration.find("\\n"), 2, "\n");
_stream << declaration;
}
for (std::vector<WidgetContainer*>::iterator iter = _container->childContainers.begin(); iter != _container->childContainers.end(); ++iter)
{
printWidgetDeclaration(*iter, _stream);
}
}
void CodeGenerator::notifyGeneratePressed(MyGUI::Widget* _sender)
{
MyGUI::LanguageManager& lm = MyGUI::LanguageManager::getInstance();
std::string panelName = mPanelNameEdit->getOnlyText();
std::string panelNamespace = mPanelNamespaceEdit->getOnlyText();
std::string includeDirectory = mIncludeDirectoryEdit->getOnlyText();
std::string sourceDirectory = mSourceDirectoryEdit->getOnlyText();
if (panelName.empty() || mPanelNameEdit->getCaption() == ("#FF0000" + replaceTags("Error")))
{
mPanelNameEdit->setCaption("#FF0000" + replaceTags("Error"));
return;
}
if (panelNamespace.empty() || mPanelNamespaceEdit->getCaption() == ("#FF0000" + replaceTags("Error")))
{
mPanelNamespaceEdit->setCaption("#FF0000" + replaceTags("Error"));
return;
}
if (includeDirectory.empty()) includeDirectory = ".";
if (sourceDirectory.empty()) sourceDirectory = ".";
lm.addUserTag("Panel_Name", panelName);
lm.addUserTag("Panel_Namespace", panelNamespace);
lm.addUserTag("Layout_Name", MyGUI::LanguageManager::getInstance().getTag("CurrentFileName_Short"));
lm.addUserTag("Include_Directory", includeDirectory);
lm.addUserTag("Source_Directory", sourceDirectory);
lm.addUserTag("Uppercase_Panel_Name", stringToUpperCase(panelName));
for (MyGUI::MapString::iterator iter = mTemplateFiles.begin(); iter != mTemplateFiles.end(); ++iter)
{
std::ifstream input_file(MyGUI::DataManager::getInstance().getDataPath(iter->first).c_str());
std::ofstream output_file(lm.replaceTags(iter->second).asUTF8_c_str());
while (!input_file.eof() && !input_file.fail() && !output_file.fail())
{
char str[256];
input_file.getline(str, sizeof(str));
output_file << lm.replaceTags(str) << std::endl;
if (strstr(str, "//%LE Widget_Declaration list start") != 0)
{
EnumeratorWidgetContainer widget = EditorWidgets::getInstance().getWidgets();
while (widget.next())
printWidgetDeclaration(widget.current(), output_file);
}
}
output_file.close();
input_file.close();
}
eventEndDialog(this, true);
}
void CodeGenerator::onDoModal()
{
MyGUI::IntSize windowSize = mMainWidget->getSize();
MyGUI::IntSize parentSize = mMainWidget->getParentSize();
mMainWidget->setPosition((parentSize.width - windowSize.width) / 2, (parentSize.height - windowSize.height) / 2);
}
void CodeGenerator::onEndModal()
{
}
void CodeGenerator::notifyCancel(MyGUI::Widget* _sender)
{
eventEndDialog(this, false);
}
void CodeGenerator::notifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _name)
{
if (_name == "close")
eventEndDialog(this, false);
}
void CodeGenerator::loadTemplate()
{
SettingsSector* sector = EditorWidgets::getInstance().getSector("CodeGenaratorSettings");
mPanelNameEdit->setCaption(sector->getPropertyValue("PanelName"));
mPanelNamespaceEdit->setCaption(sector->getPropertyValue("PanelNamespace"));
mIncludeDirectoryEdit->setCaption(sector->getPropertyValue("IncludeDirectory"));
mSourceDirectoryEdit->setCaption(sector->getPropertyValue("SourceDirectory"));
}
void CodeGenerator::saveTemplate()
{
SettingsSector* sector = EditorWidgets::getInstance().getSector("CodeGenaratorSettings");
sector->setPropertyValue("PanelName", mPanelNameEdit->getOnlyText());
sector->setPropertyValue("PanelNamespace", mPanelNamespaceEdit->getOnlyText());
sector->setPropertyValue("IncludeDirectory", mIncludeDirectoryEdit->getOnlyText());
sector->setPropertyValue("SourceDirectory", mSourceDirectoryEdit->getOnlyText());
UndoManager::getInstance().setUnsaved(true);
}
void CodeGenerator::notifyBrowseHeader(MyGUI::Widget* _sender)
{
mOpenSaveFileDialog->setCurrentFolder(mIncludeDirectoryEdit->getOnlyText());
mOpenSaveFileDialog->setMode("Header");
mOpenSaveFileDialog->doModal();
}
void CodeGenerator::notifyBrowseSource(MyGUI::Widget* _sender)
{
mOpenSaveFileDialog->setCurrentFolder(mSourceDirectoryEdit->getOnlyText());
mOpenSaveFileDialog->setMode("Source");
mOpenSaveFileDialog->doModal();
}
void CodeGenerator::notifyEndDialogOpenSaveFile(Dialog* _sender, bool _result)
{
if (_result)
{
if (mOpenSaveFileDialog->getMode() == "Header")
{
mIncludeDirectoryEdit->setCaption(mOpenSaveFileDialog->getCurrentFolder());
}
else if (mOpenSaveFileDialog->getMode() == "Source")
{
mSourceDirectoryEdit->setCaption(mOpenSaveFileDialog->getCurrentFolder());
}
}
mOpenSaveFileDialog->endModal();
}
} // namespace tools
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016-2018 Muhammad Tayyab Akram
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
extern "C" {
#include <Source/SFAlbum.h>
#include <Source/SFBase.h>
#include <Source/SFPattern.h>
#include <Source/SFPatternBuilder.h>
#include <Source/SFTextProcessor.h>
}
#include "OpenType/Base.h"
#include "OpenType/Builder.h"
#include "OpenType/Common.h"
#include "OpenType/GSUB.h"
#include "OpenType/Writer.h"
#include "TextProcessorTester.h"
using namespace std;
using namespace SheenFigure::Tester;
using namespace SheenFigure::Tester::OpenType;
struct FontObject {
Writer &writer;
SFTag tag;
};
static void loadTable(void *object, SFTag tag, SFUInt8 *buffer, SFUInteger *length)
{
FontObject *fontObject = reinterpret_cast<FontObject *>(object);
if (tag == fontObject->tag) {
if (buffer) {
memcpy(buffer, fontObject->writer.data(), (size_t)fontObject->writer.size());
}
if (length) {
*length = (SFUInteger)fontObject->writer.size();
}
}
}
static SFGlyphID getGlyphID(void *object, SFCodepoint codepoint)
{
return (SFGlyphID)codepoint;
}
static void writeTable(Writer &writer,
LookupSubtable &subtable, LookupSubtable **referrals, SFUInteger count, LookupFlag lookupFlag)
{
Builder builder;
UInt16 lookupCount = (UInt16)(count + 1);
/* Create the lookup tables. */
LookupTable *lookups = new LookupTable[lookupCount];
lookups[0].lookupType = subtable.lookupType();
lookups[0].lookupFlag = lookupFlag;
lookups[0].subTableCount = 1;
lookups[0].subtables = &subtable;
lookups[0].markFilteringSet = 0;
for (SFUInteger i = 1; i < lookupCount; i++) {
LookupSubtable *other = referrals[i - 1];
lookups[i].lookupType = other->lookupType();
lookups[i].lookupFlag = lookupFlag;
lookups[i].subTableCount = 1;
lookups[i].subtables = other;
lookups[i].markFilteringSet = 0;
}
/* Create the lookup list table. */
LookupListTable lookupList;
lookupList.lookupCount = lookupCount;
lookupList.lookupTables = lookups;
FeatureListTable &featureList = builder.createFeatureList({
{'test', builder.createFeature({ 0 })},
});
ScriptListTable &scriptList = builder.createScriptList({
{'dflt', builder.createScript(builder.createLangSys({ 0 }))}
});
/* Create the container table. */
GSUB gsub;
gsub.version = 0x00010000;
gsub.scriptList = &scriptList;
gsub.featureList = &featureList;
gsub.lookupList = &lookupList;
writer.write(&gsub);
delete [] lookups;
}
static void processSubtable(SFAlbumRef album,
const SFCodepoint *input, SFUInteger length, SFBoolean positioning,
LookupSubtable &subtable, LookupSubtable **referrals, SFUInteger count,
SFBoolean isRTL = SFFalse)
{
/* Write the table for the given lookup. */
Writer writer;
writeTable(writer, subtable, referrals, count, isRTL ? LookupFlag::RightToLeft : (LookupFlag)0);
/* Create a font object containing writer and tag. */
FontObject object = {
.writer = writer,
.tag = (positioning ? SFTagMake('G', 'P', 'O', 'S') : SFTagMake('G', 'S', 'U', 'B')),
};
/* Create the font with protocol. */
SFFontProtocol protocol = {
.finalize = NULL,
.loadTable = &loadTable,
.getGlyphIDForCodepoint = &getGlyphID,
.getAdvanceForGlyph = NULL,
};
SFFontRef font = SFFontCreateWithProtocol(&protocol, &object);
SFTextDirection direction = isRTL ? SFTextDirectionRightToLeft : SFTextDirectionLeftToRight;
/* Create a pattern. */
SFPatternRef pattern = SFPatternCreate();
/* Build the pattern. */
SFPatternBuilder builder;
SFPatternBuilderInitialize(&builder, pattern);
SFPatternBuilderSetFont(&builder, font);
SFPatternBuilderSetScript(&builder, SFTagMake('d', 'f', 'l', 't'), direction);
SFPatternBuilderSetLanguage(&builder, SFTagMake('d', 'f', 'l', 't'));
SFPatternBuilderBeginFeatures(&builder, positioning ? SFFeatureKindPositioning : SFFeatureKindSubstitution);
SFPatternBuilderAddFeature(&builder, SFTagMake('t', 'e', 's', 't'), 1, 0);
SFPatternBuilderAddLookup(&builder, 0);
SFPatternBuilderMakeFeatureUnit(&builder);
SFPatternBuilderEndFeatures(&builder);
SFPatternBuilderBuild(&builder);
/* Create the codepoint sequence. */
SBCodepointSequence sequence;
sequence.stringEncoding = SBStringEncodingUTF32;
sequence.stringBuffer = (void *)input;
sequence.stringLength = length;
/* Reset the album for given codepoints. */
SFCodepoints codepoints;
SFCodepointsInitialize(&codepoints, &sequence, SFFalse);
SFAlbumReset(album, &codepoints);
/* Process the album. */
SFTextProcessor processor;
SFTextProcessorInitialize(&processor, pattern, album, direction, SFTextModeForward, SFFalse);
SFTextProcessorDiscoverGlyphs(&processor);
SFTextProcessorSubstituteGlyphs(&processor);
SFTextProcessorPositionGlyphs(&processor);
SFTextProcessorWrapUp(&processor);
/* Release the allocated objects. */
SFPatternRelease(pattern);
SFFontRelease(font);
}
TextProcessorTester::TextProcessorTester()
{
}
void TextProcessorTester::testSubstitution(LookupSubtable &subtable,
const vector<uint32_t> codepoints,
const vector<Glyph> glyphs,
const vector<LookupSubtable *> referrals)
{
SFAlbum album;
SFAlbumInitialize(&album);
processSubtable(&album, &codepoints[0], codepoints.size(), SFFalse, subtable,
(LookupSubtable **)referrals.data(), referrals.size());
assert(SFAlbumGetGlyphCount(&album) == glyphs.size());
assert(memcmp(SFAlbumGetGlyphIDsPtr(&album), glyphs.data(), sizeof(SFGlyphID) * glyphs.size()) == 0);
}
void TextProcessorTester::testPositioning(LookupSubtable &subtable,
const vector<uint32_t> codepoints,
const vector<pair<int32_t, int32_t>> offsets,
const vector<int32_t> advances,
const vector<LookupSubtable *> referrals,
bool isRTL)
{
assert(offsets.size() == advances.size());
SFAlbum album;
SFAlbumInitialize(&album);
processSubtable(&album, &codepoints[0], codepoints.size(), SFTrue, subtable,
(LookupSubtable **)referrals.data(), referrals.size(), isRTL);
assert(SFAlbumGetGlyphCount(&album) == offsets.size());
assert(memcmp(SFAlbumGetGlyphOffsetsPtr(&album), offsets.data(), sizeof(SFPoint) * offsets.size()) == 0);
assert(memcmp(SFAlbumGetGlyphAdvancesPtr(&album), advances.data(), sizeof(SFInt32) * advances.size()) == 0);
}
void TextProcessorTester::test()
{
testSingleSubstitution();
testMultipleSubstitution();
testAlternateSubstitution();
testLigatureSubstitution();
testReverseChainContextSubstitution();
testSinglePositioning();
testPairPositioning();
testCursivePositioning();
testMarkToBasePositioning();
testMarkToLigaturePositioning();
testMarkToMarkPositioning();
testContextSubtable();
testChainContextSubtable();
testExtensionSubtable();
}
<commit_msg>[test] Used builder to create lookup list<commit_after>/*
* Copyright (C) 2016-2018 Muhammad Tayyab Akram
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
extern "C" {
#include <Source/SFAlbum.h>
#include <Source/SFBase.h>
#include <Source/SFPattern.h>
#include <Source/SFPatternBuilder.h>
#include <Source/SFTextProcessor.h>
}
#include "OpenType/Base.h"
#include "OpenType/Builder.h"
#include "OpenType/Common.h"
#include "OpenType/GSUB.h"
#include "OpenType/Writer.h"
#include "TextProcessorTester.h"
using namespace std;
using namespace SheenFigure::Tester;
using namespace SheenFigure::Tester::OpenType;
struct FontObject {
Writer &writer;
SFTag tag;
};
static void loadTable(void *object, SFTag tag, SFUInt8 *buffer, SFUInteger *length)
{
FontObject *fontObject = reinterpret_cast<FontObject *>(object);
if (tag == fontObject->tag) {
if (buffer) {
memcpy(buffer, fontObject->writer.data(), (size_t)fontObject->writer.size());
}
if (length) {
*length = (SFUInteger)fontObject->writer.size();
}
}
}
static SFGlyphID getGlyphID(void *, SFCodepoint codepoint)
{
return (SFGlyphID)codepoint;
}
static void writeTable(Writer &writer,
LookupSubtable &subtable, LookupSubtable **referrals, SFUInteger count, LookupFlag lookupFlag)
{
Builder builder;
vector<reference_wrapper<LookupTable>> lookups;
lookups.push_back(builder.createLookup({&subtable, 1}, lookupFlag));
for (size_t i = 0; i < count; i++) {
lookups.push_back(builder.createLookup({referrals[i], 1}, lookupFlag));
}
LookupListTable &lookupList = builder.createLookupList(lookups);
FeatureListTable &featureList = builder.createFeatureList({
{'test', builder.createFeature({ 0 })},
});
ScriptListTable &scriptList = builder.createScriptList({
{'dflt', builder.createScript(builder.createLangSys({ 0 }))}
});
/* Create the container table. */
GSUB gsub;
gsub.version = 0x00010000;
gsub.scriptList = &scriptList;
gsub.featureList = &featureList;
gsub.lookupList = &lookupList;
writer.write(&gsub);
}
static void processSubtable(SFAlbumRef album,
const SFCodepoint *input, SFUInteger length, SFBoolean positioning,
LookupSubtable &subtable, LookupSubtable **referrals, SFUInteger count,
SFBoolean isRTL = SFFalse)
{
/* Write the table for the given lookup. */
Writer writer;
writeTable(writer, subtable, referrals, count, isRTL ? LookupFlag::RightToLeft : (LookupFlag)0);
/* Create a font object containing writer and tag. */
FontObject object = {
.writer = writer,
.tag = (positioning ? SFTagMake('G', 'P', 'O', 'S') : SFTagMake('G', 'S', 'U', 'B')),
};
/* Create the font with protocol. */
SFFontProtocol protocol = {
.finalize = NULL,
.loadTable = &loadTable,
.getGlyphIDForCodepoint = &getGlyphID,
.getAdvanceForGlyph = NULL,
};
SFFontRef font = SFFontCreateWithProtocol(&protocol, &object);
SFTextDirection direction = isRTL ? SFTextDirectionRightToLeft : SFTextDirectionLeftToRight;
/* Create a pattern. */
SFPatternRef pattern = SFPatternCreate();
/* Build the pattern. */
SFPatternBuilder builder;
SFPatternBuilderInitialize(&builder, pattern);
SFPatternBuilderSetFont(&builder, font);
SFPatternBuilderSetScript(&builder, SFTagMake('d', 'f', 'l', 't'), direction);
SFPatternBuilderSetLanguage(&builder, SFTagMake('d', 'f', 'l', 't'));
SFPatternBuilderBeginFeatures(&builder, positioning ? SFFeatureKindPositioning : SFFeatureKindSubstitution);
SFPatternBuilderAddFeature(&builder, SFTagMake('t', 'e', 's', 't'), 1, 0);
SFPatternBuilderAddLookup(&builder, 0);
SFPatternBuilderMakeFeatureUnit(&builder);
SFPatternBuilderEndFeatures(&builder);
SFPatternBuilderBuild(&builder);
/* Create the codepoint sequence. */
SBCodepointSequence sequence;
sequence.stringEncoding = SBStringEncodingUTF32;
sequence.stringBuffer = (void *)input;
sequence.stringLength = length;
/* Reset the album for given codepoints. */
SFCodepoints codepoints;
SFCodepointsInitialize(&codepoints, &sequence, SFFalse);
SFAlbumReset(album, &codepoints);
/* Process the album. */
SFTextProcessor processor;
SFTextProcessorInitialize(&processor, pattern, album, direction, SFTextModeForward, SFFalse);
SFTextProcessorDiscoverGlyphs(&processor);
SFTextProcessorSubstituteGlyphs(&processor);
SFTextProcessorPositionGlyphs(&processor);
SFTextProcessorWrapUp(&processor);
/* Release the allocated objects. */
SFPatternRelease(pattern);
SFFontRelease(font);
}
TextProcessorTester::TextProcessorTester()
{
}
void TextProcessorTester::testSubstitution(LookupSubtable &subtable,
const vector<uint32_t> codepoints,
const vector<Glyph> glyphs,
const vector<LookupSubtable *> referrals)
{
SFAlbum album;
SFAlbumInitialize(&album);
processSubtable(&album, &codepoints[0], codepoints.size(), SFFalse, subtable,
(LookupSubtable **)referrals.data(), referrals.size());
assert(SFAlbumGetGlyphCount(&album) == glyphs.size());
assert(memcmp(SFAlbumGetGlyphIDsPtr(&album), glyphs.data(), sizeof(SFGlyphID) * glyphs.size()) == 0);
}
void TextProcessorTester::testPositioning(LookupSubtable &subtable,
const vector<uint32_t> codepoints,
const vector<pair<int32_t, int32_t>> offsets,
const vector<int32_t> advances,
const vector<LookupSubtable *> referrals,
bool isRTL)
{
assert(offsets.size() == advances.size());
SFAlbum album;
SFAlbumInitialize(&album);
processSubtable(&album, &codepoints[0], codepoints.size(), SFTrue, subtable,
(LookupSubtable **)referrals.data(), referrals.size(), isRTL);
assert(SFAlbumGetGlyphCount(&album) == offsets.size());
assert(memcmp(SFAlbumGetGlyphOffsetsPtr(&album), offsets.data(), sizeof(SFPoint) * offsets.size()) == 0);
assert(memcmp(SFAlbumGetGlyphAdvancesPtr(&album), advances.data(), sizeof(SFInt32) * advances.size()) == 0);
}
void TextProcessorTester::test()
{
testSingleSubstitution();
testMultipleSubstitution();
testAlternateSubstitution();
testLigatureSubstitution();
testReverseChainContextSubstitution();
testSinglePositioning();
testPairPositioning();
testCursivePositioning();
testMarkToBasePositioning();
testMarkToLigaturePositioning();
testMarkToMarkPositioning();
testContextSubtable();
testChainContextSubtable();
testExtensionSubtable();
}
<|endoftext|> |
<commit_before>// @(#)root/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.4 2002/04/04 17:32:14 rdm Exp $
// Author: Fons Rademakers 12/02/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootContextMenu //
// //
// This class provides an interface to context sensitive popup menus. //
// These menus pop up when the user hits the right mouse button, and //
// are destroyed when the menu pops downs. //
// The picture below shows a canvas with a pop-up menu. //
// //
//Begin_Html <img src="gif/hsumMenu.gif"> End_Html //
// //
// The picture below shows a canvas with a pop-up menu and a dialog box.//
// //
//Begin_Html <img src="gif/hsumDialog.gif"> End_Html //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRootContextMenu.h"
#include "TROOT.h"
#include "TGClient.h"
#include "TList.h"
#include "TContextMenu.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "TCanvas.h"
#include "TDataMember.h"
#include "TToggle.h"
#include "TRootDialog.h"
#include "TDataType.h"
#include "TCanvas.h"
#include "TBrowser.h"
#include "TRootCanvas.h"
#include "TRootBrowser.h"
#include "TClassMenuItem.h"
enum {
kToggleStart = 1000, // first id of toggle menu items
kToggleListStart = 2000, // first id of toggle list menu items
kUserFunctionStart = 3000 // first id of user added functions/methods, etc...
};
ClassImp(TRootContextMenu)
//______________________________________________________________________________
TRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)
: TGPopupMenu(gClient->GetRoot()), TContextMenuImp(c)
{
// Create context menu.
fDialog = 0;
fCleanup = new TList;
// Context menu handles its own messages
Associate(this);
}
//______________________________________________________________________________
TRootContextMenu::~TRootContextMenu()
{
// Delete a context menu.
delete fDialog;
if (fCleanup) fCleanup->Delete();
delete fCleanup;
}
//______________________________________________________________________________
void TRootContextMenu::DisplayPopup(Int_t x, Int_t y)
{
// Display context popup menu for currently selected object.
// delete menu items releated to previous object and reset menu size
if (fEntryList) fEntryList->Delete();
if (fCleanup) fCleanup->Delete();
fHeight = 6;
fWidth = 8;
// delete previous dialog
if (fDialog) {
delete fDialog;
fDialog = 0;
}
// add menu items to popup menu
CreateMenu(fContextMenu->GetSelectedObject());
int xx, yy, topx = 0, topy = 0;
UInt_t w, h;
if (fContextMenu->GetSelectedCanvas())
gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),
topx, topy, w, h);
xx = topx + x + 1;
yy = topy + y + 1;
PlaceMenu(xx, yy, kFALSE, kTRUE);
}
//______________________________________________________________________________
void TRootContextMenu::CreateMenu(TObject *object)
{
// Create the context menu depending on the selected object.
int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;
int userfunction = kUserFunctionStart;
// Add a title
AddLabel(fContextMenu->CreatePopupTitle(object));
AddSeparator();
// Get list of menu items from the selected object's class
TList *menuItemList = object->IsA()->GetMenuList();
TClassMenuItem *menuItem;
TIter nextItem(menuItemList);
while ((menuItem = (TClassMenuItem*) nextItem())) {
switch (menuItem->GetType()) {
case TClassMenuItem::kPopupSeparator:
AddSeparator();
break;
case TClassMenuItem::kPopupStandardList:
{
// Standard list of class methods. Rebuild from scratch.
// Get linked list of objects menu items (i.e. member functions
// with the token *MENU in their comment fields.
TList *methodList = new TList;
object->IsA()->GetMenuItems(methodList);
TMethod *method;
TClass *classPtr = 0;
TIter next(methodList);
while ((method = (TMethod*) next())) {
if (classPtr != method->GetClass()) {
AddSeparator();
classPtr = method->GetClass();
}
TDataMember *m;
EMenuItemKind menuKind = method->IsMenuItem();
switch (menuKind) {
case kMenuDialog:
AddEntry(method->GetName(), entry++, method);
break;
case kMenuSubMenu:
if ((m = method->FindDataMember())) {
if (m->GetterMethod()) {
TGPopupMenu *r = new TGPopupMenu(gClient->GetRoot());
AddPopup(method->GetName(), r);
fCleanup->Add(r);
TIter nxt(m->GetOptions());
TOptionListItem *it;
while ((it = (TOptionListItem*) nxt())) {
char *name = it->fOptName;
Long_t val = it->fValue;
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(val);
fCleanup->Add(t);
r->AddSeparator();
r->AddEntry(name, togglelist++, t);
if (t->GetState()) r->CheckEntry(togglelist-1);
}
} else {
AddEntry(method->GetName(), entry++, method);
}
}
break;
case kMenuToggle:
{
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(1);
fCleanup->Add(t);
AddEntry(method->GetName(), toggle++, t);
if (t->GetState()) CheckEntry(toggle-1);
}
break;
default:
break;
}
}
delete methodList;
}
break;
case TClassMenuItem::kPopupUserFunction:
{
if (menuItem->IsToggle()) {
if (object) {
TMethod* method =
object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(1);
fCleanup->Add(t);
AddEntry(method->GetName(), toggle++, t);
if (t->GetState()) CheckEntry(toggle-1);
} else {
Warning("Dialog","Cannot use toggle for a global function");
}
} else {
const char* menuItemTitle = menuItem->GetTitle();
if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();
AddEntry(menuItemTitle,userfunction++,menuItem);
}
}
break;
default:
break;
}
}
}
//______________________________________________________________________________
void TRootContextMenu::Dialog(TObject *object, TMethod *method)
{
// Create dialog object with OK and Cancel buttons. This dialog
// prompts for the arguments of "method".
Dialog(object,(TFunction*)method);
}
//______________________________________________________________________________
void TRootContextMenu::Dialog(TObject *object, TFunction *function)
{
// Create dialog object with OK and Cancel buttons. This dialog
// prompts for the arguments of "function".
// function may be a global function or a method
Int_t selfobjpos;
if (!function) return;
// Position, if it exists, of the argument that correspond to the object itself
if (fContextMenu->GetSelectedMenuItem())
selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();
else selfobjpos = -1;
const TGWindow *w;
if (fContextMenu->GetSelectedCanvas()) {
TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();
// Embedded canvas has no canvasimp that is a TGFrame
if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class()))
w = (TRootCanvas *) c->GetCanvasImp();
else
w = gClient->GetRoot();
} else if (fContextMenu->GetBrowser()) {
TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();
w = (TRootBrowser *) b->GetBrowserImp();
} else
w = gClient->GetRoot();
fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));
// iterate through all arguments and create apropriate input-data objects:
// inputlines, option menus...
TMethodArg *argument = 0;
TIter next(function->GetListOfMethodArgs());
Int_t argpos = 0;
while ((argument = (TMethodArg *) next())) {
// Do not input argument for self object
if (selfobjpos != argpos) {
Text_t *argname = fContextMenu->CreateArgumentTitle(argument);
const Text_t *type = argument->GetTypeName();
TDataType *datatype = gROOT->GetType(type);
const Text_t *charstar = "char*";
Text_t basictype[32];
if (datatype) {
strcpy(basictype, datatype->GetTypeName());
} else {
TClass *cl = gROOT->GetClass(type);
if (strncmp(type, "enum", 4) && (cl && !(cl->Property() & kIsEnum)))
Warning("Dialog", "data type is not basic type, assuming (int)");
strcpy(basictype, "int");
}
if (strchr(argname, '*')) {
strcat(basictype, "*");
type = charstar;
}
TDataMember *m = argument->GetDataMember();
if (m && m->GetterMethod(object->IsA())) {
// Get the current value and form it as a text:
Text_t val[256];
if (!strncmp(basictype, "char*", 5)) {
Text_t *tdefval;
m->GetterMethod()->Execute(object, "", &tdefval);
strncpy(val, tdefval, 255);
} else if (!strncmp(basictype, "float", 5) ||
!strncmp(basictype, "double", 6)) {
Double_t ddefval;
m->GetterMethod()->Execute(object, "", ddefval);
sprintf(val, "%g", ddefval);
} else if (!strncmp(basictype, "char", 4) ||
!strncmp(basictype, "int", 3) ||
!strncmp(basictype, "long", 4) ||
!strncmp(basictype, "short", 5)) {
Long_t ldefval;
m->GetterMethod()->Execute(object, "", ldefval);
sprintf(val, "%li", ldefval);
}
// Find out whether we have options ...
TList *opt;
if ((opt = m->GetOptions())) {
Warning("Dialog", "option menu not yet implemented", opt);
#if 0
TMotifOptionMenu *o= new TMotifOptionMenu(argname);
TIter nextopt(opt);
TOptionListItem *it = 0;
while ((it = (TOptionListItem*) nextopt())) {
Text_t *name = it->fOptName;
Text_t *label = it->fOptLabel;
Long_t value = it->fValue;
if (value != -9999) {
Text_t val[256];
sprintf(val, "%li", value);
o->AddItem(name, val);
}else
o->AddItem(name, label);
}
o->SetData(val);
fDialog->Add(o);
#endif
} else {
// we haven't got options - textfield ...
fDialog->Add(argname, val, type);
}
} else { // if m not found ...
char val[256] = "";
const char *tval = argument->GetDefault();
if (tval) strncpy(val, tval, 255);
fDialog->Add(argname, val, type);
}
}
argpos++;
}
fDialog->Popup();
}
//______________________________________________________________________________
Bool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
// Handle context menu messages.
switch (GET_MSG(msg)) {
case kC_COMMAND:
switch (GET_SUBMSG(msg)) {
case kCM_MENU:
if (parm1 < kToggleStart) {
TMethod *m = (TMethod *) parm2;
GetContextMenu()->Action(m);
} else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {
TToggle *t = (TToggle *) parm2;
GetContextMenu()->Action(t);
} else if (parm1 >= kToggleListStart && parm1<kUserFunctionStart) {
TToggle *t = (TToggle *) parm2;
if (t->GetState() == 0)
t->SetState(1);
} else {
TClassMenuItem* mi = (TClassMenuItem*)parm2;
GetContextMenu()->Action(mi);
}
break;
case kCM_BUTTON:
if (parm1 == 1) {
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
delete fDialog;
fDialog = 0;
}
if (parm1 == 2) {
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
}
if (parm1 == 3) {
delete fDialog;
fDialog = 0;
}
break;
default:
break;
}
break;
case kC_TEXTENTRY:
switch (GET_SUBMSG(msg)) {
case kTE_ENTER:
{
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
delete fDialog;
fDialog = 0;
}
break;
default:
break;
}
break;
default:
break;
}
return kTRUE;
}
<commit_msg>Fix from Bertrand in TRootContextMenu constructor<commit_after>// @(#)root/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.5 2002/06/09 08:26:15 brun Exp $
// Author: Fons Rademakers 12/02/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootContextMenu //
// //
// This class provides an interface to context sensitive popup menus. //
// These menus pop up when the user hits the right mouse button, and //
// are destroyed when the menu pops downs. //
// The picture below shows a canvas with a pop-up menu. //
// //
//Begin_Html <img src="gif/hsumMenu.gif"> End_Html //
// //
// The picture below shows a canvas with a pop-up menu and a dialog box.//
// //
//Begin_Html <img src="gif/hsumDialog.gif"> End_Html //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRootContextMenu.h"
#include "TROOT.h"
#include "TGClient.h"
#include "TList.h"
#include "TContextMenu.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "TCanvas.h"
#include "TDataMember.h"
#include "TToggle.h"
#include "TRootDialog.h"
#include "TDataType.h"
#include "TCanvas.h"
#include "TBrowser.h"
#include "TRootCanvas.h"
#include "TRootBrowser.h"
#include "TClassMenuItem.h"
enum {
kToggleStart = 1000, // first id of toggle menu items
kToggleListStart = 2000, // first id of toggle list menu items
kUserFunctionStart = 3000 // first id of user added functions/methods, etc...
};
ClassImp(TRootContextMenu)
//______________________________________________________________________________
TRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)
: TGPopupMenu(gClient->GetRoot()), TContextMenuImp(c)
{
// Create context menu.
fDialog = 0;
fCleanup = new TList;
// Context menu handles its own messages
Associate(this);
}
//______________________________________________________________________________
TRootContextMenu::~TRootContextMenu()
{
// Delete a context menu.
delete fDialog;
if (fCleanup) fCleanup->Delete();
delete fCleanup;
}
//______________________________________________________________________________
void TRootContextMenu::DisplayPopup(Int_t x, Int_t y)
{
// Display context popup menu for currently selected object.
// delete menu items releated to previous object and reset menu size
if (fEntryList) fEntryList->Delete();
if (fCleanup) fCleanup->Delete();
fMenuHeight = 6;
fMenuWidth = 8;
// delete previous dialog
if (fDialog) {
delete fDialog;
fDialog = 0;
}
// add menu items to popup menu
CreateMenu(fContextMenu->GetSelectedObject());
int xx, yy, topx = 0, topy = 0;
UInt_t w, h;
if (fContextMenu->GetSelectedCanvas())
gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),
topx, topy, w, h);
xx = topx + x + 1;
yy = topy + y + 1;
PlaceMenu(xx, yy, kFALSE, kTRUE);
}
//______________________________________________________________________________
void TRootContextMenu::CreateMenu(TObject *object)
{
// Create the context menu depending on the selected object.
int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;
int userfunction = kUserFunctionStart;
// Add a title
AddLabel(fContextMenu->CreatePopupTitle(object));
AddSeparator();
// Get list of menu items from the selected object's class
TList *menuItemList = object->IsA()->GetMenuList();
TClassMenuItem *menuItem;
TIter nextItem(menuItemList);
while ((menuItem = (TClassMenuItem*) nextItem())) {
switch (menuItem->GetType()) {
case TClassMenuItem::kPopupSeparator:
AddSeparator();
break;
case TClassMenuItem::kPopupStandardList:
{
// Standard list of class methods. Rebuild from scratch.
// Get linked list of objects menu items (i.e. member functions
// with the token *MENU in their comment fields.
TList *methodList = new TList;
object->IsA()->GetMenuItems(methodList);
TMethod *method;
TClass *classPtr = 0;
TIter next(methodList);
while ((method = (TMethod*) next())) {
if (classPtr != method->GetClass()) {
AddSeparator();
classPtr = method->GetClass();
}
TDataMember *m;
EMenuItemKind menuKind = method->IsMenuItem();
switch (menuKind) {
case kMenuDialog:
AddEntry(method->GetName(), entry++, method);
break;
case kMenuSubMenu:
if ((m = method->FindDataMember())) {
if (m->GetterMethod()) {
TGPopupMenu *r = new TGPopupMenu(gClient->GetRoot());
AddPopup(method->GetName(), r);
fCleanup->Add(r);
TIter nxt(m->GetOptions());
TOptionListItem *it;
while ((it = (TOptionListItem*) nxt())) {
char *name = it->fOptName;
Long_t val = it->fValue;
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(val);
fCleanup->Add(t);
r->AddSeparator();
r->AddEntry(name, togglelist++, t);
if (t->GetState()) r->CheckEntry(togglelist-1);
}
} else {
AddEntry(method->GetName(), entry++, method);
}
}
break;
case kMenuToggle:
{
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(1);
fCleanup->Add(t);
AddEntry(method->GetName(), toggle++, t);
if (t->GetState()) CheckEntry(toggle-1);
}
break;
default:
break;
}
}
delete methodList;
}
break;
case TClassMenuItem::kPopupUserFunction:
{
if (menuItem->IsToggle()) {
if (object) {
TMethod* method =
object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());
TToggle *t = new TToggle;
t->SetToggledObject(object, method);
t->SetOnValue(1);
fCleanup->Add(t);
AddEntry(method->GetName(), toggle++, t);
if (t->GetState()) CheckEntry(toggle-1);
} else {
Warning("Dialog","Cannot use toggle for a global function");
}
} else {
const char* menuItemTitle = menuItem->GetTitle();
if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();
AddEntry(menuItemTitle,userfunction++,menuItem);
}
}
break;
default:
break;
}
}
}
//______________________________________________________________________________
void TRootContextMenu::Dialog(TObject *object, TMethod *method)
{
// Create dialog object with OK and Cancel buttons. This dialog
// prompts for the arguments of "method".
Dialog(object,(TFunction*)method);
}
//______________________________________________________________________________
void TRootContextMenu::Dialog(TObject *object, TFunction *function)
{
// Create dialog object with OK and Cancel buttons. This dialog
// prompts for the arguments of "function".
// function may be a global function or a method
Int_t selfobjpos;
if (!function) return;
// Position, if it exists, of the argument that correspond to the object itself
if (fContextMenu->GetSelectedMenuItem())
selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();
else selfobjpos = -1;
const TGWindow *w;
if (fContextMenu->GetSelectedCanvas()) {
TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();
// Embedded canvas has no canvasimp that is a TGFrame
if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class()))
w = (TRootCanvas *) c->GetCanvasImp();
else
w = gClient->GetRoot();
} else if (fContextMenu->GetBrowser()) {
TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();
w = (TRootBrowser *) b->GetBrowserImp();
} else
w = gClient->GetRoot();
fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));
// iterate through all arguments and create apropriate input-data objects:
// inputlines, option menus...
TMethodArg *argument = 0;
TIter next(function->GetListOfMethodArgs());
Int_t argpos = 0;
while ((argument = (TMethodArg *) next())) {
// Do not input argument for self object
if (selfobjpos != argpos) {
Text_t *argname = fContextMenu->CreateArgumentTitle(argument);
const Text_t *type = argument->GetTypeName();
TDataType *datatype = gROOT->GetType(type);
const Text_t *charstar = "char*";
Text_t basictype[32];
if (datatype) {
strcpy(basictype, datatype->GetTypeName());
} else {
TClass *cl = gROOT->GetClass(type);
if (strncmp(type, "enum", 4) && (cl && !(cl->Property() & kIsEnum)))
Warning("Dialog", "data type is not basic type, assuming (int)");
strcpy(basictype, "int");
}
if (strchr(argname, '*')) {
strcat(basictype, "*");
type = charstar;
}
TDataMember *m = argument->GetDataMember();
if (m && m->GetterMethod(object->IsA())) {
// Get the current value and form it as a text:
Text_t val[256];
if (!strncmp(basictype, "char*", 5)) {
Text_t *tdefval;
m->GetterMethod()->Execute(object, "", &tdefval);
strncpy(val, tdefval, 255);
} else if (!strncmp(basictype, "float", 5) ||
!strncmp(basictype, "double", 6)) {
Double_t ddefval;
m->GetterMethod()->Execute(object, "", ddefval);
sprintf(val, "%g", ddefval);
} else if (!strncmp(basictype, "char", 4) ||
!strncmp(basictype, "int", 3) ||
!strncmp(basictype, "long", 4) ||
!strncmp(basictype, "short", 5)) {
Long_t ldefval;
m->GetterMethod()->Execute(object, "", ldefval);
sprintf(val, "%li", ldefval);
}
// Find out whether we have options ...
TList *opt;
if ((opt = m->GetOptions())) {
Warning("Dialog", "option menu not yet implemented", opt);
#if 0
TMotifOptionMenu *o= new TMotifOptionMenu(argname);
TIter nextopt(opt);
TOptionListItem *it = 0;
while ((it = (TOptionListItem*) nextopt())) {
Text_t *name = it->fOptName;
Text_t *label = it->fOptLabel;
Long_t value = it->fValue;
if (value != -9999) {
Text_t val[256];
sprintf(val, "%li", value);
o->AddItem(name, val);
}else
o->AddItem(name, label);
}
o->SetData(val);
fDialog->Add(o);
#endif
} else {
// we haven't got options - textfield ...
fDialog->Add(argname, val, type);
}
} else { // if m not found ...
char val[256] = "";
const char *tval = argument->GetDefault();
if (tval) strncpy(val, tval, 255);
fDialog->Add(argname, val, type);
}
}
argpos++;
}
fDialog->Popup();
}
//______________________________________________________________________________
Bool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
// Handle context menu messages.
switch (GET_MSG(msg)) {
case kC_COMMAND:
switch (GET_SUBMSG(msg)) {
case kCM_MENU:
if (parm1 < kToggleStart) {
TMethod *m = (TMethod *) parm2;
GetContextMenu()->Action(m);
} else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {
TToggle *t = (TToggle *) parm2;
GetContextMenu()->Action(t);
} else if (parm1 >= kToggleListStart && parm1<kUserFunctionStart) {
TToggle *t = (TToggle *) parm2;
if (t->GetState() == 0)
t->SetState(1);
} else {
TClassMenuItem* mi = (TClassMenuItem*)parm2;
GetContextMenu()->Action(mi);
}
break;
case kCM_BUTTON:
if (parm1 == 1) {
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
delete fDialog;
fDialog = 0;
}
if (parm1 == 2) {
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
}
if (parm1 == 3) {
delete fDialog;
fDialog = 0;
}
break;
default:
break;
}
break;
case kC_TEXTENTRY:
switch (GET_SUBMSG(msg)) {
case kTE_ENTER:
{
const char *args = fDialog->GetParameters();
GetContextMenu()->Execute((char *)args);
delete fDialog;
fDialog = 0;
}
break;
default:
break;
}
break;
default:
break;
}
return kTRUE;
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <vector>
#include <json/json.h>
#include "Entity/World.hpp"
class TextureAsset;
class ScriptFile;
/// A hymn to beauty.
class ActiveHymn {
friend ActiveHymn& Hymn();
public:
/// Clear the hymn of all properties.
void Clear();
/// Get the path where the hymn is saved.
/**
* @return The hymn's path.
*/
const std::string& GetPath() const;
/// Set the path where the hymn is saved.
/**
* @param path New path.
*/
void SetPath(const std::string& path);
/// Save the hymn.
void Save() const;
/// Load a hymn.
/**
* @param path Path to the saved hymn.
*/
void Load(const std::string& path);
/// Convert the hymn to Json.
/**
* @return The hymn as a Json.
*/
Json::Value ToJson() const;
/// Convert a Json to a Hymn.
/**
* @param root The Json file to load.
*/
void FromJson(Json::Value root);
/// Update the world.
/**
* @param deltaTime Time since last frame (in seconds).
*/
void Update(float deltaTime);
/// Render the world.
/**
* @param camera Camera through which to render (or first camera in the world if nullptr).
* @param soundSources Whether to show sound sources.
* @param particleEmitters Whether to show particle emitters.
* @param lightSources Whether to show light sources.
* @param cameras Whether to show cameras.
* @param physics Whether to show physics volumes.
*/
void Render(Entity* camera = nullptr, bool soundSources = false, bool particleEmitters = false, bool lightSources = false, bool cameras = false, bool physics = false, bool gridSettings = false);
/// Create static grid.
/**
* @param scale Scales the grid, scale can be a maximum of 100.
*/
void CreateGrid(int scale);
/// The game world.
World world;
/// The id of the next entity to create.
unsigned int entityNumber = 1U;
/// Scripts.
std::vector<ScriptFile*> scripts;
/// The id of the next script to create.
unsigned int scriptNumber = 0U;
/// Default albedo texture.
TextureAsset* defaultAlbedo;
/// Default normal texture.
TextureAsset* defaultNormal;
/// Default metallic texture.
TextureAsset* defaultMetallic;
/// Default roughness texture.
TextureAsset* defaultRoughness;
/// Grid settings.
struct GridSettings
{
int gridScale = 10;
bool gridSettingsOpen = true;
};
GridSettings gridSettings;
/// Filter settings.
struct FilterSettings {
/// Whether to enable color.
bool color = false;
/// The color to blend with.
glm::vec3 colorColor = glm::vec3(1.0f, 1.0f, 1.0f);
/// Whether to enable fog.
bool fog = false;
/// Fog density.
float fogDensity = 0.01f;
/// Fog color.
glm::vec3 fogColor = glm::vec3(1.0f, 1.0f, 1.0f);
/// Whether to enable FXAA.
bool fxaa = true;
/// Whether to enable glow.
bool glow = true;
/// How many times to blur the glow buffer.
int glowBlurAmount = 1;
};
/// Filter settings.
FilterSettings filterSettings;
private:
static ActiveHymn& GetInstance();
ActiveHymn();
ActiveHymn(ActiveHymn const&) = delete;
void operator=(ActiveHymn const&) = delete;
std::string path = "";
};
/// Get the active hymn.
/**
* @return The %ActiveHymn instance.
*/
ActiveHymn& Hymn();
<commit_msg>small change no grid at beginning<commit_after>#pragma once
#include <string>
#include <vector>
#include <json/json.h>
#include "Entity/World.hpp"
class TextureAsset;
class ScriptFile;
/// A hymn to beauty.
class ActiveHymn {
friend ActiveHymn& Hymn();
public:
/// Clear the hymn of all properties.
void Clear();
/// Get the path where the hymn is saved.
/**
* @return The hymn's path.
*/
const std::string& GetPath() const;
/// Set the path where the hymn is saved.
/**
* @param path New path.
*/
void SetPath(const std::string& path);
/// Save the hymn.
void Save() const;
/// Load a hymn.
/**
* @param path Path to the saved hymn.
*/
void Load(const std::string& path);
/// Convert the hymn to Json.
/**
* @return The hymn as a Json.
*/
Json::Value ToJson() const;
/// Convert a Json to a Hymn.
/**
* @param root The Json file to load.
*/
void FromJson(Json::Value root);
/// Update the world.
/**
* @param deltaTime Time since last frame (in seconds).
*/
void Update(float deltaTime);
/// Render the world.
/**
* @param camera Camera through which to render (or first camera in the world if nullptr).
* @param soundSources Whether to show sound sources.
* @param particleEmitters Whether to show particle emitters.
* @param lightSources Whether to show light sources.
* @param cameras Whether to show cameras.
* @param physics Whether to show physics volumes.
*/
void Render(Entity* camera = nullptr, bool soundSources = false, bool particleEmitters = false, bool lightSources = false, bool cameras = false, bool physics = false, bool gridSettings = false);
/// Create static grid.
/**
* @param scale Scales the grid, scale can be a maximum of 100.
*/
void CreateGrid(int scale);
/// The game world.
World world;
/// The id of the next entity to create.
unsigned int entityNumber = 1U;
/// Scripts.
std::vector<ScriptFile*> scripts;
/// The id of the next script to create.
unsigned int scriptNumber = 0U;
/// Default albedo texture.
TextureAsset* defaultAlbedo;
/// Default normal texture.
TextureAsset* defaultNormal;
/// Default metallic texture.
TextureAsset* defaultMetallic;
/// Default roughness texture.
TextureAsset* defaultRoughness;
/// Grid settings.
struct GridSettings
{
int gridScale = 0;
bool gridSettingsOpen = true;
};
GridSettings gridSettings;
/// Filter settings.
struct FilterSettings {
/// Whether to enable color.
bool color = false;
/// The color to blend with.
glm::vec3 colorColor = glm::vec3(1.0f, 1.0f, 1.0f);
/// Whether to enable fog.
bool fog = false;
/// Fog density.
float fogDensity = 0.01f;
/// Fog color.
glm::vec3 fogColor = glm::vec3(1.0f, 1.0f, 1.0f);
/// Whether to enable FXAA.
bool fxaa = true;
/// Whether to enable glow.
bool glow = true;
/// How many times to blur the glow buffer.
int glowBlurAmount = 1;
};
/// Filter settings.
FilterSettings filterSettings;
private:
static ActiveHymn& GetInstance();
ActiveHymn();
ActiveHymn(ActiveHymn const&) = delete;
void operator=(ActiveHymn const&) = delete;
std::string path = "";
};
/// Get the active hymn.
/**
* @return The %ActiveHymn instance.
*/
ActiveHymn& Hymn();
<|endoftext|> |
<commit_before>#include <k52/parallel/worker_pool_factory.h>
#include <stdexcept>
#include "sequential_worker_pool.h"
using ::k52::parallel::SequentialWorkerPool;
#ifdef BUILD_WITH_BOOST_THREAD
#include "thread/thread_worker_pool.h"
using ::k52::parallel::thread::ThreadWorkerPool;
#endif
#ifdef BUILD_WITH_MPI
#include "mpi/mpi_worker_pool.h"
using ::k52::parallel::mpi::MpiWorkerPool;
#endif
namespace k52
{
namespace parallel
{
IWorkerPool::shared_ptr WorkerPoolFactory::CreateBestWorkerPool()
{
IWorkerPool::shared_ptr best_worker_pool;
WorkerPoolType worker_pool_type;
for(int i=0; i<3; i++)
{
switch (i)
{
case 0:
worker_pool_type = WorkerPoolFactory::kMpiWorkerPool;
break;
case 1:
worker_pool_type = WorkerPoolFactory::kThreadWorkerPool;
break;
case 2:
worker_pool_type = WorkerPoolFactory::kSequentialWorkerPool;
break;
default:
throw std::runtime_error("Bug in WorkerPoolFactory::CreateBestWorkerPool");
}
best_worker_pool = WorkerPoolFactory::CreateWorkerPool(worker_pool_type);
if(best_worker_pool->IsValid())
{
return best_worker_pool;
}
}
throw std::runtime_error("Can not create valid best_worker_pool.");
}
IWorkerPool::shared_ptr WorkerPoolFactory::CreateWorkerPool(WorkerPoolType worker_pool_type)
{
switch (worker_pool_type)
{
case kThreadWorkerPool:
#ifdef BUILD_WITH_BOOST_THREAD
return ThreadWorkerPool::shared_ptr (new ThreadWorkerPool());
#else
throw std::runtime_error("k52::parallel was build with boost::thread support. Try define BUILD_WITH_BOOST_THREAD.");
#endif
case kMpiWorkerPool:
#ifdef BUILD_WITH_MPI
if(WorkerPoolFactory::was_mpi_worker_pool_created_)
{
throw std::runtime_error("MpiWorkerPool was already created. Only one creation of this type is allowed.");
}
else
{
was_mpi_worker_pool_created_ = true;
return MpiWorkerPool::shared_ptr (new MpiWorkerPool());
}
#else
throw std::runtime_error("k52::parallel was not build with MPI support. Try define BUILD_WITH_MPI.");
#endif
case kSequentialWorkerPool:
return SequentialWorkerPool::shared_ptr (new SequentialWorkerPool());
default:
throw std::runtime_error("WorkerPoolType not supported.");
}
}
bool WorkerPoolFactory::CanCreateWorkerPool(WorkerPoolType worker_pool_type)
{
switch (worker_pool_type)
{
case kThreadWorkerPool:
#ifdef BUILD_WITH_BOOST_THREAD
return true;
#else
return false;
#endif
case kMpiWorkerPool:
#ifdef BUILD_WITH_MPI
return !WorkerPoolFactory::was_mpi_worker_pool_created_;
#else
return false;
#endif
case kSequentialWorkerPool:
return true;
default:
return false;
}
}
bool WorkerPoolFactory::was_mpi_worker_pool_created_ = false;
} /* namespace parallel */
} /* namespace k52 */
<commit_msg>Selecting only creatable WP's<commit_after>#include <k52/parallel/worker_pool_factory.h>
#include <stdexcept>
#include "sequential_worker_pool.h"
using ::k52::parallel::SequentialWorkerPool;
#ifdef BUILD_WITH_BOOST_THREAD
#include "thread/thread_worker_pool.h"
using ::k52::parallel::thread::ThreadWorkerPool;
#endif
#ifdef BUILD_WITH_MPI
#include "mpi/mpi_worker_pool.h"
using ::k52::parallel::mpi::MpiWorkerPool;
#endif
namespace k52
{
namespace parallel
{
IWorkerPool::shared_ptr WorkerPoolFactory::CreateBestWorkerPool()
{
IWorkerPool::shared_ptr best_worker_pool;
WorkerPoolType worker_pool_type;
for(int i=0; i<3; i++)
{
switch (i)
{
case 0:
worker_pool_type = WorkerPoolFactory::kMpiWorkerPool;
break;
case 1:
worker_pool_type = WorkerPoolFactory::kThreadWorkerPool;
break;
case 2:
worker_pool_type = WorkerPoolFactory::kSequentialWorkerPool;
break;
default:
throw std::runtime_error("Bug in WorkerPoolFactory::CreateBestWorkerPool");
}
if(!WorkerPoolFactory::CanCreateWorkerPool(worker_pool_type))
{
continue;
}
best_worker_pool = WorkerPoolFactory::CreateWorkerPool(worker_pool_type);
if(best_worker_pool->IsValid())
{
return best_worker_pool;
}
}
throw std::runtime_error("Can not create valid best_worker_pool.");
}
IWorkerPool::shared_ptr WorkerPoolFactory::CreateWorkerPool(WorkerPoolType worker_pool_type)
{
switch (worker_pool_type)
{
case kThreadWorkerPool:
#ifdef BUILD_WITH_BOOST_THREAD
return ThreadWorkerPool::shared_ptr (new ThreadWorkerPool());
#else
throw std::runtime_error("k52::parallel was build with boost::thread support. Try define BUILD_WITH_BOOST_THREAD.");
#endif
case kMpiWorkerPool:
#ifdef BUILD_WITH_MPI
if(WorkerPoolFactory::was_mpi_worker_pool_created_)
{
throw std::runtime_error("MpiWorkerPool was already created. Only one creation of this type is allowed.");
}
else
{
was_mpi_worker_pool_created_ = true;
return MpiWorkerPool::shared_ptr (new MpiWorkerPool());
}
#else
throw std::runtime_error("k52::parallel was not build with MPI support. Try define BUILD_WITH_MPI.");
#endif
case kSequentialWorkerPool:
return SequentialWorkerPool::shared_ptr (new SequentialWorkerPool());
default:
throw std::runtime_error("WorkerPoolType not supported.");
}
}
bool WorkerPoolFactory::CanCreateWorkerPool(WorkerPoolType worker_pool_type)
{
switch (worker_pool_type)
{
case kThreadWorkerPool:
#ifdef BUILD_WITH_BOOST_THREAD
return true;
#else
return false;
#endif
case kMpiWorkerPool:
#ifdef BUILD_WITH_MPI
return !WorkerPoolFactory::was_mpi_worker_pool_created_;
#else
return false;
#endif
case kSequentialWorkerPool:
return true;
default:
return false;
}
}
bool WorkerPoolFactory::was_mpi_worker_pool_created_ = false;
} /* namespace parallel */
} /* namespace k52 */
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/nacl/nacl_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
namespace {
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:5103/tests/prebuilt");
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
FILE_PATH_LITERAL("npapi_hw.html");
} // anonymous namespace
NaClTest::NaClTest()
: UITest(), use_x64_nexes_(false) {
launch_arguments_.AppendSwitch(switches::kEnableNaCl);
// Currently we disable some of the sandboxes. See:
// Make NaCl work in Chromium's Linux seccomp sandbox and the Mac sandbox
// http://code.google.com/p/nativeclient/issues/detail?id=344
#if defined(OS_LINUX) && defined(USE_SECCOMP_SANDBOX)
launch_arguments_.AppendSwitch(switches::kDisableSeccompSandbox);
#endif
}
NaClTest::~NaClTest() {}
FilePath NaClTest::GetTestRootDir() {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("native_client");
return path;
}
GURL NaClTest::GetTestUrl(const FilePath& filename) {
FilePath path(kBaseUrl);
if (use_x64_nexes_)
path = path.AppendASCII("x64");
else
path = path.AppendASCII("x86");
path = path.Append(filename);
return GURL(path.value());
}
void NaClTest::WaitForFinish(const FilePath& filename,
int wait_time) {
GURL url = GetTestUrl(filename);
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
bool test_result = WaitUntilCookieValue(tab.get(),
url,
kTestCompleteCookie,
wait_time,
kTestCompleteSuccess);
EXPECT_TRUE(test_result);
}
void NaClTest::RunTest(const FilePath& filename, int timeout) {
GURL url = GetTestUrl(filename);
NavigateToURL(url);
WaitForFinish(filename, timeout);
}
void NaClTest::SetUp() {
FilePath nacl_test_dir = GetTestRootDir();
#if defined(OS_WIN)
if (NaClOsIs64BitWindows())
use_x64_nexes_ = true;
#elif defined(OS_LINUX) && defined(__LP64__)
use_x64_nexes_ = true;
#endif
UITest::SetUp();
StartHttpServerWithPort(nacl_test_dir, L"5103");
}
void NaClTest::TearDown() {
StopHttpServer();
UITest::TearDown();
}
// See bug http://code.google.com/p/chromium/issues/detail?id=41007
TEST_F(NaClTest, FLAKY_ServerTest) {
FilePath test_file(kServerHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcHelloWorld) {
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcBasicTest) {
FilePath test_file(kSrpcBasicHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcSockAddrTest) {
FilePath test_file(kSrpcSockAddrHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcShmTest) {
FilePath test_file(kSrpcShmHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcPluginTest) {
FilePath test_file(kSrpcPluginHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcNrdXferTest) {
FilePath test_file(kSrpcNrdXferHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
// The test seems to be flaky.
// http://code.google.com/p/chromium/issues/detail?id=40669
TEST_F(NaClTest, FLAKY_NpapiHwTest) {
FilePath test_file(kNpapiHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
<commit_msg>Make 2 NaCl integration tests not flaky BUG=40669,41007 Review URL: http://codereview.chromium.org/1605025<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/nacl/nacl_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
namespace {
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:5103/tests/prebuilt");
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
FILE_PATH_LITERAL("npapi_hw.html");
} // anonymous namespace
NaClTest::NaClTest()
: UITest(), use_x64_nexes_(false) {
launch_arguments_.AppendSwitch(switches::kEnableNaCl);
// Currently we disable some of the sandboxes. See:
// Make NaCl work in Chromium's Linux seccomp sandbox and the Mac sandbox
// http://code.google.com/p/nativeclient/issues/detail?id=344
#if defined(OS_LINUX) && defined(USE_SECCOMP_SANDBOX)
launch_arguments_.AppendSwitch(switches::kDisableSeccompSandbox);
#endif
}
NaClTest::~NaClTest() {}
FilePath NaClTest::GetTestRootDir() {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("native_client");
return path;
}
GURL NaClTest::GetTestUrl(const FilePath& filename) {
FilePath path(kBaseUrl);
if (use_x64_nexes_)
path = path.AppendASCII("x64");
else
path = path.AppendASCII("x86");
path = path.Append(filename);
return GURL(path.value());
}
void NaClTest::WaitForFinish(const FilePath& filename,
int wait_time) {
GURL url = GetTestUrl(filename);
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
bool test_result = WaitUntilCookieValue(tab.get(),
url,
kTestCompleteCookie,
wait_time,
kTestCompleteSuccess);
EXPECT_TRUE(test_result);
}
void NaClTest::RunTest(const FilePath& filename, int timeout) {
GURL url = GetTestUrl(filename);
NavigateToURL(url);
WaitForFinish(filename, timeout);
}
void NaClTest::SetUp() {
FilePath nacl_test_dir = GetTestRootDir();
#if defined(OS_WIN)
if (NaClOsIs64BitWindows())
use_x64_nexes_ = true;
#elif defined(OS_LINUX) && defined(__LP64__)
use_x64_nexes_ = true;
#endif
UITest::SetUp();
StartHttpServerWithPort(nacl_test_dir, L"5103");
}
void NaClTest::TearDown() {
StopHttpServer();
UITest::TearDown();
}
TEST_F(NaClTest, ServerTest) {
FilePath test_file(kServerHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcHelloWorld) {
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcBasicTest) {
FilePath test_file(kSrpcBasicHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcSockAddrTest) {
FilePath test_file(kSrpcSockAddrHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcShmTest) {
FilePath test_file(kSrpcShmHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcPluginTest) {
FilePath test_file(kSrpcPluginHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, SrpcNrdXferTest) {
FilePath test_file(kSrpcNrdXferHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClTest, NpapiHwTest) {
FilePath test_file(kNpapiHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
<|endoftext|> |
<commit_before><commit_msg>disable failing tests while I debug<commit_after><|endoftext|> |
<commit_before>#include "Connection.h"
#include <TelepathyQt4/ContactManager>
namespace TelepathyIM
{
Connection::Connection(Tp::ConnectionManagerPtr tp_connection_manager, const Communication::CredentialsInterface &credentials) : tp_connection_manager_(tp_connection_manager), name_("Gabble"), protocol_("jabber"), state_(STATE_INITIALIZING)
{
CreateTpConnection(credentials);
}
void Connection::CreateTpConnection(const Communication::CredentialsInterface &credentials)
{
QVariantMap params;
params.insert("account", credentials.GetUserID());
params.insert("password", credentials.GetPassword());
params.insert("server", credentials.GetServer());
params.insert("port", QVariant( (unsigned int)credentials.GetPort() ));
//std::string message = "Try to open connection to IM server: ";
//message.append( server.toStdString () );
//LogInfo(message);
Tp::PendingConnection *pending_connection = tp_connection_manager_->requestConnection(credentials.GetProtocol(), params);
QObject::connect(pending_connection, SIGNAL( finished(Tp::PendingOperation *) ), SLOT( OnConnectionCreated(Tp::PendingOperation *) ));
server_ = credentials.GetServer();
}
Connection::~Connection()
{
if (!tp_connection_.isNull())
tp_connection_->requestDisconnect();
}
QString Connection::GetName() const
{
return name_;
}
QString Connection::GetProtocol() const
{
return protocol_;
}
Communication::ConnectionInterface::State Connection::GetState() const
{
return state_;
}
QString Connection::GetServer() const
{
return server_;
}
QString Connection::GetReason() const
{
return reason_;
}
Communication::ContactGroupInterface& Connection::GetContacts()
{
return friend_list_;
}
QStringList Connection::GetPresenceStatusOptionsForContact() const
{
//! @todo IMPLEMENT
QStringList empty;
return empty;
}
QStringList Connection::GetPresenceStatusOptionsForSelf() const
{
//! @todo IMPLEMENT
QStringList empty;
return empty;
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const Communication::ContactInterface &contact)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const QString& user_id)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
Communication::ChatSessionInterface* Connection::OpenChatSession(const QString &channel)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
void Connection::SendFriendRequest(const QString &target, const QString &message)
{
//! @todo IMPLEMENT
}
Communication::FriendRequestVector Connection::GetFriendRequests() const
{
//! @todo IMPLEMENT
Communication::FriendRequestVector requests;
return requests;
}
void Connection::Close()
{
if ( tp_connection_.isNull() )
return; // nothing to close
Tp::PendingOperation* op = tp_connection_->requestDisconnect();
connect(op, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( OnConnectionClosed(Tp::PendingOperation*) ));
}
void Connection::OnConnectionCreated(Tp::PendingOperation *op)
{
if (op->isError())
{
//std::string message = "Cannot create a connection object: ";
//message.append( op->errorMessage().toStdString() );
//LogError(message);
state_ = STATE_ERROR;
reason_ = op->errorMessage();
emit( ConnectionError(*this) );
// throw Core::Exception( op->errorMessage().toStdString().c_str() );
}
Tp::PendingConnection *c = qobject_cast<Tp::PendingConnection *>(op);
tp_connection_ = c->connection();
//std::string message = "Connection created to IM server.";
//LogInfo(message);
QObject::connect(tp_connection_->requestConnect(),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(OnConnectionConnected(Tp::PendingOperation *)));
QObject::connect(tp_connection_.data(),
SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
SLOT(OnConnectionInvalidated(Tp::DBusProxy *, const QString &, const QString &)));
state_ = STATE_OPEN;
emit( ConnectionReady(*this) );
}
void Connection::OnConnectionConnected(Tp::PendingOperation *op)
{
if (op->isError())
{
//QString reason = "Cannot connect to IM server:: ";
//reason.append(op->errorMessage());
//LogError(reason.toStdString());
state_ = STATE_ERROR;
throw Core::Exception( op->errorMessage().toStdString().c_str() );
}
//std::string message = "Connection established successfully to IM server.";
//LogInfo(message);
Tp::Features features;
features.insert(Tp::Connection::FeatureSimplePresence);
features.insert(Tp::Connection::FeatureRoster);
features.insert(Tp::Connection::FeatureSelfContact);
features.insert(Tp::Connection::FeatureCore);
QObject::connect(tp_connection_->becomeReady(features),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(OnConnectionReady(Tp::PendingOperation *)));
if( tp_connection_->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS) )
{
QObject::connect(tp_connection_->requestsInterface(),
SIGNAL(NewChannels(const Tp::ChannelDetailsList&)),
SLOT(OnNewChannels(const Tp::ChannelDetailsList&)));
}
}
void Connection::OnConnectionReady(Tp::PendingOperation *op)
{
if (op->isError())
{
//QString message = "Connection initialization to IM server failed: ";
//message.append(op->errorMessage());
//LogError(message.toStdString());
state_ = STATE_ERROR;
throw Core::Exception( op->errorMessage().toStdString().c_str() );
}
connect(tp_connection_->contactManager(), SIGNAL( presencePublicationRequested(const Tp::Contacts &) ), SLOT( OnPresencePublicationRequested(const Tp::Contacts &) ));
HandleAllKnownTpContacts();
state_ = STATE_OPEN;
emit( ConnectionReady(*this) );
}
void Connection::HandleAllKnownTpContacts()
{
ContactVector new_contacts;
//! Check every known telepathy contact and determinate their nature by state of subscribtionState and publistState values
//! Combinations are:
//! subscription: publish:
//! - Normal contact YES YES
//! - friend request (sended)
//! - friend request (received) ASK YES
//! - banned contact NO *
//! - unknow (all the other combinations)
foreach (const Tp::ContactPtr &contact, tp_connection_->contactManager()->allKnownContacts())
{
switch ( contact->subscriptionState() )
{
case Tp::Contact::PresenceStateNo:
// User have already make a decicion to not accpet this contact to the a part of the friend list..
break;
case Tp::Contact::PresenceStateYes:
{
// A friend list item
switch ( contact->publishState() )
{
case Tp::Contact::PresenceStateNo:
{
//! We have subsribed presence status of this contact
//! but we have not published our own presence!
//! -> We unsubsribe this contact
Tp::PendingOperation* pending_remove_subscription = contact->removePresenceSubscription();
//! check result of this
}
break;
case Tp::Contact::PresenceStateYes:
//! This is a normal state
break;
case Tp::Contact::PresenceStateAsk:
//! We have subscribed presence of this contact
//! but we don't publish our?
//! Publicity level should be same to the both directions
Tp::PendingOperation* op = contact->authorizePresencePublication("");
//! todo: check the end result of this operation
break;
}
Contact* c = new Contact(contact);
new_contacts.push_back(c);
}
break;
case Tp::Contact::PresenceStateAsk:
{
// User have not yet made the decision to accept or reject presence subscription
// So we create a FriendRequest obeject
//! @todo IMPLEMENT
//FriendRequest* request = new FriendRequest(contact);
//received_friend_requests_.push_back(request);
//emit ReceivedFriendRequest(request);
}
break;
}
}
if ( new_contacts.size() > 0 )
{
for (ContactVector::iterator i = new_contacts.begin(); i != new_contacts.end(); ++i)
{
contacts_.push_back(*i);
friend_list_.AddContact(*i);
}
//! @todo emit signal about contact list change
}
}
void Connection::OnNewChannels(const Tp::ChannelDetailsList& details)
{
//! @todo IMPLEMENT
}
void Connection::OnConnectionInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage)
{
state_ = STATE_ERROR;
reason_ = errorMessage;
emit( ConnectionError(*this) );
//! @todo IMPLEMENT
}
void Connection::OnConnectionClosed(Tp::PendingOperation *op)
{
state_ = STATE_CLOSED;
emit( ConnectionClosed(*this) );
}
void Connection::OnPresencePublicationRequested(const Tp::Contacts &contacts)
{
//! @todo IMPLEMENT
}
} // end of namespace: TelepathyIM
<commit_msg>Fix error handling<commit_after>#include "Connection.h"
#include <TelepathyQt4/ContactManager>
namespace TelepathyIM
{
Connection::Connection(Tp::ConnectionManagerPtr tp_connection_manager, const Communication::CredentialsInterface &credentials) : tp_connection_manager_(tp_connection_manager), name_("Gabble"), protocol_("jabber"), state_(STATE_INITIALIZING)
{
CreateTpConnection(credentials);
}
void Connection::CreateTpConnection(const Communication::CredentialsInterface &credentials)
{
QVariantMap params;
params.insert("account", credentials.GetUserID());
params.insert("password", credentials.GetPassword());
params.insert("server", credentials.GetServer());
params.insert("port", QVariant( (unsigned int)credentials.GetPort() ));
//std::string message = "Try to open connection to IM server: ";
//message.append( server.toStdString () );
//LogInfo(message);
Tp::PendingConnection *pending_connection = tp_connection_manager_->requestConnection(credentials.GetProtocol(), params);
QObject::connect(pending_connection, SIGNAL( finished(Tp::PendingOperation *) ), SLOT( OnConnectionCreated(Tp::PendingOperation *) ));
server_ = credentials.GetServer();
}
Connection::~Connection()
{
if (!tp_connection_.isNull())
tp_connection_->requestDisconnect();
}
QString Connection::GetName() const
{
return name_;
}
QString Connection::GetProtocol() const
{
return protocol_;
}
Communication::ConnectionInterface::State Connection::GetState() const
{
return state_;
}
QString Connection::GetServer() const
{
return server_;
}
QString Connection::GetReason() const
{
return reason_;
}
Communication::ContactGroupInterface& Connection::GetContacts()
{
return friend_list_;
}
QStringList Connection::GetPresenceStatusOptionsForContact() const
{
//! @todo IMPLEMENT
QStringList empty;
return empty;
}
QStringList Connection::GetPresenceStatusOptionsForSelf() const
{
//! @todo IMPLEMENT
QStringList empty;
return empty;
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const Communication::ContactInterface &contact)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const QString& user_id)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
Communication::ChatSessionInterface* Connection::OpenChatSession(const QString &channel)
{
//! @todo IMPLEMENT
throw Core::Exception("NOT IMPLEMENTED");
}
void Connection::SendFriendRequest(const QString &target, const QString &message)
{
//! @todo IMPLEMENT
}
Communication::FriendRequestVector Connection::GetFriendRequests() const
{
//! @todo IMPLEMENT
Communication::FriendRequestVector requests;
return requests;
}
void Connection::Close()
{
if ( tp_connection_.isNull() )
return; // nothing to close
Tp::PendingOperation* op = tp_connection_->requestDisconnect();
connect(op, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( OnConnectionClosed(Tp::PendingOperation*) ));
}
void Connection::OnConnectionCreated(Tp::PendingOperation *op)
{
if (op->isError())
{
state_ = STATE_ERROR;
reason_ = op->errorMessage();
emit( ConnectionError(*this) );
return;
}
Tp::PendingConnection *c = qobject_cast<Tp::PendingConnection *>(op);
tp_connection_ = c->connection();
QObject::connect(tp_connection_->requestConnect(),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(OnConnectionConnected(Tp::PendingOperation *)));
QObject::connect(tp_connection_.data(),
SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
SLOT(OnConnectionInvalidated(Tp::DBusProxy *, const QString &, const QString &)));
}
void Connection::OnConnectionConnected(Tp::PendingOperation *op)
{
if (op->isError())
{
state_ = STATE_ERROR;
reason_ = op->errorMessage();
emit( ConnectionError(*this) );
return;
}
Tp::Features features;
features.insert(Tp::Connection::FeatureSimplePresence);
features.insert(Tp::Connection::FeatureRoster);
features.insert(Tp::Connection::FeatureSelfContact);
features.insert(Tp::Connection::FeatureCore);
QObject::connect(tp_connection_->becomeReady(features),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(OnConnectionReady(Tp::PendingOperation *)));
if( tp_connection_->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS) )
{
QObject::connect(tp_connection_->requestsInterface(),
SIGNAL(NewChannels(const Tp::ChannelDetailsList&)),
SLOT(OnNewChannels(const Tp::ChannelDetailsList&)));
}
}
void Connection::OnConnectionReady(Tp::PendingOperation *op)
{
if (op->isError())
{
state_ = STATE_ERROR;
reason_ = op->errorMessage();
emit( ConnectionError(*this) );
return;
}
connect(tp_connection_->contactManager(), SIGNAL( presencePublicationRequested(const Tp::Contacts &) ), SLOT( OnPresencePublicationRequested(const Tp::Contacts &) ));
HandleAllKnownTpContacts();
state_ = STATE_OPEN;
emit( ConnectionReady(*this) );
}
void Connection::HandleAllKnownTpContacts()
{
ContactVector new_contacts;
//! Check every known telepathy contact and determinate their nature by state of subscribtionState and publistState values
//! Combinations are:
//! subscription: publish:
//! - Normal contact YES YES
//! - friend request (sended)
//! - friend request (received) ASK YES
//! - banned contact NO *
//! - unknow (all the other combinations)
foreach (const Tp::ContactPtr &contact, tp_connection_->contactManager()->allKnownContacts())
{
switch ( contact->subscriptionState() )
{
case Tp::Contact::PresenceStateNo:
// User have already make a decicion to not accpet this contact to the a part of the friend list..
break;
case Tp::Contact::PresenceStateYes:
{
// A friend list item
switch ( contact->publishState() )
{
case Tp::Contact::PresenceStateNo:
{
//! We have subsribed presence status of this contact
//! but we have not published our own presence!
//! -> We unsubsribe this contact
Tp::PendingOperation* pending_remove_subscription = contact->removePresenceSubscription();
//! check result of this
}
break;
case Tp::Contact::PresenceStateYes:
//! This is a normal state
break;
case Tp::Contact::PresenceStateAsk:
//! We have subscribed presence of this contact
//! but we don't publish our?
//! Publicity level should be same to the both directions
Tp::PendingOperation* op = contact->authorizePresencePublication("");
//! todo: check the end result of this operation
break;
}
Contact* c = new Contact(contact);
new_contacts.push_back(c);
}
break;
case Tp::Contact::PresenceStateAsk:
{
// User have not yet made the decision to accept or reject presence subscription
// So we create a FriendRequest obeject
//! @todo IMPLEMENT
//FriendRequest* request = new FriendRequest(contact);
//received_friend_requests_.push_back(request);
//emit ReceivedFriendRequest(request);
}
break;
}
}
if ( new_contacts.size() > 0 )
{
for (ContactVector::iterator i = new_contacts.begin(); i != new_contacts.end(); ++i)
{
contacts_.push_back(*i);
friend_list_.AddContact(*i);
}
//! @todo emit signal about contact list change
}
}
void Connection::OnNewChannels(const Tp::ChannelDetailsList& details)
{
//! @todo IMPLEMENT
}
void Connection::OnConnectionInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage)
{
state_ = STATE_ERROR;
reason_ = errorMessage;
emit( ConnectionError(*this) );
//! @todo IMPLEMENT
}
void Connection::OnConnectionClosed(Tp::PendingOperation *op)
{
state_ = STATE_CLOSED;
emit( ConnectionClosed(*this) );
}
void Connection::OnPresencePublicationRequested(const Tp::Contacts &contacts)
{
//! @todo IMPLEMENT
}
} // end of namespace: TelepathyIM
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* VListCF.cpp
*
* Created on: Feb 24, 2011
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "items/VListCF.h"
using namespace Visualization;
using namespace Model;
namespace ControlFlowVisualization {
ITEM_COMMON_DEFINITIONS( VListCF )
VListCF::VListCF(Item* parent, NodeType* node, const StyleType* style) :
ItemWithNode< ControlFlowItem, List>(parent, node, style)
{
}
VListCF::~VListCF()
{
for (int i = 0; i<items_.size(); i++) SAFE_DELETE_ITEM( items_[i]);
}
bool VListCF::isEmpty() const
{
return items_.empty();
}
void VListCF::determineChildren()
{
//TODO this
// Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.
for (int i = 0; i < node()->size(); ++i)
{
if (i >= lengthSingle() ) appendSingle( renderer->render(NULL, node()->at<Node>(i))); // This node is new
else if ( atSingle(i)->node() == node()->at<Node>(i) ) continue; // This node is already there
else
{
// This node might appear somewhere ahead, we should look for it
bool found = false;
for (int k = i + 1; k<lengthSingle(); ++k)
{
if ( atSingle(k)->node() == node()->at<Node>(i) )
{
// We found this node, swap the visualizations
swapSingle(i, k);
found = true;
break;
}
}
// The node was not found, insert a visualization here
if (!found ) insertSingle( renderer->render(NULL, node()->at<Node>(i)), i);
}
}
// Remove excess items
while (lengthSingle() > node()->size()) removeLastSingle();
}
void VListCF::updateGeometry(int, int)
{
breaks_.clear();
continues_.clear();
//TODO this
}
void VListCF::appendSingle( Visualization::Item* item)
{
insertSingle(item, lengthSingle() );
}
void VListCF::insertSingle( Visualization::Item* item, int pos);
void VListCF::swapSingle(int i, int j);
void VListCF::removeLastSingle();
Visualization::Item* VListCF::atSingle(int pos)
{
int index = pos;
for (int i = 0; i<items_.size(); ++i)
{
SequentialLayout* seq = dynamic_cast<SequentialLayout*> (items_[i]);
if (seq)
{
if (index < seq->length()) return seq->at<Item>(index);
else index -= seq->length();
}
else
{
if (index == 0) return items_[i];
else --index;
}
}
return NULL;
}
int VListCF::lengthSingle()
{
int len = 0;
for (int i = 0; i<items_.size(); ++i)
{
SequentialLayout* seq = dynamic_cast<SequentialLayout*> (items_[i]);
if (seq) len += seq->length(); // This is a sequnce of Items which are not ControlFlowItems.
else ++len; // This is a single ControlFlowItem
}
}
bool VListCF::focusChild(FocusTarget /*location*/)
{
//TODO implement this
return false;
}
}
<commit_msg>CHANGED: Added a few todo's.<commit_after>/***********************************************************************************************************************
* VListCF.cpp
*
* Created on: Feb 24, 2011
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "items/VListCF.h"
using namespace Visualization;
using namespace Model;
namespace ControlFlowVisualization {
ITEM_COMMON_DEFINITIONS( VListCF )
VListCF::VListCF(Item* parent, NodeType* node, const StyleType* style) :
ItemWithNode< ControlFlowItem, List>(parent, node, style)
{
}
VListCF::~VListCF()
{
for (int i = 0; i<items_.size(); i++) SAFE_DELETE_ITEM( items_[i]);
}
bool VListCF::isEmpty() const
{
return items_.empty();
}
void VListCF::determineChildren()
{
//TODO this
// Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.
for (int i = 0; i < node()->size(); ++i)
{
if (i >= lengthSingle() ) appendSingle( renderer->render(NULL, node()->at<Node>(i))); // This node is new
else if ( atSingle(i)->node() == node()->at<Node>(i) ) continue; // This node is already there
else
{
// This node might appear somewhere ahead, we should look for it
bool found = false;
for (int k = i + 1; k<lengthSingle(); ++k)
{
if ( atSingle(k)->node() == node()->at<Node>(i) )
{
// We found this node, swap the visualizations
swapSingle(i, k);
found = true;
break;
}
}
// The node was not found, insert a visualization here
if (!found ) insertSingle( renderer->render(NULL, node()->at<Node>(i)), i);
}
}
// Remove excess items
while (lengthSingle() > node()->size()) removeLastSingle();
}
void VListCF::updateGeometry(int, int)
{
breaks_.clear();
continues_.clear();
//TODO this
}
void VListCF::appendSingle( Visualization::Item* item)
{
insertSingle(item, lengthSingle() );
}
//TODO these
void VListCF::insertSingle( Visualization::Item* item, int pos);
void VListCF::swapSingle(int i, int j);
void VListCF::removeLastSingle();
Visualization::Item* VListCF::atSingle(int pos)
{
int index = pos;
for (int i = 0; i<items_.size(); ++i)
{
SequentialLayout* seq = dynamic_cast<SequentialLayout*> (items_[i]);
if (seq)
{
if (index < seq->length()) return seq->at<Item>(index);
else index -= seq->length();
}
else
{
if (index == 0) return items_[i];
else --index;
}
}
return NULL;
}
int VListCF::lengthSingle()
{
int len = 0;
for (int i = 0; i<items_.size(); ++i)
{
SequentialLayout* seq = dynamic_cast<SequentialLayout*> (items_[i]);
if (seq) len += seq->length(); // This is a sequnce of Items which are not ControlFlowItems.
else ++len; // This is a single ControlFlowItem
}
}
bool VListCF::focusChild(FocusTarget /*location*/)
{
//TODO implement this
return false;
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include "CmdSession.h"
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/IO/MatrixIO.h>
#define HELP_NAME "help"
#define PRIOR_NAME "prior"
#define FEATURES_NAME "features"
#define TEST_NAME "test"
#define TRAIN_NAME "train"
#define BURNIN_NAME "burnin"
#define NSAMPLES_NAME "nsamples"
#define NUM_LATENT_NAME "num-latent"
#define RESTORE_PREFIX_NAME "restore-prefix"
#define RESTORE_SUFFIX_NAME "restore-suffix"
#define INIT_MODEL_NAME "init-model"
#define SAVE_PREFIX_NAME "save-prefix"
#define SAVE_SUFFIX_NAME "save-suffix"
#define SAVE_FREQ_NAME "save-freq"
#define THRESHOLD_NAME "threshold"
#define VERBOSE_NAME "verbose"
#define QUIET_NAME "quiet"
#define VERSION_NAME "version"
#define STATUS_NAME "status"
#define SEED_NAME "seed"
#define PRECISION_NAME "precision"
#define ADAPTIVE_NAME "adaptive"
#define PROBIT_NAME "probit"
#define LAMBDA_BETA_NAME "lambda-beta"
#define TOL_NAME "tol"
#define DIRECT_NAME "direct"
using namespace smurff;
boost::program_options::options_description get_desc()
{
boost::program_options::options_description basic_desc("Basic options");
basic_desc.add_options()
(HELP_NAME, "show help information");
boost::program_options::options_description priors_desc("Priors and side Info");
priors_desc.add_options()
(PRIOR_NAME, boost::program_options::value<std::vector<std::string> >()->multitoken(), "One of <normal|spikeandslab|macau|macauone>")
(FEATURES_NAME, boost::program_options::value<std::vector<std::string> >()->multitoken(), "Side info for each dimention");
boost::program_options::options_description train_test_desc("Test and train matrices");
train_test_desc.add_options()
(TEST_NAME, boost::program_options::value<std::string>(), "test data (for computing RMSE)")
(TRAIN_NAME, boost::program_options::value<std::string>(), "train data file");
boost::program_options::options_description general_desc("General parameters");
general_desc.add_options()
(BURNIN_NAME, boost::program_options::value<int>()->default_value(200), "number of samples to discard")
(NSAMPLES_NAME, boost::program_options::value<int>()->default_value(800), "number of samples to collect")
(NUM_LATENT_NAME, boost::program_options::value<int>()->default_value(96), "number of latent dimensions")
(RESTORE_PREFIX_NAME, boost::program_options::value<std::string>()->default_value(std::string()), "prefix for file to initialize state")
(RESTORE_SUFFIX_NAME, boost::program_options::value<std::string>()->default_value(".csv"), "suffix for initialization files (.csv or .ddm)")
(INIT_MODEL_NAME, boost::program_options::value<std::string>()->default_value(MODEL_INIT_NAME_ZERO), "One of <random|zero>")
(SAVE_PREFIX_NAME, boost::program_options::value<std::string>()->default_value("save"), "prefix for result files")
(SAVE_SUFFIX_NAME, boost::program_options::value<std::string>()->default_value(".csv"), "suffix for result files (.csv or .ddm)")
(SAVE_FREQ_NAME, boost::program_options::value<int>()->default_value(0), "save every n iterations (0 == never, -1 == final model)")
(THRESHOLD_NAME, boost::program_options::value<double>(), "threshold for binary classification")
(VERBOSE_NAME, boost::program_options::value<int>()->default_value(1), "verbose output")
(QUIET_NAME, "no output")
(VERSION_NAME, "print version info")
(STATUS_NAME, boost::program_options::value<std::string>()->default_value(std::string()), "output progress to csv file")
(SEED_NAME, boost::program_options::value<int>(), "random number generator seed");
boost::program_options::options_description noise_desc("Noise model");
noise_desc.add_options()
(PRECISION_NAME, boost::program_options::value<std::string>()->default_value("5.0"), "precision of observations")
(ADAPTIVE_NAME, boost::program_options::value<std::string>()->default_value("1.0,10.0"), "adaptive precision of observations");
(PROBIT, boost::program_options::value<std::string>()->default_value("0.0"), "probit noise model with given threshold");
boost::program_options::options_description macau_prior_desc("For the macau prior");
macau_prior_desc.add_options()
(LAMBDA_BETA_NAME, boost::program_options::value<double>()->default_value(10.0), "initial value of lambda beta")
(TOL_NAME, boost::program_options::value<double>()->default_value(1e-6), "tolerance for CG")
(DIRECT_NAME, "Use Cholesky decomposition i.o. CG Solver");
boost::program_options::options_description desc("SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff");
desc.add(basic_desc);
desc.add(priors_desc);
desc.add(train_test_desc);
desc.add(general_desc);
desc.add(noise_desc);
desc.add(macau_prior_desc);
return desc;
}
void set_noise_model(Config& config, std::string noiseName, std::string optarg)
{
NoiseConfig nc;
nc.setNoiseType(smurff::stringToNoiseType(noiseName));
if (nc.getNoiseType() == NoiseTypes::adaptive)
{
std::stringstream lineStream(optarg);
std::string token;
std::vector<std::string> tokens;
while (std::getline(lineStream, token, ','))
tokens.push_back(token);
if(tokens.size() != 2)
THROWERROR("invalid number of options for adaptive noise");
nc.sn_init = strtod(tokens[0].c_str(), NULL);
nc.sn_max = strtod(tokens[1].c_str(), NULL);
}
else if (nc.getNoiseType() == NoiseTypes::fixed)
{
nc.precision = strtod(optarg.c_str(), NULL);
}
else if (nc.getNoiseType() == NoiseTypes::probit)
{
nc.threshold = strtod(optarg.c_str(), NULL);
}
if(!config.getTrain())
THROWERROR("train data is not provided");
// set global noise model
if (config.getTrain()->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
config.getTrain()->setNoiseConfig(nc);
//set for feautres
for(auto& featureSet : config.getFeatures())
{
for(auto features : featureSet)
{
if (features->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
features->setNoiseConfig(nc);
}
}
}
void fill_config(boost::program_options::variables_map& vm, Config& config)
{
if (vm.count(PRIOR_NAME))
for (auto& pr : vm[PRIOR_NAME].as<std::vector<std::string> >())
config.getPriorTypes().push_back(stringToPriorType(pr));
if (vm.count(FEATURES_NAME))
{
for (auto featString : vm[FEATURES_NAME].as<std::vector<std::string> >())
{
config.getFeatures().push_back(std::vector<std::shared_ptr<MatrixConfig> >());
auto& dimFeatures = config.getFeatures().back();
std::stringstream lineStream(featString);
std::string token;
while (std::getline(lineStream, token, ','))
{
//add ability to skip features for specific dimention
if(token == "none")
continue;
dimFeatures.push_back(matrix_io::read_matrix(token, false));
}
}
}
if (vm.count(TEST_NAME))
config.setTest(generic_io::read_data_config(vm[TEST_NAME].as<std::string>(), true));
if (vm.count(TRAIN_NAME))
config.setTrain(generic_io::read_data_config(vm[TRAIN_NAME].as<std::string>(), true));
if (vm.count(BURNIN_NAME))
config.setBurnin(vm[BURNIN_NAME].as<int>());
if (vm.count(NSAMPLES_NAME))
config.setNSamples(vm[NSAMPLES_NAME].as<int>());
if(vm.count(NUM_LATENT_NAME))
config.setNumLatent(vm[NUM_LATENT_NAME].as<int>());
if(vm.count(RESTORE_PREFIX_NAME))
config.setRestorePrefix(vm[RESTORE_PREFIX_NAME].as<std::string>());
if(vm.count(RESTORE_SUFFIX_NAME))
config.setRestoreSuffix(vm[RESTORE_SUFFIX_NAME].as<std::string>());
if(vm.count(INIT_MODEL_NAME))
config.setModelInitType(stringToModelInitType(vm[INIT_MODEL_NAME].as<std::string>()));
if(vm.count(SAVE_PREFIX_NAME))
config.setSavePrefix(vm[SAVE_PREFIX_NAME].as<std::string>());
if(vm.count(SAVE_SUFFIX_NAME))
config.setSaveSuffix(vm[SAVE_SUFFIX_NAME].as<std::string>());
if(vm.count(SAVE_FREQ_NAME))
config.setSaveFreq(vm[SAVE_FREQ_NAME].as<int>());
if(vm.count(THRESHOLD_NAME))
{
config.setThreshold(vm[THRESHOLD_NAME].as<double>());
config.setClassify(true);
}
if(vm.count(VERBOSE_NAME))
config.setVerbose(vm[VERBOSE_NAME].as<int>());
if(vm.count(QUIET_NAME))
config.setVerbose(0);
if(vm.count(STATUS_NAME))
config.setCsvStatus(vm[STATUS_NAME].as<std::string>());
if(vm.count(SEED_NAME))
{
config.setRandomSeedSet(true);
config.setRandomSeed(vm[SEED_NAME].as<int>());
}
if(vm.count(PRECISION_NAME))
set_noise_model(config, NOISE_NAME_FIXED, vm[PRECISION_NAME].as<std::string>());
if(vm.count(ADAPTIVE_NAME))
set_noise_model(config, NOISE_NAME_ADAPTIVE, vm[ADAPTIVE_NAME].as<std::string>());
if(vm.count(PROBIT_NAME))
set_noise_model(config, NOISE_NAME_PROBIT, vm[PROBIT_NAME].as<std::string>());
if(vm.count(LAMBDA_BETA_NAME))
config.setLambdaBeta(vm[LAMBDA_BETA_NAME].as<double>());
if(vm.count(TOL_NAME))
config.setTol(vm[TOL_NAME].as<double>());
if(vm.count(DIRECT_NAME))
config.setDirect(true);
}
bool parse_options(int argc, char* argv[], Config& config)
{
try
{
boost::program_options::options_description desc = get_desc();
boost::program_options::variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if(vm.count(HELP_NAME))
{
std::cout << desc << std::endl;
return false;
}
if(vm.count(VERSION_NAME))
{
std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl;
return false;
}
fill_config(vm, config);
return true;
}
catch (const boost::program_options::error &ex)
{
std::cerr << "Failed to parse command line arguments: " << std::endl;
std::cerr << ex.what() << std::endl;
return false;
}
catch (std::runtime_error& ex)
{
std::cerr << "Failed to parse command line arguments: " << std::endl;
std::cerr << ex.what() << std::endl;
return false;
}
}
void CmdSession::setFromArgs(int argc, char** argv)
{
Config config;
if(!parse_options(argc, argv, config))
exit(0); //need a way to figure out how to handle help and version
setFromConfig(config);
}
//create cmd session
//parses args with setFromArgs, then internally calls setFromConfig (to validate, save, set config)
std::shared_ptr<ISession> smurff::create_cmd_session(int argc, char** argv)
{
std::shared_ptr<CmdSession> session(new CmdSession());
session->setFromArgs(argc, argv);
return session;
}
<commit_msg>Fixes related to prev. merge<commit_after>#include <string>
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include "CmdSession.h"
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/IO/MatrixIO.h>
#define HELP_NAME "help"
#define PRIOR_NAME "prior"
#define FEATURES_NAME "features"
#define TEST_NAME "test"
#define TRAIN_NAME "train"
#define BURNIN_NAME "burnin"
#define NSAMPLES_NAME "nsamples"
#define NUM_LATENT_NAME "num-latent"
#define RESTORE_PREFIX_NAME "restore-prefix"
#define RESTORE_SUFFIX_NAME "restore-suffix"
#define INIT_MODEL_NAME "init-model"
#define SAVE_PREFIX_NAME "save-prefix"
#define SAVE_SUFFIX_NAME "save-suffix"
#define SAVE_FREQ_NAME "save-freq"
#define THRESHOLD_NAME "threshold"
#define VERBOSE_NAME "verbose"
#define QUIET_NAME "quiet"
#define VERSION_NAME "version"
#define STATUS_NAME "status"
#define SEED_NAME "seed"
#define PRECISION_NAME "precision"
#define ADAPTIVE_NAME "adaptive"
#define PROBIT_NAME "probit"
#define LAMBDA_BETA_NAME "lambda-beta"
#define TOL_NAME "tol"
#define DIRECT_NAME "direct"
using namespace smurff;
boost::program_options::options_description get_desc()
{
boost::program_options::options_description basic_desc("Basic options");
basic_desc.add_options()
(HELP_NAME, "show help information");
boost::program_options::options_description priors_desc("Priors and side Info");
priors_desc.add_options()
(PRIOR_NAME, boost::program_options::value<std::vector<std::string> >()->multitoken(), "One of <normal|spikeandslab|macau|macauone>")
(FEATURES_NAME, boost::program_options::value<std::vector<std::string> >()->multitoken(), "Side info for each dimention");
boost::program_options::options_description train_test_desc("Test and train matrices");
train_test_desc.add_options()
(TEST_NAME, boost::program_options::value<std::string>(), "test data (for computing RMSE)")
(TRAIN_NAME, boost::program_options::value<std::string>(), "train data file");
boost::program_options::options_description general_desc("General parameters");
general_desc.add_options()
(BURNIN_NAME, boost::program_options::value<int>()->default_value(200), "number of samples to discard")
(NSAMPLES_NAME, boost::program_options::value<int>()->default_value(800), "number of samples to collect")
(NUM_LATENT_NAME, boost::program_options::value<int>()->default_value(96), "number of latent dimensions")
(RESTORE_PREFIX_NAME, boost::program_options::value<std::string>()->default_value(std::string()), "prefix for file to initialize state")
(RESTORE_SUFFIX_NAME, boost::program_options::value<std::string>()->default_value(".csv"), "suffix for initialization files (.csv or .ddm)")
(INIT_MODEL_NAME, boost::program_options::value<std::string>()->default_value(MODEL_INIT_NAME_ZERO), "One of <random|zero>")
(SAVE_PREFIX_NAME, boost::program_options::value<std::string>()->default_value("save"), "prefix for result files")
(SAVE_SUFFIX_NAME, boost::program_options::value<std::string>()->default_value(".csv"), "suffix for result files (.csv or .ddm)")
(SAVE_FREQ_NAME, boost::program_options::value<int>()->default_value(0), "save every n iterations (0 == never, -1 == final model)")
(THRESHOLD_NAME, boost::program_options::value<double>(), "threshold for binary classification")
(VERBOSE_NAME, boost::program_options::value<int>()->default_value(1), "verbose output")
(QUIET_NAME, "no output")
(VERSION_NAME, "print version info")
(STATUS_NAME, boost::program_options::value<std::string>()->default_value(std::string()), "output progress to csv file")
(SEED_NAME, boost::program_options::value<int>(), "random number generator seed");
boost::program_options::options_description noise_desc("Noise model");
noise_desc.add_options()
(PRECISION_NAME, boost::program_options::value<std::string>()->default_value("5.0"), "precision of observations")
(ADAPTIVE_NAME, boost::program_options::value<std::string>()->default_value("1.0,10.0"), "adaptive precision of observations")
(PROBIT_NAME, boost::program_options::value<std::string>()->default_value("0.0"), "probit noise model with given threshold");
boost::program_options::options_description macau_prior_desc("For the macau prior");
macau_prior_desc.add_options()
(LAMBDA_BETA_NAME, boost::program_options::value<double>()->default_value(10.0), "initial value of lambda beta")
(TOL_NAME, boost::program_options::value<double>()->default_value(1e-6), "tolerance for CG")
(DIRECT_NAME, "Use Cholesky decomposition i.o. CG Solver");
boost::program_options::options_description desc("SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff");
desc.add(basic_desc);
desc.add(priors_desc);
desc.add(train_test_desc);
desc.add(general_desc);
desc.add(noise_desc);
desc.add(macau_prior_desc);
return desc;
}
void set_noise_model(Config& config, std::string noiseName, std::string optarg)
{
NoiseConfig nc;
nc.setNoiseType(smurff::stringToNoiseType(noiseName));
if (nc.getNoiseType() == NoiseTypes::adaptive)
{
std::stringstream lineStream(optarg);
std::string token;
std::vector<std::string> tokens;
while (std::getline(lineStream, token, ','))
tokens.push_back(token);
if(tokens.size() != 2)
THROWERROR("invalid number of options for adaptive noise");
nc.sn_init = strtod(tokens[0].c_str(), NULL);
nc.sn_max = strtod(tokens[1].c_str(), NULL);
}
else if (nc.getNoiseType() == NoiseTypes::fixed)
{
nc.precision = strtod(optarg.c_str(), NULL);
}
else if (nc.getNoiseType() == NoiseTypes::probit)
{
nc.threshold = strtod(optarg.c_str(), NULL);
}
if(!config.getTrain())
THROWERROR("train data is not provided");
// set global noise model
if (config.getTrain()->getNoiseConfig().getNoiseType() == NoiseTypes::unset)
config.getTrain()->setNoiseConfig(nc);
//set for feautres
for(auto& featureSet : config.getFeatures())
{
for(auto features : featureSet)
{
if (features->getNoiseConfig().getNoiseType() == NoiseTypes::unset)
features->setNoiseConfig(nc);
}
}
}
void fill_config(boost::program_options::variables_map& vm, Config& config)
{
if (vm.count(PRIOR_NAME))
for (auto& pr : vm[PRIOR_NAME].as<std::vector<std::string> >())
config.getPriorTypes().push_back(stringToPriorType(pr));
if (vm.count(FEATURES_NAME))
{
for (auto featString : vm[FEATURES_NAME].as<std::vector<std::string> >())
{
config.getFeatures().push_back(std::vector<std::shared_ptr<MatrixConfig> >());
auto& dimFeatures = config.getFeatures().back();
std::stringstream lineStream(featString);
std::string token;
while (std::getline(lineStream, token, ','))
{
//add ability to skip features for specific dimention
if(token == "none")
continue;
dimFeatures.push_back(matrix_io::read_matrix(token, false));
}
}
}
if (vm.count(TEST_NAME))
config.setTest(generic_io::read_data_config(vm[TEST_NAME].as<std::string>(), true));
if (vm.count(TRAIN_NAME))
config.setTrain(generic_io::read_data_config(vm[TRAIN_NAME].as<std::string>(), true));
if (vm.count(BURNIN_NAME))
config.setBurnin(vm[BURNIN_NAME].as<int>());
if (vm.count(NSAMPLES_NAME))
config.setNSamples(vm[NSAMPLES_NAME].as<int>());
if(vm.count(NUM_LATENT_NAME))
config.setNumLatent(vm[NUM_LATENT_NAME].as<int>());
if(vm.count(RESTORE_PREFIX_NAME))
config.setRestorePrefix(vm[RESTORE_PREFIX_NAME].as<std::string>());
if(vm.count(RESTORE_SUFFIX_NAME))
config.setRestoreSuffix(vm[RESTORE_SUFFIX_NAME].as<std::string>());
if(vm.count(INIT_MODEL_NAME))
config.setModelInitType(stringToModelInitType(vm[INIT_MODEL_NAME].as<std::string>()));
if(vm.count(SAVE_PREFIX_NAME))
config.setSavePrefix(vm[SAVE_PREFIX_NAME].as<std::string>());
if(vm.count(SAVE_SUFFIX_NAME))
config.setSaveSuffix(vm[SAVE_SUFFIX_NAME].as<std::string>());
if(vm.count(SAVE_FREQ_NAME))
config.setSaveFreq(vm[SAVE_FREQ_NAME].as<int>());
if(vm.count(THRESHOLD_NAME))
{
config.setThreshold(vm[THRESHOLD_NAME].as<double>());
config.setClassify(true);
}
if(vm.count(VERBOSE_NAME))
config.setVerbose(vm[VERBOSE_NAME].as<int>());
if(vm.count(QUIET_NAME))
config.setVerbose(0);
if(vm.count(STATUS_NAME))
config.setCsvStatus(vm[STATUS_NAME].as<std::string>());
if(vm.count(SEED_NAME))
{
config.setRandomSeedSet(true);
config.setRandomSeed(vm[SEED_NAME].as<int>());
}
if(vm.count(PRECISION_NAME))
set_noise_model(config, NOISE_NAME_FIXED, vm[PRECISION_NAME].as<std::string>());
if(vm.count(ADAPTIVE_NAME))
set_noise_model(config, NOISE_NAME_ADAPTIVE, vm[ADAPTIVE_NAME].as<std::string>());
if(vm.count(PROBIT_NAME))
set_noise_model(config, NOISE_NAME_PROBIT, vm[PROBIT_NAME].as<std::string>());
if(vm.count(LAMBDA_BETA_NAME))
config.setLambdaBeta(vm[LAMBDA_BETA_NAME].as<double>());
if(vm.count(TOL_NAME))
config.setTol(vm[TOL_NAME].as<double>());
if(vm.count(DIRECT_NAME))
config.setDirect(true);
}
bool parse_options(int argc, char* argv[], Config& config)
{
try
{
boost::program_options::options_description desc = get_desc();
boost::program_options::variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if(vm.count(HELP_NAME))
{
std::cout << desc << std::endl;
return false;
}
if(vm.count(VERSION_NAME))
{
std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl;
return false;
}
fill_config(vm, config);
return true;
}
catch (const boost::program_options::error &ex)
{
std::cerr << "Failed to parse command line arguments: " << std::endl;
std::cerr << ex.what() << std::endl;
return false;
}
catch (std::runtime_error& ex)
{
std::cerr << "Failed to parse command line arguments: " << std::endl;
std::cerr << ex.what() << std::endl;
return false;
}
}
void CmdSession::setFromArgs(int argc, char** argv)
{
Config config;
if(!parse_options(argc, argv, config))
exit(0); //need a way to figure out how to handle help and version
setFromConfig(config);
}
//create cmd session
//parses args with setFromArgs, then internally calls setFromConfig (to validate, save, set config)
std::shared_ptr<ISession> smurff::create_cmd_session(int argc, char** argv)
{
std::shared_ptr<CmdSession> session(new CmdSession());
session->setFromArgs(argc, argv);
return session;
}
<|endoftext|> |
<commit_before>#include "private_window.h"
#include <game/DirectWindow.h>
// We really shouldn't be compiled with an older compiler to begin with...we need epic TCO to work properly...
#if __cplusplus > 199711L
#define ATHENA_OVERRIDE override
#else
#define ATHENA_OVERRIDE
#endif
#include <vector>
#include <algorithm>
class Athena_Window : public BDirectWindow{
/*
typedef struct {
direct_buffer_state buffer_state;
direct_driver_state driver_state;
void* bits;
void* pci_bits;
int32 bytes_per_row;
uint32 bits_per_pixel;
color_space pixel_format;
buffer_layout layout;
buffer_orientation orientation;
uint32 _reserved[9];
uint32 _dd_type_;
uint32 _dd_token_;
uint32 clip_list_count;
clipping_rect window_bounds;
clipping_rect clip_bounds;
clipping_rect clip_list[1];
} direct_buffer_info;
*/
uint8_t *screen;
uint32_t pitch, depth; // both in bytes.
color_space format;
clipping_rect bounds;
std::vector<clipping_rect> clip_list;
bool connected, connection_disabled;
static void ConvertColorSpaces(const uint32_t *in, void *out, size_t num_pixels, color_space c);
public:
Athena_Window(int x, int y, unsigned w, unsigned h, const char *title)
: BDirectWindow(BRect(x, y, x + w, y + h), title, B_TITLED_WINDOW, B_NOT_RESIZABLE|B_QUIT_ON_WINDOW_CLOSE, B_CURRENT_WORKSPACE){
}
~Athena_Window(){
connection_disabled = false;
Hide();
Sync();
}
int DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB);
int DrawRect(int x, int y, unsigned w, unsigned h, const struct Athena_Color *color);
virtual void DirectConnected(direct_buffer_info* info) ATHENA_OVERRIDE;
};
void Athena_Window::ConvertColorSpaces(const uint32_t *in, void *out, size_t num_pixels, color_space c){
switch(c){
case B_RGB32:
case B_RGBA32:
case B_RGB32_BIG:
case B_RGBA32_BIG:
std::copy(in, in + num_pixels, static_cast<uint32_t *>(out));
break;
case B_RGB24:
case B_RGB24_BIG:
for(unsigned i = 0; i<num_pixels; i++){
uint8_t *pixel = static_cast<uint8_t *>(out) + (3 * i);
pixel[0] = in[i] & 0xFF;
pixel[1] = (in[i] >> 8) & 0xFF;
pixel[2] = (in[i] >> 16) & 0xFF;
}
break;
default:
// ...
break;
}
}
void Athena_Window::DirectConnected(direct_buffer_info *info){
switch(info->buffer_state & B_DIRECT_MODE_MASK){
case B_DIRECT_START:
connected = true;
case B_DIRECT_MODIFY:
clip_list.clear();
clip_list.insert(clip_list.end(), info->clip_list, info->clip_list + info->clip_list_count);
screen = reinterpret_cast<uint8_t *>(info->bits);
pitch = info->bytes_per_row;
depth = info->bits_per_pixel >> 3;
format = info->pixel_format;
bounds = info->window_bounds;
case B_DIRECT_STOP:
connected = false;
}
}
void *Athena_Private_CreateHandle();
int Athena_Private_DestroyHandle(void *);
int Athena_Private_CreateWindow(void *handle, int x, int y, unsigned w, unsigned h, const char *title);
int Athena_Private_ShowWindow(void *);
int Athena_Private_HideWindow(void *);
/* Neither the BeBook nor the Haiku docs mention the composition of a clipping_rect :( */
int Athena_Private_DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB){
return static_cast<Athena_Window *>(handle)->DrawImage(x, y, w, h, format, RGB);
}
int Athena_Window::DrawImage(int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB){
/* In terms of RGB */
const int starting_x = std::max(0, -x),
starting_y = std::max(0, -y),
ending_x = std::min<int>(w, static_cast<int>(bounds.right) - x),
ending_y = std::min<int>(h, static_cast<int>(bounds.bottom) - y);
uint8_t *row_start = screen + (starting_y * pitch);
for(int i = starting_y; i < ending_y; i++){
for(int e = starting_x; e < ending_x; e++){
ConvertColorSpaces(static_cast<uint32_t *>(RGB) + e + (i * w), row_start + (x * depth), format);
}
row_start += pitch;
}
}
int Athena_Private_DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const struct Athena_Color *color){
return static_cast<Athena_Window *>(handle)->DrawRect(x, y, w, h, format, color);
}
int Athena_Window::DrawRect(int x, int y, unsigned w, unsigned h, const struct Athena_Color *color){
const int starting_x = std::max(0, -x),
starting_y = std::max(0, -y),
ending_x = std::min<int>(w, static_cast<int>(window->bounds.right) - x),
ending_y = std::min<int>(h, static_cast<int>(window->bounds.bottom) - y);
uint8_t *row_start = screen + (starting_y * pitch);
for(int i = starting_y; i < ending_y; i++){
ConvertColorSpaces(static_cast<uint32_t *>(RGB) + e + (i * w), row_start + (x * depth), ending_x - starting_x, format);
row_start += pitch;
}
}
int Athena_Private_DrawLine(void *that, int x1, int y1, int x2, int y2, const struct Athena_Color *color){
return 0;
}
int Athena_Private_FlipWindow(void *handle){
}
unsigned Athena_Private_GetEvent(void *handle, struct Athena_Event *to);
/* Athena_Common functions are common to all backends, but are private to this library.
* These are intended to be used from the Athena_Private functions.
* No Athena_Common function will call any Athena_Private function, to categorically avoid infinite mutual recursion.
*/
int Athena_Common_Line(void *handle, void *arg, int x1, int y1, int x2, int y2, athena_point_callback callback);
int Athena_Common_ColorToUnsignedByte(const struct Athena_Color *color, unsigned char *red, unsigned char *greeb, unsigned char *blue, unsigned char *alpha);
int Athena_Common_ColorToUnsignedShort(const struct Athena_Color *color, unsigned short *red, unsigned short *greeb, unsigned short *blue, unsigned short *alpha);
int Athena_Private_IsKeyPressed(void *handle, unsigned key);
<commit_msg>Slightly less malformed Haiku window backend<commit_after>#include "private_window.h"
#include <game/DirectWindow.h>
// We really shouldn't be compiled with an older compiler to begin with...we need epic TCO to work properly...
#if __cplusplus > 199711L
#define ATHENA_OVERRIDE override
#else
#define ATHENA_OVERRIDE
#endif
#include <vector>
#include <algorithm>
class Athena_Window : public BDirectWindow{
/*
typedef struct {
direct_buffer_state buffer_state;
direct_driver_state driver_state;
void* bits;
void* pci_bits;
int32 bytes_per_row;
uint32 bits_per_pixel;
color_space pixel_format;
buffer_layout layout;
buffer_orientation orientation;
uint32 _reserved[9];
uint32 _dd_type_;
uint32 _dd_token_;
uint32 clip_list_count;
clipping_rect window_bounds;
clipping_rect clip_bounds;
clipping_rect clip_list[1];
} direct_buffer_info;
*/
uint8_t *screen;
uint32_t pitch, depth; // both in bytes.
color_space format;
clipping_rect bounds;
std::vector<clipping_rect> clip_list;
bool connected, connection_disabled;
static void ConvertColorSpaces(const uint32_t *in, void *out, size_t num_pixels, color_space c);
public:
Athena_Window(int x, int y, unsigned w, unsigned h, const char *title)
: BDirectWindow(BRect(x, y, x + w, y + h), title, B_TITLED_WINDOW, B_NOT_RESIZABLE|B_QUIT_ON_WINDOW_CLOSE, B_CURRENT_WORKSPACE){
}
~Athena_Window(){
connection_disabled = false;
Hide();
Sync();
}
int DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB);
int DrawRect(int x, int y, unsigned w, unsigned h, const struct Athena_Color *color);
virtual void DirectConnected(direct_buffer_info* info) ATHENA_OVERRIDE;
};
void Athena_Window::ConvertColorSpaces(const uint32_t *in, void *out, size_t num_pixels, color_space c){
switch(c){
case B_RGB32:
case B_RGBA32:
case B_RGB32_BIG:
case B_RGBA32_BIG:
std::copy(in, in + num_pixels, static_cast<uint32_t *>(out));
break;
case B_RGB24:
case B_RGB24_BIG:
for(unsigned i = 0; i<num_pixels; i++){
uint8_t *pixel = static_cast<uint8_t *>(out) + (3 * i);
pixel[0] = in[i] & 0xFF;
pixel[1] = (in[i] >> 8) & 0xFF;
pixel[2] = (in[i] >> 16) & 0xFF;
}
break;
default:
// ...
break;
}
}
void Athena_Window::DirectConnected(direct_buffer_info *info){
switch(info->buffer_state & B_DIRECT_MODE_MASK){
case B_DIRECT_START:
connected = true;
case B_DIRECT_MODIFY:
clip_list.clear();
clip_list.insert(clip_list.end(), info->clip_list, info->clip_list + info->clip_list_count);
screen = reinterpret_cast<uint8_t *>(info->bits);
pitch = info->bytes_per_row;
depth = info->bits_per_pixel >> 3;
format = info->pixel_format;
bounds = info->window_bounds;
case B_DIRECT_STOP:
connected = false;
}
}
void *Athena_Private_CreateHandle();
int Athena_Private_DestroyHandle(void *);
int Athena_Private_CreateWindow(void *handle, int x, int y, unsigned w, unsigned h, const char *title);
int Athena_Private_ShowWindow(void *);
int Athena_Private_HideWindow(void *);
/* Neither the BeBook nor the Haiku docs mention the composition of a clipping_rect :( */
int Athena_Private_DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB){
return static_cast<Athena_Window *>(handle)->DrawImage(x, y, w, h, format, RGB);
}
int Athena_Window::DrawImage(int x, int y, unsigned w, unsigned h, unsigned format, const void *RGB){
/* In terms of RGB */
const int starting_x = std::max(0, -x),
starting_y = std::max(0, -y),
ending_x = std::min<int>(w, static_cast<int>(bounds.right) - x),
ending_y = std::min<int>(h, static_cast<int>(bounds.bottom) - y);
uint8_t *row_start = screen + (starting_y * pitch);
for(int i = starting_y; i < ending_y; i++){
ConvertColorSpaces(static_cast<uint32_t *>(RGB) + starting_x + (i * w), row_start + (x * depth), format);
row_start += pitch;
}
return 0;
}
int Athena_Private_DrawImage(void *handle, int x, int y, unsigned w, unsigned h, unsigned format, const struct Athena_Color *color){
return 0;
}
int Athena_Private_DrawLine(void *handle, int x1, int y1, int x2, int y2, const struct Athena_Color *color){
return 0;
}
int Athena_Private_FlipWindow(void *handle){
}
unsigned Athena_Private_GetEvent(void *handle, struct Athena_Event *to);
int Athena_Private_IsKeyPressed(void *handle, unsigned key);
<|endoftext|> |
<commit_before>#include "Expressions.hpp"
#include "RegisterPool.hpp"
#include "ProcessLog.hpp"
#include "StringTable.hpp"
#include "SymbolTable.hpp"
#include <fstream>
extern std::ostream cpslout;
namespace
{
bool isValidPair(MemoryLocation* a, Expr* b)
{
if(!a) return false;
if(!b) return false;
return a->type == b->type;
}
bool isValidPair(Expr* a, Expr* b)
{
if(!a) return false;
if(!b) return false;
return a->type == b->type;
}
Expr* binaryOp(std::string op,Expr*a,Expr*b)
{
if(!isValidPair(a,b))
{
ProcessLog::getInstance()->logError("Type mismatch in expression");
delete(a);
delete(b);
return nullptr;
}
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\t" << op << " "
<< result->reg << ","
<< a->reg << ","
<< b->reg << std::endl;
delete(a);
delete(b);
return result;
}
Expr* binaryOpWithMove(std::string op,std::string source,Expr*a,Expr*b)
{
if(!isValidPair(a,b))
{
ProcessLog::getInstance()->logError("Type mismatch in expression");
delete(a);
delete(b);
return nullptr;
}
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\t" << op << " "
<< a->reg << ","
<< b->reg << std::endl;
cpslout << "\tmf" << source
<< " " << result->reg << std::endl;
delete(a);
delete(b);
return result;
}
Expr* unaryOp(std::string op,Expr*a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
cpslout << "\t" << op << " "
<< a->reg << ","
<< a->reg << std::endl;
return a;
}
}
Expr * emitOr(Expr * a, Expr * b){return binaryOp("or",a,b);}
Expr * emitAnd(Expr * a, Expr * b){return binaryOp("and",a,b);}
Expr * emitEq(Expr * a, Expr * b){return binaryOp("seq",a,b);}
Expr * emitNeq(Expr * a, Expr * b){return emitNot(binaryOp("seq",a,b));}
Expr * emitLte(Expr * a, Expr * b){return emitNot(binaryOp("slt",b,a));}
Expr * emitGte(Expr * a, Expr * b){return emitNot(binaryOp("slt",a,b));}
Expr * emitLt(Expr * a, Expr * b){return binaryOp("slt",a,b);}
Expr * emitGt(Expr * a, Expr * b){return binaryOp("slt",b,a);}
Expr * emitAdd(Expr * a, Expr * b){return binaryOp("add",a,b);}
Expr * emitSub(Expr * a, Expr * b){return binaryOp("sub",a,b);}
Expr * emitMult(Expr * a, Expr * b){return binaryOpWithMove("mult","lo",a,b);}
Expr * emitDiv(Expr * a, Expr * b){return binaryOpWithMove("div","lo",a,b);}
Expr * emitMod(Expr * a, Expr * b){return binaryOpWithMove("div","hi",a,b);}
Expr * emitNot(Expr * a){return binaryOp("xor",a,load(1));}
Expr * emitNeg(Expr * a){return unaryOp("neg",a);}
Expr * chr(Expr * a)
{
if(a->type != SymbolTable::getInstance()->getIntType())
{
ProcessLog::getInstance()->logError("chr() only defined for integer expressions");
}
else
{
a->type = SymbolTable::getInstance()->getCharType();
}
return a;
}
Expr * ord(Expr * a)
{
if(a->type != SymbolTable::getInstance()->getCharType())
{
ProcessLog::getInstance()->logError("chr() only defined for character expressions");
}
else
{
a->type = SymbolTable::getInstance()->getIntType();
}
return a;
}
Expr * pred(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
if(a->type == SymbolTable::getInstance()->getBoolType())
{
return unaryOp("not",a);
}
else if((a->type == SymbolTable::getInstance()->getIntType())||(a->type == SymbolTable::getInstance()->getCharType()))
{
cpslout << "\taddi " << a->reg << ","
<< a->reg << ",1" << std::endl;
return a;
}
else
{
ProcessLog::getInstance()->logError("pred() not defined for this expression");
}
return nullptr;
}
Expr * succ(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
if(a->type == SymbolTable::getInstance()->getBoolType())
{
return unaryOp("not",a);
}
else if((a->type == SymbolTable::getInstance()->getIntType())||(a->type == SymbolTable::getInstance()->getCharType()))
{
cpslout << "\taddi " << a->reg << ","
<< a->reg << ",-1" << std::endl;
return a;
}
else
{
ProcessLog::getInstance()->logError("succ() not defined for this expression");
}
return nullptr;
}
Expr * load(MemoryLocation * a)
{
auto result = new Expr();
if(!a)
{
ProcessLog::getInstance()->logError("Missing memory location");
}
else
{
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\tlw "
<< result->reg << ","
<< a->offset << "(" << a->base << ")" << std::endl;
}
return result;
}
Expr * load(char * a)
{
auto label = StringTable::getInstance()->add(a);
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getStringType();
cpslout << "\tla "<< result->reg << "," << label << std::endl;
return result;
}
Expr * load(char a)
{
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getCharType();
cpslout << "\tli " << result->reg << "," << static_cast<int>(a) << std::endl;
return result;
}
Expr * load(int a)
{
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getIntType();
cpslout << "\tli " << result->reg << "," << a << std::endl;
return result;
}
void store(MemoryLocation * loc, Expr * val)
{
if(!isValidPair(loc,val))
{
ProcessLog::getInstance()->logError("Type mismatch in assignment");
}
else
{
cpslout << "\tsw "
<< val->reg << ", "
<< loc->offset << "(" << loc->base << ")" << std::endl;
}
delete(val);
}
void write(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return;
}
else if(a->type == SymbolTable::getInstance()->getCharType())
{
cpslout << "\tli $v0, 11" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else if(a->type == SymbolTable::getInstance()->getIntType())
{
cpslout << "\tli $v0, 1" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else if(a->type == SymbolTable::getInstance()->getStringType())
{
cpslout << "\tli $v0, 4" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else
{
ProcessLog::getInstance()->logError("write() only defined for basic types");
}
delete(a);
}
void read(MemoryLocation * loc)
{
if(!loc)
{
ProcessLog::getInstance()->logError("Missing expression");
return;
}
else if(loc->type == SymbolTable::getInstance()->getCharType())
{
cpslout << "\tli $v0, 12" << std::endl;
cpslout << "\tsyscall" << std::endl;
cpslout << "\tsw $v0," << loc->offset
<< "(" << loc->base << ")" << std::endl;
}
else if(loc->type == SymbolTable::getInstance()->getIntType())
{
cpslout << "\tli $v0, 5" << std::endl;
cpslout << "\tsyscall" << std::endl;
cpslout << "\tsw $v0," << loc->offset
<< "(" << loc->base << ")" << std::endl;
}
else
{
ProcessLog::getInstance()->logError("read() only defined for basic types");
}
}
void emitLabel(char * a){cpslout << a << ":" << std::endl;}
void emitJump(char * a){cpslout << "j " << a << std::endl;}
void emitLabel(std::string a){cpslout << a << ":" << std::endl;}
void emitJump(std::string a){cpslout << "j " << a << std::endl;}
void emitBtrue(Expr * a, std::string label){cpslout << "bne $zero," << a->reg << "," << label << std::endl;}
void emitBfalse(Expr * a, std::string label){cpslout << "beq $zero," << a->reg << "," << label << std::endl;}
int ifcounter = 0;
std::stack<std::pair<int, int>> ifcurrent;
void emitIfControl(Expr * a)
{
emitBfalse(a, "elseif" + std::to_string(++ifcounter) + "_1");
ifcurrent.push(std::pair<int, int>(ifcounter, 1));
};
void emitElseIfLabel()
{
emitLabel("elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(ifcurrent.top().second));
};
void emitElseIfControl(Expr * a)
{
emitBfalse(a, "elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(++ifcurrent.top().second));
};
void emitElseLabel()
{
emitLabel("elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(ifcurrent.top().second++));
};
void emitFiJump()
{
// Could be removed if we detect an if fallthrough.
emitJump("fi" + std::to_string(ifcurrent.top().first));
};
void emitFiLabel()
{
emitElseLabel();
emitLabel("fi" + std::to_string(ifcurrent.top().first));
ifcurrent.pop();
};
int repeatcounter = 0;
std::stack<int> repeatcurrent;
void emitRepeatLabel(){emitLabel("repeat" + std::to_string(++repeatcounter)); repeatcurrent.push(repeatcounter);}
void emitRepeatControl(Expr * a){emitBfalse(a, "repeat" + std::to_string(repeatcurrent.top())); repeatcurrent.pop();}
int whilecounter = 0;
std::stack<int> whilecurrent;
void emitWhileTopLabel(){emitLabel("whiletop" + std::to_string(++whilecounter)); whilecurrent.push(whilecounter);};
void emitWhileControl(Expr * a){emitBfalse(a, "whilebottom" + std::to_string(whilecurrent.top()));};
void emitWhileJump(){emitJump("whiletop" + std::to_string(whilecurrent.top()));};
void emitWhileBottomLabel(){emitLabel("whilebottom" + std::to_string(whilecurrent.top())); whilecurrent.pop();};
// forstartshere
std::shared_ptr<ForLoop> ForLoop::get_instance()
{
return forcurrent.top();
};
void ForLoop::init()
{ forcurrent.push(std::shared_ptr<ForLoop>(new ForLoop())); };
void ForLoop::deinit()
{ forcurrent.pop(); };
void ForLoop::emit_init(Expr* a)
{
store(SymbolTable::getInstance()->lookupVariable(id).get(), a);
};
void ForLoop::emit_top_label()
{
emitLabel("for_" + std::to_string(fornum) + "_top");
};
void ForLoop::emit_control(Expr* a)
{
emitBfalse(dir ?
emitGte(load(SymbolTable::getInstance()->lookupVariable(id).get()), a) :
emitLte(load(SymbolTable::getInstance()->lookupVariable(id).get()), a),
"for_" + std::to_string(fornum) + "_bottom");
};
void ForLoop::emit_rement()
{
Expr * a = load(SymbolTable::getInstance()->lookupVariable(id).get());
cpslout << "addi " << a->reg << "," << a->reg << "," << (dir ? "1" : "-1") << std::endl;
};
void ForLoop::emit_jump()
{
emitJump("for_" + std::to_string(fornum) + "_top");
};
void ForLoop::emit_bottom_label()
{
emitLabel("for_" + std::to_string(fornum) + "_bottom");
};
//void ForLoop::emit_deinit();
//This definition intentionally left blank.
int ForLoop::forcounter = 0;
std::stack<std::shared_ptr<ForLoop>> ForLoop::forcurrent = std::stack<std::shared_ptr<ForLoop>>();
ForLoop::ForLoop()
: fornum(forcounter++), id(""), dir(-1)
{};
<commit_msg>I am almost certain that for loops, nested or otherwise are completely functional, they seem to have passed the control_statements.cpsl test.<commit_after>#include "Expressions.hpp"
#include "RegisterPool.hpp"
#include "ProcessLog.hpp"
#include "StringTable.hpp"
#include "SymbolTable.hpp"
#include <fstream>
extern std::ostream cpslout;
namespace
{
bool isValidPair(MemoryLocation* a, Expr* b)
{
if(!a) return false;
if(!b) return false;
return a->type == b->type;
}
bool isValidPair(Expr* a, Expr* b)
{
if(!a) return false;
if(!b) return false;
return a->type == b->type;
}
Expr* binaryOp(std::string op,Expr*a,Expr*b)
{
if(!isValidPair(a,b))
{
ProcessLog::getInstance()->logError("Type mismatch in expression");
delete(a);
delete(b);
return nullptr;
}
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\t" << op << " "
<< result->reg << ","
<< a->reg << ","
<< b->reg << std::endl;
delete(a);
delete(b);
return result;
}
Expr* binaryOpWithMove(std::string op,std::string source,Expr*a,Expr*b)
{
if(!isValidPair(a,b))
{
ProcessLog::getInstance()->logError("Type mismatch in expression");
delete(a);
delete(b);
return nullptr;
}
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\t" << op << " "
<< a->reg << ","
<< b->reg << std::endl;
cpslout << "\tmf" << source
<< " " << result->reg << std::endl;
delete(a);
delete(b);
return result;
}
Expr* unaryOp(std::string op,Expr*a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
cpslout << "\t" << op << " "
<< a->reg << ","
<< a->reg << std::endl;
return a;
}
}
Expr * emitOr(Expr * a, Expr * b){return binaryOp("or",a,b);}
Expr * emitAnd(Expr * a, Expr * b){return binaryOp("and",a,b);}
Expr * emitEq(Expr * a, Expr * b){return binaryOp("seq",a,b);}
Expr * emitNeq(Expr * a, Expr * b){return emitNot(binaryOp("seq",a,b));}
Expr * emitLte(Expr * a, Expr * b){return emitNot(binaryOp("slt",b,a));}
Expr * emitGte(Expr * a, Expr * b){return emitNot(binaryOp("slt",a,b));}
Expr * emitLt(Expr * a, Expr * b){return binaryOp("slt",a,b);}
Expr * emitGt(Expr * a, Expr * b){return binaryOp("slt",b,a);}
Expr * emitAdd(Expr * a, Expr * b){return binaryOp("add",a,b);}
Expr * emitSub(Expr * a, Expr * b){return binaryOp("sub",a,b);}
Expr * emitMult(Expr * a, Expr * b){return binaryOpWithMove("mult","lo",a,b);}
Expr * emitDiv(Expr * a, Expr * b){return binaryOpWithMove("div","lo",a,b);}
Expr * emitMod(Expr * a, Expr * b){return binaryOpWithMove("div","hi",a,b);}
Expr * emitNot(Expr * a){return binaryOp("xor",a,load(1));}
Expr * emitNeg(Expr * a){return unaryOp("neg",a);}
Expr * chr(Expr * a)
{
if(a->type != SymbolTable::getInstance()->getIntType())
{
ProcessLog::getInstance()->logError("chr() only defined for integer expressions");
}
else
{
a->type = SymbolTable::getInstance()->getCharType();
}
return a;
}
Expr * ord(Expr * a)
{
if(a->type != SymbolTable::getInstance()->getCharType())
{
ProcessLog::getInstance()->logError("chr() only defined for character expressions");
}
else
{
a->type = SymbolTable::getInstance()->getIntType();
}
return a;
}
Expr * pred(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
if(a->type == SymbolTable::getInstance()->getBoolType())
{
return unaryOp("not",a);
}
else if((a->type == SymbolTable::getInstance()->getIntType())||(a->type == SymbolTable::getInstance()->getCharType()))
{
cpslout << "\taddi " << a->reg << ","
<< a->reg << ",1" << std::endl;
return a;
}
else
{
ProcessLog::getInstance()->logError("pred() not defined for this expression");
}
return nullptr;
}
Expr * succ(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return nullptr;
}
if(a->type == SymbolTable::getInstance()->getBoolType())
{
return unaryOp("not",a);
}
else if((a->type == SymbolTable::getInstance()->getIntType())||(a->type == SymbolTable::getInstance()->getCharType()))
{
cpslout << "\taddi " << a->reg << ","
<< a->reg << ",-1" << std::endl;
return a;
}
else
{
ProcessLog::getInstance()->logError("succ() not defined for this expression");
}
return nullptr;
}
Expr * load(MemoryLocation * a)
{
auto result = new Expr();
if(!a)
{
ProcessLog::getInstance()->logError("Missing memory location");
}
else
{
result->reg = RegisterPool::getInstance()->allocate();
result->type = a->type;
cpslout << "\tlw "
<< result->reg << ","
<< a->offset << "(" << a->base << ")" << std::endl;
}
return result;
}
Expr * load(char * a)
{
auto label = StringTable::getInstance()->add(a);
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getStringType();
cpslout << "\tla "<< result->reg << "," << label << std::endl;
return result;
}
Expr * load(char a)
{
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getCharType();
cpslout << "\tli " << result->reg << "," << static_cast<int>(a) << std::endl;
return result;
}
Expr * load(int a)
{
auto result = new Expr();
result->reg = RegisterPool::getInstance()->allocate();
result->type = SymbolTable::getInstance()->getIntType();
cpslout << "\tli " << result->reg << "," << a << std::endl;
return result;
}
void store(MemoryLocation * loc, Expr * val)
{
if(!isValidPair(loc,val))
{
ProcessLog::getInstance()->logError("Type mismatch in assignment");
}
else
{
cpslout << "\tsw "
<< val->reg << ", "
<< loc->offset << "(" << loc->base << ")" << std::endl;
}
delete(val);
}
void write(Expr * a)
{
if(!a)
{
ProcessLog::getInstance()->logError("Missing expression");
return;
}
else if(a->type == SymbolTable::getInstance()->getCharType())
{
cpslout << "\tli $v0, 11" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else if(a->type == SymbolTable::getInstance()->getIntType())
{
cpslout << "\tli $v0, 1" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else if(a->type == SymbolTable::getInstance()->getStringType())
{
cpslout << "\tli $v0, 4" << std::endl;
cpslout << "\tori $a0," << a->reg << ",0" << std::endl;
cpslout << "\tsyscall" << std::endl;
}
else
{
ProcessLog::getInstance()->logError("write() only defined for basic types");
}
delete(a);
}
void read(MemoryLocation * loc)
{
if(!loc)
{
ProcessLog::getInstance()->logError("Missing expression");
return;
}
else if(loc->type == SymbolTable::getInstance()->getCharType())
{
cpslout << "\tli $v0, 12" << std::endl;
cpslout << "\tsyscall" << std::endl;
cpslout << "\tsw $v0," << loc->offset
<< "(" << loc->base << ")" << std::endl;
}
else if(loc->type == SymbolTable::getInstance()->getIntType())
{
cpslout << "\tli $v0, 5" << std::endl;
cpslout << "\tsyscall" << std::endl;
cpslout << "\tsw $v0," << loc->offset
<< "(" << loc->base << ")" << std::endl;
}
else
{
ProcessLog::getInstance()->logError("read() only defined for basic types");
}
}
void emitLabel(char * a){cpslout << "\t" << a << ":" << std::endl;}
void emitJump(char * a){cpslout << "\t" << "j " << a << std::endl;}
void emitLabel(std::string a){cpslout << a << ":" << std::endl;}
void emitJump(std::string a){cpslout << "\t" << "j " << a << std::endl;}
void emitBtrue(Expr * a, std::string label){cpslout << "\t" << "bne $zero," << a->reg << "," << label << std::endl;}
void emitBfalse(Expr * a, std::string label){cpslout << "\t" << "beq $zero," << a->reg << "," << label << std::endl;}
int ifcounter = 0;
std::stack<std::pair<int, int>> ifcurrent;
void emitIfControl(Expr * a)
{
emitBfalse(a, "elseif" + std::to_string(++ifcounter) + "_1");
ifcurrent.push(std::pair<int, int>(ifcounter, 1));
};
void emitElseIfLabel()
{
emitLabel("elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(ifcurrent.top().second));
};
void emitElseIfControl(Expr * a)
{
emitBfalse(a, "elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(++ifcurrent.top().second));
};
void emitElseLabel()
{
emitLabel("elseif" + std::to_string(ifcurrent.top().first) + "_" + std::to_string(ifcurrent.top().second++));
};
void emitFiJump()
{
// Could be removed if we detect an if fallthrough.
emitJump("fi" + std::to_string(ifcurrent.top().first));
};
void emitFiLabel()
{
emitElseLabel();
emitLabel("fi" + std::to_string(ifcurrent.top().first));
ifcurrent.pop();
};
int repeatcounter = 0;
std::stack<int> repeatcurrent;
void emitRepeatLabel(){emitLabel("repeat" + std::to_string(++repeatcounter)); repeatcurrent.push(repeatcounter);}
void emitRepeatControl(Expr * a){emitBfalse(a, "repeat" + std::to_string(repeatcurrent.top())); repeatcurrent.pop();}
int whilecounter = 0;
std::stack<int> whilecurrent;
void emitWhileTopLabel(){emitLabel("whiletop" + std::to_string(++whilecounter)); whilecurrent.push(whilecounter);};
void emitWhileControl(Expr * a){emitBfalse(a, "whilebottom" + std::to_string(whilecurrent.top()));};
void emitWhileJump(){emitJump("whiletop" + std::to_string(whilecurrent.top()));};
void emitWhileBottomLabel(){emitLabel("whilebottom" + std::to_string(whilecurrent.top())); whilecurrent.pop();};
// forstartshere
std::shared_ptr<ForLoop> ForLoop::get_instance()
{
return forcurrent.top();
};
void ForLoop::init()
{ forcurrent.push(std::shared_ptr<ForLoop>(new ForLoop())); };
void ForLoop::deinit()
{ forcurrent.pop(); };
void ForLoop::emit_init(Expr* a)
{
store(SymbolTable::getInstance()->lookupVariable(id).get(), a);
};
void ForLoop::emit_top_label()
{
emitLabel("for_" + std::to_string(fornum) + "_top");
};
void ForLoop::emit_control(Expr* a)
{
emitBtrue(dir ?
binaryOp("slt", load(SymbolTable::getInstance()->lookupVariable(id).get()), a) :
binaryOp("slt", a, load(SymbolTable::getInstance()->lookupVariable(id).get())),
"for_" + std::to_string(fornum) + "_bottom");
};
void ForLoop::emit_rement()
{
Expr * a = load(SymbolTable::getInstance()->lookupVariable(id).get());
cpslout << "\t" << "addi " << a->reg << "," << a->reg << "," << (dir ? "-1" : "1") << std::endl;
store(SymbolTable::getInstance()->lookupVariable(id).get(), a);
};
void ForLoop::emit_jump()
{
emitJump("for_" + std::to_string(fornum) + "_top");
};
void ForLoop::emit_bottom_label()
{
emitLabel("for_" + std::to_string(fornum) + "_bottom");
};
//void ForLoop::emit_deinit();
//This definition intentionally left blank.
int ForLoop::forcounter = 0;
std::stack<std::shared_ptr<ForLoop>> ForLoop::forcurrent = std::stack<std::shared_ptr<ForLoop>>();
ForLoop::ForLoop()
: fornum(forcounter++), id(""), dir(-1)
{};
<|endoftext|> |
<commit_before>#include "util.h"
#include <mysql++.h>
#include <iostream>
using namespace std;
int
main(int argc, char *argv[])
{
try {
mysqlpp::Connection con(mysqlpp::use_exceptions);
if (!connect_sample_db(argc, argv, con, "")) {
return 1;
}
bool created = false;
try {
con.select_db(kpcSampleDatabase);
}
catch (mysqlpp::BadQuery &) {
// Couldn't switch to the sample database, so assume that it
// doesn't exist and create it. If that doesn't work, exit
// with an error.
if (con.create_db(kpcSampleDatabase)) {
cerr << "Failed to create sample database." << endl;
return 1;
}
else if (!con.select_db(kpcSampleDatabase)) {
cerr << "Failed to select sample database." << endl;
return 1;
}
else {
created = true;
}
}
mysqlpp::Query query = con.query(); // create a new query object
try {
query.execute("drop table stock");
}
catch (mysqlpp::BadQuery&) {
// ignore any errors
}
// Send the query to create the table and execute it.
query << "create table stock (item char(20) not null, num bigint,"
<< "weight double, price double, sdate date)";
query.execute();
// Set up the template query to insert the data. The parse
// call tells the query object that this is a template and
// not a literal query string.
query << "insert into %5:table values (%0q, %1q, %2, %3, %4q)";
query.parse();
// This is setting the parameter named table to stock.
query.def["table"] = "stock";
// The last parameter "table" is not specified here. Thus
// the default value for "table" is used, which is "stock".
query.execute("Hamburger Buns", 56, 1.25, 1.1, "1998-04-26");
query.execute("Hotdog Buns", 65, 1.1, 1.1, "1998-04-23");
query.execute("Dinner Rolls", 75, .95, .97, "1998-05-25");
query.execute("White Bread", 87, 1.5, 1.75, "1998-09-04");
if (created) {
cout << "Created";
}
else {
cout << "Reinitialized";
}
cout << " sample database successfully." << endl;
}
catch (mysqlpp::BadQuery& er) {
// Handle any connection or query errors that may come up
#ifdef USE_STANDARD_EXCEPTION
cerr << "Error: " << er.what() << endl;
#else
cerr << "Error: " << er.error << endl;
#endif
return -1;
}
catch (mysqlpp::BadConversion& er) {
// Handle bad conversions
#ifdef USE_STANDARD_EXCEPTION
cerr << "Error: " << er.what() << "\"." << endl
<< "retrieved data size: " << er.retrieved
<< " actual data size: " << er.actual_size << endl;
#else
cerr << "Error: Tried to convert \"" << er.data << "\" to a \""
<< er.type_name << "\"." << endl;
#endif
return -1;
}
#ifdef USE_STANDARD_EXCEPTION
catch (exception& er) {
cerr << "Error: " << er.what() << endl;
return -1;
}
#endif
}
<commit_msg>Replaced intentional bad grammar, and added a comment so I don't take it out again. (It's fixed by custom3)<commit_after>#include "util.h"
#include <mysql++.h>
#include <iostream>
using namespace std;
int
main(int argc, char *argv[])
{
try {
mysqlpp::Connection con(mysqlpp::use_exceptions);
if (!connect_sample_db(argc, argv, con, "")) {
return 1;
}
bool created = false;
try {
con.select_db(kpcSampleDatabase);
}
catch (mysqlpp::BadQuery &) {
// Couldn't switch to the sample database, so assume that it
// doesn't exist and create it. If that doesn't work, exit
// with an error.
if (con.create_db(kpcSampleDatabase)) {
cerr << "Failed to create sample database." << endl;
return 1;
}
else if (!con.select_db(kpcSampleDatabase)) {
cerr << "Failed to select sample database." << endl;
return 1;
}
else {
created = true;
}
}
mysqlpp::Query query = con.query(); // create a new query object
try {
query.execute("drop table stock");
}
catch (mysqlpp::BadQuery&) {
// ignore any errors
}
// Send the query to create the table and execute it.
query << "create table stock (item char(20) not null, num bigint,"
<< "weight double, price double, sdate date)";
query.execute();
// Set up the template query to insert the data. The parse
// call tells the query object that this is a template and
// not a literal query string.
query << "insert into %5:table values (%0q, %1q, %2, %3, %4q)";
query.parse();
// This is setting the parameter named table to stock.
query.def["table"] = "stock";
// The last parameter "table" is not specified here. Thus the
// default value for "table" is used, which is "stock". Also,
// the bad grammar in the second row is intentional -- it is
// fixed by the custom3 example.
query.execute("Hamburger Buns", 56, 1.25, 1.1, "1998-04-26");
query.execute("Hotdogs' Buns", 65, 1.1, 1.1, "1998-04-23");
query.execute("Dinner Rolls", 75, .95, .97, "1998-05-25");
query.execute("White Bread", 87, 1.5, 1.75, "1998-09-04");
if (created) {
cout << "Created";
}
else {
cout << "Reinitialized";
}
cout << " sample database successfully." << endl;
}
catch (mysqlpp::BadQuery& er) {
// Handle any connection or query errors that may come up
#ifdef USE_STANDARD_EXCEPTION
cerr << "Error: " << er.what() << endl;
#else
cerr << "Error: " << er.error << endl;
#endif
return -1;
}
catch (mysqlpp::BadConversion& er) {
// Handle bad conversions
#ifdef USE_STANDARD_EXCEPTION
cerr << "Error: " << er.what() << "\"." << endl
<< "retrieved data size: " << er.retrieved
<< " actual data size: " << er.actual_size << endl;
#else
cerr << "Error: Tried to convert \"" << er.data << "\" to a \""
<< er.type_name << "\"." << endl;
#endif
return -1;
}
#ifdef USE_STANDARD_EXCEPTION
catch (exception& er) {
cerr << "Error: " << er.what() << endl;
return -1;
}
#endif
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016,
Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
All rights reserved. See COPYING.txt for more details.
*/
#include "FrameBuffer.h"
#include "boost/format.hpp"
using namespace aton;
const std::string chStr::RGBA = "RGBA",
chStr::rgb = "rgb",
chStr::depth = "depth",
chStr::Z = "Z",
chStr::N = "N",
chStr::P = "P",
chStr::_red = ".red",
chStr::_green = ".green",
chStr::_blue = ".blue",
chStr::_X = ".X",
chStr::_Y = ".Y",
chStr::_Z = ".Z";
// Lightweight color pixel class
RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; }
float& RenderColor::operator[](int i) { return _val[i]; }
const float& RenderColor::operator[](int i) const { return _val[i]; }
void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; }
// RenderBuffer class
RenderBuffer::RenderBuffer(const unsigned int& width,
const unsigned int& height,
const int& spp)
{
int size = width * height;
switch (spp)
{
case 1: // Float channels
_float_data.resize(size);
break;
case 3: // Color Channels
_color_data.resize(size);
break;
case 4: // Color + Alpha channels
_color_data.resize(size);
_float_data.resize(size);
break;
}
}
// FrameBuffer class
FrameBuffer::FrameBuffer(const double& currentFrame,
const int& w,
const int& h): _frame(currentFrame),
_width(w),
_height(h),
_progress(0),
_time(0),
_ram(0),
_pram(0),
_ready(false) {}
// Add new buffer
void FrameBuffer::addBuffer(const char* aov,
const int& spp)
{
RenderBuffer buffer(_width, _height, spp);
_buffers.push_back(buffer);
_aovs.push_back(aov);
}
// Get writable buffer object
void FrameBuffer::setBufferPix(const int& b,
const unsigned int& x,
const unsigned int& y,
const int& spp,
const int& c,
const float& pix)
{
RenderBuffer& rb = _buffers[b];
unsigned int index = (_width * y) + x;
if (c < 3 && spp != 1)
rb._color_data[index][c] = pix;
else
rb._float_data[index] = pix;
}
// Get read only buffer object
const float& FrameBuffer::getBufferPix(const int& b,
const unsigned int& x,
const unsigned int& y,
const int& c) const
{
const RenderBuffer& rb = _buffers[b];
unsigned int index = (_width * y) + x;
if (c < 3 && !rb._color_data.empty())
return rb._color_data[index][c];
else
return rb._float_data[index];
}
// Get the current buffer index
int FrameBuffer::getBufferIndex(const Channel& z)
{
int b_index = 0;
if (_aovs.size() > 1)
{
using namespace chStr;
std::string layer = getLayerName(z);
std::vector<std::string>::iterator it;
for(it = _aovs.begin(); it != _aovs.end(); ++it)
{
if (*it == layer)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
else if (*it == Z && layer == depth)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
}
}
return b_index;
}
// Get the current buffer index
int FrameBuffer::getBufferIndex(const char* aovName)
{
int b_index = 0;
if (_aovs.size() > 1)
{
std::vector<std::string>::iterator it;
for(it = _aovs.begin(); it != _aovs.end(); ++it)
{
if (*it == aovName)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
}
}
return b_index;
}
// Get N buffer/aov name name
const char* FrameBuffer::getBufferName(const int& index)
{
const char* aovName = "";
if(!_aovs.empty())
try
{
aovName = _aovs.at(index).c_str();
}
catch (const std::out_of_range& e) {}
catch (...)
{
std::cerr << "Unexpected error at getting buffer name" << std::endl;
}
return aovName;
}
// Get last buffer/aov name
bool FrameBuffer::isFirstBufferName(const char* aovName)
{
return strcmp(_aovs.front().c_str(), aovName) == 0;;
}
// Check if Frame has been changed
bool FrameBuffer::isFrameChanged(const double& frame)
{
return frame != _frame;
}
// Check if Aovs has been changed
bool FrameBuffer::isAovsChanged(const std::vector<std::string>& aovs)
{
return (aovs != _aovs);
}
// Check if Resolution has been changed
bool FrameBuffer::isResolutionChanged(const unsigned int& w,
const unsigned int& h)
{
return (w != _width && h != _height);
}
// Resize the containers to match the resolution
void FrameBuffer::setResolution(const unsigned int& w,
const unsigned int& h)
{
_width = w;
_height = h;
int bfSize = _width * _height;
std::vector<RenderBuffer>::iterator iRB;
for(iRB = _buffers.begin(); iRB != _buffers.end(); ++iRB)
{
if (!iRB->_color_data.empty())
{
std::vector<RenderColor>::iterator iRC;
for(iRC = iRB->_color_data.begin(); iRC != iRB->_color_data.end(); ++iRC)
iRC->reset();
iRB->_color_data.resize(bfSize);
}
if (!iRB->_float_data.empty())
{
std::fill(iRB->_float_data.begin(), iRB->_float_data.end(), 0.0f);
iRB->_float_data.resize(bfSize);
}
}
}
// Clear buffers and aovs
void FrameBuffer::clearAll()
{
_buffers = std::vector<RenderBuffer>();
_aovs = std::vector<std::string>();
}
// Check if the given buffer/aov name name is exist
bool FrameBuffer::isBufferExist(const char* aovName)
{
return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end();
}
// Get width of the buffer
const int& FrameBuffer::getWidth() { return _width; }
// Get height of the buffer
const int& FrameBuffer::getHeight() { return _height; }
// Get size of the buffers aka AOVs count
size_t FrameBuffer::size() { return _aovs.size(); }
// Resize the buffers
void FrameBuffer::resize(const size_t& s)
{
_buffers.resize(s);
_aovs.resize(s);
}
// Set status parameters
void FrameBuffer::setProgress(const long long& progress)
{
_progress = progress > 100 ? 100 : progress;
}
void FrameBuffer::setRAM(const long long& ram)
{
int ramGb = static_cast<int>(ram / 1048576);
_ram = ramGb;
_pram = ramGb > _pram ? ramGb : _pram;
}
void FrameBuffer::setTime(const int& time,
const int& dtime)
{
_time = dtime > time ? time : time - dtime;
}
// Get status parameters
const long long& FrameBuffer::getProgress() { return _progress; }
const long long& FrameBuffer::getRAM() { return _ram; }
const long long& FrameBuffer::getPRAM() { return _pram; }
const int& FrameBuffer::getTime() { return _time; }
// Set Arnold core version
void FrameBuffer::setArnoldVersion(const int& version)
{
// Construct a string from the version number passed
int archV = (version % 10000000) / 1000000;
int majorV = (version % 1000000) / 10000;
int minorV = (version % 10000) / 100;
int fixV = version % 100;
std::stringstream stream;
stream << archV << "." << majorV << "." << minorV << "." << fixV;
_version = stream.str();
}
// Get Arnold core version
const char* FrameBuffer::getArnoldVersion() { return _version.c_str(); }
// Set the frame number of this framebuffer
void FrameBuffer::setFrame(const double& frame) { _frame = frame; }
// Get the frame number of this framebuffer
const double& FrameBuffer::getFrame() { return _frame; }
// Check if this framebuffer is empty
bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; }
// To keep False while writing the buffer
void FrameBuffer::ready(const bool& ready) { _ready = ready; }
const bool& FrameBuffer::isReady() { return _ready; }
<commit_msg>Code cleanup<commit_after>/*
Copyright (c) 2016,
Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
All rights reserved. See COPYING.txt for more details.
*/
#include "FrameBuffer.h"
#include "boost/format.hpp"
using namespace aton;
const std::string chStr::RGBA = "RGBA",
chStr::rgb = "rgb",
chStr::depth = "depth",
chStr::Z = "Z",
chStr::N = "N",
chStr::P = "P",
chStr::_red = ".red",
chStr::_green = ".green",
chStr::_blue = ".blue",
chStr::_X = ".X",
chStr::_Y = ".Y",
chStr::_Z = ".Z";
// Lightweight color pixel class
RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; }
float& RenderColor::operator[](int i) { return _val[i]; }
const float& RenderColor::operator[](int i) const { return _val[i]; }
void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; }
// RenderBuffer class
RenderBuffer::RenderBuffer(const unsigned int& width,
const unsigned int& height,
const int& spp)
{
int size = width * height;
switch (spp)
{
case 1: // Float channels
_float_data.resize(size);
break;
case 3: // Color Channels
_color_data.resize(size);
break;
case 4: // Color + Alpha channels
_color_data.resize(size);
_float_data.resize(size);
break;
}
}
// FrameBuffer class
FrameBuffer::FrameBuffer(const double& currentFrame,
const int& w,
const int& h): _frame(currentFrame),
_width(w),
_height(h),
_progress(0),
_time(0),
_ram(0),
_pram(0),
_ready(false) {}
// Add new buffer
void FrameBuffer::addBuffer(const char* aov,
const int& spp)
{
RenderBuffer buffer(_width, _height, spp);
_buffers.push_back(buffer);
_aovs.push_back(aov);
}
// Get writable buffer object
void FrameBuffer::setBufferPix(const int& b,
const unsigned int& x,
const unsigned int& y,
const int& spp,
const int& c,
const float& pix)
{
RenderBuffer& rb = _buffers[b];
unsigned int index = (_width * y) + x;
if (c < 3 && spp != 1)
rb._color_data[index][c] = pix;
else
rb._float_data[index] = pix;
}
// Get read only buffer object
const float& FrameBuffer::getBufferPix(const int& b,
const unsigned int& x,
const unsigned int& y,
const int& c) const
{
const RenderBuffer& rb = _buffers[b];
unsigned int index = (_width * y) + x;
if (c < 3 && !rb._color_data.empty())
return rb._color_data[index][c];
else
return rb._float_data[index];
}
// Get the current buffer index
int FrameBuffer::getBufferIndex(const Channel& z)
{
int b_index = 0;
if (_aovs.size() > 1)
{
using namespace chStr;
std::string layer = getLayerName(z);
std::vector<std::string>::iterator it;
for(it = _aovs.begin(); it != _aovs.end(); ++it)
{
if (*it == layer)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
else if (*it == Z && layer == depth)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
}
}
return b_index;
}
// Get the current buffer index
int FrameBuffer::getBufferIndex(const char* aovName)
{
int b_index = 0;
if (_aovs.size() > 1)
{
std::vector<std::string>::iterator it;
for(it = _aovs.begin(); it != _aovs.end(); ++it)
{
if (*it == aovName)
{
b_index = static_cast<int>(it - _aovs.begin());
break;
}
}
}
return b_index;
}
// Get N buffer/aov name name
const char* FrameBuffer::getBufferName(const int& index)
{
const char* aovName = "";
if(!_aovs.empty())
try
{
aovName = _aovs.at(index).c_str();
}
catch (const std::out_of_range& e) {}
catch (...)
{
std::cerr << "Unexpected error at getting buffer name" << std::endl;
}
return aovName;
}
// Get last buffer/aov name
bool FrameBuffer::isFirstBufferName(const char* aovName)
{
return strcmp(_aovs.front().c_str(), aovName) == 0;;
}
// Check if Frame has been changed
bool FrameBuffer::isFrameChanged(const double& frame)
{
return frame != _frame;
}
// Check if Aovs has been changed
bool FrameBuffer::isAovsChanged(const std::vector<std::string>& aovs)
{
return (aovs != _aovs);
}
// Check if Resolution has been changed
bool FrameBuffer::isResolutionChanged(const unsigned int& w,
const unsigned int& h)
{
return (w != _width && h != _height);
}
// Resize the containers to match the resolution
void FrameBuffer::setResolution(const unsigned int& w,
const unsigned int& h)
{
_width = w;
_height = h;
int bfSize = _width * _height;
std::vector<RenderBuffer>::iterator iRB;
for(iRB = _buffers.begin(); iRB != _buffers.end(); ++iRB)
{
if (!iRB->_color_data.empty())
{
RenderColor color;
std::fill(iRB->_color_data.begin(), iRB->_color_data.end(), color);
iRB->_color_data.resize(bfSize);
}
if (!iRB->_float_data.empty())
{
std::fill(iRB->_float_data.begin(), iRB->_float_data.end(), 0.0f);
iRB->_float_data.resize(bfSize);
}
}
}
// Clear buffers and aovs
void FrameBuffer::clearAll()
{
_buffers = std::vector<RenderBuffer>();
_aovs = std::vector<std::string>();
}
// Check if the given buffer/aov name name is exist
bool FrameBuffer::isBufferExist(const char* aovName)
{
return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end();
}
// Get width of the buffer
const int& FrameBuffer::getWidth() { return _width; }
// Get height of the buffer
const int& FrameBuffer::getHeight() { return _height; }
// Get size of the buffers aka AOVs count
size_t FrameBuffer::size() { return _aovs.size(); }
// Resize the buffers
void FrameBuffer::resize(const size_t& s)
{
_buffers.resize(s);
_aovs.resize(s);
}
// Set status parameters
void FrameBuffer::setProgress(const long long& progress)
{
_progress = progress > 100 ? 100 : progress;
}
void FrameBuffer::setRAM(const long long& ram)
{
int ramGb = static_cast<int>(ram / 1048576);
_ram = ramGb;
_pram = ramGb > _pram ? ramGb : _pram;
}
void FrameBuffer::setTime(const int& time,
const int& dtime)
{
_time = dtime > time ? time : time - dtime;
}
// Get status parameters
const long long& FrameBuffer::getProgress() { return _progress; }
const long long& FrameBuffer::getRAM() { return _ram; }
const long long& FrameBuffer::getPRAM() { return _pram; }
const int& FrameBuffer::getTime() { return _time; }
// Set Arnold core version
void FrameBuffer::setArnoldVersion(const int& version)
{
// Construct a string from the version number passed
int archV = (version % 10000000) / 1000000;
int majorV = (version % 1000000) / 10000;
int minorV = (version % 10000) / 100;
int fixV = version % 100;
std::stringstream stream;
stream << archV << "." << majorV << "." << minorV << "." << fixV;
_version = stream.str();
}
// Get Arnold core version
const char* FrameBuffer::getArnoldVersion() { return _version.c_str(); }
// Set the frame number of this framebuffer
void FrameBuffer::setFrame(const double& frame) { _frame = frame; }
// Get the frame number of this framebuffer
const double& FrameBuffer::getFrame() { return _frame; }
// Check if this framebuffer is empty
bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; }
// To keep False while writing the buffer
void FrameBuffer::ready(const bool& ready) { _ready = ready; }
const bool& FrameBuffer::isReady() { return _ready; }
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
using namespace std;
class Calculator
{
public:
Calculator(string strr)
{
str = strr;
counter = 0;
}
double result()
{
double res = calculate();
if (counter != str.length())
throw "Invalid expression";
return res;
}
private:
string str;
int counter;
double get_number_without_sign()
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
return res;
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
if (counter < str.length() && str[counter] == 'e') //если e
{
counter++;
return 2.7;
}
else
if (counter < str.length() && str[counter] == 'P') //если Pi
{
counter++;
if (counter < str.length() && str[counter] == 'i')
{
counter++;
return 3.14;
}
}
else //если число
{
while (counter < str.length() && str[counter] <= '9' && str[counter] >= '0')
{
res = res * 10 + (str[counter] - '0');
counter++;
}
return res;
}
return 1;
}
double get_number()
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
return res;
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
if (str[counter] == '-')
{
counter++;
return get_number_without_sign() * (-1);
}
else
return get_number_without_sign();
return 1;
}
double get_term() //слагаемое
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
res = get_number();
while (counter < str.length() && (str[counter] == '*' || str[counter] == '/'))
{
if (str[counter] == '*')
{
counter++;
res *= get_number();
}
if (str[counter] == '/')
{
counter++;
int n = get_number();
if (n)
res /= n;
else
throw "Invalid operation";
}
}
return res;
}
double calculate()
{
double res = get_term();
while (counter < str.length() && (str[counter] == '+' || str[counter] == '-'))
{
if (str[counter] == '+')
{
counter++;
res += get_term();
}
if (str[counter] == '-')
{
counter++;
res -= get_term();
}
}
return res;
}
};
void delete_spaces(string& str)
{
for (int i = 0; i < str.length(); i++)
if (str[i] == ' ')
{
str = str.erase(i, 1);
i--;
}
if (str.length() == 0)
throw "Empty expression";
}
int main(int argc, const char * argv[])
{
try
{
string str = argv[1];
if (argc < 2)
{
cout << "No expression to calculate" << endl;
return 1;
}
if (str.length() == 0)
throw "Empty expression";
delete_spaces(str);
Calculator Calc(str);
double result = Calc.result();
cout << result << endl;
return 0;
}
catch (const char* str)
{
cout << str << endl;
return 1;
}
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <string>
using namespace std;
class Calculator
{
public:
Calculator(string strr)
{
str = strr;
counter = 0;
}
double result()
{
double res = calculate();
if (counter != str.length())
throw "Invalid expression";
return res;
}
private:
string str;
int counter;
double get_number_without_sign()
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
return res;
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
if (counter < str.length() && str[counter] == 'e') //если e
{
counter++;
return 2.7;
}
else
if (counter < str.length() && str[counter] == 'P') //если Pi
{
counter++;
if (counter < str.length() && str[counter] == 'i')
{
counter++;
return 3.14;
}
}
else
if (counter < str.length() && isdigit(str[counter]))
{
while (counter < str.length() && str[counter] <= '9' && str[counter] >= '0')
{
res = res * 10 + (str[counter] - '0');
counter++;
}
return res;
}
else
throw "Invalid expression";
return 1;
}
double get_number()
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
return res;
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
if (str[counter] == '-')
{
counter++;
return get_number_without_sign() * (-1);
}
else
return get_number_without_sign();
return 1;
}
double get_term() //слагаемое
{
double res = 0;
if (counter < str.length() && str[counter] == '(')
{
counter++;
res = calculate();
if (counter < str.length() && str[counter] == ')')
counter++;
else
throw "Invalid braces";
}
else
if (counter < str.length() && str[counter] == ')')
throw "Invalid braces";
else
res = get_number();
while (counter < str.length() && (str[counter] == '*' || str[counter] == '/'))
{
if (str[counter] == '*')
{
counter++;
res *= get_number();
}
if (str[counter] == '/')
{
counter++;
int n = get_number();
if (n)
res /= n;
else
throw "Invalid operation";
}
}
return res;
}
double calculate()
{
double res = get_term();
while (counter < str.length() && (str[counter] == '+' || str[counter] == '-'))
{
if (str[counter] == '+')
{
counter++;
res += get_term();
}
if (str[counter] == '-')
{
counter++;
res -= get_term();
}
}
return res;
}
};
void delete_spaces(string& str)
{
for (int i = 0; i < str.length(); i++)
if (str[i] == ' ')
{
str = str.erase(i, 1);
i--;
}
if (str.length() == 0)
throw "Empty expression";
}
int main(int argc, const char * argv[])
{
try
{
string str = argv[1];
if (argc < 2)
{
cout << "No expression to calculate" << endl;
return 1;
}
if (str.length() == 0)
throw "Empty expression";
delete_spaces(str);
Calculator Calc(str);
double result = Calc.result();
cout << result << endl;
return 0;
}
catch (const char* str)
{
cout << str << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of audio output
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
* @author Thomas Gubler <thomasgubler@gmail.com>
*
*/
#include <QApplication>
#include <QSettings>
#include <QTemporaryFile>
#include "GAudioOutput.h"
#include "MG.h"
#include <QDebug>
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
//using System;
//using System.Speech.Synthesis;
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
ISpVoice *GAudioOutput::pVoice = NULL;
#endif
/**
* This class follows the singleton design pattern
* @see http://en.wikipedia.org/wiki/Singleton_pattern
* A call to this function thus returns the only instance of this object
* the call can occur at any place in the code, no reference to the
* GAudioOutput object has to be passed.
*/
GAudioOutput *GAudioOutput::instance()
{
static GAudioOutput *_instance = 0;
if (_instance == 0)
{
_instance = new GAudioOutput();
// Set the application as parent to ensure that this object
// will be destroyed when the main application exits
_instance->setParent(qApp);
}
return _instance;
}
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
GAudioOutput::GAudioOutput(QObject *parent) : QObject(parent),
voiceIndex(0),
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
settings.sync();
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 500, NULL, 0); // initialize for playback with 500ms buffer and no options (see speak_lib.h)
espeak_VOICE espeak_voice;
memset(&espeak_voice, 0, sizeof(espeak_VOICE)); // Zero out the voice first
espeak_voice.languages = "en-uk"; // Default to British English
espeak_voice.name = "klatt"; // espeak voice name
espeak_voice.gender = 2; // Female
espeak_SetVoiceByProperties(&espeak_voice);
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//hr = pVoice->Speak(L"QGC audio output active!", 0, NULL);
//pVoice->Release();
//pVoice = NULL;
}
}
#endif
// Initialize audio output
m_media = new Phonon::MediaObject(this);
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
createPath(m_media, audioOutput);
// Prepare regular emergency signal, will be fired off on calling startEmergency()
emergencyTimer = new QTimer();
connect(emergencyTimer, SIGNAL(timeout()), this, SLOT(beep()));
switch (voiceIndex)
{
case 0:
selectFemaleVoice();
break;
default:
selectMaleVoice();
break;
}
}
GAudioOutput::~GAudioOutput()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice->Release();
pVoice = NULL;
::CoUninitialize();
#endif
}
void GAudioOutput::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
settings.sync();
emit mutedChanged(muted);
}
}
bool GAudioOutput::isMuted()
{
return this->muted;
}
bool GAudioOutput::say(QString text, int severity)
{
if (!muted)
{
// TODO Add severity filter
Q_UNUSED(severity);
bool res = false;
if (!emergency)
{
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
/*SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SelectVoice("Microsoft Anna");
synth.SpeakText(text.toStdString().c_str());
res = true;*/
/*ISpVoice * pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if( SUCCEEDED( hr ) )
{
hr = */pVoice->Speak(text.toStdWString().c_str(), SPF_ASYNC, NULL);
/*pVoice->WaitUntilDone(5000);
pVoice->Release();
pVoice = NULL;
}
}*/
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
unsigned int espeak_size = strlen(text.toStdString().c_str());
espeak_Synth(text.toStdString().c_str(), espeak_size, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); // see the documentation in speak_lib.h for the description of the arguments
#endif
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
QStdWString str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toAscii().data(), str.length());
SpeakString(str2);
res = true;
#endif
}
return res;
}
else
{
return false;
}
}
/**
* @param text This message will be played after the alert beep
*/
bool GAudioOutput::alert(QString text)
{
if (!emergency || !muted)
{
// Play alert sound
beep();
// Say alert message
say(text, 2);
return true;
}
else
{
return false;
}
}
void GAudioOutput::notifyPositive()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/double_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::notifyNegative()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/flat_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
/**
* The emergency sound will be played continously during the emergency.
* call stopEmergency() to disable it again. No speech synthesis or other
* audio output is available during the emergency.
*
* @return true if the emergency could be started, false else
*/
bool GAudioOutput::startEmergency()
{
if (!emergency)
{
emergency = true;
// Beep immediately and then start timer
if (!muted) beep();
emergencyTimer->start(1500);
QTimer::singleShot(5000, this, SLOT(stopEmergency()));
}
return true;
}
/**
* Stops the continous emergency sound. Use startEmergency() to start
* the emergency sound.
*
* @return true if the emergency could be stopped, false else
*/
bool GAudioOutput::stopEmergency()
{
if (emergency)
{
emergency = false;
emergencyTimer->stop();
}
return true;
}
void GAudioOutput::beep()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/alert.wav"));
qDebug() << "FILE:" << f.fileName();
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::selectFemaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_slt(NULL);
#endif
}
void GAudioOutput::selectMaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_rms(NULL);
#endif
}
/*
void GAudioOutput::selectNeutralVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
this->voice = register_cmu_us_awb(NULL);
#endif
}*/
QStringList GAudioOutput::listVoices(void)
{
QStringList l;
return l;
}
<commit_msg>espeak: remove c style zero initialize<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of audio output
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
* @author Thomas Gubler <thomasgubler@gmail.com>
*
*/
#include <QApplication>
#include <QSettings>
#include <QTemporaryFile>
#include "GAudioOutput.h"
#include "MG.h"
#include <QDebug>
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
//using System;
//using System.Speech.Synthesis;
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
ISpVoice *GAudioOutput::pVoice = NULL;
#endif
/**
* This class follows the singleton design pattern
* @see http://en.wikipedia.org/wiki/Singleton_pattern
* A call to this function thus returns the only instance of this object
* the call can occur at any place in the code, no reference to the
* GAudioOutput object has to be passed.
*/
GAudioOutput *GAudioOutput::instance()
{
static GAudioOutput *_instance = 0;
if (_instance == 0)
{
_instance = new GAudioOutput();
// Set the application as parent to ensure that this object
// will be destroyed when the main application exits
_instance->setParent(qApp);
}
return _instance;
}
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
GAudioOutput::GAudioOutput(QObject *parent) : QObject(parent),
voiceIndex(0),
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
settings.sync();
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 500, NULL, 0); // initialize for playback with 500ms buffer and no options (see speak_lib.h)
espeak_VOICE espeak_voice = {};
espeak_voice.languages = "en-uk"; // Default to British English
espeak_voice.name = "klatt"; // espeak voice name
espeak_voice.gender = 2; // Female
espeak_SetVoiceByProperties(&espeak_voice);
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//hr = pVoice->Speak(L"QGC audio output active!", 0, NULL);
//pVoice->Release();
//pVoice = NULL;
}
}
#endif
// Initialize audio output
m_media = new Phonon::MediaObject(this);
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
createPath(m_media, audioOutput);
// Prepare regular emergency signal, will be fired off on calling startEmergency()
emergencyTimer = new QTimer();
connect(emergencyTimer, SIGNAL(timeout()), this, SLOT(beep()));
switch (voiceIndex)
{
case 0:
selectFemaleVoice();
break;
default:
selectMaleVoice();
break;
}
}
GAudioOutput::~GAudioOutput()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice->Release();
pVoice = NULL;
::CoUninitialize();
#endif
}
void GAudioOutput::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
settings.sync();
emit mutedChanged(muted);
}
}
bool GAudioOutput::isMuted()
{
return this->muted;
}
bool GAudioOutput::say(QString text, int severity)
{
if (!muted)
{
// TODO Add severity filter
Q_UNUSED(severity);
bool res = false;
if (!emergency)
{
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
/*SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SelectVoice("Microsoft Anna");
synth.SpeakText(text.toStdString().c_str());
res = true;*/
/*ISpVoice * pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if( SUCCEEDED( hr ) )
{
hr = */pVoice->Speak(text.toStdWString().c_str(), SPF_ASYNC, NULL);
/*pVoice->WaitUntilDone(5000);
pVoice->Release();
pVoice = NULL;
}
}*/
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
unsigned int espeak_size = strlen(text.toStdString().c_str());
espeak_Synth(text.toStdString().c_str(), espeak_size, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); // see the documentation in speak_lib.h for the description of the arguments
#endif
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
QStdWString str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toAscii().data(), str.length());
SpeakString(str2);
res = true;
#endif
}
return res;
}
else
{
return false;
}
}
/**
* @param text This message will be played after the alert beep
*/
bool GAudioOutput::alert(QString text)
{
if (!emergency || !muted)
{
// Play alert sound
beep();
// Say alert message
say(text, 2);
return true;
}
else
{
return false;
}
}
void GAudioOutput::notifyPositive()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/double_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::notifyNegative()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/flat_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
/**
* The emergency sound will be played continously during the emergency.
* call stopEmergency() to disable it again. No speech synthesis or other
* audio output is available during the emergency.
*
* @return true if the emergency could be started, false else
*/
bool GAudioOutput::startEmergency()
{
if (!emergency)
{
emergency = true;
// Beep immediately and then start timer
if (!muted) beep();
emergencyTimer->start(1500);
QTimer::singleShot(5000, this, SLOT(stopEmergency()));
}
return true;
}
/**
* Stops the continous emergency sound. Use startEmergency() to start
* the emergency sound.
*
* @return true if the emergency could be stopped, false else
*/
bool GAudioOutput::stopEmergency()
{
if (emergency)
{
emergency = false;
emergencyTimer->stop();
}
return true;
}
void GAudioOutput::beep()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/alert.wav"));
qDebug() << "FILE:" << f.fileName();
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::selectFemaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_slt(NULL);
#endif
}
void GAudioOutput::selectMaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_rms(NULL);
#endif
}
/*
void GAudioOutput::selectNeutralVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
this->voice = register_cmu_us_awb(NULL);
#endif
}*/
QStringList GAudioOutput::listVoices(void)
{
QStringList l;
return l;
}
<|endoftext|> |
<commit_before>/*
kopeteaccountmanager.cpp - Kopete Account Manager
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteaccountmanager.h"
#include <qapplication.h>
#include <qregexp.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kplugininfo.h>
#include "kopeteaccount.h"
#include "kopeteaway.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
class KopeteAccountPtrList : public QPtrList<KopeteAccount>
{
protected:
int compareItems( KopeteAccountPtrList::Item a, KopeteAccountPtrList::Item b )
{
uint priority1 = static_cast<KopeteAccount*>(a)->priority();
uint priority2 = static_cast<KopeteAccount*>(b)->priority();
if( priority1 == priority2 )
return 0;
else if( priority1 > priority2 )
return -1;
else
return 1;
}
};
class KopeteAccountManagerPrivate
{
public:
static KopeteAccountManager *s_manager;
KopeteAccountPtrList accounts;
};
KopeteAccountManager * KopeteAccountManagerPrivate::s_manager = 0L;
KopeteAccountManager * KopeteAccountManager::manager()
{
if ( !KopeteAccountManagerPrivate::s_manager )
KopeteAccountManagerPrivate::s_manager = new KopeteAccountManager;
return KopeteAccountManagerPrivate::s_manager;
}
KopeteAccountManager::KopeteAccountManager()
: QObject( qApp, "KopeteAccountManager" )
{
d = new KopeteAccountManagerPrivate;
}
KopeteAccountManager::~KopeteAccountManager()
{
KopeteAccountManagerPrivate::s_manager = 0L;
delete d;
}
void KopeteAccountManager::connectAll()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->connect();
}
void KopeteAccountManager::disconnectAll()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->disconnect();
}
void KopeteAccountManager::setAwayAll( const QString &awayReason )
{
KopeteAway::setGlobalAway( true );
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->isConnected() && !it.current()->isAway() )
it.current()->setAway( true, awayReason.isNull() ? KopeteAway::message() : awayReason );
}
}
void KopeteAccountManager::setAvailableAll()
{
KopeteAway::setGlobalAway( false );
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->isConnected() && it.current()->isAway() )
it.current()->setAway( false );
}
}
QColor KopeteAccountManager::guessColor( KopeteProtocol *protocol )
{
// FIXME: Use a different algoritm. It should check if the color is really not
// used - Olivier
int protocolCount = 0;
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol()->pluginId() == protocol->pluginId() )
protocolCount++;
}
// let's figure a color
QColor color;
switch ( protocolCount % 7 )
{
case 0:
color = QColor();
break;
case 1:
color = Qt::red;
break;
case 2:
color = Qt::green;
break;
case 3:
color = Qt::blue;
break;
case 4:
color = Qt::yellow;
break;
case 5:
color = Qt::magenta;
break;
case 6:
color = Qt::cyan;
break;
}
return color;
}
void KopeteAccountManager::registerAccount( KopeteAccount *account )
{
if ( !account || account->accountId().isNull() )
return;
// If this account already exists, do nothing
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( ( account->protocol() == it.current()->protocol() ) && ( account->accountId() == it.current()->accountId() ) )
return;
}
d->accounts.append( account );
}
const QPtrList<KopeteAccount>& KopeteAccountManager::accounts() const
{
return d->accounts;
}
QDict<KopeteAccount> KopeteAccountManager::accounts( const KopeteProtocol *protocol )
{
QDict<KopeteAccount> dict;
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol() == protocol && !it.current()->accountId().isNull() )
dict.insert( it.current()->accountId(), it.current() );
}
return dict;
}
KopeteAccount * KopeteAccountManager::findAccount( const QString &protocolId, const QString &accountId )
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol()->pluginId() == protocolId && it.current()->accountId() == accountId )
return it.current();
}
return 0L;
}
void KopeteAccountManager::removeAccount( KopeteAccount *account )
{
kdDebug( 14010 ) << k_funcinfo << "Removing account '" << account->accountId() << "' and cleanning up config" << endl;
KopeteProtocol *protocol = account->protocol();
KConfig *config = KGlobal::config();
QString groupName = account->configGroup();
// Clean up the account list
d->accounts.remove( account );
delete account;
// Clean up configuration
config->deleteGroup( groupName );
config->sync();
if ( KopeteAccountManager::manager()->accounts( protocol ).isEmpty() )
{
// FIXME: pluginId() should return the internal name and not the class name, so
// we can get rid of this hack - Olivier/Martijn
QString protocolName = protocol->pluginId().remove( QString::fromLatin1( "Protocol" ) ).lower();
KopetePluginManager::self()->setPluginEnabled( protocolName, false );
KopetePluginManager::self()->unloadPlugin( protocolName );
}
}
void KopeteAccountManager::unregisterAccount( KopeteAccount *account )
{
kdDebug(14010) << k_funcinfo << "Unregistering account " << account->accountId() << endl;
emit accountUnregistered( account );
}
void KopeteAccountManager::save()
{
kdDebug( 14010 ) << k_funcinfo << endl;
d->accounts.sort();
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->writeConfig( it.current()->configGroup() );
KGlobal::config()->sync();
}
void KopeteAccountManager::load()
{
connect( KopetePluginManager::self(), SIGNAL( pluginLoaded( KopetePlugin * ) ), SLOT( slotPluginLoaded( KopetePlugin * ) ) );
// Iterate over all groups that start with "Account_" as those are accounts
// and load the required protocols if the account is enabled.
// Don't try to optimize duplicate calls out, the plugin queue is smart enough
// (and fast enough) to handle that without adding complexity here
KConfig *config = KGlobal::config();
QStringList accountGroups = config->groupList().grep( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
QString protocol = config->readEntry( "Protocol" );
if ( protocol.endsWith( QString::fromLatin1( "Protocol" ) ) )
protocol = QString::fromLatin1( "kopete_" ) + protocol.lower().remove( QString::fromLatin1( "protocol" ) );
if ( config->readBoolEntry( "Enabled", true ) )
KopetePluginManager::self()->loadPlugin( protocol, KopetePluginManager::LoadAsync );
}
}
void KopeteAccountManager::slotPluginLoaded( KopetePlugin *plugin )
{
KopeteProtocol* protocol = dynamic_cast<KopeteProtocol*>( plugin );
if ( !protocol )
return;
// Iterate over all groups that start with "Account_" as those are accounts
// and parse them if they are from this protocol
KConfig *config = KGlobal::config();
QStringList accountGroups = config->groupList().grep( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
if ( config->readEntry( "Protocol" ) != protocol->pluginId() )
continue;
// There's no GUI for this, but developers may want to disable an account.
if ( !config->readBoolEntry( "Enabled", true ) )
continue;
QString accountId = config->readEntry( "AccountId" );
if ( accountId.isEmpty() )
{
kdWarning( 14010 ) << k_funcinfo << "Not creating account for empty accountId." << endl;
continue;
}
kdDebug( 14010 ) << k_funcinfo << "Creating account for '" << accountId << "'" << endl;
KopeteAccount *account = protocol->createNewAccount( accountId );
if ( !account )
{
kdWarning( 14010 ) << k_funcinfo << "Failed to create account for '" << accountId << "'" << endl;
continue;
}
account->readConfig( *it );
}
}
void KopeteAccountManager::autoConnect()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->autoLogin() )
it.current()->connect();
}
}
void KopeteAccountManager::notifyAccountReady( KopeteAccount *account )
{
kdDebug() << k_funcinfo << account->accountId() << endl;
emit accountReady( account );
d->accounts.sort();
}
#include "kopeteaccountmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>forward port of bugfix for 74308<commit_after>/*
kopeteaccountmanager.cpp - Kopete Account Manager
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteaccountmanager.h"
#include <qapplication.h>
#include <qregexp.h>
#include <qtimer.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kplugininfo.h>
#include "kopeteaccount.h"
#include "kopeteaway.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
class KopeteAccountPtrList : public QPtrList<KopeteAccount>
{
protected:
int compareItems( KopeteAccountPtrList::Item a, KopeteAccountPtrList::Item b )
{
uint priority1 = static_cast<KopeteAccount*>(a)->priority();
uint priority2 = static_cast<KopeteAccount*>(b)->priority();
if( priority1 == priority2 )
return 0;
else if( priority1 > priority2 )
return -1;
else
return 1;
}
};
class KopeteAccountManagerPrivate
{
public:
static KopeteAccountManager *s_manager;
KopeteAccountPtrList accounts;
};
KopeteAccountManager * KopeteAccountManagerPrivate::s_manager = 0L;
KopeteAccountManager * KopeteAccountManager::manager()
{
if ( !KopeteAccountManagerPrivate::s_manager )
KopeteAccountManagerPrivate::s_manager = new KopeteAccountManager;
return KopeteAccountManagerPrivate::s_manager;
}
KopeteAccountManager::KopeteAccountManager()
: QObject( qApp, "KopeteAccountManager" )
{
d = new KopeteAccountManagerPrivate;
}
KopeteAccountManager::~KopeteAccountManager()
{
KopeteAccountManagerPrivate::s_manager = 0L;
delete d;
}
void KopeteAccountManager::connectAll()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->connect();
}
void KopeteAccountManager::disconnectAll()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->disconnect();
}
void KopeteAccountManager::setAwayAll( const QString &awayReason )
{
KopeteAway::setGlobalAway( true );
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->isConnected() && !it.current()->isAway() )
it.current()->setAway( true, awayReason.isNull() ? KopeteAway::message() : awayReason );
}
}
void KopeteAccountManager::setAvailableAll()
{
KopeteAway::setGlobalAway( false );
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->isConnected() && it.current()->isAway() )
it.current()->setAway( false );
}
}
QColor KopeteAccountManager::guessColor( KopeteProtocol *protocol )
{
// FIXME: Use a different algoritm. It should check if the color is really not
// used - Olivier
int protocolCount = 0;
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol()->pluginId() == protocol->pluginId() )
protocolCount++;
}
// let's figure a color
QColor color;
switch ( protocolCount % 7 )
{
case 0:
color = QColor();
break;
case 1:
color = Qt::red;
break;
case 2:
color = Qt::green;
break;
case 3:
color = Qt::blue;
break;
case 4:
color = Qt::yellow;
break;
case 5:
color = Qt::magenta;
break;
case 6:
color = Qt::cyan;
break;
}
return color;
}
void KopeteAccountManager::registerAccount( KopeteAccount *account )
{
if ( !account || account->accountId().isNull() )
return;
// If this account already exists, do nothing
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( ( account->protocol() == it.current()->protocol() ) && ( account->accountId() == it.current()->accountId() ) )
return;
}
d->accounts.append( account );
}
const QPtrList<KopeteAccount>& KopeteAccountManager::accounts() const
{
return d->accounts;
}
QDict<KopeteAccount> KopeteAccountManager::accounts( const KopeteProtocol *protocol )
{
QDict<KopeteAccount> dict;
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol() == protocol && !it.current()->accountId().isNull() )
dict.insert( it.current()->accountId(), it.current() );
}
return dict;
}
KopeteAccount * KopeteAccountManager::findAccount( const QString &protocolId, const QString &accountId )
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->protocol()->pluginId() == protocolId && it.current()->accountId() == accountId )
return it.current();
}
return 0L;
}
void KopeteAccountManager::removeAccount( KopeteAccount *account )
{
kdDebug( 14010 ) << k_funcinfo << "Removing account '" << account->accountId() << "' and cleanning up config" << endl;
KopeteProtocol *protocol = account->protocol();
KConfig *config = KGlobal::config();
QString groupName = account->configGroup();
// Clean up the account list
d->accounts.remove( account );
delete account;
// Clean up configuration
config->deleteGroup( groupName );
config->sync();
if ( KopeteAccountManager::manager()->accounts( protocol ).isEmpty() )
{
// FIXME: pluginId() should return the internal name and not the class name, so
// we can get rid of this hack - Olivier/Martijn
QString protocolName = protocol->pluginId().remove( QString::fromLatin1( "Protocol" ) ).lower();
KopetePluginManager::self()->setPluginEnabled( protocolName, false );
KopetePluginManager::self()->unloadPlugin( protocolName );
}
}
void KopeteAccountManager::unregisterAccount( KopeteAccount *account )
{
kdDebug( 14010 ) << k_funcinfo << "Unregistering account " << account->accountId() << endl;
d->accounts.remove( account );
emit accountUnregistered( account );
}
void KopeteAccountManager::save()
{
kdDebug( 14010 ) << k_funcinfo << endl;
d->accounts.sort();
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
it.current()->writeConfig( it.current()->configGroup() );
KGlobal::config()->sync();
}
void KopeteAccountManager::load()
{
connect( KopetePluginManager::self(), SIGNAL( pluginLoaded( KopetePlugin * ) ), SLOT( slotPluginLoaded( KopetePlugin * ) ) );
// Iterate over all groups that start with "Account_" as those are accounts
// and load the required protocols if the account is enabled.
// Don't try to optimize duplicate calls out, the plugin queue is smart enough
// (and fast enough) to handle that without adding complexity here
KConfig *config = KGlobal::config();
QStringList accountGroups = config->groupList().grep( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
QString protocol = config->readEntry( "Protocol" );
if ( protocol.endsWith( QString::fromLatin1( "Protocol" ) ) )
protocol = QString::fromLatin1( "kopete_" ) + protocol.lower().remove( QString::fromLatin1( "protocol" ) );
if ( config->readBoolEntry( "Enabled", true ) )
KopetePluginManager::self()->loadPlugin( protocol, KopetePluginManager::LoadAsync );
}
}
void KopeteAccountManager::slotPluginLoaded( KopetePlugin *plugin )
{
KopeteProtocol* protocol = dynamic_cast<KopeteProtocol*>( plugin );
if ( !protocol )
return;
// Iterate over all groups that start with "Account_" as those are accounts
// and parse them if they are from this protocol
KConfig *config = KGlobal::config();
QStringList accountGroups = config->groupList().grep( QRegExp( QString::fromLatin1( "^Account_" ) ) );
for ( QStringList::Iterator it = accountGroups.begin(); it != accountGroups.end(); ++it )
{
config->setGroup( *it );
if ( config->readEntry( "Protocol" ) != protocol->pluginId() )
continue;
// There's no GUI for this, but developers may want to disable an account.
if ( !config->readBoolEntry( "Enabled", true ) )
continue;
QString accountId = config->readEntry( "AccountId" );
if ( accountId.isEmpty() )
{
kdWarning( 14010 ) << k_funcinfo << "Not creating account for empty accountId." << endl;
continue;
}
kdDebug( 14010 ) << k_funcinfo << "Creating account for '" << accountId << "'" << endl;
KopeteAccount *account = protocol->createNewAccount( accountId );
if ( !account )
{
kdWarning( 14010 ) << k_funcinfo << "Failed to create account for '" << accountId << "'" << endl;
continue;
}
account->readConfig( *it );
}
}
void KopeteAccountManager::autoConnect()
{
for ( QPtrListIterator<KopeteAccount> it( d->accounts ); it.current(); ++it )
{
if ( it.current()->autoLogin() )
it.current()->connect();
}
}
void KopeteAccountManager::notifyAccountReady( KopeteAccount *account )
{
kdDebug() << k_funcinfo << account->accountId() << endl;
emit accountReady( account );
d->accounts.sort();
}
#include "kopeteaccountmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*
This file is part of the KDE libraries
Copyright (C) 2005 Daniel Molkentin <molkentin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <QtGui>
#include <QTimeLine>
#include <collapsiblewidget.h>
/******************************************************************
* Helper classes
*****************************************************************/
ClickableLabel::ClickableLabel( QWidget* parent )
: QLabel( parent )
{
}
ClickableLabel::~ClickableLabel()
{
}
void ClickableLabel::mouseReleaseEvent( QMouseEvent *e )
{
Q_UNUSED( e );
emit clicked();
}
ArrowButton::ArrowButton( QWidget *parent )
: QAbstractButton( parent )
{
}
ArrowButton::~ArrowButton()
{
}
void ArrowButton::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event );
QPainter p( this );
QStyleOption opt;
int h = sizeHint().height();
opt.rect = QRect(0,( height()- h )/2, h, h);
opt.palette = palette();
opt.state = QStyle::State_Children;
if (isChecked())
opt.state |= QStyle::State_Open;
style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, &p);
p.end();
}
/******************************************************************
* Private classes
*****************************************************************/
class CollapsibleWidget::Private
{
public:
QGridLayout *gridLayout;
QWidget *innerWidget;
ClickableLabel *label;
ArrowButton *colButton;
QTimeLine *timeline;
QWidget *expander;
QVBoxLayout *expanderLayout;
};
class SettingsContainer::Private
{
public:
QVBoxLayout *layout;
};
/******************************************************************
* Implementation
*****************************************************************/
SettingsContainer::SettingsContainer(QWidget *parent)
: QScrollArea( parent ), d(new SettingsContainer::Private)
{
QWidget *w = new QWidget;
QVBoxLayout *helperLay = new QVBoxLayout(w);
d->layout = new QVBoxLayout;
helperLay->addLayout( d->layout );
helperLay->addStretch(1);
setWidget(w);
setWidgetResizable(true);
}
SettingsContainer::~SettingsContainer()
{
delete d;
}
CollapsibleWidget* SettingsContainer::insertWidget( QWidget *w, const QString& name )
{
if (w && w->layout()) {
QLayout *lay = w->layout();
lay->setMargin(2);
lay->setSpacing(0);
}
CollapsibleWidget *cw = new CollapsibleWidget( name );
d->layout->addWidget( cw );
cw->setInnerWidget( w );
return cw;
}
CollapsibleWidget::CollapsibleWidget(QWidget *parent)
: QWidget(parent), d(new CollapsibleWidget::Private)
{
init();
}
CollapsibleWidget::CollapsibleWidget(const QString& caption, QWidget *parent)
: QWidget(parent), d(new CollapsibleWidget::Private)
{
init();
setCaption(caption);
}
void CollapsibleWidget::init()
{
d->expander = 0;
d->expanderLayout = 0;
d->timeline = new QTimeLine( 150, this );
d->timeline->setCurveShape( QTimeLine::EaseInOutCurve );
connect( d->timeline, SIGNAL(valueChanged(qreal)),
this, SLOT(animateCollapse(qreal)) );
d->innerWidget = 0;
d->gridLayout = new QGridLayout( this );
d->gridLayout->setMargin(0);
d->colButton = new ArrowButton;
d->colButton->setCheckable(true);
d->label = new ClickableLabel;
d->label->setSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::Preferred);
d->gridLayout->addWidget(d->colButton, 1, 1);
d->gridLayout->addWidget(d->label, 1, 2);
connect(d->label, SIGNAL(clicked()),
d->colButton, SLOT(click()));
connect(d->colButton, SIGNAL(toggled(bool)),
SLOT(setExpanded(bool)));
setExpanded(false);
setEnabled(false);
}
CollapsibleWidget::~CollapsibleWidget()
{
delete d;
}
QWidget* CollapsibleWidget::innerWidget() const
{
return d->innerWidget;
}
//#define SIMPLE
void CollapsibleWidget::setInnerWidget(QWidget *w)
{
if (!w) {
return;
}
bool first = d->innerWidget == 0;
d->innerWidget = w;
#ifdef SIMPLE
if ( !isExpanded() ) {
d->innerWidget->hide();
}
d->gridLayout->addWidget( d->innerWidget, 2, 2 );
d->gridLayout->setRowStretch( 2, 1 );
#else
if ( !d->expander ) {
d->expander = new QWidget( this );
d->expander->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum));
d->gridLayout->addWidget( d->expander, 2, 2 );
d->gridLayout->setRowStretch( 2, 1 );
d->expanderLayout = new QVBoxLayout( d->expander );
d->expanderLayout->setMargin( 0 );
d->expanderLayout->setSpacing( 0 );
d->expander->setFixedHeight( 0 );
}
d->innerWidget->setParent( d->expander );
d->innerWidget->show();
d->expanderLayout->addWidget( d->innerWidget );
#endif
setEnabled( true );
if ( isExpanded() ) {
setExpanded( true );
}
}
void CollapsibleWidget::setCaption(const QString& caption)
{
d->label->setText(QString("<b>%1</b>").arg(caption));
}
QString CollapsibleWidget::caption() const
{
return d->label->text();
}
void CollapsibleWidget::setExpanded(bool expanded)
{
if ( !d->innerWidget ) {
return;
}
#ifdef SIMPLE
if ( !expanded ) {
d->innerWidget->setVisible( false );
}
#else
if ( expanded ) {
d->expander->setVisible( true );
}
d->innerWidget->setVisible( expanded );
#endif
d->colButton->setChecked( expanded );
d->timeline->setDirection( expanded ? QTimeLine::Forward
: QTimeLine::Backward );
d->timeline->start();
}
void CollapsibleWidget::animateCollapse( qreal showAmount )
{
int pixels = d->innerWidget->sizeHint().height() * showAmount;
d->gridLayout->setRowMinimumHeight( 2, pixels );
#ifdef SIMPLE
d->gridLayout->setRowMinimumHeight( 2, pixels );
if ( showAmount == 1 ) {
d->innerWidget->setVisible( true );
}
#else
d->expander->setFixedHeight( pixels );
if (parentWidget() && parentWidget()->layout())
parentWidget()->layout()->update();
#endif
}
bool CollapsibleWidget::isExpanded() const
{
return d->colButton->isChecked();
}
#include "collapsiblewidget.moc"
<commit_msg>unused variable--<commit_after>/*
This file is part of the KDE libraries
Copyright (C) 2005 Daniel Molkentin <molkentin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <QtGui>
#include <QTimeLine>
#include <collapsiblewidget.h>
/******************************************************************
* Helper classes
*****************************************************************/
ClickableLabel::ClickableLabel( QWidget* parent )
: QLabel( parent )
{
}
ClickableLabel::~ClickableLabel()
{
}
void ClickableLabel::mouseReleaseEvent( QMouseEvent *e )
{
Q_UNUSED( e );
emit clicked();
}
ArrowButton::ArrowButton( QWidget *parent )
: QAbstractButton( parent )
{
}
ArrowButton::~ArrowButton()
{
}
void ArrowButton::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event );
QPainter p( this );
QStyleOption opt;
int h = sizeHint().height();
opt.rect = QRect(0,( height()- h )/2, h, h);
opt.palette = palette();
opt.state = QStyle::State_Children;
if (isChecked())
opt.state |= QStyle::State_Open;
style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, &p);
p.end();
}
/******************************************************************
* Private classes
*****************************************************************/
class CollapsibleWidget::Private
{
public:
QGridLayout *gridLayout;
QWidget *innerWidget;
ClickableLabel *label;
ArrowButton *colButton;
QTimeLine *timeline;
QWidget *expander;
QVBoxLayout *expanderLayout;
};
class SettingsContainer::Private
{
public:
QVBoxLayout *layout;
};
/******************************************************************
* Implementation
*****************************************************************/
SettingsContainer::SettingsContainer(QWidget *parent)
: QScrollArea( parent ), d(new SettingsContainer::Private)
{
QWidget *w = new QWidget;
QVBoxLayout *helperLay = new QVBoxLayout(w);
d->layout = new QVBoxLayout;
helperLay->addLayout( d->layout );
helperLay->addStretch(1);
setWidget(w);
setWidgetResizable(true);
}
SettingsContainer::~SettingsContainer()
{
delete d;
}
CollapsibleWidget* SettingsContainer::insertWidget( QWidget *w, const QString& name )
{
if (w && w->layout()) {
QLayout *lay = w->layout();
lay->setMargin(2);
lay->setSpacing(0);
}
CollapsibleWidget *cw = new CollapsibleWidget( name );
d->layout->addWidget( cw );
cw->setInnerWidget( w );
return cw;
}
CollapsibleWidget::CollapsibleWidget(QWidget *parent)
: QWidget(parent), d(new CollapsibleWidget::Private)
{
init();
}
CollapsibleWidget::CollapsibleWidget(const QString& caption, QWidget *parent)
: QWidget(parent), d(new CollapsibleWidget::Private)
{
init();
setCaption(caption);
}
void CollapsibleWidget::init()
{
d->expander = 0;
d->expanderLayout = 0;
d->timeline = new QTimeLine( 150, this );
d->timeline->setCurveShape( QTimeLine::EaseInOutCurve );
connect( d->timeline, SIGNAL(valueChanged(qreal)),
this, SLOT(animateCollapse(qreal)) );
d->innerWidget = 0;
d->gridLayout = new QGridLayout( this );
d->gridLayout->setMargin(0);
d->colButton = new ArrowButton;
d->colButton->setCheckable(true);
d->label = new ClickableLabel;
d->label->setSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::Preferred);
d->gridLayout->addWidget(d->colButton, 1, 1);
d->gridLayout->addWidget(d->label, 1, 2);
connect(d->label, SIGNAL(clicked()),
d->colButton, SLOT(click()));
connect(d->colButton, SIGNAL(toggled(bool)),
SLOT(setExpanded(bool)));
setExpanded(false);
setEnabled(false);
}
CollapsibleWidget::~CollapsibleWidget()
{
delete d;
}
QWidget* CollapsibleWidget::innerWidget() const
{
return d->innerWidget;
}
//#define SIMPLE
void CollapsibleWidget::setInnerWidget(QWidget *w)
{
if (!w) {
return;
}
//bool first = d->innerWidget == 0;
d->innerWidget = w;
#ifdef SIMPLE
if ( !isExpanded() ) {
d->innerWidget->hide();
}
d->gridLayout->addWidget( d->innerWidget, 2, 2 );
d->gridLayout->setRowStretch( 2, 1 );
#else
if ( !d->expander ) {
d->expander = new QWidget( this );
d->expander->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum));
d->gridLayout->addWidget( d->expander, 2, 2 );
d->gridLayout->setRowStretch( 2, 1 );
d->expanderLayout = new QVBoxLayout( d->expander );
d->expanderLayout->setMargin( 0 );
d->expanderLayout->setSpacing( 0 );
d->expander->setFixedHeight( 0 );
}
d->innerWidget->setParent( d->expander );
d->innerWidget->show();
d->expanderLayout->addWidget( d->innerWidget );
#endif
setEnabled( true );
if ( isExpanded() ) {
setExpanded( true );
}
}
void CollapsibleWidget::setCaption(const QString& caption)
{
d->label->setText(QString("<b>%1</b>").arg(caption));
}
QString CollapsibleWidget::caption() const
{
return d->label->text();
}
void CollapsibleWidget::setExpanded(bool expanded)
{
if ( !d->innerWidget ) {
return;
}
#ifdef SIMPLE
if ( !expanded ) {
d->innerWidget->setVisible( false );
}
#else
if ( expanded ) {
d->expander->setVisible( true );
}
d->innerWidget->setVisible( expanded );
#endif
d->colButton->setChecked( expanded );
d->timeline->setDirection( expanded ? QTimeLine::Forward
: QTimeLine::Backward );
d->timeline->start();
}
void CollapsibleWidget::animateCollapse( qreal showAmount )
{
int pixels = d->innerWidget->sizeHint().height() * showAmount;
d->gridLayout->setRowMinimumHeight( 2, pixels );
#ifdef SIMPLE
d->gridLayout->setRowMinimumHeight( 2, pixels );
if ( showAmount == 1 ) {
d->innerWidget->setVisible( true );
}
#else
d->expander->setFixedHeight( pixels );
if (parentWidget() && parentWidget()->layout())
parentWidget()->layout()->update();
#endif
}
bool CollapsibleWidget::isExpanded() const
{
return d->colButton->isChecked();
}
#include "collapsiblewidget.moc"
<|endoftext|> |
<commit_before><commit_msg>rejigged overrides <commit_after><|endoftext|> |
<commit_before><commit_msg>Correctly compute the gradients for RNN<commit_after><|endoftext|> |
<commit_before><commit_msg>not set ebx and edx before call cupid<commit_after><|endoftext|> |
<commit_before>#include "HAL/HAL.hpp"
#include "HAL/Port.h"
#include "HAL/Errors.hpp"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include "ChipObject.h"
#include "NetworkCommunication/FRCComm.h"
#include "NetworkCommunication/UsageReporting.h"
#include "NetworkCommunication/LoadOut.h"
#include "NetworkCommunication/CANSessionMux.h"
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;
static tGlobal *global;
static tSysWatchdog *watchdog;
void* getPort(uint8_t pin)
{
Port* port = new Port();
port->pin = pin;
port->module = 1;
return port;
}
/**
* @deprecated Uses module numbers
*/
void* getPortWithModule(uint8_t module, uint8_t pin)
{
Port* port = new Port();
port->pin = pin;
port->module = module;
return port;
}
const char* getHALErrorMessage(int32_t code)
{
switch(code) {
case 0:
return "";
case CTR_RxTimeout:
return CTR_RxTimeout_MESSAGE;
case CTR_TxTimeout:
return CTR_TxTimeout_MESSAGE;
case CTR_InvalidParamValue:
return CTR_InvalidParamValue_MESSAGE;
case CTR_UnexpectedArbId:
return CTR_UnexpectedArbId_MESSAGE;
case CTR_TxFailed:
return CTR_TxFailed_MESSAGE;
case CTR_SigNotUpdated:
return CTR_SigNotUpdated_MESSAGE;
case NiFpga_Status_FifoTimeout:
return NiFpga_Status_FifoTimeout_MESSAGE;
case NiFpga_Status_TransferAborted:
return NiFpga_Status_TransferAborted_MESSAGE;
case NiFpga_Status_MemoryFull:
return NiFpga_Status_MemoryFull_MESSAGE;
case NiFpga_Status_SoftwareFault:
return NiFpga_Status_SoftwareFault_MESSAGE;
case NiFpga_Status_InvalidParameter:
return NiFpga_Status_InvalidParameter_MESSAGE;
case NiFpga_Status_ResourceNotFound:
return NiFpga_Status_ResourceNotFound_MESSAGE;
case NiFpga_Status_ResourceNotInitialized:
return NiFpga_Status_ResourceNotInitialized_MESSAGE;
case NiFpga_Status_HardwareFault:
return NiFpga_Status_HardwareFault_MESSAGE;
case NiFpga_Status_IrqTimeout:
return NiFpga_Status_IrqTimeout_MESSAGE;
case SAMPLE_RATE_TOO_HIGH:
return SAMPLE_RATE_TOO_HIGH_MESSAGE;
case VOLTAGE_OUT_OF_RANGE:
return VOLTAGE_OUT_OF_RANGE_MESSAGE;
case LOOP_TIMING_ERROR:
return LOOP_TIMING_ERROR_MESSAGE;
case SPI_WRITE_NO_MOSI:
return SPI_WRITE_NO_MOSI_MESSAGE;
case SPI_READ_NO_MISO:
return SPI_READ_NO_MISO_MESSAGE;
case SPI_READ_NO_DATA:
return SPI_READ_NO_DATA_MESSAGE;
case INCOMPATIBLE_STATE:
return INCOMPATIBLE_STATE_MESSAGE;
case NO_AVAILABLE_RESOURCES:
return NO_AVAILABLE_RESOURCES_MESSAGE;
case NULL_PARAMETER:
return NULL_PARAMETER_MESSAGE;
case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
case PARAMETER_OUT_OF_RANGE:
return PARAMETER_OUT_OF_RANGE_MESSAGE;
case ERR_CANSessionMux_InvalidBuffer:
return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
case ERR_CANSessionMux_MessageNotFound:
return ERR_CANSessionMux_MessageNotFound_MESSAGE;
case WARN_CANSessionMux_NoToken:
return WARN_CANSessionMux_NoToken_MESSAGE;
case ERR_CANSessionMux_NotAllowed:
return ERR_CANSessionMux_NotAllowed_MESSAGE;
case ERR_CANSessionMux_NotInitialized:
return ERR_CANSessionMux_NotInitialized_MESSAGE;
case VI_ERROR_SYSTEM_ERROR:
return VI_ERROR_SYSTEM_ERROR_MESSAGE;
case VI_ERROR_INV_OBJECT:
return VI_ERROR_INV_OBJECT_MESSAGE;
case VI_ERROR_RSRC_LOCKED:
return VI_ERROR_RSRC_LOCKED_MESSAGE;
case VI_ERROR_RSRC_NFOUND:
return VI_ERROR_RSRC_NFOUND_MESSAGE;
case VI_ERROR_INV_RSRC_NAME:
return VI_ERROR_INV_RSRC_NAME_MESSAGE;
case VI_ERROR_QUEUE_OVERFLOW:
return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
case VI_ERROR_IO:
return VI_ERROR_IO_MESSAGE;
case VI_ERROR_ASRL_PARITY:
return VI_ERROR_ASRL_PARITY_MESSAGE;
case VI_ERROR_ASRL_FRAMING:
return VI_ERROR_ASRL_FRAMING_MESSAGE;
case VI_ERROR_ASRL_OVERRUN:
return VI_ERROR_ASRL_OVERRUN_MESSAGE;
case VI_ERROR_RSRC_BUSY:
return VI_ERROR_RSRC_BUSY_MESSAGE;
case VI_ERROR_INV_PARAMETER:
return VI_ERROR_INV_PARAMETER_MESSAGE;
default:
return "Unknown error status";
}
}
/**
* Return the FPGA Version number.
* For now, expect this to be competition year.
* @return FPGA Version number.
*/
uint16_t getFPGAVersion(int32_t *status)
{
return global->readVersion(status);
}
/**
* Return the FPGA Revision number.
* The format of the revision is 3 numbers.
* The 12 most significant bits are the Major Revision.
* the next 8 bits are the Minor Revision.
* The 12 least significant bits are the Build Number.
* @return FPGA Revision number.
*/
uint32_t getFPGARevision(int32_t *status)
{
return global->readRevision(status);
}
/**
* Read the microsecond-resolution timer on the FPGA.
*
* @return The current time in microseconds according to the FPGA (since FPGA reset).
*/
uint32_t getFPGATime(int32_t *status)
{
return global->readLocalTime(status);
}
/**
* Get the state of the "USER" button on the RoboRIO
* @return true if the button is currently pressed down
*/
bool getFPGAButton(int32_t *status)
{
return global->readUserButton(status);
}
int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
return setErrorData(errors, errorsLength, wait_ms);
}
bool HALGetSystemActive(int32_t *status)
{
return watchdog->readStatus_SystemActive(status);
}
bool HALGetBrownedOut(int32_t *status)
{
return !(watchdog->readStatus_PowerAlive(status));
}
/**
* Call this to start up HAL. This is required for robot programs.
*/
int HALInitialize(int mode)
{
setlinebuf(stdin);
setlinebuf(stdout);
prctl(PR_SET_PDEATHSIG, SIGTERM);
FRC_NetworkCommunication_Reserve(nullptr);
// image 4; Fixes errors caused by multiple processes. Talk to NI about this
nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
nLoadOut::kTargetClass_RoboRIO;
int32_t status;
global = tGlobal::create(&status);
watchdog = tSysWatchdog::create(&status);
// Kill any previous robot programs
std::fstream fs;
// By making this both in/out, it won't give us an error if it doesnt exist
fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
if (fs.bad())
return 0;
pid_t pid = 0;
if (!fs.eof() && !fs.fail())
{
fs >> pid;
//see if the pid is around, but we don't want to mess with init id=1, or ourselves
if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
{
std::cout << "Killing previously running FRC program..."
<< std::endl;
kill(pid, SIGTERM); // try to kill it
delayMillis(100);
if (kill(pid, 0) == 0)
{
// still not successfull
if (mode == 0)
{
std::cout << "FRC pid " << pid
<< " did not die within 110ms. Aborting"
<< std::endl;
return 0; // just fail
}
else if (mode == 1) // kill -9 it
kill(pid, SIGKILL);
else
{
std::cout << "WARNING: FRC pid " << pid
<< " did not die within 110ms." << std::endl;
}
}
}
}
fs.close();
// we will re-open it write only to truncate the file
fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
fs.seekp(0);
pid = getpid();
fs << pid << std::endl;
fs.close();
return 1;
}
uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
const char *feature)
{
if(feature == NULL)
{
feature = "";
}
return FRC_NetworkCommunication_nUsageReporting_report(resource, instanceNumber, context, feature);
}
// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}
void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}
<commit_msg>Initialize status in HALInitialize.<commit_after>#include "HAL/HAL.hpp"
#include "HAL/Port.h"
#include "HAL/Errors.hpp"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include "ChipObject.h"
#include "NetworkCommunication/FRCComm.h"
#include "NetworkCommunication/UsageReporting.h"
#include "NetworkCommunication/LoadOut.h"
#include "NetworkCommunication/CANSessionMux.h"
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;
static tGlobal *global;
static tSysWatchdog *watchdog;
void* getPort(uint8_t pin)
{
Port* port = new Port();
port->pin = pin;
port->module = 1;
return port;
}
/**
* @deprecated Uses module numbers
*/
void* getPortWithModule(uint8_t module, uint8_t pin)
{
Port* port = new Port();
port->pin = pin;
port->module = module;
return port;
}
const char* getHALErrorMessage(int32_t code)
{
switch(code) {
case 0:
return "";
case CTR_RxTimeout:
return CTR_RxTimeout_MESSAGE;
case CTR_TxTimeout:
return CTR_TxTimeout_MESSAGE;
case CTR_InvalidParamValue:
return CTR_InvalidParamValue_MESSAGE;
case CTR_UnexpectedArbId:
return CTR_UnexpectedArbId_MESSAGE;
case CTR_TxFailed:
return CTR_TxFailed_MESSAGE;
case CTR_SigNotUpdated:
return CTR_SigNotUpdated_MESSAGE;
case NiFpga_Status_FifoTimeout:
return NiFpga_Status_FifoTimeout_MESSAGE;
case NiFpga_Status_TransferAborted:
return NiFpga_Status_TransferAborted_MESSAGE;
case NiFpga_Status_MemoryFull:
return NiFpga_Status_MemoryFull_MESSAGE;
case NiFpga_Status_SoftwareFault:
return NiFpga_Status_SoftwareFault_MESSAGE;
case NiFpga_Status_InvalidParameter:
return NiFpga_Status_InvalidParameter_MESSAGE;
case NiFpga_Status_ResourceNotFound:
return NiFpga_Status_ResourceNotFound_MESSAGE;
case NiFpga_Status_ResourceNotInitialized:
return NiFpga_Status_ResourceNotInitialized_MESSAGE;
case NiFpga_Status_HardwareFault:
return NiFpga_Status_HardwareFault_MESSAGE;
case NiFpga_Status_IrqTimeout:
return NiFpga_Status_IrqTimeout_MESSAGE;
case SAMPLE_RATE_TOO_HIGH:
return SAMPLE_RATE_TOO_HIGH_MESSAGE;
case VOLTAGE_OUT_OF_RANGE:
return VOLTAGE_OUT_OF_RANGE_MESSAGE;
case LOOP_TIMING_ERROR:
return LOOP_TIMING_ERROR_MESSAGE;
case SPI_WRITE_NO_MOSI:
return SPI_WRITE_NO_MOSI_MESSAGE;
case SPI_READ_NO_MISO:
return SPI_READ_NO_MISO_MESSAGE;
case SPI_READ_NO_DATA:
return SPI_READ_NO_DATA_MESSAGE;
case INCOMPATIBLE_STATE:
return INCOMPATIBLE_STATE_MESSAGE;
case NO_AVAILABLE_RESOURCES:
return NO_AVAILABLE_RESOURCES_MESSAGE;
case NULL_PARAMETER:
return NULL_PARAMETER_MESSAGE;
case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
case PARAMETER_OUT_OF_RANGE:
return PARAMETER_OUT_OF_RANGE_MESSAGE;
case ERR_CANSessionMux_InvalidBuffer:
return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
case ERR_CANSessionMux_MessageNotFound:
return ERR_CANSessionMux_MessageNotFound_MESSAGE;
case WARN_CANSessionMux_NoToken:
return WARN_CANSessionMux_NoToken_MESSAGE;
case ERR_CANSessionMux_NotAllowed:
return ERR_CANSessionMux_NotAllowed_MESSAGE;
case ERR_CANSessionMux_NotInitialized:
return ERR_CANSessionMux_NotInitialized_MESSAGE;
case VI_ERROR_SYSTEM_ERROR:
return VI_ERROR_SYSTEM_ERROR_MESSAGE;
case VI_ERROR_INV_OBJECT:
return VI_ERROR_INV_OBJECT_MESSAGE;
case VI_ERROR_RSRC_LOCKED:
return VI_ERROR_RSRC_LOCKED_MESSAGE;
case VI_ERROR_RSRC_NFOUND:
return VI_ERROR_RSRC_NFOUND_MESSAGE;
case VI_ERROR_INV_RSRC_NAME:
return VI_ERROR_INV_RSRC_NAME_MESSAGE;
case VI_ERROR_QUEUE_OVERFLOW:
return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
case VI_ERROR_IO:
return VI_ERROR_IO_MESSAGE;
case VI_ERROR_ASRL_PARITY:
return VI_ERROR_ASRL_PARITY_MESSAGE;
case VI_ERROR_ASRL_FRAMING:
return VI_ERROR_ASRL_FRAMING_MESSAGE;
case VI_ERROR_ASRL_OVERRUN:
return VI_ERROR_ASRL_OVERRUN_MESSAGE;
case VI_ERROR_RSRC_BUSY:
return VI_ERROR_RSRC_BUSY_MESSAGE;
case VI_ERROR_INV_PARAMETER:
return VI_ERROR_INV_PARAMETER_MESSAGE;
default:
return "Unknown error status";
}
}
/**
* Return the FPGA Version number.
* For now, expect this to be competition year.
* @return FPGA Version number.
*/
uint16_t getFPGAVersion(int32_t *status)
{
return global->readVersion(status);
}
/**
* Return the FPGA Revision number.
* The format of the revision is 3 numbers.
* The 12 most significant bits are the Major Revision.
* the next 8 bits are the Minor Revision.
* The 12 least significant bits are the Build Number.
* @return FPGA Revision number.
*/
uint32_t getFPGARevision(int32_t *status)
{
return global->readRevision(status);
}
/**
* Read the microsecond-resolution timer on the FPGA.
*
* @return The current time in microseconds according to the FPGA (since FPGA reset).
*/
uint32_t getFPGATime(int32_t *status)
{
return global->readLocalTime(status);
}
/**
* Get the state of the "USER" button on the RoboRIO
* @return true if the button is currently pressed down
*/
bool getFPGAButton(int32_t *status)
{
return global->readUserButton(status);
}
int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
return setErrorData(errors, errorsLength, wait_ms);
}
bool HALGetSystemActive(int32_t *status)
{
return watchdog->readStatus_SystemActive(status);
}
bool HALGetBrownedOut(int32_t *status)
{
return !(watchdog->readStatus_PowerAlive(status));
}
/**
* Call this to start up HAL. This is required for robot programs.
*/
int HALInitialize(int mode)
{
setlinebuf(stdin);
setlinebuf(stdout);
prctl(PR_SET_PDEATHSIG, SIGTERM);
FRC_NetworkCommunication_Reserve(nullptr);
// image 4; Fixes errors caused by multiple processes. Talk to NI about this
nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
nLoadOut::kTargetClass_RoboRIO;
int32_t status = 0;
global = tGlobal::create(&status);
watchdog = tSysWatchdog::create(&status);
// Kill any previous robot programs
std::fstream fs;
// By making this both in/out, it won't give us an error if it doesnt exist
fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
if (fs.bad())
return 0;
pid_t pid = 0;
if (!fs.eof() && !fs.fail())
{
fs >> pid;
//see if the pid is around, but we don't want to mess with init id=1, or ourselves
if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
{
std::cout << "Killing previously running FRC program..."
<< std::endl;
kill(pid, SIGTERM); // try to kill it
delayMillis(100);
if (kill(pid, 0) == 0)
{
// still not successfull
if (mode == 0)
{
std::cout << "FRC pid " << pid
<< " did not die within 110ms. Aborting"
<< std::endl;
return 0; // just fail
}
else if (mode == 1) // kill -9 it
kill(pid, SIGKILL);
else
{
std::cout << "WARNING: FRC pid " << pid
<< " did not die within 110ms." << std::endl;
}
}
}
}
fs.close();
// we will re-open it write only to truncate the file
fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
fs.seekp(0);
pid = getpid();
fs << pid << std::endl;
fs.close();
return 1;
}
uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
const char *feature)
{
if(feature == NULL)
{
feature = "";
}
return FRC_NetworkCommunication_nUsageReporting_report(resource, instanceNumber, context, feature);
}
// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}
void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}
<|endoftext|> |
<commit_before>/*
* Author(s):
* - Laurent Lec <llec@aldebaran-robotics.com>
*
* Copyright (C) 2012 Aldebaran Robotics
*/
#pragma once
#ifndef _QIMESSAGING_URL_HPP_
#define _QIMESSAGING_URL_HPP_
#include <string>
#include <sstream>
namespace qi {
class Url
{
private:
std::string _url;
unsigned short _port;
std::string _host;
unsigned int _protocol;
public:
enum UrlProtocol {
Invalid = 0,
Unknown = 1,
Tcp = 2,
};
Url(const std::string &url)
: _url(url)
{
size_t begin = 0;
size_t end = 0;
end = url.find(":");
std::string type = url.substr(begin, end);
if (type == "tcp")
{
_protocol = Tcp;
}
else
{
_protocol = Unknown;
}
begin = end + 3;
end = url.find(":", begin);
_host = url.substr(begin, end - begin);
begin = end + 1;
std::stringstream ss(url.substr(begin));
ss >> _port;
}
unsigned short port() const { return _port; }
const std::string& host() const { return _host; }
unsigned int protocol() const { return _protocol; }
const std::string& str() const { return _url; }
};
}
#endif // _QIMESSAGING_URL_HPP_
<commit_msg>Rename Protocol enum in Url::.<commit_after>/*
* Author(s):
* - Laurent Lec <llec@aldebaran-robotics.com>
*
* Copyright (C) 2012 Aldebaran Robotics
*/
#pragma once
#ifndef _QIMESSAGING_URL_HPP_
#define _QIMESSAGING_URL_HPP_
#include <string>
#include <sstream>
namespace qi {
class Url
{
private:
std::string _url;
unsigned short _port;
std::string _host;
unsigned int _protocol;
public:
enum Protocol {
Protocol_Invalid = 0,
Protocol_Unknown = 1,
Protocol_Tcp = 2,
};
Url(const std::string &url)
: _url(url)
{
size_t begin = 0;
size_t end = 0;
end = url.find(":");
std::string type = url.substr(begin, end);
if (type == "tcp")
{
_protocol = Protocol_Tcp;
}
else
{
_protocol = Protocol_Unknown;
}
begin = end + 3;
end = url.find(":", begin);
_host = url.substr(begin, end - begin);
begin = end + 1;
std::stringstream ss(url.substr(begin));
ss >> _port;
}
unsigned short port() const { return _port; }
const std::string& host() const { return _host; }
unsigned int protocol() const { return _protocol; }
const std::string& str() const { return _url; }
};
}
#endif // _QIMESSAGING_URL_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ArchiveImageProvider.h"
#include "ArchiveBookModel.h"
#include <karchive.h>
#include <karchivefile.h>
#include <QBuffer>
#include <QIcon>
#include <QImageReader>
#include <QPainter>
#include <QThreadPool>
#include <AcbfDocument.h>
#include <AcbfBinary.h>
#include <AcbfData.h>
#include <qtquick_debug.h>
class ArchiveImageProvider::Private
{
public:
Private() {}
QThreadPool pool;
ArchiveBookModel* bookModel{nullptr};
QString prefix;
};
ArchiveImageProvider::ArchiveImageProvider()
: QQuickAsyncImageProvider()
, d(new Private)
{
}
ArchiveImageProvider::~ArchiveImageProvider()
{
delete d;
}
class ArchiveImageResponse : public QQuickImageResponse
{
public:
ArchiveImageResponse(const QString &id, const QSize &requestedSize, ArchiveBookModel* bookModel, const QString& prefix, QThreadPool *pool)
{
m_runnable = new ArchiveImageRunnable(id, requestedSize, bookModel, prefix);
m_runnable->setAutoDelete(false);
connect(m_runnable, &ArchiveImageRunnable::done, this, &ArchiveImageResponse::handleDone, Qt::QueuedConnection);
pool->start(m_runnable);
}
virtual ~ArchiveImageResponse()
{
m_runnable->deleteLater();
}
void handleDone(QImage image) {
m_image = image;
emit finished();
}
QQuickTextureFactory *textureFactory() const override
{
return QQuickTextureFactory::textureFactoryForImage(m_image);
}
void cancel() override
{
m_runnable->abort();
}
ArchiveImageRunnable* m_runnable{nullptr};
QImage m_image;
};
QQuickImageResponse * ArchiveImageProvider::requestImageResponse(const QString& id, const QSize& requestedSize)
{
ArchiveImageResponse* response = new ArchiveImageResponse(id, requestedSize, d->bookModel, d->prefix, &d->pool);
return response;
}
void ArchiveImageProvider::setArchiveBookModel(ArchiveBookModel* model)
{
d->bookModel = model;
}
void ArchiveImageProvider::setPrefix(QString prefix)
{
d->prefix = prefix;
}
QString ArchiveImageProvider::prefix() const
{
return d->prefix;
}
class ArchiveImageRunnable::Private {
public:
Private() {}
QString id;
QSize requestedSize;
bool abort{false};
ArchiveBookModel* bookModel{nullptr};
QString prefix;
QString errorString;
bool loadImage(QImage *image, const QByteArray &data)
{
QBuffer b;
b.setData(data);
b.open(QIODevice::ReadOnly);
QImageReader reader(&b, nullptr);
bool success = reader.read(image);
if (success) {
errorString.clear();
} else {
errorString = reader.errorString();
}
return success;
}
};
ArchiveImageRunnable::ArchiveImageRunnable(const QString& id, const QSize& requestedSize, ArchiveBookModel* bookModel, const QString& prefix)
: d(new Private)
{
d->id = id;
d->requestedSize = requestedSize;
d->bookModel = bookModel;
d->prefix = prefix;
}
void ArchiveImageRunnable::abort()
{
d->abort = true;
}
void ArchiveImageRunnable::run()//const QString& id, QSize* size, const QSize& requestedSize)
{
QImage img;
bool success = false;
/*
* In ACBF, image references starting with a '#' refer to files embedded
* in the <data> section of the .acbf file.
* see: http://acbf.wikia.com/wiki/Body_Section_Definition#Image
* TODO: binary files can also handle fonts, and those cannot be loaded into a QImage.
*/
if (d->id.startsWith('#')) {
auto document = qobject_cast<AdvancedComicBookFormat::Document*>(d->bookModel->acbfData());
if (document) {
AdvancedComicBookFormat::Binary* binary = document->data()->binary(d->id.mid(1));
if (!d->abort && binary) {
success = d->loadImage(&img, binary->data());
}
}
}
if (!d->abort && !success) {
const KArchiveFile* entry = d->bookModel->archiveFile(d->id);
if(!d->abort && entry) {
success = d->loadImage(&img, entry->data());
}
}
if (!d->abort && !success) {
QIcon oops = QIcon::fromTheme("unknown");
img = oops.pixmap(oops.availableSizes().last()).toImage();
QPainter thing(&img);
thing.drawText(img.rect(), Qt::AlignCenter | Qt::TextWordWrap, d->errorString);
qCDebug(QTQUICK_LOG) << "Failed to load image with id:" << d->id << "and the error" << d->errorString;
}
Q_EMIT done(img);
}
<commit_msg>Lock the access to the archive when reading<commit_after>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ArchiveImageProvider.h"
#include "ArchiveBookModel.h"
#include <karchive.h>
#include <karchivefile.h>
#include <QBuffer>
#include <QIcon>
#include <QImageReader>
#include <QPainter>
#include <QThreadPool>
#include <AcbfDocument.h>
#include <AcbfBinary.h>
#include <AcbfData.h>
#include <qtquick_debug.h>
class ArchiveImageProvider::Private
{
public:
Private() {}
QThreadPool pool;
ArchiveBookModel* bookModel{nullptr};
QString prefix;
};
ArchiveImageProvider::ArchiveImageProvider()
: QQuickAsyncImageProvider()
, d(new Private)
{
}
ArchiveImageProvider::~ArchiveImageProvider()
{
delete d;
}
class ArchiveImageResponse : public QQuickImageResponse
{
public:
ArchiveImageResponse(const QString &id, const QSize &requestedSize, ArchiveBookModel* bookModel, const QString& prefix, QThreadPool *pool)
{
m_runnable = new ArchiveImageRunnable(id, requestedSize, bookModel, prefix);
m_runnable->setAutoDelete(false);
connect(m_runnable, &ArchiveImageRunnable::done, this, &ArchiveImageResponse::handleDone, Qt::QueuedConnection);
pool->start(m_runnable);
}
virtual ~ArchiveImageResponse()
{
m_runnable->deleteLater();
}
void handleDone(QImage image) {
m_image = image;
emit finished();
}
QQuickTextureFactory *textureFactory() const override
{
return QQuickTextureFactory::textureFactoryForImage(m_image);
}
void cancel() override
{
m_runnable->abort();
}
ArchiveImageRunnable* m_runnable{nullptr};
QImage m_image;
};
QQuickImageResponse * ArchiveImageProvider::requestImageResponse(const QString& id, const QSize& requestedSize)
{
ArchiveImageResponse* response = new ArchiveImageResponse(id, requestedSize, d->bookModel, d->prefix, &d->pool);
return response;
}
void ArchiveImageProvider::setArchiveBookModel(ArchiveBookModel* model)
{
d->bookModel = model;
}
void ArchiveImageProvider::setPrefix(QString prefix)
{
d->prefix = prefix;
}
QString ArchiveImageProvider::prefix() const
{
return d->prefix;
}
class ArchiveImageRunnable::Private {
public:
Private() {}
QString id;
QSize requestedSize;
bool abort{false};
ArchiveBookModel* bookModel{nullptr};
QString prefix;
QString errorString;
bool loadImage(QImage *image, const QByteArray &data)
{
QBuffer b;
b.setData(data);
b.open(QIODevice::ReadOnly);
QImageReader reader(&b, nullptr);
bool success = reader.read(image);
if (success) {
errorString.clear();
} else {
errorString = reader.errorString();
}
return success;
}
};
ArchiveImageRunnable::ArchiveImageRunnable(const QString& id, const QSize& requestedSize, ArchiveBookModel* bookModel, const QString& prefix)
: d(new Private)
{
d->id = id;
d->requestedSize = requestedSize;
d->bookModel = bookModel;
d->prefix = prefix;
}
void ArchiveImageRunnable::abort()
{
d->abort = true;
}
void ArchiveImageRunnable::run()//const QString& id, QSize* size, const QSize& requestedSize)
{
QImage img;
bool success = false;
/*
* In ACBF, image references starting with a '#' refer to files embedded
* in the <data> section of the .acbf file.
* see: http://acbf.wikia.com/wiki/Body_Section_Definition#Image
* TODO: binary files can also handle fonts, and those cannot be loaded into a QImage.
*/
if (d->id.startsWith('#')) {
auto document = qobject_cast<AdvancedComicBookFormat::Document*>(d->bookModel->acbfData());
if (document) {
AdvancedComicBookFormat::Binary* binary = document->data()->binary(d->id.mid(1));
if (!d->abort && binary) {
success = d->loadImage(&img, binary->data());
}
}
}
if (!d->abort && !success) {
QMutexLocker locker(&d->bookModel->archiveMutex);
const KArchiveFile* entry = d->bookModel->archiveFile(d->id);
if(!d->abort && entry) {
success = d->loadImage(&img, entry->data());
}
}
if (!d->abort && !success) {
QIcon oops = QIcon::fromTheme("unknown");
img = oops.pixmap(oops.availableSizes().last()).toImage();
QPainter thing(&img);
thing.drawText(img.rect(), Qt::AlignCenter | Qt::TextWordWrap, d->errorString);
qCDebug(QTQUICK_LOG) << "Failed to load image with id:" << d->id << "and the error" << d->errorString;
}
Q_EMIT done(img);
}
<|endoftext|> |
<commit_before>#include "ScreenActor.h"
#include "ScreenState.h"
ScreenActor::ScreenActor(ScreenState* startingState)
{
_numberOfLines = 0;
state = startingState;
}
ScreenActor::~ScreenActor()
{
state = NULL;
}
void ScreenActor::doUpdate(const UpdateState & us)
{
ScreenState* newState = state->update(*this);
if (newState != NULL && !isTextTweening && textQueue.size() <= 0) {
cout << "Switching to a new state!" << endl;
// Remove old text from queue
textQueue.clear();
// If state returns a new state then delete the old one
// And then set the current state to new state
state = newState;
// Initializing state
state->enter(*this);
}
// See if we need to show anymore text
if (textQueue.size() > 0 && !isTextTweening) {
addText(textQueue[0]);
textQueue.erase(textQueue.begin());
}
_sliding->snap();
}
void ScreenActor::onTextTweenDone(Event * event)
{
// TODO: Add skipping tween animation
isTextTweening = false;
}
void ScreenActor::createScreen()
{
// Create slidding background
spSlidingActor slidding = new SlidingActor();
slidding->setSize(getSize());
// Createing a new Text Field and making it non interactable
_text = new TextField;
_text->setTouchEnabled(true);
TextStyle style;
style.color = Color::White;
style.hAlign = TextStyle::HALIGN_LEFT;
style.vAlign = TextStyle::VALIGN_TOP;
style.multiline = true;
style.font = Res::gameResources.getResFont("main")->getFont();
_text->setStyle(style);
_text->setText("");
_text->setWidth(this->getWidth());
_text->setHeight(this->getHeight() * 2);
slidding->setContent(_text);
slidding->attachTo(this);
_sliding = slidding;
//addChild(_text);
}
void ScreenActor::addText(const string& line)
{
//TODO: Add text scrolling
// Check if we are adding a line right now
if (isTextTweening) {
textQueue.push_back(line);
}
else {
// Add a line then add new text
_numberOfLines++;
if (_numberOfLines > 28) {
_text->setPosition(_text->getPosition().x, _text->getPosition().y - 48);
}
else if (_numberOfLines > 53) {
clearText();
}
_text->addTween(TweenText(line), 1000, 1, false)->setDoneCallback(CLOSURE(this, &ScreenActor::onTextTweenDone));
isTextTweening = true;
}
}
void ScreenActor::clearText()
{
_text->setHtmlText("");
_numberOfLines = 0;
_text->setPosition(this->getPosition());
}
void ScreenActor::init()
{
createScreen();
state->enter(*this);
}
<commit_msg>Added some todos.<commit_after>#include "ScreenActor.h"
#include "ScreenState.h"
ScreenActor::ScreenActor(ScreenState* startingState)
{
_numberOfLines = 0;
state = startingState;
}
ScreenActor::~ScreenActor()
{
state = NULL;
}
void ScreenActor::doUpdate(const UpdateState & us)
{
ScreenState* newState = state->update(*this);
if (newState != NULL && !isTextTweening && textQueue.size() <= 0) {
cout << "Switching to a new state!" << endl;
// Remove old text from queue
textQueue.clear();
// If state returns a new state then delete the old one
// And then set the current state to new state
state = newState;
// Initializing state
state->enter(*this);
}
// See if we need to show anymore text
if (textQueue.size() > 0 && !isTextTweening) {
addText(textQueue[0]);
textQueue.erase(textQueue.begin());
}
_sliding->snap();
}
void ScreenActor::onTextTweenDone(Event * event)
{
// TODO: Add skipping tween animation
isTextTweening = false;
}
void ScreenActor::createScreen()
{
// Create slidding background
spSlidingActor slidding = new SlidingActor();
slidding->setSize(getSize());
// Createing a new Text Field and making it non interactable
_text = new TextField;
_text->setTouchEnabled(true);
TextStyle style;
style.color = Color::White;
style.hAlign = TextStyle::HALIGN_LEFT;
style.vAlign = TextStyle::VALIGN_TOP;
style.multiline = true;
style.font = Res::gameResources.getResFont("main")->getFont();
_text->setStyle(style);
_text->setText("");
_text->setWidth(this->getWidth());
_text->setHeight(this->getHeight() * 2);
slidding->setContent(_text);
slidding->attachTo(this);
_sliding = slidding;
//addChild(_text);
}
void ScreenActor::addText(const string& line)
{
//TODO: Prevent text from scrolling when there isn't enough
//TODO: Clear the oldest text lines when we get so far
// Check if we are adding a line right now
if (isTextTweening) {
textQueue.push_back(line);
}
else {
// Add a line then add new text
_numberOfLines++;
if (_numberOfLines > 28) {
_text->setPosition(_text->getPosition().x, _text->getPosition().y - 48);
}
else if (_numberOfLines > 53) {
clearText();
}
_text->addTween(TweenText(line), 1000, 1, false)->setDoneCallback(CLOSURE(this, &ScreenActor::onTextTweenDone));
isTextTweening = true;
}
}
void ScreenActor::clearText()
{
_text->setHtmlText("");
_numberOfLines = 0;
_text->setPosition(this->getPosition());
}
void ScreenActor::init()
{
createScreen();
state->enter(*this);
}
<|endoftext|> |
<commit_before>#include "namespace.hpp"
#include "runtime.hpp"
#include <siplasplas/utility/string.hpp>
using namespace cpp;
using namespace dynamic_reflection;
Namespace::Namespace(const Namespace::Metadata& metadata) :
Entity(metadata)
{
assert(metadata.kind() == SourceInfo::Kind::NAMESPACE);
}
std::shared_ptr<Namespace> Namespace::create(const Namespace::Metadata& metadata)
{
return std::shared_ptr<Namespace>{new Namespace(metadata)};
}
Namespace& Namespace::fromEntity(const std::shared_ptr<Entity>& entity)
{
if(entity->sourceInfo().kind() == SourceInfo::Kind::NAMESPACE)
{
return static_cast<Namespace&>(*entity);
}
else
{
throw cpp::exception<std::runtime_error>(
"Entity '{}' is not a namespace",
entity->fullName()
);
}
}
Namespace& Namespace::namespace_(const std::string& name)
{
return Namespace::fromEntity(getChildByName(name).pointer());
}
Class& Namespace::class_(const std::string& name)
{
return Class::fromEntity(getChildByName(name).pointer());
}
Enum& Namespace::enum_(const std::string& name)
{
return Enum::fromEntity(getChildByName(name).pointer());
}
<commit_msg>[#bugfix siplasplas-reflection-dynamic] Remove Namespace::Metadata references and use SourceInfo instead<commit_after>#include "namespace.hpp"
#include "runtime.hpp"
#include <siplasplas/utility/string.hpp>
#include <siplasplas/utility/assert.hpp>
using namespace cpp;
using namespace dynamic_reflection;
Namespace::Namespace(const SourceInfo& sourceInfo) :
Entity(sourceInfo)
{
SIPLASPLAS_ASSERT(sourceInfo.kind() == SourceInfo::Kind::NAMESPACE);
}
std::shared_ptr<Namespace> Namespace::create(const SourceInfo& sourceInfo)
{
return std::shared_ptr<Namespace>{new Namespace(sourceInfo)};
}
Namespace& Namespace::fromEntity(const std::shared_ptr<Entity>& entity)
{
if(entity->sourceInfo().kind() == SourceInfo::Kind::NAMESPACE)
{
return static_cast<Namespace&>(*entity);
}
else
{
throw cpp::exception<std::runtime_error>(
"Entity '{}' is not a namespace",
entity->fullName()
);
}
}
Namespace& Namespace::namespace_(const std::string& name)
{
return Namespace::fromEntity(getChildByName(name).pointer());
}
Class& Namespace::class_(const std::string& name)
{
return Class::fromEntity(getChildByName(name).pointer());
}
Enum& Namespace::enum_(const std::string& name)
{
return Enum::fromEntity(getChildByName(name).pointer());
}
<|endoftext|> |
<commit_before>/*
* tools_p.cpp
*
* Copyright (c) 2001, 2002, 2003 Frerich Raabe <raabe@kde.org>
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. For licensing and distribution details, check the
* accompanying file 'COPYING'.
*/
#include "tools_p.h"
#include <krfcdate.h>
#include <qdom.h>
#include <kcharsets.h>
#include <qregexp.h>
time_t RSS::parseISO8601Date(const QString &s)
{
// do some sanity check: 26-12-2004T00:00+00:00 is parsed to epoch+1 in the KRFCDate, which is wrong. So let's check if the date begins with YYYY -fo
if (s.stripWhiteSpace().left(4).toInt() < 1000)
return 0; // error
// FIXME: imho this is done in KRFCDate::parseDateISO8601() automatically, so we could omit it? -fo
if (s.find('T') != -1)
return KRFCDate::parseDateISO8601(s);
else
return KRFCDate::parseDateISO8601(s + "T12:00:00");
}
QString RSS::childNodesAsXML(const QDomNode& parent)
{
QDomNodeList list = parent.childNodes();
QString str;
QTextStream ts( &str, IO_WriteOnly );
for (uint i = 0; i < list.count(); ++i)
ts << list.item(i);
return str.stripWhiteSpace();
}
QString RSS::extractNode(const QDomNode &parent, const QString &elemName, bool isInlined)
{
QDomNode node = parent.namedItem(elemName);
if (node.isNull())
return QString::null;
QDomElement e = node.toElement();
QString result;
if (elemName == "content" && ((e.hasAttribute("mode") && e.attribute("mode") == "xml") || !e.hasAttribute("mode")))
result = childNodesAsXML(node);
else
result = e.text();
bool hasPre = result.contains("<pre>",false);
bool hasHtml = hasPre || result.contains("<"); // FIXME: test if we have html, should be more clever -> regexp
if(!isInlined && !hasHtml) // perform nl2br if not a inline elt and it has no html elts
result = result = result.replace(QChar('\n'), "<br />");
if(!hasPre) // strip white spaces if no <pre>
result = result.simplifyWhiteSpace();
if (result.isEmpty())
return QString::null;
return result;
}
QString RSS::extractTitle(const QDomNode & parent)
{
QDomNode node = parent.namedItem(QString::fromLatin1("title"));
if (node.isNull())
return QString::null;
QString result = node.toElement().text();
result = KCharsets::resolveEntities(KCharsets::resolveEntities(result).replace(QRegExp("<[^>]*>"), "").remove("\\"));
result = result.simplifyWhiteSpace();
if (result.isEmpty())
return QString::null;
return result;
}
// vim:noet:ts=4
<commit_msg>fix atom:content parsing: Don't show tags when for Atom 1.0 feeds with escaped HTML in it<commit_after>/*
* tools_p.cpp
*
* Copyright (c) 2001, 2002, 2003 Frerich Raabe <raabe@kde.org>
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. For licensing and distribution details, check the
* accompanying file 'COPYING'.
*/
#include "tools_p.h"
#include <krfcdate.h>
#include <qdom.h>
#include <kcharsets.h>
#include <qregexp.h>
time_t RSS::parseISO8601Date(const QString &s)
{
// do some sanity check: 26-12-2004T00:00+00:00 is parsed to epoch+1 in the KRFCDate, which is wrong. So let's check if the date begins with YYYY -fo
if (s.stripWhiteSpace().left(4).toInt() < 1000)
return 0; // error
// FIXME: imho this is done in KRFCDate::parseDateISO8601() automatically, so we could omit it? -fo
if (s.find('T') != -1)
return KRFCDate::parseDateISO8601(s);
else
return KRFCDate::parseDateISO8601(s + "T12:00:00");
}
QString RSS::childNodesAsXML(const QDomNode& parent)
{
QDomNodeList list = parent.childNodes();
QString str;
QTextStream ts( &str, IO_WriteOnly );
for (uint i = 0; i < list.count(); ++i)
ts << list.item(i);
return str.stripWhiteSpace();
}
QString RSS::extractNode(const QDomNode &parent, const QString &elemName, bool isInlined)
{
QDomNode node = parent.namedItem(elemName);
if (node.isNull())
return QString::null;
QDomElement e = node.toElement();
QString result;
bool doHTMLCheck = true;
if (elemName == "content") // we have Atom here
{
doHTMLCheck = false;
// the first line is always the Atom 0.3, the second Atom 1.0
if (( e.hasAttribute("mode") && e.attribute("mode") == "escaped" && e.attribute("type") == "text/html" )
|| (!e.hasAttribute("mode") && e.attribute("type") == "html"))
{
result = KCharsets::resolveEntities(e.text().simplifyWhiteSpace()); // escaped html
}
else if (( e.hasAttribute("mode") && e.attribute("mode") == "escaped" && e.attribute("type") == "text/plain" )
|| (!e.hasAttribute("mode") && e.attribute("type") == "text"))
{
result = e.text().stripWhiteSpace(); // plain text
}
else if (( e.hasAttribute("mode") && e.attribute("mode") == "xml" )
|| (!e.hasAttribute("mode") && e.attribute("type") == "xhtml"))
{
result = childNodesAsXML(e); // embedded XHMTL
}
}
if (doHTMLCheck) // check for HTML; not necessary for Atom:content
{
bool hasPre = result.contains("<pre>",false);
bool hasHtml = hasPre || result.contains("<"); // FIXME: test if we have html, should be more clever -> regexp
if(!isInlined && !hasHtml) // perform nl2br if not a inline elt and it has no html elts
result = result = result.replace(QChar('\n'), "<br />");
if(!hasPre) // strip white spaces if no <pre>
result = result.simplifyWhiteSpace();
if (result.isEmpty())
return QString::null;
}
return result;
}
QString RSS::extractTitle(const QDomNode & parent)
{
QDomNode node = parent.namedItem(QString::fromLatin1("title"));
if (node.isNull())
return QString::null;
QString result = node.toElement().text();
result = KCharsets::resolveEntities(KCharsets::resolveEntities(result).replace(QRegExp("<[^>]*>"), "").remove("\\"));
result = result.simplifyWhiteSpace();
if (result.isEmpty())
return QString::null;
return result;
}
// vim:noet:ts=4
<|endoftext|> |
<commit_before>#include "packetfactory.h"
#include "cli_accept_req.h"
#include "cli_channel_list_req.h"
#include "cli_char_list_req.h"
#include "cli_create_char_req.h"
#include "cli_delete_char_req.h"
#include "cli_join_server_req.h"
#include "cli_login_req.h"
#include "cli_select_char_req.h"
#include "cli_srv_select_req.h"
#include "isc_alive.h"
#include "isc_server_register.h"
#include "isc_shutdown.h"
#include "srv_accept_reply.h"
#include "srv_channel_list_reply.h"
#include "srv_char_list_reply.h"
#include "srv_create_char_reply.h"
#include "srv_delete_char_reply.h"
#include "srv_inventory_data.h"
#include "srv_join_server_reply.h"
#include "srv_login_reply.h"
#include "srv_quest_data.h"
#include "srv_screen_shot_time_reply.h"
#include "srv_srv_select_reply.h"
#include "srv_switch_server.h"
using namespace RoseCommon;
using namespace RoseCommon::Packet;
#define REGISTER_SEND_PACKET(Type, Class) SendvPacketFactory::registerPacket<uint8_t*>(Type, &createPacket<Class>);
#define REGISTER_RECV_PACKET(Type, Class) RecvPacketFactory::registerPacket<uint8_t*>(Type, &createPacket<Class>);
void RoseCommon::register_recv_packets() {
REGISTER_RECV_PACKET(ePacketType::PAKCS_ACCEPT_REQ, CliAcceptReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CHANNEL_LIST_REQ, CliChannelListReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CHAR_LIST_REQ, CliCharListReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CREATE_CHAR_REQ, CliCreateCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_DELETE_CHAR_REQ, CliDeleteCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_LOGIN_REQ, CliLoginReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_SELECT_CHAR_REQ, CliSelectCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_SRV_SELECT_REQ, CliSrvSelectReq);
REGISTER_RECV_PACKET(ePacketType::ISC_ALIVE, IscAlive);
REGISTER_RECV_PACKET(ePacketType::ISC_SERVER_REGISTER, IscServerRegister);
REGISTER_RECV_PACKET(ePacketType::ISC_SHUTDOWN, IscShutdown);
}
void RoseCommon::register_send_packets() {
REGISTER_SEND_PACKET(ePacketType::ISC_ALIVE, IscAlive);
REGISTER_SEND_PACKET(ePacketType::ISC_SERVER_REGISTER, IscServerRegister);
REGISTER_SEND_PACKET(ePacketType::ISC_SHUTDOWN, IscShutdown);
REGISTER_SEND_PACKET(ePacketType::PAKSS_ACCEPT_REPLY, SrvAcceptReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_CHANNEL_LIST_REPLY, SrvChannelListReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_CHAR_LIST_REPLY, SrvCharListReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_CREATE_CHAR_REPLY, SrvCreateCharReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_DELETE_CHAR_REPLY, SrvDeleteCharReply);
REGISTER_SEND_PACKET(ePacketType::PAKWC_INVENTORY_DATA, SrvInventoryData);
REGISTER_SEND_PACKET(ePacketType::PAKSC_JOIN_SERVER_REPLY, SrvJoinServerReply);
REGISTER_SEND_PACKET(ePacketType::PAKSC_JOIN_SERVER_REPLY, SrvLoginReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_LOGIN_REPLY, SrvLoginReply);
REGISTER_SEND_PACKET(ePacketType::PAKWC_QUEST_DATA, SrvQuestData);
REGISTER_SEND_PACKET(ePacketType::PAKSC_SCREEN_SHOT_TIME_REPLY, SrvScreenShotTimeReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_SRV_SELECT_REPLY, SrvSrvSelectReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_SWITCH_SERVER, SrvSwitchServer);
}
<commit_msg>Update packetfactory.cpp<commit_after>#include "packetfactory.h"
#include "cli_accept_req.h"
#include "cli_alive.h"
#include "cli_channel_list_req.h"
#include "cli_char_list_req.h"
#include "cli_create_char_req.h"
#include "cli_delete_char_req.h"
#include "cli_join_server_req.h"
#include "cli_login_req.h"
#include "cli_normal_chat.h"
#include "cli_select_char_req.h"
#include "cli_srv_select_req.h"
#include "isc_alive.h"
#include "isc_server_register.h"
#include "isc_shutdown.h"
#include "srv_accept_reply.h"
#include "srv_billing_message.h"
#include "srv_channel_list_reply.h"
#include "srv_char_list_reply.h"
#include "srv_create_char_reply.h"
#include "srv_delete_char_reply.h"
#include "srv_inventory_data.h"
#include "srv_join_server_reply.h"
#include "srv_login_reply.h"
#include "srv_quest_data.h"
#include "srv_screen_shot_time_reply.h"
#include "srv_select_char_reply.h"
#include "srv_srv_select_reply.h"
#include "srv_switch_server.h"
using namespace RoseCommon;
using namespace RoseCommon::Packet;
#define REGISTER_SEND_PACKET(Type, Class) SendvPacketFactory::registerPacket<uint8_t*>(Type, &createPacket<Class>);
#define REGISTER_RECV_PACKET(Type, Class) RecvPacketFactory::registerPacket<uint8_t*>(Type, &createPacket<Class>);
void RoseCommon::register_recv_packets() {
REGISTER_RECV_PACKET(ePacketType::PAKCS_ACCEPT_REQ, CliAcceptReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_ALIVE, CliAlive);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CHANNEL_LIST_REQ, CliChannelListReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CHAR_LIST_REQ, CliCharListReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_CREATE_CHAR_REQ, CliCreateCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_DELETE_CHAR_REQ, CliDeleteCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_LOGIN_REQ, CliLoginReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_NORMAL_CHAT, CliNormalChat);
REGISTER_RECV_PACKET(ePacketType::PAKCS_SELECT_CHAR_REQ, CliSelectCharReq);
REGISTER_RECV_PACKET(ePacketType::PAKCS_SRV_SELECT_REQ, CliSrvSelectReq);
REGISTER_RECV_PACKET(ePacketType::ISC_ALIVE, IscAlive);
REGISTER_RECV_PACKET(ePacketType::ISC_SERVER_REGISTER, IscServerRegister);
REGISTER_RECV_PACKET(ePacketType::ISC_SHUTDOWN, IscShutdown);
}
void RoseCommon::register_send_packets() {
REGISTER_SEND_PACKET(ePacketType::ISC_ALIVE, IscAlive);
REGISTER_SEND_PACKET(ePacketType::ISC_SERVER_REGISTER, IscServerRegister);
REGISTER_SEND_PACKET(ePacketType::ISC_SHUTDOWN, IscShutdown);
REGISTER_SEND_PACKET(ePacketType::PAKSS_ACCEPT_REPLY, SrvAcceptReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_CHANNEL_LIST_REPLY, SrvChannelListReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_CHAR_LIST_REPLY, SrvCharListReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_CREATE_CHAR_REPLY, SrvCreateCharReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_DELETE_CHAR_REPLY, SrvDeleteCharReply);
REGISTER_SEND_PACKET(ePacketType::PAKWC_INVENTORY_DATA, SrvInventoryData);
REGISTER_SEND_PACKET(ePacketType::PAKSC_JOIN_SERVER_REPLY, SrvJoinServerReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_LOGIN_REPLY, SrvLoginReply);
REGISTER_SEND_PACKET(ePacketType::PAKWC_QUEST_DATA, SrvQuestData);
REGISTER_SEND_PACKET(ePacketType::PAKSC_SCREEN_SHOT_TIME_REPLY, SrvScreenShotTimeReply);
REGISTER_SEND_PACKET(ePacketType::PAKWC_SELECT_CHAR_REPLY, SrvSelectCharReply);
REGISTER_SEND_PACKET(ePacketType::PAKLC_SRV_SELECT_REPLY, SrvSrvSelectReply);
REGISTER_SEND_PACKET(ePacketType::PAKCC_SWITCH_SERVER, SrvSwitchServer);
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;
int get_frequency_delta(string input) {
int delta = stoi(input.substr(1, input.length() - 1));
if (input[0] == '+') {
return delta;
}
return delta * -1;
}
int solution1() {
int frequency = 0;
string input;
while (cin >> input) {
// cout << input << endl;
frequency += get_frequency_delta(input);
}
return frequency;
}
vector<int> read_input() {
vector<int> deltas;
string input;
int delta;
while (cin >> input) {
delta = get_frequency_delta(input);
deltas.push_back(delta);
}
return deltas;
}
int solution2() {
vector<int> deltas = read_input();
int frequency = 0;
set<int> frequencies_seen;
frequencies_seen.insert(frequency);
while (true) {
for (int i = 0; i < deltas.size(); i++) {
frequency += deltas[i];
set<int>::iterator it = frequencies_seen.find(frequency);
if (it != frequencies_seen.end()){
return frequency;
}
frequencies_seen.insert(frequency);
}
}
}
int main() {
// cout << solution1() << endl;
cout << solution2() << endl;
return 0;
}<commit_msg>Some notes<commit_after>/**
* Day 1
*
* sets, vectors
*/
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;
int get_frequency_delta(string input) {
int delta = stoi(input.substr(1, input.length() - 1));
if (input[0] == '+') {
return delta;
}
return delta * -1;
}
int solution1() {
int frequency = 0;
string input;
while (cin >> input) {
// cout << input << endl;
frequency += get_frequency_delta(input);
}
return frequency;
}
vector<int> read_input() {
vector<int> deltas;
string input;
int delta;
while (cin >> input) {
delta = get_frequency_delta(input);
deltas.push_back(delta);
}
return deltas;
}
int solution2() {
vector<int> deltas = read_input();
int frequency = 0;
set<int> frequencies_seen;
frequencies_seen.insert(frequency);
while (true) {
for (int i = 0; i < deltas.size(); i++) {
frequency += deltas[i];
set<int>::iterator it = frequencies_seen.find(frequency);
if (it != frequencies_seen.end()){
return frequency;
}
frequencies_seen.insert(frequency);
}
}
}
int main() {
// cout << solution1() << endl;
cout << solution2() << endl;
return 0;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F2.cpp
* Author : Kazune Takahashi
* Created : 2019/9/1 22:51:39
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using point = complex<double>;
bool cmp(point x, point y)
{
return arg(x) < arg(y);
}
int main()
{
int N;
cin >> N;
vector<point> V(N);
for (auto i = 0; i < N; i++)
{
double x, y;
cin >> x >> y;
V[i] = {x, y};
}
sort(V.begin(), V.end(), cmp);
double ans{0};
point S{};
for (auto i = 0; i < N; i++)
{
S += V[i];
}
for (auto l = 0; l < N; l++)
{
int r{l};
point now{0, 0};
for (auto i = 0; i < N; i++)
{
now += V[r];
maxs(ans, norm(now));
r = (r + 1) % N;
}
}
/*
for (auto i = 0; i < N; i++)
{
for (auto j = i; j <= N; j++)
{
point sum{0};
for (auto k = i; k < j; k++)
{
sum += V[k];
}
maxs(ans, norm(sum));
maxs(ans, norm(S - sum));
}
}
*/
cout << fixed << setprecision(30) << sqrt(ans) << endl;
}<commit_msg>submit F2.cpp to 'F - Engines' (abc139) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : F2.cpp
* Author : Kazune Takahashi
* Created : 2019/9/1 22:51:39
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using point = complex<double>;
bool cmp(point x, point y)
{
return arg(x) < arg(y);
}
int main()
{
int N;
cin >> N;
vector<point> V(N);
for (auto i = 0; i < N; i++)
{
double x, y;
cin >> x >> y;
V[i] = {x, y};
}
sort(V.begin(), V.end(), cmp);
double ans{0};
point S{};
for (auto i = 0; i < N; i++)
{
S += V[i];
}
for (auto l = 0; l < N; l++)
{
int r{l};
point now{0, 0};
for (auto i = 0; i < N; i++)
{
now += V[r];
maxs(ans, norm(now));
r = (r + 1) % N;
}
}
cout << fixed << setprecision(12) << sqrt(ans) << endl;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPainter>
#include <QColorDialog>
#include "rviz/properties/color_property.h"
#include "rviz/properties/parse_color.h"
#include "rviz/properties/color_editor.h"
namespace rviz
{
ColorEditor::ColorEditor(ColorProperty* property, QWidget* parent)
: LineEditWithButton(parent), property_(property)
{
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(parseText()));
}
void ColorEditor::paintEvent(QPaintEvent* event)
{
LineEditWithButton::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::black);
paintColorBox(&painter, rect(), color_);
}
void ColorEditor::paintColorBox(QPainter* painter, const QRect& rect, const QColor& color)
{
int padding = 3;
int size = rect.height() - padding * 2 - 1;
painter->save();
painter->setBrush(color);
painter->drawRoundedRect(rect.x() + padding + 3, rect.y() + padding, size, size, 0, 0,
Qt::AbsoluteSize);
painter->restore();
}
void ColorEditor::resizeEvent(QResizeEvent* event)
{
// Do the normal line-edit-with-button thing
LineEditWithButton::resizeEvent(event);
// Then add text padding on the left to make room for the color swatch
QMargins marge = textMargins();
setTextMargins(height(), marge.top(), marge.right(), marge.bottom());
}
void ColorEditor::parseText()
{
QColor new_color = parseColor(text());
if (new_color.isValid())
{
color_ = new_color;
if (property_)
{
property_->setColor(new_color);
}
}
}
void ColorEditor::setColor(const QColor& color)
{
color_ = color;
setText(printColor(color));
if (property_)
{
property_->setColor(color);
}
}
void ColorEditor::onButtonClick()
{
ColorProperty* prop = property_;
QColor original_color = prop->getColor();
QColorDialog dialog(color_, window());
connect(&dialog, SIGNAL(currentColorChanged(const QColor&)), property_, SLOT(setColor(const QColor&)));
// Without this connection the PropertyTreeWidget does not update
// the color info "live" when it changes in the dialog and the 3D
// view.
connect(&dialog, SIGNAL(currentColorChanged(const QColor&)), parentWidget(), SLOT(update()));
// On the TWM window manager under linux, and on OSX, this
// ColorEditor object is destroyed when (or soon after) the dialog
// opens. Therefore, here we delete this ColorEditor immediately to
// force them all to act the same.
deleteLater();
// dialog->exec() will call an event loop internally, so
// deleteLater() will take effect and "this" will be destroyed.
// Therefore, everything we do in this function after dialog->exec()
// should only use variables on the stack, not member variables.
if (dialog.exec() != QDialog::Accepted)
{
prop->setColor(original_color);
}
}
} // end namespace rviz
<commit_msg>ColorEditor: maintain edited text + cursor pos (#1609)<commit_after>/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPainter>
#include <QColorDialog>
#include "rviz/properties/color_property.h"
#include "rviz/properties/parse_color.h"
#include "rviz/properties/color_editor.h"
namespace rviz
{
ColorEditor::ColorEditor(ColorProperty* property, QWidget* parent)
: LineEditWithButton(parent), property_(property)
{
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(parseText()));
}
void ColorEditor::paintEvent(QPaintEvent* event)
{
LineEditWithButton::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::black);
paintColorBox(&painter, rect(), color_);
}
void ColorEditor::paintColorBox(QPainter* painter, const QRect& rect, const QColor& color)
{
int padding = 3;
int size = rect.height() - padding * 2 - 1;
painter->save();
painter->setBrush(color);
painter->drawRoundedRect(rect.x() + padding + 3, rect.y() + padding, size, size, 0, 0,
Qt::AbsoluteSize);
painter->restore();
}
void ColorEditor::resizeEvent(QResizeEvent* event)
{
// Do the normal line-edit-with-button thing
LineEditWithButton::resizeEvent(event);
// Then add text padding on the left to make room for the color swatch
QMargins marge = textMargins();
setTextMargins(height(), marge.top(), marge.right(), marge.bottom());
}
void ColorEditor::parseText()
{
const QString t = text();
QColor new_color = parseColor(t);
if (new_color.isValid())
{
color_ = new_color;
if (property_)
{
auto pos = cursorPosition();
property_->setColor(new_color);
// setColor() normalizes the text display and thus looses cursor pos
setText(t); // thus: restore original, unnormalized text
setCursorPosition(pos); // as well as cursor position
}
}
}
void ColorEditor::setColor(const QColor& color)
{
color_ = color;
setText(printColor(color));
if (property_)
{
property_->setColor(color);
}
}
void ColorEditor::onButtonClick()
{
ColorProperty* prop = property_;
QColor original_color = prop->getColor();
QColorDialog dialog(color_, window());
connect(&dialog, SIGNAL(currentColorChanged(const QColor&)), property_, SLOT(setColor(const QColor&)));
// Without this connection the PropertyTreeWidget does not update
// the color info "live" when it changes in the dialog and the 3D
// view.
connect(&dialog, SIGNAL(currentColorChanged(const QColor&)), parentWidget(), SLOT(update()));
// On the TWM window manager under linux, and on OSX, this
// ColorEditor object is destroyed when (or soon after) the dialog
// opens. Therefore, here we delete this ColorEditor immediately to
// force them all to act the same.
deleteLater();
// dialog->exec() will call an event loop internally, so
// deleteLater() will take effect and "this" will be destroyed.
// Therefore, everything we do in this function after dialog->exec()
// should only use variables on the stack, not member variables.
if (dialog.exec() != QDialog::Accepted)
{
prop->setColor(original_color);
}
}
} // end namespace rviz
<|endoftext|> |
<commit_before><commit_msg>Reset Element's input on disconnect<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/error.hpp"
#include "vast/logger.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/meta_store.hpp"
#include "vast/system/tracker.hpp"
using namespace caf;
namespace vast {
namespace system {
namespace {
struct terminator_state {
terminator_state(event_based_actor* selfptr) : self(selfptr) {
// nop
}
caf::error reason;
actor parent;
component_state_map components;
std::vector<std::string> victim_stack;
size_t pending_down_messages = 0;
event_based_actor* self;
// Keeps this actor alive until we manually stop it.
strong_actor_ptr anchor;
static inline const char* name = "terminator";
void init(caf::error reason, caf::actor parent,
component_state_map components,
std::vector<std::string> victim_stack) {
VAST_TRACE(VAST_ARG(components), VAST_ARG(victim_stack));
this->anchor = actor_cast<strong_actor_ptr>(self);
this->reason = std::move(reason);
this->parent = std::move(parent);
this->components = std::move(components);
this->victim_stack = std::move(victim_stack);
}
template <class Label>
void kill(const caf::actor& actor, const Label& label) {
VAST_IGNORE_UNUSED(label);
VAST_DEBUG(self, "sends exit_msg to", label);
self->monitor(actor);
self->send_exit(actor, reason);
++pending_down_messages;
}
void kill_next() {
VAST_TRACE("");
do {
if (victim_stack.empty()) {
if (parent == nullptr) {
VAST_DEBUG(self, "stops after stopping all components");
anchor = nullptr;
self->quit();
return;
}
VAST_DEBUG(self, "kills parent and remaining components");
for (auto& component : components)
kill(component.second.actor, component.second.label);
components.clear();
kill(parent, "tracker");
parent = nullptr;
return;
}
auto er = components.equal_range(victim_stack.back());
for (auto i = er.first; i != er.second; ++i)
kill(i->second.actor, i->second.label);
components.erase(er.first, er.second);
victim_stack.pop_back();
} while (pending_down_messages == 0);
}
void got_down_msg() {
VAST_TRACE("");
if (--pending_down_messages == 0)
kill_next();
}
};
behavior terminator(stateful_actor<terminator_state>* self, caf::error reason,
caf::actor parent, component_state_map components,
std::vector<std::string> victim_stack) {
VAST_DEBUG(self, "starts terminator with", victim_stack.size(),
"victims on the stack and", components.size(), "in total");
self->state.init(std::move(reason), std::move(parent), std::move(components),
std::move(victim_stack));
self->state.kill_next();
self->set_down_handler([=](const down_msg&) {
self->state.got_down_msg();
});
return {
[] {
// Dummy message handler to keep the actor alive and kicking.
}
};
}
void put_component(scheduled_actor* self, tracker_state& st,
const std::string& type, const actor& component,
std::string& label) {
using caf::anon_send;
// Save new component.
self->monitor(component);
auto& local = st.registry.components[st.node];
local.emplace(type, component_state{component, label});
// Wire it to existing components.
auto actors = [&](auto key) {
std::vector<actor> result;
auto er = local.equal_range(key);
for (auto i = er.first; i != er.second; ++i)
result.push_back(i->second.actor);
return result;
};
if (type == "exporter") {
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("sink"))
anon_send(component, sink_atom::value, a);
} else if (type == "importer") {
for (auto& a : actors("metastore"))
anon_send(component, actor_cast<meta_store_type>(a));
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("source"))
anon_send(a, sink_atom::value, component);
} else if (type == "source") {
for (auto& a : actors("importer"))
anon_send(component, sink_atom::value, a);
} else if (type == "sink") {
for (auto& a : actors("exporter"))
anon_send(a, sink_atom::value, component);
}
// Propagate new component to peer.
auto msg = make_message(put_atom::value, st.node, type, component, label);
for (auto& peer : st.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
anon_send(t, msg);
}
}
} // namespace <anonymous>
tracker_type::behavior_type
tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node) {
self->state.node = node;
// Insert ourself into the registry.
self->state.registry.components[node].emplace(
"tracker", component_state{actor_cast<actor>(self), "tracker"});
// Insert the accountant into the registry so that it is easy for remote
// actors who query the registry to obtain a reference to the actor.
auto ptr = self->system().registry().get(accountant_atom::value);
VAST_ASSERT(ptr != nullptr);
self->state.registry.components[node].emplace(
"accountant", component_state{actor_cast<actor>(ptr), "accountant"});
self->set_down_handler(
[=](const down_msg& msg) {
auto pred = [&](auto& p) { return p.second.actor == msg.source; };
for (auto& [node, comp_state] : self->state.registry.components) {
auto i = std::find_if(comp_state.begin(), comp_state.end(), pred);
if (i != comp_state.end()) {
if (i->first == "tracker")
self->state.registry.components.erase(node);
else
comp_state.erase(i);
return;
}
}
}
);
self->set_exit_handler(
[=](const exit_msg& msg) {
// Only trap the first exit, regularly shutdown on the next one.
self->set_exit_handler({});
// We shut down the components in the order in which data flows so that
// downstream components can still process in-flight data. Because the
// terminator operates with a stack of components, we specify them in
// reverse order.
self->spawn(terminator, msg.reason, actor_cast<actor>(self),
self->state.registry.components[node],
std::vector<std::string>{"exporter", "index", "archive",
"importer", "source"});
}
);
return {
[=](put_atom, const std::string& type, const actor& component,
std::string& label) -> result<ok_atom> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
put_component(self, self->state, type, component, label);
return ok_atom::value;
},
[=](try_put_atom, const std::string& type, const actor& component,
std::string& label) -> result<void> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
auto& st = self->state;
auto& local = st.registry.components[node];
if (local.count(type) != 0)
return make_error(ec::unspecified, "component already exists");
put_component(self, st, type, component, label);
return caf::unit;
},
[=](put_atom, const std::string& name, const std::string& type,
const actor& component, const std::string& label) {
VAST_DEBUG(self, "got PUT from peer", name, "for", type);
auto& components = self->state.registry.components[name];
components.emplace(type, component_state{component, label});
self->monitor(component);
},
[=](get_atom) -> result<registry> {
return self->state.registry;
},
[=](peer_atom, const actor& peer, const std::string& peer_name)
-> typed_response_promise<state_atom, registry> {
auto rp = self->make_response_promise<state_atom, registry>();
if (self->state.registry.components.count(peer_name) > 0) {
VAST_ERROR(self, "peer name already exists", peer_name);
return rp.deliver(make_error(ec::unspecified, "duplicate node name"));
}
VAST_DEBUG(self, "shipping state to new peer", peer_name);
rp.delegate(peer, state_atom::value, self->state.registry);
return rp;
},
[=](state_atom, registry& reg) -> result<ok_atom> {
VAST_DEBUG(self, "got state for", reg.components.size(), "peers");
// Monitor all remote components.
for (auto& peer : reg.components)
for (auto& pair : peer.second)
self->monitor(pair.second.actor);
// Incorporate new state from peer.
std::move(reg.components.begin(), reg.components.end(),
std::inserter(self->state.registry.components,
self->state.registry.components.end()));
// Broadcast our own state to all peers, without expecting a reply.
auto i = self->state.registry.components.find(node);
VAST_ASSERT(i != self->state.registry.components.end());
for (auto& peer : self->state.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
self->send(actor_cast<tracker_type>(t), state_atom::value,
component_map_entry{*i});
}
return ok_atom::value;
},
[=](state_atom, component_map_entry& entry) {
VAST_DEBUG(self, "got components from new peer");
for (auto& pair : entry.second)
self->monitor(pair.second.actor);
auto result = self->state.registry.components.insert(std::move(entry));
VAST_ASSERT(result.second);
}
};
}
} // namespace system
} // namespace vast
<commit_msg>Rename helper function {put => register}_component<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/all.hpp>
#include "vast/error.hpp"
#include "vast/logger.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/meta_store.hpp"
#include "vast/system/tracker.hpp"
using namespace caf;
namespace vast {
namespace system {
namespace {
struct terminator_state {
terminator_state(event_based_actor* selfptr) : self(selfptr) {
// nop
}
caf::error reason;
actor parent;
component_state_map components;
std::vector<std::string> victim_stack;
size_t pending_down_messages = 0;
event_based_actor* self;
// Keeps this actor alive until we manually stop it.
strong_actor_ptr anchor;
static inline const char* name = "terminator";
void init(caf::error reason, caf::actor parent,
component_state_map components,
std::vector<std::string> victim_stack) {
VAST_TRACE(VAST_ARG(components), VAST_ARG(victim_stack));
this->anchor = actor_cast<strong_actor_ptr>(self);
this->reason = std::move(reason);
this->parent = std::move(parent);
this->components = std::move(components);
this->victim_stack = std::move(victim_stack);
}
template <class Label>
void kill(const caf::actor& actor, const Label& label) {
VAST_IGNORE_UNUSED(label);
VAST_DEBUG(self, "sends exit_msg to", label);
self->monitor(actor);
self->send_exit(actor, reason);
++pending_down_messages;
}
void kill_next() {
VAST_TRACE("");
do {
if (victim_stack.empty()) {
if (parent == nullptr) {
VAST_DEBUG(self, "stops after stopping all components");
anchor = nullptr;
self->quit();
return;
}
VAST_DEBUG(self, "kills parent and remaining components");
for (auto& component : components)
kill(component.second.actor, component.second.label);
components.clear();
kill(parent, "tracker");
parent = nullptr;
return;
}
auto er = components.equal_range(victim_stack.back());
for (auto i = er.first; i != er.second; ++i)
kill(i->second.actor, i->second.label);
components.erase(er.first, er.second);
victim_stack.pop_back();
} while (pending_down_messages == 0);
}
void got_down_msg() {
VAST_TRACE("");
if (--pending_down_messages == 0)
kill_next();
}
};
behavior terminator(stateful_actor<terminator_state>* self, caf::error reason,
caf::actor parent, component_state_map components,
std::vector<std::string> victim_stack) {
VAST_DEBUG(self, "starts terminator with", victim_stack.size(),
"victims on the stack and", components.size(), "in total");
self->state.init(std::move(reason), std::move(parent), std::move(components),
std::move(victim_stack));
self->state.kill_next();
self->set_down_handler([=](const down_msg&) {
self->state.got_down_msg();
});
return {
[] {
// Dummy message handler to keep the actor alive and kicking.
}
};
}
void register_component(scheduled_actor* self, tracker_state& st,
const std::string& type, const actor& component,
std::string& label) {
using caf::anon_send;
// Save new component.
self->monitor(component);
auto& local = st.registry.components[st.node];
local.emplace(type, component_state{component, label});
// Wire it to existing components.
auto actors = [&](auto key) {
std::vector<actor> result;
auto er = local.equal_range(key);
for (auto i = er.first; i != er.second; ++i)
result.push_back(i->second.actor);
return result;
};
if (type == "exporter") {
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("sink"))
anon_send(component, sink_atom::value, a);
} else if (type == "importer") {
for (auto& a : actors("metastore"))
anon_send(component, actor_cast<meta_store_type>(a));
for (auto& a : actors("archive"))
anon_send(component, actor_cast<archive_type>(a));
for (auto& a : actors("index"))
anon_send(component, index_atom::value, a);
for (auto& a : actors("source"))
anon_send(a, sink_atom::value, component);
} else if (type == "source") {
for (auto& a : actors("importer"))
anon_send(component, sink_atom::value, a);
} else if (type == "sink") {
for (auto& a : actors("exporter"))
anon_send(a, sink_atom::value, component);
}
// Propagate new component to peer.
auto msg = make_message(put_atom::value, st.node, type, component, label);
for (auto& peer : st.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
anon_send(t, msg);
}
}
} // namespace <anonymous>
tracker_type::behavior_type
tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node) {
self->state.node = node;
// Insert ourself into the registry.
self->state.registry.components[node].emplace(
"tracker", component_state{actor_cast<actor>(self), "tracker"});
// Insert the accountant into the registry so that it is easy for remote
// actors who query the registry to obtain a reference to the actor.
auto ptr = self->system().registry().get(accountant_atom::value);
VAST_ASSERT(ptr != nullptr);
self->state.registry.components[node].emplace(
"accountant", component_state{actor_cast<actor>(ptr), "accountant"});
self->set_down_handler(
[=](const down_msg& msg) {
auto pred = [&](auto& p) { return p.second.actor == msg.source; };
for (auto& [node, comp_state] : self->state.registry.components) {
auto i = std::find_if(comp_state.begin(), comp_state.end(), pred);
if (i != comp_state.end()) {
if (i->first == "tracker")
self->state.registry.components.erase(node);
else
comp_state.erase(i);
return;
}
}
}
);
self->set_exit_handler(
[=](const exit_msg& msg) {
// Only trap the first exit, regularly shutdown on the next one.
self->set_exit_handler({});
// We shut down the components in the order in which data flows so that
// downstream components can still process in-flight data. Because the
// terminator operates with a stack of components, we specify them in
// reverse order.
self->spawn(terminator, msg.reason, actor_cast<actor>(self),
self->state.registry.components[node],
std::vector<std::string>{"exporter", "index", "archive",
"importer", "source"});
}
);
return {
[=](put_atom, const std::string& type, const actor& component,
std::string& label) -> result<ok_atom> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
register_component(self, self->state, type, component, label);
return ok_atom::value;
},
[=](try_put_atom, const std::string& type, const actor& component,
std::string& label) -> result<void> {
VAST_DEBUG(self, "got new", type, '(' << label << ')');
auto& st = self->state;
auto& local = st.registry.components[node];
if (local.count(type) != 0)
return make_error(ec::unspecified, "component already exists");
register_component(self, st, type, component, label);
return caf::unit;
},
[=](put_atom, const std::string& name, const std::string& type,
const actor& component, const std::string& label) {
VAST_DEBUG(self, "got PUT from peer", name, "for", type);
auto& components = self->state.registry.components[name];
components.emplace(type, component_state{component, label});
self->monitor(component);
},
[=](get_atom) -> result<registry> {
return self->state.registry;
},
[=](peer_atom, const actor& peer, const std::string& peer_name)
-> typed_response_promise<state_atom, registry> {
auto rp = self->make_response_promise<state_atom, registry>();
if (self->state.registry.components.count(peer_name) > 0) {
VAST_ERROR(self, "peer name already exists", peer_name);
return rp.deliver(make_error(ec::unspecified, "duplicate node name"));
}
VAST_DEBUG(self, "shipping state to new peer", peer_name);
rp.delegate(peer, state_atom::value, self->state.registry);
return rp;
},
[=](state_atom, registry& reg) -> result<ok_atom> {
VAST_DEBUG(self, "got state for", reg.components.size(), "peers");
// Monitor all remote components.
for (auto& peer : reg.components)
for (auto& pair : peer.second)
self->monitor(pair.second.actor);
// Incorporate new state from peer.
std::move(reg.components.begin(), reg.components.end(),
std::inserter(self->state.registry.components,
self->state.registry.components.end()));
// Broadcast our own state to all peers, without expecting a reply.
auto i = self->state.registry.components.find(node);
VAST_ASSERT(i != self->state.registry.components.end());
for (auto& peer : self->state.registry.components) {
auto& t = peer.second.find("tracker")->second.actor;
if (t != self)
self->send(actor_cast<tracker_type>(t), state_atom::value,
component_map_entry{*i});
}
return ok_atom::value;
},
[=](state_atom, component_map_entry& entry) {
VAST_DEBUG(self, "got components from new peer");
for (auto& pair : entry.second)
self->monitor(pair.second.actor);
auto result = self->state.registry.components.insert(std::move(entry));
VAST_ASSERT(result.second);
}
};
}
} // namespace system
} // namespace vast
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cclass_unicode.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: er $ $Date: 2002-03-26 17:57:44 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _I18N_CCLASS_UNICODE_HXX_
#define _I18N_CCLASS_UNICODE_HXX_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hdl>
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <com/sun/star/lang/XServiceInfo.hpp>
#define TRANSLITERATION_casemapping
#include <transliteration_body.hxx>
namespace com { namespace sun { namespace star { namespace i18n {
typedef sal_uInt32 UPT_FLAG_TYPE;
class cclass_Unicode : public cppu::WeakImplHelper1 < XCharacterClassification >
{
public:
cclass_Unicode(com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xSMgr );
~cclass_Unicode();
virtual rtl::OUString SAL_CALL toUpper( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual rtl::OUString SAL_CALL toLower( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual rtl::OUString SAL_CALL toTitle( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getType( const rtl::OUString& Text, sal_Int32 nPos ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getCharacterDirection( const rtl::OUString& Text, sal_Int32 nPos )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getScript( const rtl::OUString& Text, sal_Int32 nPos ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCharacterType( const rtl::OUString& text, sal_Int32 nPos,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getStringType( const rtl::OUString& text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual ParseResult SAL_CALL parseAnyToken( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& rLocale, sal_Int32 nStartCharFlags, const rtl::OUString& userDefinedCharactersStart,
sal_Int32 nContCharFlags, const rtl::OUString& userDefinedCharactersCont ) throw(com::sun::star::uno::RuntimeException);
virtual ParseResult SAL_CALL parsePredefinedToken( sal_Int32 nTokenType, const rtl::OUString& Text,
sal_Int32 nPos, const com::sun::star::lang::Locale& rLocale, sal_Int32 nStartCharFlags,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 nContCharFlags,
const rtl::OUString& userDefinedCharactersCont ) throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException );
protected:
sal_Char *cClass;
private:
Transliteration_casemapping *trans;
// --- parser specific (implemented in cclass_unicode_parser.cxx) ---
enum ScanState
{
ssGetChar,
ssGetValue,
ssGetWord,
ssGetWordFirstChar,
ssGetString,
ssGetBool,
ssStopBack,
ssBounce,
ssStop
};
static const sal_uInt8 nDefCnt;
static const UPT_FLAG_TYPE pDefaultParserTable[];
static const sal_Int32 pParseTokensType[];
/// Flag values of table.
static const UPT_FLAG_TYPE TOKEN_ILLEGAL;
static const UPT_FLAG_TYPE TOKEN_CHAR;
static const UPT_FLAG_TYPE TOKEN_CHAR_BOOL;
static const UPT_FLAG_TYPE TOKEN_CHAR_WORD;
static const UPT_FLAG_TYPE TOKEN_CHAR_VALUE;
static const UPT_FLAG_TYPE TOKEN_CHAR_STRING;
static const UPT_FLAG_TYPE TOKEN_CHAR_DONTCARE;
static const UPT_FLAG_TYPE TOKEN_BOOL;
static const UPT_FLAG_TYPE TOKEN_WORD;
static const UPT_FLAG_TYPE TOKEN_WORD_SEP;
static const UPT_FLAG_TYPE TOKEN_VALUE;
static const UPT_FLAG_TYPE TOKEN_VALUE_SEP;
static const UPT_FLAG_TYPE TOKEN_VALUE_EXP;
static const UPT_FLAG_TYPE TOKEN_VALUE_SIGN;
static const UPT_FLAG_TYPE TOKEN_VALUE_EXP_VALUE;
static const UPT_FLAG_TYPE TOKEN_VALUE_DIGIT;
static const UPT_FLAG_TYPE TOKEN_NAME_SEP;
static const UPT_FLAG_TYPE TOKEN_STRING_SEP;
static const UPT_FLAG_TYPE TOKEN_EXCLUDED;
/// If and where c occurs in pStr
static const sal_Unicode* StrChr( const sal_Unicode* pStr, sal_Unicode c );
com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;
/// used for parser only
com::sun::star::lang::Locale aParserLocale;
com::sun::star::uno::Reference < XLocaleData > xLocaleData;
rtl::OUString aStartChars;
rtl::OUString aContChars;
UPT_FLAG_TYPE* pTable;
UPT_FLAG_TYPE* pStart;
UPT_FLAG_TYPE* pCont;
sal_Int32 nStartTypes;
sal_Int32 nContTypes;
ScanState eState;
sal_Unicode cGroupSep;
sal_Unicode cDecimalSep;
/// Get corresponding KParseTokens flag for a character
sal_Int32 getParseTokensType( sal_Unicode c );
/// Access parser table flags.
UPT_FLAG_TYPE getFlags( sal_Unicode c );
/// Access parser flags via International and special definitions.
UPT_FLAG_TYPE getFlagsExtended( sal_Unicode c );
/// Access parser table flags for user defined start characters.
UPT_FLAG_TYPE getStartCharsFlags( sal_Unicode c );
/// Access parser table flags for user defined continuation characters.
UPT_FLAG_TYPE getContCharsFlags( sal_Unicode c );
/// Setup parser table. Calls initParserTable() only if needed.
void setupParserTable( const com::sun::star::lang::Locale& rLocale, sal_Int32 startCharTokenType,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType,
const rtl::OUString& userDefinedCharactersCont );
/// Init parser table.
void initParserTable( const com::sun::star::lang::Locale& rLocale, sal_Int32 startCharTokenType,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType,
const rtl::OUString& userDefinedCharactersCont );
/// Destroy parser table.
void destroyParserTable();
/// Parse a text.
void parseText( ParseResult& r, const rtl::OUString& rText, sal_Int32 nPos,
sal_Int32 nTokenType = 0xffffffff );
/// Setup International class, new'ed only if different from existing.
sal_Bool setupInternational( const com::sun::star::lang::Locale& rLocale );
/// Implementation of getCharacterType() for one single character
sal_Int32 getCharType( sal_Unicode c );
};
} } } }
/**************************************************************************
Source Code Control System - Updates
$Log: not supported by cvs2svn $
Revision 1.1 2002/03/26 13:36:40 bustamam
#97583# add Include files
Revision 1.3 2001/10/19 21:16:45 bustamam.harun
#84725# Add XServiceInfo implementation
Revision 1.2 2001/05/18 17:57:33 er
#79771# optimize: disentangled: cclass_unicode not derived from CharacterClassificationImpl; reuse instance if locale didn't change; rtl::OUString instead of String
Revision 1.1 2001/03/27 21:13:45 bustamam.harun
rename characterclassification to cclass_unicode
Revision 1.6 2001/01/29 17:05:55 er
CharacterClassification with service manager
Revision 1.5 2000/10/29 17:01:45 er
i18n API moved from com.sun.star.lang to com.sun.star.i18n
Revision 1.4 2000/08/11 14:51:29 er
removed queryInterface/aquire/release, using WeakImplHelper instead
Revision 1.3 2000/07/06 15:49:21 gmu
changed parsing functions
Revision 1.2 2000/07/06 15:21:04 er
define USE_I18N_DEFAULT_IMPLEMENTATION and Locale dependent source
Revision 1.1 2000/07/06 08:51:54 er
new: CharacterClassification with parser
**************************************************************************/
#endif
<commit_msg>#100065# use NativeNumberSupplier<commit_after>/*************************************************************************
*
* $RCSfile: cclass_unicode.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: er $ $Date: 2002-08-05 16:22:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _I18N_CCLASS_UNICODE_HXX_
#define _I18N_CCLASS_UNICODE_HXX_
#include <drafts/com/sun/star/i18n/XNativeNumberSupplier.hpp>
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hdl>
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <com/sun/star/lang/XServiceInfo.hpp>
#define TRANSLITERATION_casemapping
#include <transliteration_body.hxx>
namespace com { namespace sun { namespace star { namespace i18n {
typedef sal_uInt32 UPT_FLAG_TYPE;
class cclass_Unicode : public cppu::WeakImplHelper1 < XCharacterClassification >
{
public:
cclass_Unicode(com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xSMgr );
~cclass_Unicode();
virtual rtl::OUString SAL_CALL toUpper( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual rtl::OUString SAL_CALL toLower( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual rtl::OUString SAL_CALL toTitle( const rtl::OUString& Text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getType( const rtl::OUString& Text, sal_Int32 nPos ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getCharacterDirection( const rtl::OUString& Text, sal_Int32 nPos )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int16 SAL_CALL getScript( const rtl::OUString& Text, sal_Int32 nPos ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCharacterType( const rtl::OUString& text, sal_Int32 nPos,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getStringType( const rtl::OUString& text, sal_Int32 nPos, sal_Int32 nCount,
const com::sun::star::lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException);
virtual ParseResult SAL_CALL parseAnyToken( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& rLocale, sal_Int32 nStartCharFlags, const rtl::OUString& userDefinedCharactersStart,
sal_Int32 nContCharFlags, const rtl::OUString& userDefinedCharactersCont ) throw(com::sun::star::uno::RuntimeException);
virtual ParseResult SAL_CALL parsePredefinedToken( sal_Int32 nTokenType, const rtl::OUString& Text,
sal_Int32 nPos, const com::sun::star::lang::Locale& rLocale, sal_Int32 nStartCharFlags,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 nContCharFlags,
const rtl::OUString& userDefinedCharactersCont ) throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException );
protected:
sal_Char *cClass;
private:
Transliteration_casemapping *trans;
// --- parser specific (implemented in cclass_unicode_parser.cxx) ---
enum ScanState
{
ssGetChar,
ssGetValue,
ssGetWord,
ssGetWordFirstChar,
ssGetString,
ssGetBool,
ssStopBack,
ssBounce,
ssStop
};
static const sal_uInt8 nDefCnt;
static const UPT_FLAG_TYPE pDefaultParserTable[];
static const sal_Int32 pParseTokensType[];
/// Flag values of table.
static const UPT_FLAG_TYPE TOKEN_ILLEGAL;
static const UPT_FLAG_TYPE TOKEN_CHAR;
static const UPT_FLAG_TYPE TOKEN_CHAR_BOOL;
static const UPT_FLAG_TYPE TOKEN_CHAR_WORD;
static const UPT_FLAG_TYPE TOKEN_CHAR_VALUE;
static const UPT_FLAG_TYPE TOKEN_CHAR_STRING;
static const UPT_FLAG_TYPE TOKEN_CHAR_DONTCARE;
static const UPT_FLAG_TYPE TOKEN_BOOL;
static const UPT_FLAG_TYPE TOKEN_WORD;
static const UPT_FLAG_TYPE TOKEN_WORD_SEP;
static const UPT_FLAG_TYPE TOKEN_VALUE;
static const UPT_FLAG_TYPE TOKEN_VALUE_SEP;
static const UPT_FLAG_TYPE TOKEN_VALUE_EXP;
static const UPT_FLAG_TYPE TOKEN_VALUE_SIGN;
static const UPT_FLAG_TYPE TOKEN_VALUE_EXP_VALUE;
static const UPT_FLAG_TYPE TOKEN_VALUE_DIGIT;
static const UPT_FLAG_TYPE TOKEN_NAME_SEP;
static const UPT_FLAG_TYPE TOKEN_STRING_SEP;
static const UPT_FLAG_TYPE TOKEN_EXCLUDED;
/// If and where c occurs in pStr
static const sal_Unicode* StrChr( const sal_Unicode* pStr, sal_Unicode c );
com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;
/// used for parser only
com::sun::star::lang::Locale aParserLocale;
com::sun::star::uno::Reference < XLocaleData > xLocaleData;
com::sun::star::uno::Reference < drafts::com::sun::star::i18n::XNativeNumberSupplier > xNatNumSup;
rtl::OUString aStartChars;
rtl::OUString aContChars;
UPT_FLAG_TYPE* pTable;
UPT_FLAG_TYPE* pStart;
UPT_FLAG_TYPE* pCont;
sal_Int32 nStartTypes;
sal_Int32 nContTypes;
ScanState eState;
sal_Unicode cGroupSep;
sal_Unicode cDecimalSep;
/// Get corresponding KParseTokens flag for a character
sal_Int32 getParseTokensType( sal_Unicode c );
/// Access parser table flags.
UPT_FLAG_TYPE getFlags( sal_Unicode c );
/// Access parser flags via International and special definitions.
UPT_FLAG_TYPE getFlagsExtended( sal_Unicode c );
/// Access parser table flags for user defined start characters.
UPT_FLAG_TYPE getStartCharsFlags( sal_Unicode c );
/// Access parser table flags for user defined continuation characters.
UPT_FLAG_TYPE getContCharsFlags( sal_Unicode c );
/// Setup parser table. Calls initParserTable() only if needed.
void setupParserTable( const com::sun::star::lang::Locale& rLocale, sal_Int32 startCharTokenType,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType,
const rtl::OUString& userDefinedCharactersCont );
/// Init parser table.
void initParserTable( const com::sun::star::lang::Locale& rLocale, sal_Int32 startCharTokenType,
const rtl::OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType,
const rtl::OUString& userDefinedCharactersCont );
/// Destroy parser table.
void destroyParserTable();
/// Parse a text.
void parseText( ParseResult& r, const rtl::OUString& rText, sal_Int32 nPos,
sal_Int32 nTokenType = 0xffffffff );
/// Setup International class, new'ed only if different from existing.
sal_Bool setupInternational( const com::sun::star::lang::Locale& rLocale );
/// Implementation of getCharacterType() for one single character
sal_Int32 getCharType( sal_Unicode c );
};
} } } }
#endif
<|endoftext|> |
<commit_before>#ifndef __SERIALIZER_SEMANTIC_CHECKING_HPP__
#define __SERIALIZER_SEMANTIC_CHECKING_HPP__
#include "errors.hpp"
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/crc.hpp>
#include "arch/arch.hpp"
#include "config/args.hpp"
#include "serializer/serializer.hpp"
#include "containers/two_level_array.hpp"
/* This is a thin wrapper around the log serializer that makes sure that the
serializer has the correct semantics. It must have exactly the same API as
the log serializer. */
//#define SERIALIZER_DEBUG_PRINT 1
// TODO make this just an interface and move implementation into semantic_checking.tcc, then use
// tim's template hack to instantiate as necessary in a .cc file.
// TODO (rntz) fix this for new serializer interface
template<class inner_serializer_t>
class semantic_checking_serializer_t :
public serializer_t
{
private:
inner_serializer_t inner_serializer;
typedef uint32_t crc_t;
struct block_info_t {
enum state_t {
state_unknown,
state_deleted,
state_have_crc
} state;
crc_t crc;
// For compatibility with two_level_array_t
block_info_t() : state(state_unknown) {}
operator bool() { return state != state_unknown; }
};
two_level_array_t<block_info_t, MAX_BLOCK_ID> blocks;
crc_t compute_crc(const void *buf) {
boost::crc_32_type crc_computer;
// We need to not crc BLOCK_META_DATA_SIZE because it's
// internal to the serializer.
crc_computer.process_bytes(buf, get_block_size().value());
return crc_computer.checksum();
}
int last_write_started, last_write_callbacked;
struct persisted_block_info_t {
block_id_t block_id;
block_info_t block_info;
};
int semantic_fd;
public:
typedef typename inner_serializer_t::private_dynamic_config_t private_dynamic_config_t;
typedef typename inner_serializer_t::dynamic_config_t dynamic_config_t;
typedef typename inner_serializer_t::static_config_t static_config_t;
static void create(dynamic_config_t *config, private_dynamic_config_t *private_config, static_config_t *static_config) {
inner_serializer_t::create(config, private_config, static_config);
}
semantic_checking_serializer_t(dynamic_config_t *config, private_dynamic_config_t *private_config)
: inner_serializer(config, private_config),
last_write_started(0), last_write_callbacked(0),
semantic_fd(-1)
{
semantic_fd = open(private_config->semantic_filename.c_str(),
O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if (semantic_fd == INVALID_FD)
fail_due_to_user_error("Inaccessible semantic checking file: \"%s\": %s", private_config->semantic_filename.c_str(), strerror(errno));
// fill up the blocks from the semantic checking file
int res = -1;
do {
persisted_block_info_t buf;
res = read(semantic_fd, &buf, sizeof(buf));
guarantee_err(res != -1, "Could not read from the semantic checker file");
if(res == sizeof(persisted_block_info_t)) {
blocks.set(buf.block_id.value, buf.block_info);
}
} while(res == sizeof(persisted_block_info_t));
}
~semantic_checking_serializer_t() {
close(semantic_fd);
}
typedef typename inner_serializer_t::check_callback_t check_callback_t;
static void check_existing(const char *db_path, check_callback_t *cb) {
inner_serializer_t::check_existing(db_path, cb);
}
void *malloc() {
return inner_serializer.malloc();
}
void *clone(void *data) {
return inner_serializer.clone(data);
}
void free(void *ptr) {
inner_serializer.free(ptr);
}
file_t::account_t *make_io_account(int priority, int outstanding_requests_limit = UNLIMITED_OUTSTANDING_REQUESTS) {
return inner_serializer.make_io_account(priority, outstanding_requests_limit);
}
/* For reads, we check to make sure that the data we get back in the read is
consistent with what was last written there. */
struct reader_t :
public read_callback_t
{
semantic_checking_serializer_t *parent;
block_id_t block_id;
void *buf;
block_info_t expected_block_state;
read_callback_t *callback;
reader_t(semantic_checking_serializer_t *parent, block_id_t block_id, void *buf, block_info_t expected_block_state)
: parent(parent), block_id(block_id), buf(buf), expected_block_state(expected_block_state) {}
void on_serializer_read() {
/* Make sure that the value that the serializer returned was valid */
crc_t actual_crc = parent->compute_crc(buf);
switch (expected_block_state.state) {
case block_info_t::state_unknown: {
/* We don't know what this block was supposed to contain, so we can't do any
verification */
break;
}
case block_info_t::state_deleted: {
unreachable("Cache asked for a deleted block, and serializer didn't complain.");
}
case block_info_t::state_have_crc: {
#ifdef SERIALIZER_DEBUG_PRINT
printf("Read %ld: %u\n", block_id, actual_crc);
#endif
guarantee(expected_block_state.crc == actual_crc, "Serializer returned bad value for block ID %u", block_id.value);
break;
}
default:
unreachable();
}
if (callback) callback->on_serializer_read();
delete this;
}
};
bool do_read(block_id_t block_id, void *buf, file_t::account_t *io_account, read_callback_t *callback) {
#ifdef SERIALIZER_DEBUG_PRINT
printf("Reading %ld\n", block_id);
#endif
reader_t *reader = new reader_t(this, block_id, buf, blocks.get(block_id.value));
reader->callback = NULL;
if (inner_serializer.do_read(block_id, buf, io_account, reader)) {
reader->on_serializer_read();
return true;
} else {
reader->callback = callback;
return false;
}
}
ser_transaction_id_t get_current_transaction_id(block_id_t block_id, const void* buf) {
// TODO: Implement some checking for this operation
return inner_serializer.get_current_transaction_id(block_id, buf);
}
/* For writes, we make sure that the writes come back in the same order that
we send them to the serializer. */
struct writer_t :
public write_txn_callback_t
{
semantic_checking_serializer_t *parent;
int version;
write_txn_callback_t *callback;
writer_t(semantic_checking_serializer_t *parent, int version)
: parent(parent), version(version) {}
void on_serializer_write_txn() {
guarantee(parent->last_write_callbacked == version-1, "Serializer completed writes in the wrong order.");
parent->last_write_callbacked = version;
if (callback) callback->on_serializer_write_txn();
delete this;
}
};
bool do_write(write_t *writes, int num_writes, file_t::account_t *io_account, write_txn_callback_t *callback, write_tid_callback_t *tid_callback = NULL) {
for (int i = 0; i < num_writes; i++) {
if (!writes[i].buf_specified) continue;
block_info_t b;
memset(&b, 0, sizeof(b)); // make valgrind happy
if (writes[i].buf) {
b.state = block_info_t::state_have_crc;
b.crc = compute_crc(writes[i].buf);
#ifdef SERIALIZER_DEBUG_PRINT
printf("Writing %ld: %u\n", writes[i].block_id, b.crc);
#endif
} else {
b.state = block_info_t::state_deleted;
#ifdef SERIALIZER_DEBUG_PRINT
printf("Deleting %ld\n", writes[i].block_id);
#endif
}
blocks.set(writes[i].block_id.value, b);
// Add the block to the semantic checker file
persisted_block_info_t buf;
#ifdef VALGRIND
memset(&buf, 0, sizeof(buf)); // make valgrind happy
#endif
buf.block_id = writes[i].block_id;
buf.block_info = b;
int res = write(semantic_fd, &buf, sizeof(buf));
guarantee_err(res == sizeof(buf), "Could not write data to semantic checker file");
}
writer_t *writer = new writer_t(this, ++last_write_started);
writer->callback = NULL;
if (inner_serializer.do_write(writes, num_writes, io_account, writer, tid_callback)) {
writer->on_serializer_write_txn();
return true;
} else {
writer->callback = callback;
return false;
}
}
block_size_t get_block_size() {
return inner_serializer.get_block_size();
}
block_id_t max_block_id() {
return inner_serializer.max_block_id();
}
bool block_in_use(block_id_t id) {
bool in_use = inner_serializer.block_in_use(id);
switch (blocks.get(id.value).state) {
case block_info_t::state_unknown: break;
case block_info_t::state_deleted: rassert(!in_use); break;
case block_info_t::state_have_crc: rassert(in_use); break;
default: unreachable();
}
return in_use;
}
repli_timestamp_t get_recency(block_id_t id) {
return inner_serializer.get_recency(id);
}
bool register_read_ahead_cb(read_ahead_callback_t *cb) {
// Ignore this, it might make the checking ineffective...
}
bool unregister_read_ahead_cb(read_ahead_callback_t *cb) {
return false;
}
struct shutdown_callback_t {
virtual void on_serializer_shutdown(semantic_checking_serializer_t *) = 0;
virtual ~shutdown_callback_t() {}
};
bool shutdown(shutdown_callback_t *cb) {
shutdown_callback = cb;
return inner_serializer.shutdown(this);
}
private:
shutdown_callback_t *shutdown_callback;
void on_serializer_shutdown(inner_serializer_t *ser) {
if (shutdown_callback) shutdown_callback->on_serializer_shutdown(this);
}
public:
typedef typename inner_serializer_t::gc_disable_callback_t gc_disable_callback_t;
bool disable_gc(gc_disable_callback_t *cb) {
return inner_serializer.disable_gc(cb);
}
bool enable_gc() {
return inner_serializer.enable_gc();
}
};
#endif /* __SERIALIZER_SEMANTIC_CHECKING_HPP__ */
<commit_msg>add XXX to self<commit_after>#ifndef __SERIALIZER_SEMANTIC_CHECKING_HPP__
#define __SERIALIZER_SEMANTIC_CHECKING_HPP__
#include "errors.hpp"
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/crc.hpp>
#include "arch/arch.hpp"
#include "config/args.hpp"
#include "serializer/serializer.hpp"
#include "containers/two_level_array.hpp"
/* This is a thin wrapper around the log serializer that makes sure that the
serializer has the correct semantics. It must have exactly the same API as
the log serializer. */
//#define SERIALIZER_DEBUG_PRINT 1
// TODO make this just an interface and move implementation into semantic_checking.tcc, then use
// tim's template hack to instantiate as necessary in a .cc file.
// TODO (rntz) fix this for new serializer interface
template<class inner_serializer_t>
class semantic_checking_serializer_t :
public serializer_t
{
private:
inner_serializer_t inner_serializer;
typedef uint32_t crc_t;
struct block_info_t {
enum state_t {
state_unknown,
state_deleted,
state_have_crc
} state;
crc_t crc;
// For compatibility with two_level_array_t
block_info_t() : state(state_unknown) {}
operator bool() { return state != state_unknown; }
};
two_level_array_t<block_info_t, MAX_BLOCK_ID> blocks;
crc_t compute_crc(const void *buf) {
boost::crc_32_type crc_computer;
// We need to not crc BLOCK_META_DATA_SIZE because it's
// internal to the serializer.
crc_computer.process_bytes(buf, get_block_size().value());
return crc_computer.checksum();
}
int last_write_started, last_write_callbacked;
struct persisted_block_info_t {
block_id_t block_id;
block_info_t block_info;
};
int semantic_fd;
public:
typedef typename inner_serializer_t::private_dynamic_config_t private_dynamic_config_t;
typedef typename inner_serializer_t::dynamic_config_t dynamic_config_t;
typedef typename inner_serializer_t::static_config_t static_config_t;
static void create(dynamic_config_t *config, private_dynamic_config_t *private_config, static_config_t *static_config) {
inner_serializer_t::create(config, private_config, static_config);
}
semantic_checking_serializer_t(dynamic_config_t *config, private_dynamic_config_t *private_config)
: inner_serializer(config, private_config),
last_write_started(0), last_write_callbacked(0),
semantic_fd(-1)
{
semantic_fd = open(private_config->semantic_filename.c_str(),
O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if (semantic_fd == INVALID_FD)
fail_due_to_user_error("Inaccessible semantic checking file: \"%s\": %s", private_config->semantic_filename.c_str(), strerror(errno));
// fill up the blocks from the semantic checking file
int res = -1;
do {
persisted_block_info_t buf;
res = read(semantic_fd, &buf, sizeof(buf));
guarantee_err(res != -1, "Could not read from the semantic checker file");
if(res == sizeof(persisted_block_info_t)) { // XXX (rntz) shouldn't it be an error if this is not the case?
blocks.set(buf.block_id.value, buf.block_info);
}
} while(res == sizeof(persisted_block_info_t));
}
~semantic_checking_serializer_t() {
close(semantic_fd);
}
typedef typename inner_serializer_t::check_callback_t check_callback_t;
static void check_existing(const char *db_path, check_callback_t *cb) {
inner_serializer_t::check_existing(db_path, cb);
}
void *malloc() {
return inner_serializer.malloc();
}
void *clone(void *data) {
return inner_serializer.clone(data);
}
void free(void *ptr) {
inner_serializer.free(ptr);
}
file_t::account_t *make_io_account(int priority, int outstanding_requests_limit = UNLIMITED_OUTSTANDING_REQUESTS) {
return inner_serializer.make_io_account(priority, outstanding_requests_limit);
}
/* For reads, we check to make sure that the data we get back in the read is
consistent with what was last written there. */
struct reader_t :
public read_callback_t
{
semantic_checking_serializer_t *parent;
block_id_t block_id;
void *buf;
block_info_t expected_block_state;
read_callback_t *callback;
reader_t(semantic_checking_serializer_t *parent, block_id_t block_id, void *buf, block_info_t expected_block_state)
: parent(parent), block_id(block_id), buf(buf), expected_block_state(expected_block_state) {}
void on_serializer_read() {
/* Make sure that the value that the serializer returned was valid */
crc_t actual_crc = parent->compute_crc(buf);
switch (expected_block_state.state) {
case block_info_t::state_unknown: {
/* We don't know what this block was supposed to contain, so we can't do any
verification */
break;
}
case block_info_t::state_deleted: {
unreachable("Cache asked for a deleted block, and serializer didn't complain.");
}
case block_info_t::state_have_crc: {
#ifdef SERIALIZER_DEBUG_PRINT
printf("Read %ld: %u\n", block_id, actual_crc);
#endif
guarantee(expected_block_state.crc == actual_crc, "Serializer returned bad value for block ID %u", block_id.value);
break;
}
default:
unreachable();
}
if (callback) callback->on_serializer_read();
delete this;
}
};
bool do_read(block_id_t block_id, void *buf, file_t::account_t *io_account, read_callback_t *callback) {
#ifdef SERIALIZER_DEBUG_PRINT
printf("Reading %ld\n", block_id);
#endif
reader_t *reader = new reader_t(this, block_id, buf, blocks.get(block_id.value));
reader->callback = NULL;
if (inner_serializer.do_read(block_id, buf, io_account, reader)) {
reader->on_serializer_read();
return true;
} else {
reader->callback = callback;
return false;
}
}
ser_transaction_id_t get_current_transaction_id(block_id_t block_id, const void* buf) {
// TODO: Implement some checking for this operation
return inner_serializer.get_current_transaction_id(block_id, buf);
}
/* For writes, we make sure that the writes come back in the same order that
we send them to the serializer. */
struct writer_t :
public write_txn_callback_t
{
semantic_checking_serializer_t *parent;
int version;
write_txn_callback_t *callback;
writer_t(semantic_checking_serializer_t *parent, int version)
: parent(parent), version(version) {}
void on_serializer_write_txn() {
guarantee(parent->last_write_callbacked == version-1, "Serializer completed writes in the wrong order.");
parent->last_write_callbacked = version;
if (callback) callback->on_serializer_write_txn();
delete this;
}
};
bool do_write(write_t *writes, int num_writes, file_t::account_t *io_account, write_txn_callback_t *callback, write_tid_callback_t *tid_callback = NULL) {
for (int i = 0; i < num_writes; i++) {
if (!writes[i].buf_specified) continue;
block_info_t b;
memset(&b, 0, sizeof(b)); // make valgrind happy
if (writes[i].buf) {
b.state = block_info_t::state_have_crc;
b.crc = compute_crc(writes[i].buf);
#ifdef SERIALIZER_DEBUG_PRINT
printf("Writing %ld: %u\n", writes[i].block_id, b.crc);
#endif
} else {
b.state = block_info_t::state_deleted;
#ifdef SERIALIZER_DEBUG_PRINT
printf("Deleting %ld\n", writes[i].block_id);
#endif
}
blocks.set(writes[i].block_id.value, b);
// Add the block to the semantic checker file
persisted_block_info_t buf;
#ifdef VALGRIND
memset(&buf, 0, sizeof(buf)); // make valgrind happy
#endif
buf.block_id = writes[i].block_id;
buf.block_info = b;
int res = write(semantic_fd, &buf, sizeof(buf));
guarantee_err(res == sizeof(buf), "Could not write data to semantic checker file");
}
writer_t *writer = new writer_t(this, ++last_write_started);
writer->callback = NULL;
if (inner_serializer.do_write(writes, num_writes, io_account, writer, tid_callback)) {
writer->on_serializer_write_txn();
return true;
} else {
writer->callback = callback;
return false;
}
}
block_size_t get_block_size() {
return inner_serializer.get_block_size();
}
block_id_t max_block_id() {
return inner_serializer.max_block_id();
}
bool block_in_use(block_id_t id) {
bool in_use = inner_serializer.block_in_use(id);
switch (blocks.get(id.value).state) {
case block_info_t::state_unknown: break;
case block_info_t::state_deleted: rassert(!in_use); break;
case block_info_t::state_have_crc: rassert(in_use); break;
default: unreachable();
}
return in_use;
}
repli_timestamp_t get_recency(block_id_t id) {
return inner_serializer.get_recency(id);
}
bool register_read_ahead_cb(read_ahead_callback_t *cb) {
// Ignore this, it might make the checking ineffective...
}
bool unregister_read_ahead_cb(read_ahead_callback_t *cb) {
return false;
}
struct shutdown_callback_t {
virtual void on_serializer_shutdown(semantic_checking_serializer_t *) = 0;
virtual ~shutdown_callback_t() {}
};
bool shutdown(shutdown_callback_t *cb) {
shutdown_callback = cb;
return inner_serializer.shutdown(this);
}
private:
shutdown_callback_t *shutdown_callback;
void on_serializer_shutdown(inner_serializer_t *ser) {
if (shutdown_callback) shutdown_callback->on_serializer_shutdown(this);
}
public:
typedef typename inner_serializer_t::gc_disable_callback_t gc_disable_callback_t;
bool disable_gc(gc_disable_callback_t *cb) {
return inner_serializer.disable_gc(cb);
}
bool enable_gc() {
return inner_serializer.enable_gc();
}
};
#endif /* __SERIALIZER_SEMANTIC_CHECKING_HPP__ */
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <stdlib.h>
#include <string>
#include <ros/publisher.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
pcl::PointCloud<pcl::PointXYZ>::Ptr map_cloud;
ros::Publisher _pointcloud_pub;
void publish_map()
{
}
void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)
{
}
int main(int argc, char** argv)
{
map_cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());
ros::init(argc, argv, "global_mapper");
ros::NodeHandle nh;
std::string topics;
std::list<ros::Subscriber> subs;
ros::NodeHandle pNh("~");
if(!pNh.hasParam("topics"))
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
pNh.getParam("topics", topics);
if(topics.empty())
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
std::istringstream iss(topics);
std::vector<std::string> tokens { std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };
for(auto topic : tokens)
{
ROS_INFO_STREAM("Mapper subscribing to " << topic);
subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ> >(topic, 1, boost::bind(frame_callback, _1, topic)));
}
map_cloud->header.frame_id = "/map";
_pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ> >("/map", 1);
ros::spin();
}<commit_msg>Included icp algorithm for global mapping<commit_after>#include <ros/ros.h>
#include <stdlib.h>
#include <string>
#include <ros/publisher.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/icp.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
pcl::PointCloud<pcl::PointXYZ>::Ptr global_map;
ros::Publisher _pointcloud_pub;
tf::TransformListener *tf_listener;
std::set<std::string> frames_seen;
void icp_transform(pcl::PointCloud<pcl::PointXYZ>::Ptr input) {
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputSource(input);
icp.setInputTarget(global_map);
pcl::PointCloud<pcl::PointXYZ> Final;
icp.align(Final);
*global_map = Final;
}
void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr transformed;
tf::StampedTransform transform;
if(frames_seen.find(msg->header.frame_id) == frames_seen.end())
{
frames_seen.insert(msg->header.frame_id);
tf_listener->waitForTransform("/map", msg->header.frame_id, ros::Time(0), ros::Duration(5));
}
tf_listener->lookupTransform("/map", msg->header.frame_id, ros::Time(0), transform);
pcl_ros::transformPointCloud(*msg, *transformed, transform);
for (auto point : *transformed) {
point.z = 0;
}
icp_transform(transformed);
_pointcloud_pub.publish(global_map);
}
int main(int argc, char** argv)
{
global_map = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());
ros::init(argc, argv, "global_mapper");
ros::NodeHandle nh;
tf_listener = new tf::TransformListener();
std::string topics;
std::list<ros::Subscriber> subs;
ros::NodeHandle pNh("~");
if(!pNh.hasParam("topics"))
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
pNh.getParam("topics", topics);
if(topics.empty())
ROS_WARN_STREAM("No topics specified for mapper. No map will be generated.");
std::istringstream iss(topics);
std::vector<std::string> tokens { std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };
for(auto topic : tokens)
{
ROS_INFO_STREAM("Mapper subscribing to " << topic);
subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ> >(topic, 1, boost::bind(frame_callback, _1, topic)));
}
global_map->header.frame_id = "/map";
_pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ> >("/map", 1);
ros::spin();
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBlockItem.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkBlockItem.h"
// Get my new commands
#include "vtkCommand.h"
#include "vtkContext2D.h"
#include "vtkContextScene.h"
#include "vtkPen.h"
#include "vtkBrush.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkBlockItem);
//-----------------------------------------------------------------------------
vtkBlockItem::vtkBlockItem()
{
this->Label = NULL;
this->MouseOver = false;
this->MouseButtonPressed = -1;
this->scalarFunction = NULL;
}
//-----------------------------------------------------------------------------
vtkBlockItem::~vtkBlockItem()
{
this->SetLabel(NULL);
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::Paint(vtkContext2D *painter)
{
painter->GetTextProp()->SetVerticalJustificationToCentered();
painter->GetTextProp()->SetJustificationToCentered();
painter->GetTextProp()->SetColor(0.0, 0.0, 0.0);
painter->GetTextProp()->SetFontSize(24);
painter->GetPen()->SetColor(0, 0, 0);
if (this->MouseOver)
{
painter->GetBrush()->SetColor(255, 0, 0);
}
else
{
painter->GetBrush()->SetColor(0, 255, 0);
}
painter->DrawRect(this->Dimensions[0], this->Dimensions[1],
this->Dimensions[2], this->Dimensions[3]);
int x = static_cast<int>(this->Dimensions[0] + 0.5 * this->Dimensions[2]);
int y = static_cast<int>(this->Dimensions[1] + 0.5 * this->Dimensions[3]);
painter->DrawString(x, y, this->Label);
if (this->scalarFunction)
{
// We have a function pointer - do something...
;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::Hit(const vtkContextMouseEvent &mouse)
{
if (mouse.Pos[0] > this->Dimensions[0] &&
mouse.Pos[0] < this->Dimensions[0]+this->Dimensions[2] &&
mouse.Pos[1] > this->Dimensions[1] &&
mouse.Pos[1] < this->Dimensions[1]+this->Dimensions[3])
{
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseEnterEvent(const vtkContextMouseEvent &)
{
this->MouseOver = true;
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseMoveEvent(const vtkContextMouseEvent &mouse)
{
int deltaX = static_cast<int>(mouse.Pos[0] - this->LastPosition[0]);
int deltaY = static_cast<int>(mouse.Pos[1] - this->LastPosition[1]);
this->LastPosition[0] = mouse.Pos[0];
this->LastPosition[1] = mouse.Pos[1];
if (this->MouseButtonPressed == 0)
{
// Move the block by this amount
this->Dimensions[0] += deltaX;
this->Dimensions[1] += deltaY;
return true;
}
else if (this->MouseButtonPressed == 1)
{
// Resize the block by this amount
this->Dimensions[0] += deltaX;
this->Dimensions[1] += deltaY;
this->Dimensions[2] -= deltaX;
this->Dimensions[3] -= deltaY;
return true;
}
else if (this->MouseButtonPressed == 2)
{
// Resize the block by this amount
this->Dimensions[2] += deltaX;
this->Dimensions[3] += deltaY;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseLeaveEvent(const vtkContextMouseEvent &)
{
this->MouseOver = false;
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseButtonPressEvent(const vtkContextMouseEvent &mouse)
{
this->MouseButtonPressed = mouse.Button;
this->LastPosition[0] = mouse.Pos[0];
this->LastPosition[1] = mouse.Pos[1];
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseButtonReleaseEvent(const vtkContextMouseEvent &)
{
this->MouseButtonPressed = -1;
return true;
}
void vtkBlockItem::SetScalarFunctor(double (*ScalarFunction)(double, double))
{
this->scalarFunction = ScalarFunction;
}
//-----------------------------------------------------------------------------
void vtkBlockItem::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG: Mark the scene as dirty when necessary.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBlockItem.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkBlockItem.h"
// Get my new commands
#include "vtkCommand.h"
#include "vtkContext2D.h"
#include "vtkContextScene.h"
#include "vtkPen.h"
#include "vtkBrush.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkBlockItem);
//-----------------------------------------------------------------------------
vtkBlockItem::vtkBlockItem()
{
this->Label = NULL;
this->MouseOver = false;
this->MouseButtonPressed = -1;
this->scalarFunction = NULL;
}
//-----------------------------------------------------------------------------
vtkBlockItem::~vtkBlockItem()
{
this->SetLabel(NULL);
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::Paint(vtkContext2D *painter)
{
painter->GetTextProp()->SetVerticalJustificationToCentered();
painter->GetTextProp()->SetJustificationToCentered();
painter->GetTextProp()->SetColor(0.0, 0.0, 0.0);
painter->GetTextProp()->SetFontSize(24);
painter->GetPen()->SetColor(0, 0, 0);
if (this->MouseOver)
{
painter->GetBrush()->SetColor(255, 0, 0);
}
else
{
painter->GetBrush()->SetColor(0, 255, 0);
}
painter->DrawRect(this->Dimensions[0], this->Dimensions[1],
this->Dimensions[2], this->Dimensions[3]);
int x = static_cast<int>(this->Dimensions[0] + 0.5 * this->Dimensions[2]);
int y = static_cast<int>(this->Dimensions[1] + 0.5 * this->Dimensions[3]);
painter->DrawString(x, y, this->Label);
if (this->scalarFunction)
{
// We have a function pointer - do something...
;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::Hit(const vtkContextMouseEvent &mouse)
{
if (mouse.Pos[0] > this->Dimensions[0] &&
mouse.Pos[0] < this->Dimensions[0]+this->Dimensions[2] &&
mouse.Pos[1] > this->Dimensions[1] &&
mouse.Pos[1] < this->Dimensions[1]+this->Dimensions[3])
{
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseEnterEvent(const vtkContextMouseEvent &)
{
this->MouseOver = true;
this->GetScene()->SetDirty(true);
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseMoveEvent(const vtkContextMouseEvent &mouse)
{
int deltaX = static_cast<int>(mouse.Pos[0] - this->LastPosition[0]);
int deltaY = static_cast<int>(mouse.Pos[1] - this->LastPosition[1]);
this->LastPosition[0] = mouse.Pos[0];
this->LastPosition[1] = mouse.Pos[1];
if (this->MouseButtonPressed == 0)
{
// Move the block by this amount
this->Dimensions[0] += deltaX;
this->Dimensions[1] += deltaY;
this->GetScene()->SetDirty(true);
return true;
}
else if (this->MouseButtonPressed == 1)
{
// Resize the block by this amount
this->Dimensions[0] += deltaX;
this->Dimensions[1] += deltaY;
this->Dimensions[2] -= deltaX;
this->Dimensions[3] -= deltaY;
this->GetScene()->SetDirty(true);
return true;
}
else if (this->MouseButtonPressed == 2)
{
// Resize the block by this amount
this->Dimensions[2] += deltaX;
this->Dimensions[3] += deltaY;
this->GetScene()->SetDirty(true);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseLeaveEvent(const vtkContextMouseEvent &)
{
this->MouseOver = false;
this->GetScene()->SetDirty(true);
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseButtonPressEvent(const vtkContextMouseEvent &mouse)
{
this->MouseButtonPressed = mouse.Button;
this->LastPosition[0] = mouse.Pos[0];
this->LastPosition[1] = mouse.Pos[1];
return true;
}
//-----------------------------------------------------------------------------
bool vtkBlockItem::MouseButtonReleaseEvent(const vtkContextMouseEvent &)
{
this->MouseButtonPressed = -1;
return true;
}
void vtkBlockItem::SetScalarFunctor(double (*ScalarFunction)(double, double))
{
this->scalarFunction = ScalarFunction;
}
//-----------------------------------------------------------------------------
void vtkBlockItem::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "Include/AppDelegate.h"
#include "Include/HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
typedef struct
{
Size size;
char directory[100];
}jazzResource_t;
const jazzResource_t SDResource = { Size(480, 270), "SD" };
const jazzResource_t HDResource = { Size(960, 540), "HD" };
const jazzResource_t HDRResource = { Size(1920, 1080), "HDR" };
const Size designResolutionSize = Size(1920, 1080);
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
auto fileUtils = FileUtils::getInstance();
std::vector <std::string> resourceFolders;
if(!glview) {
glview = GLViewImpl::create("Taotris");
//glview->setDesignResolutionSize(1920, 1080, (ResolutionPolicy) 3 );
director->setOpenGLView(glview);
/* * This function is needed in order to create a design space.
* The main idea of having a Design Space is to draw everything using
* a single resolution (E.g. using always the same coordinates, and then
* transform these coordinates in the screen space.
*
* In this way you do a double passage: first you scale graphical
* resources to the design space, then you scale from design space
* to screen space. Obviously sprites are not converted two times, it's
* just a computation. But in this way you don't have to do computations
* for scaling resources or game elements.
*
* Put it AFTER the initialisation of the OpenGL view. I'm dumb.
*/
//glview->setFrameSize(854, 480);
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::SHOW_ALL);
//glview->setDesignResolutionSize(1920, 1080, ResolutionPolicy::SHOW_ALL);
}
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
auto screenSize = director->getOpenGLView()->getFrameSize();
std::cout << "getVisibleSize " << screenSize.height;
// loads the spritesheet into the manager
auto squareCache = SpriteFrameCache::getInstance();
if (screenSize.height > 540) {
resourceFolders.push_back(HDRResource.directory);
director->setContentScaleFactor(HDRResource.size.height/1080.0);
} else if (screenSize.height > 270) {
resourceFolders.push_back(HDResource.directory);
director->setContentScaleFactor(HDResource.size.height/1080.0);
} else {
resourceFolders.push_back(SDResource.directory);
director->setContentScaleFactor(SDResource.size.height/1080.0);
}
fileUtils->setSearchPaths(resourceFolders);
squareCache->addSpriteFramesWithFile("TaotrisRes.plist");
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
<commit_msg>Aaaaand now it's working.<commit_after>#include <iostream>
#include "Include/AppDelegate.h"
#include "Include/HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
typedef struct
{
Size size;
char directory[100];
}jazzResource_t;
const jazzResource_t SDResource = { Size(480, 270), "SD" };
const jazzResource_t HDResource = { Size(960, 540), "HD" };
const jazzResource_t HDRResource = { Size(1920, 1080), "HDR" };
const Size designResolutionSize = Size(1920, 1080);
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
auto fileUtils = FileUtils::getInstance();
std::vector <std::string> resourceFolders;
if(!glview) {
glview = GLViewImpl::create("Taotris");
//glview->setDesignResolutionSize(1920, 1080, (ResolutionPolicy) 3 );
director->setOpenGLView(glview);
/* * This function is needed in order to create a design space.
* The main idea of having a Design Space is to draw everything using
* a single resolution (E.g. using always the same coordinates, and then
* transform these coordinates in the screen space.
*
* In this way you do a double passage: first you scale graphical
* resources to the design space, then you scale from design space
* to screen space. Obviously sprites are not converted two times, it's
* just a computation. But in this way you don't have to do computations
* for scaling resources or game elements.
*
* Put it AFTER the initialisation of the OpenGL view. I'm dumb.
*/
glview->setFrameSize(854, 480);
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::SHOW_ALL);
//glview->setDesignResolutionSize(1920, 1080, ResolutionPolicy::SHOW_ALL);
}
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
auto screenSize = director->getOpenGLView()->getFrameSize();
std::cout << "getVisibleSize " << screenSize.height;
// loads the spritesheet into the manager
auto squareCache = SpriteFrameCache::getInstance();
if (screenSize.height > 540) {
resourceFolders.push_back(HDRResource.directory);
director->setContentScaleFactor(HDRResource.size.height/1080.0);
} else if (screenSize.height > 270) {
resourceFolders.push_back(HDResource.directory);
director->setContentScaleFactor(HDResource.size.height/1080.0);
} else {
resourceFolders.push_back(SDResource.directory);
director->setContentScaleFactor(SDResource.size.height/1080.0);
}
fileUtils->setSearchPaths(resourceFolders);
squareCache->addSpriteFramesWithFile("TaotrisRes.plist");
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
<|endoftext|> |
<commit_before>#include "GameManager.h"
#include "GameLogic.h"
#include "NetworkLogic.h"
CGameManager* CGameManager::m_pInstance = nullptr;
CGameManager::CGameManager(void)
{
m_IsOnlineGame = false;
m_IsUpdated = false;
m_GameData = nullptr;
}
CGameManager::~CGameManager(void)
{
}
CGameManager* CGameManager::GetInstance()
{
if (m_pInstance == nullptr)
{
m_pInstance = new CGameManager();
}
return m_pInstance;
}
void CGameManager::ReleaseInstance()
{
}
bool CGameManager::init()
{
CGameLogic::GetInstance()->init();
m_GameData = cocos2d::CCUserDefault::sharedUserDefault();
// ӵͰ ʱⰪ ؼ Ѵ.
if (!m_GameData->isXMLFileExist() )
{
m_GameData->setStringForKey("tokenId", "temptoken 1");
m_GameData->setStringForKey("usersName", "noname 1");
m_GameData->setBoolForKey("two", true);
m_GameData->setBoolForKey("three", true);
m_GameData->setBoolForKey("four", true);
}
return true;
}
void CGameManager::SetPlayerName(int playerId, const std::string& playerName )
{
if (m_IsOnlineGame)
{
// ٸ ̸ ƿ
// ̸ shared data ϹǷ Լ
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetPlayerName(playerId,playerName) );
}
}
const std::string& CGameManager::GetPlayerName(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerName(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerName(playerIdx);
}
}
int CGameManager::GetCurrentPlayerNumber()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetCurrentPlayerNumber();
}
else
{
return CGameLogic::GetInstance()->GetCurrentPlayerNumber();
}
}
//!!
//̰ ȣϴ Լ ƴ
void CGameManager::SetCurrentPlayerNumber(int PlayerNumber)
{
if (m_IsOnlineGame)
{
// player number matching thread ؼ ϹǷ
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetCurrentPlayerNumber(PlayerNumber) );
}
}
int CGameManager::GetWinnerIdx()
{
if (m_IsOnlineGame)
{
// server ʿ ´.
// winner idx - 쵵 ؾ
}
else
{
return CGameLogic::GetInstance()->GetWinnerIdx();
}
}
int CGameManager::GetElementCount(int playerIdx, MO_ITEM item)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerResult(playerIdx, item);
}
else
{
return CGameLogic::GetInstance()->GetPlayerResult(playerIdx, item);
}
}
int CGameManager::GetTotalScore(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerTotalScore(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerTotalScore(playerIdx);
}
}
const std::string& CGameManager::GetCharacterResultFaceFileName(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerResultImage(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerResultImage(playerIdx);
}
}
void CGameManager::SelectCharacter( int characterId )
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SelectCharacter(characterId);
}
else
{
SetUpdateFlag( CGameLogic::GetInstance()->SetPlayerCharacterId( characterId ) );
}
}
bool CGameManager::isCharacterSelected( int characterId )
{
if (m_IsOnlineGame)
{
// ʿѰ?
return false;
}
else
{
return CGameLogic::GetInstance()->isCharacterSelected(characterId);
}
}
int CGameManager::GetCharacterId( int playerId )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerCharacterId( playerId );
}
else
{
return CGameLogic::GetInstance()->GetPlayerCharacterId( playerId );
}
}
int CGameManager::GetPlayerIdByTurn( int currentTurn )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerIdByTurn(currentTurn);
}
else
{
return CGameLogic::GetInstance()->GetPlayerIdByTurn(currentTurn);
}
}
void CGameManager::StartGame()
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SettingReady();
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->StartGame() );
}
}
void CGameManager::SetMapSize( MapSelect mapSize )
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SetMapSize(mapSize);
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetSelectedMapSize( mapSize ) );
}
}
bool CGameManager::IsEnd()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->IsEnd();
}
else
{
return CGameLogic::GetInstance()->IsEnd();
}
}
MapSelect CGameManager::GetSelectedMapSize()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetSelectedMapSize();
}
else
{
return CGameLogic::GetInstance()->GetSelectedMapSize();
}
}
MO_TYPE CGameManager::GetMapType( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetMapType(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetMapType(indexedPosition);
}
}
MO_OWNER CGameManager::GetMapOwner( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetMapOwner(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetMapOwner(indexedPosition);
}
}
MO_ITEM CGameManager::GetItem( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetItem(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetItem(indexedPosition);
}
}
void CGameManager::DrawLine( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->DrawLine(indexedPosition);
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->EventHandle(indexedPosition) );
CCLOG("draw line : %d, %d",indexedPosition.m_PosI,indexedPosition.m_PosJ);
}
}
const std::string& CGameManager::GetCharacterPlayFaceById( int playerIdx )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerPlayImage(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerPlayImage(playerIdx);
}
}
MO_TYPE CGameManager::IsConnected(IndexedPosition indexedPosition)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->IsConnected(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->IsConnected(indexedPosition);
}
}
int CGameManager::GetPlayerTurn( int playerId )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerTurnById(playerId);
}
else
{
return CGameLogic::GetInstance()->GetPlayerTurnById(playerId);
}
}
int CGameManager::GetCurrentPlayerId()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerIdByCurrentTurn();
}
else
{
return CGameLogic::GetInstance()->GetPlayerIdByCurrentTurn();
}
}
int CGameManager::GetTileAnimationTurn(IndexedPosition indexedPosition)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetTileAnimationTurn(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetTileAnimationTurn(indexedPosition);
}
}
bool CGameManager::IsPlayerNumberAndMapSeleted()
{
if (m_IsOnlineGame)
{
// ä ϰ ϸ true
// Ͱ ƴ ڽ Ȯؼ true / false
// Ƽ NEXT ư return false
return false;
}
else
{
return CGameLogic::GetInstance()->IsPlayerNumberAndMapSeleted();
}
}
int CGameManager::GetPlayerNumberOfThisGame()
{
if (m_IsOnlineGame)
{
// ʿѰ?
}
else
{
return CGameLogic::GetInstance()->GetPlayerNumberOfThisGame();
}
}
bool CGameManager::GetStatusPlayerNumber(int playerNumber)
{
std::string key = "";
switch (playerNumber)
{
case 2:
key = "two";
break;
case 3:
key = "three";
break;
case 4:
key = "four";
break;
default:
break;
}
return m_GameData->getBoolForKey(key.c_str() );
}
void CGameManager::SetPlayerNumberOfThisGame( int PlayerNumber )
{
if (m_IsOnlineGame)
{
// shared data player number flags
std::string key = "";
switch (PlayerNumber)
{
case 2:
key = "two";
break;
case 3:
key = "three";
break;
case 4:
key = "four";
break;
default:
break;
}
bool value = m_GameData->getBoolForKey(key.c_str() );
m_GameData->setBoolForKey(key.c_str(), !value);
SetUpdateFlag(true);
}
else
{
CGameLogic::GetInstance()->SetPlayerNumberOfThisGame(PlayerNumber);
}
}
void CGameManager::SetOnlineMode(bool flag)
{
m_IsOnlineGame = flag;
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SetCurrentNetworkPhase(NP_PLAYER_NUMBER_SETTING);
}
}
NetworkPhase CGameManager::GetCurrentNetworkPhase()
{
return CNetworkLogic::GetInstance()->GetCurrentNetworkPhase();
}
bool CGameManager::InitNetworkLogic()
{
return CNetworkLogic::GetInstance()->Init();
}
void CGameManager::Login()
{
CNetworkLogic::GetInstance()->Login();
}
bool CGameManager::IsNextButtonSelected()
{
if (m_IsOnlineGame)
{
// Logic
// !! Single !
return CGameLogic::GetInstance()->IsNextButtonSelected();
}
else
{
return CGameLogic::GetInstance()->IsNextButtonSelected();
}
}
void CGameManager::SetNextButtonSelected()
{
if (m_IsOnlineGame)
{
// Logic
}
else
{
CGameLogic::GetInstance()->SetNextButtonSelected();
}
}
void CGameManager::TimeOut()
{
if (m_IsOnlineGame)
{
// Logic
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->TimeOut());
}
}
std::string CGameManager::GetUsersName()
{
return m_GameData->getStringForKey("usersName");
}
std::string CGameManager::GetTokenId()
{
return m_GameData->getStringForKey("tokenId");
}
bool CGameManager::GetPlayerNumberSelection(int number)
{
switch (number)
{
case 2:
return m_GameData->getBoolForKey("two");
break;
case 3:
return m_GameData->getBoolForKey("three");
break;
case 4:
return m_GameData->getBoolForKey("four");
break;
default:
break;
}
return false;
}
void CGameManager::SetUsersName(std::string name)
{
m_GameData->setStringForKey("usersName", name);
}
void CGameManager::SetTokenId(std::string tokenId)
{
m_GameData->setStringForKey("tokenId", tokenId);
}
void CGameManager::SetPlayerNumberSelection(int number, bool selection)
{
switch (number)
{
case 2:
return m_GameData->setBoolForKey("two", selection);
break;
case 3:
return m_GameData->setBoolForKey("three", selection);
break;
case 4:
return m_GameData->setBoolForKey("four", selection);
break;
default:
break;
}
}<commit_msg>sharedUserDefault init 수정 <commit_after>#include "GameManager.h"
#include "GameLogic.h"
#include "NetworkLogic.h"
CGameManager* CGameManager::m_pInstance = nullptr;
CGameManager::CGameManager(void)
{
m_IsOnlineGame = false;
m_IsUpdated = false;
m_GameData = nullptr;
}
CGameManager::~CGameManager(void)
{
}
CGameManager* CGameManager::GetInstance()
{
if (m_pInstance == nullptr)
{
m_pInstance = new CGameManager();
}
return m_pInstance;
}
void CGameManager::ReleaseInstance()
{
}
bool CGameManager::init()
{
CGameLogic::GetInstance()->init();
m_GameData = cocos2d::CCUserDefault::sharedUserDefault();
// ӵͰ ʱⰪ ؼ Ѵ.
if (!m_GameData->getBoolForKey("initialized") )
{
m_GameData->setStringForKey("tokenId", "temptoken 1");
m_GameData->setStringForKey("usersName", "noname 1");
m_GameData->setBoolForKey("two", true);
m_GameData->setBoolForKey("three", true);
m_GameData->setBoolForKey("four", true);
m_GameData->setBoolForKey("initialized", true);
}
return true;
}
void CGameManager::SetPlayerName(int playerId, const std::string& playerName )
{
if (m_IsOnlineGame)
{
// ٸ ̸ ƿ
// ̸ shared data ϹǷ Լ
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetPlayerName(playerId,playerName) );
}
}
const std::string& CGameManager::GetPlayerName(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerName(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerName(playerIdx);
}
}
int CGameManager::GetCurrentPlayerNumber()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetCurrentPlayerNumber();
}
else
{
return CGameLogic::GetInstance()->GetCurrentPlayerNumber();
}
}
//!!
//̰ ȣϴ Լ ƴ
void CGameManager::SetCurrentPlayerNumber(int PlayerNumber)
{
if (m_IsOnlineGame)
{
// player number matching thread ؼ ϹǷ
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetCurrentPlayerNumber(PlayerNumber) );
}
}
int CGameManager::GetWinnerIdx()
{
if (m_IsOnlineGame)
{
// server ʿ ´.
// winner idx - 쵵 ؾ
}
else
{
return CGameLogic::GetInstance()->GetWinnerIdx();
}
}
int CGameManager::GetElementCount(int playerIdx, MO_ITEM item)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerResult(playerIdx, item);
}
else
{
return CGameLogic::GetInstance()->GetPlayerResult(playerIdx, item);
}
}
int CGameManager::GetTotalScore(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerTotalScore(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerTotalScore(playerIdx);
}
}
const std::string& CGameManager::GetCharacterResultFaceFileName(int playerIdx)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerResultImage(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerResultImage(playerIdx);
}
}
void CGameManager::SelectCharacter( int characterId )
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SelectCharacter(characterId);
}
else
{
SetUpdateFlag( CGameLogic::GetInstance()->SetPlayerCharacterId( characterId ) );
}
}
bool CGameManager::isCharacterSelected( int characterId )
{
if (m_IsOnlineGame)
{
// ʿѰ?
return false;
}
else
{
return CGameLogic::GetInstance()->isCharacterSelected(characterId);
}
}
int CGameManager::GetCharacterId( int playerId )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerCharacterId( playerId );
}
else
{
return CGameLogic::GetInstance()->GetPlayerCharacterId( playerId );
}
}
int CGameManager::GetPlayerIdByTurn( int currentTurn )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerIdByTurn(currentTurn);
}
else
{
return CGameLogic::GetInstance()->GetPlayerIdByTurn(currentTurn);
}
}
void CGameManager::StartGame()
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SettingReady();
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->StartGame() );
}
}
void CGameManager::SetMapSize( MapSelect mapSize )
{
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SetMapSize(mapSize);
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->SetSelectedMapSize( mapSize ) );
}
}
bool CGameManager::IsEnd()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->IsEnd();
}
else
{
return CGameLogic::GetInstance()->IsEnd();
}
}
MapSelect CGameManager::GetSelectedMapSize()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetSelectedMapSize();
}
else
{
return CGameLogic::GetInstance()->GetSelectedMapSize();
}
}
MO_TYPE CGameManager::GetMapType( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetMapType(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetMapType(indexedPosition);
}
}
MO_OWNER CGameManager::GetMapOwner( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetMapOwner(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetMapOwner(indexedPosition);
}
}
MO_ITEM CGameManager::GetItem( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetItem(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetItem(indexedPosition);
}
}
void CGameManager::DrawLine( IndexedPosition indexedPosition )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->DrawLine(indexedPosition);
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->EventHandle(indexedPosition) );
CCLOG("draw line : %d, %d",indexedPosition.m_PosI,indexedPosition.m_PosJ);
}
}
const std::string& CGameManager::GetCharacterPlayFaceById( int playerIdx )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerPlayImage(playerIdx);
}
else
{
return CGameLogic::GetInstance()->GetPlayerPlayImage(playerIdx);
}
}
MO_TYPE CGameManager::IsConnected(IndexedPosition indexedPosition)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->IsConnected(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->IsConnected(indexedPosition);
}
}
int CGameManager::GetPlayerTurn( int playerId )
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerTurnById(playerId);
}
else
{
return CGameLogic::GetInstance()->GetPlayerTurnById(playerId);
}
}
int CGameManager::GetCurrentPlayerId()
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetPlayerIdByCurrentTurn();
}
else
{
return CGameLogic::GetInstance()->GetPlayerIdByCurrentTurn();
}
}
int CGameManager::GetTileAnimationTurn(IndexedPosition indexedPosition)
{
if (m_IsOnlineGame)
{
return CNetworkLogic::GetInstance()->GetTileAnimationTurn(indexedPosition);
}
else
{
return CGameLogic::GetInstance()->GetTileAnimationTurn(indexedPosition);
}
}
bool CGameManager::IsPlayerNumberAndMapSeleted()
{
if (m_IsOnlineGame)
{
// ä ϰ ϸ true
// Ͱ ƴ ڽ Ȯؼ true / false
// Ƽ NEXT ư return false
return false;
}
else
{
return CGameLogic::GetInstance()->IsPlayerNumberAndMapSeleted();
}
}
int CGameManager::GetPlayerNumberOfThisGame()
{
if (m_IsOnlineGame)
{
// ʿѰ?
}
else
{
return CGameLogic::GetInstance()->GetPlayerNumberOfThisGame();
}
}
bool CGameManager::GetStatusPlayerNumber(int playerNumber)
{
std::string key = "";
switch (playerNumber)
{
case 2:
key = "two";
break;
case 3:
key = "three";
break;
case 4:
key = "four";
break;
default:
break;
}
return m_GameData->getBoolForKey(key.c_str() );
}
void CGameManager::SetPlayerNumberOfThisGame( int PlayerNumber )
{
if (m_IsOnlineGame)
{
// shared data player number flags
std::string key = "";
switch (PlayerNumber)
{
case 2:
key = "two";
break;
case 3:
key = "three";
break;
case 4:
key = "four";
break;
default:
break;
}
bool value = m_GameData->getBoolForKey(key.c_str() );
m_GameData->setBoolForKey(key.c_str(), !value);
SetUpdateFlag(true);
}
else
{
CGameLogic::GetInstance()->SetPlayerNumberOfThisGame(PlayerNumber);
}
}
void CGameManager::SetOnlineMode(bool flag)
{
m_IsOnlineGame = flag;
if (m_IsOnlineGame)
{
CNetworkLogic::GetInstance()->SetCurrentNetworkPhase(NP_PLAYER_NUMBER_SETTING);
}
}
NetworkPhase CGameManager::GetCurrentNetworkPhase()
{
return CNetworkLogic::GetInstance()->GetCurrentNetworkPhase();
}
bool CGameManager::InitNetworkLogic()
{
return CNetworkLogic::GetInstance()->Init();
}
void CGameManager::Login()
{
CNetworkLogic::GetInstance()->Login();
}
bool CGameManager::IsNextButtonSelected()
{
if (m_IsOnlineGame)
{
// Logic
// !! Single !
return CGameLogic::GetInstance()->IsNextButtonSelected();
}
else
{
return CGameLogic::GetInstance()->IsNextButtonSelected();
}
}
void CGameManager::SetNextButtonSelected()
{
if (m_IsOnlineGame)
{
// Logic
}
else
{
CGameLogic::GetInstance()->SetNextButtonSelected();
}
}
void CGameManager::TimeOut()
{
if (m_IsOnlineGame)
{
// Logic
}
else
{
SetUpdateFlag(CGameLogic::GetInstance()->TimeOut());
}
}
std::string CGameManager::GetUsersName()
{
return m_GameData->getStringForKey("usersName");
}
std::string CGameManager::GetTokenId()
{
return m_GameData->getStringForKey("tokenId");
}
bool CGameManager::GetPlayerNumberSelection(int number)
{
switch (number)
{
case 2:
return m_GameData->getBoolForKey("two");
break;
case 3:
return m_GameData->getBoolForKey("three");
break;
case 4:
return m_GameData->getBoolForKey("four");
break;
default:
break;
}
return false;
}
void CGameManager::SetUsersName(std::string name)
{
m_GameData->setStringForKey("usersName", name);
}
void CGameManager::SetTokenId(std::string tokenId)
{
m_GameData->setStringForKey("tokenId", tokenId);
}
void CGameManager::SetPlayerNumberSelection(int number, bool selection)
{
switch (number)
{
case 2:
return m_GameData->setBoolForKey("two", selection);
break;
case 3:
return m_GameData->setBoolForKey("three", selection);
break;
case 4:
return m_GameData->setBoolForKey("four", selection);
break;
default:
break;
}
}<|endoftext|> |
<commit_before>#include <appbase/application.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/net_plugin/net_plugin.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "config.hpp"
using namespace appbase;
using namespace eosio;
namespace detail {
void configure_logging(const bfs::path& config_path)
{
try {
try {
fc::configure_logging(config_path);
} catch (...) {
elog("Error reloading logging.json");
throw;
}
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
// empty
}
}
} // namespace detail
void logging_conf_handler()
{
auto config_path = app().get_logging_conf();
ilog("Received HUP. Reloading logging configuration from ${p}.", ("p", config_path.string()));
if(fc::exists(config_path))
::detail::configure_logging(config_path);
fc::log_config::initialize_appenders( app().get_io_service() );
}
void initialize_logging()
{
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
fc::configure_logging(config_path); // intentionally allowing exceptions to escape
fc::log_config::initialize_appenders( app().get_io_service() );
app().set_sighup_callback(logging_conf_handler);
}
enum return_codes {
OTHER_FAIL = -2,
INITIALIZE_FAIL = -1,
SUCCESS = 0,
BAD_ALLOC = 1,
DATABASE_DIRTY = 2,
FIXED_REVERSIBLE = SUCCESS,
EXTRACTED_GENESIS = SUCCESS,
NODE_MANAGEMENT_SUCCESS = 5
};
int main(int argc, char** argv)
{
try {
app().set_version(eosio::nodeos::config::version);
auto root = fc::app_path();
app().set_default_data_dir(root / "eosio" / nodeos::config::node_executable_name / "data" );
app().set_default_config_dir(root / "eosio" / nodeos::config::node_executable_name / "config" );
http_plugin::set_defaults({
.default_unix_socket_path = "",
.default_http_port = 8888
});
if(!app().initialize<chain_plugin, net_plugin, producer_plugin>(argc, argv)) {
if(app().get_options().count("help") || app().get_options().count("version")) {
return SUCCESS;
}
return INITIALIZE_FAIL;
}
initialize_logging();
ilog("${name} version ${ver}", ("name", nodeos::config::node_executable_name)("ver", app().version_string()));
ilog("${name} using configuration file ${c}", ("name", nodeos::config::node_executable_name)("c", app().full_config_file_path().string()));
ilog("${name} data directory is ${d}", ("name", nodeos::config::node_executable_name)("d", app().data_dir().string()));
app().startup();
app().set_thread_priority_max();
app().exec();
} catch( const extract_genesis_state_exception& e ) {
return EXTRACTED_GENESIS;
} catch( const fixed_reversible_db_exception& e ) {
return FIXED_REVERSIBLE;
} catch( const node_management_success& e ) {
return NODE_MANAGEMENT_SUCCESS;
} catch( const fc::exception& e ) {
if( e.code() == fc::std_exception_code ) {
if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
}
}
elog( "${e}", ("e", e.to_detail_string()));
return OTHER_FAIL;
} catch( const boost::interprocess::bad_alloc& e ) {
elog("bad alloc");
return BAD_ALLOC;
} catch( const boost::exception& e ) {
elog("${e}", ("e",boost::diagnostic_information(e)));
return OTHER_FAIL;
} catch( const std::runtime_error& e ) {
if( std::string(e.what()).find("database dirty flag set") != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else {
elog( "${e}", ("e",e.what()));
}
return OTHER_FAIL;
} catch( const std::exception& e ) {
elog("${e}", ("e",e.what()));
return OTHER_FAIL;
} catch( ... ) {
elog("unknown exception");
return OTHER_FAIL;
}
ilog("${name} successfully exiting", ("name", nodeos::config::node_executable_name));
return SUCCESS;
}
<commit_msg>Restore default logging if logging.json is removed when SIGHUP.<commit_after>#include <appbase/application.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/net_plugin/net_plugin.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "config.hpp"
using namespace appbase;
using namespace eosio;
namespace detail {
void configure_logging(const bfs::path& config_path)
{
try {
try {
if( fc::exists( config_path ) ) {
fc::configure_logging( config_path );
} else {
fc::configure_logging( fc::logging_config::default_config() );
}
} catch (...) {
elog("Error reloading logging.json");
throw;
}
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
// empty
}
}
} // namespace detail
void logging_conf_handler()
{
auto config_path = app().get_logging_conf();
if( fc::exists( config_path ) ) {
ilog( "Received HUP. Reloading logging configuration from ${p}.", ("p", config_path.string()) );
} else {
ilog( "Received HUP. No log config found at ${p}, setting to default.", ("p", config_path.string()) );
}
::detail::configure_logging( config_path );
fc::log_config::initialize_appenders( app().get_io_service() );
}
void initialize_logging()
{
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
fc::configure_logging(config_path); // intentionally allowing exceptions to escape
fc::log_config::initialize_appenders( app().get_io_service() );
app().set_sighup_callback(logging_conf_handler);
}
enum return_codes {
OTHER_FAIL = -2,
INITIALIZE_FAIL = -1,
SUCCESS = 0,
BAD_ALLOC = 1,
DATABASE_DIRTY = 2,
FIXED_REVERSIBLE = SUCCESS,
EXTRACTED_GENESIS = SUCCESS,
NODE_MANAGEMENT_SUCCESS = 5
};
int main(int argc, char** argv)
{
try {
app().set_version(eosio::nodeos::config::version);
auto root = fc::app_path();
app().set_default_data_dir(root / "eosio" / nodeos::config::node_executable_name / "data" );
app().set_default_config_dir(root / "eosio" / nodeos::config::node_executable_name / "config" );
http_plugin::set_defaults({
.default_unix_socket_path = "",
.default_http_port = 8888
});
if(!app().initialize<chain_plugin, net_plugin, producer_plugin>(argc, argv)) {
if(app().get_options().count("help") || app().get_options().count("version")) {
return SUCCESS;
}
return INITIALIZE_FAIL;
}
initialize_logging();
ilog("${name} version ${ver}", ("name", nodeos::config::node_executable_name)("ver", app().version_string()));
ilog("${name} using configuration file ${c}", ("name", nodeos::config::node_executable_name)("c", app().full_config_file_path().string()));
ilog("${name} data directory is ${d}", ("name", nodeos::config::node_executable_name)("d", app().data_dir().string()));
app().startup();
app().set_thread_priority_max();
app().exec();
} catch( const extract_genesis_state_exception& e ) {
return EXTRACTED_GENESIS;
} catch( const fixed_reversible_db_exception& e ) {
return FIXED_REVERSIBLE;
} catch( const node_management_success& e ) {
return NODE_MANAGEMENT_SUCCESS;
} catch( const fc::exception& e ) {
if( e.code() == fc::std_exception_code ) {
if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
}
}
elog( "${e}", ("e", e.to_detail_string()));
return OTHER_FAIL;
} catch( const boost::interprocess::bad_alloc& e ) {
elog("bad alloc");
return BAD_ALLOC;
} catch( const boost::exception& e ) {
elog("${e}", ("e",boost::diagnostic_information(e)));
return OTHER_FAIL;
} catch( const std::runtime_error& e ) {
if( std::string(e.what()).find("database dirty flag set") != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else {
elog( "${e}", ("e",e.what()));
}
return OTHER_FAIL;
} catch( const std::exception& e ) {
elog("${e}", ("e",e.what()));
return OTHER_FAIL;
} catch( ... ) {
elog("unknown exception");
return OTHER_FAIL;
}
ilog("${name} successfully exiting", ("name", nodeos::config::node_executable_name));
return SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2016 INRA
*
* 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 ORG_VLEPROJECT_UNIT_TEST_HPP
#define ORG_VLEPROJECT_UNIT_TEST_HPP
#include <iostream>
#include <cstdlib>
namespace unit_test {
namespace detail {
struct tester
{
int errors = 0;
bool called_report_function = false;
tester& operator++() noexcept
{
errors++;
return *this;
}
~tester() noexcept
{
if (called_report_function == false) {
std::cerr << "unit_test::report_errors() not called.\n\nUsage:\n"
<< "int main(int argc, char*[] argc)\n"
<< "{\n"
<< " [...]\n"
<< " return unit_test::report_errors();\n"
<< "}\n";
std::abort();
}
}
};
inline tester&
test_errors()
{
static tester t;
return t;
}
inline void
ensures_impl(const char* expr,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr
<< "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_equal_impl(const char* expr1,
const char* expr2,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr1
<< " == " << expr2 << "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_not_equal_impl(const char* expr1,
const char* expr2,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr1
<< " != " << expr2 << "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_throw_impl(const char* excep,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): exception '"
<< excep << "' throw failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_not_throw_impl(const char* excep,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): exception '"
<< excep << "' not throw failed in function '"
<< function << "'\n";
++test_errors();
}
} // namespace details
inline int
report_errors()
{
auto& tester = unit_test::detail::test_errors();
tester.called_report_function = true;
int errors = tester.errors;
if (errors == 0) {
std::cerr << "No errors detected.\n";
return 0;
}
std::cerr << errors << " error" << (errors == 1 ? "": "s") << " detected.\n";
return 1;
}
} // namespace unit_test
#define Ensures(expr) \
do { \
if (not (expr)) { \
unit_test::detail::ensures_impl(#expr, __FILE__, \
__LINE__, __func__); \
} \
} while (0)
#define EnsuresEqual(expr1, expr2) \
do { \
if (not ((expr1) == (expr2))) { \
unit_test::detail::ensures_equal_impl(#expr1, #expr2, \
__FILE__, __LINE__, \
__func__); \
} \
} while (0)
#define EnsuresNotEqual(expr1, expr2) \
do { \
if (not ((expr1) != (expr2))) { \
unit_test::detail::ensures_not_equal_impl(#expr1, #expr2, \
__FILE__, \
__LINE__, \
__func__); \
} \
} while (0)
#define EnsuresThrow(expr, Excep) \
do { \
try { \
expr; \
unit_test::detail::ensures_throw_impl(#Excep, __FILE__, \
__LINE__, __func__); \
} catch (const Excep&) { \
} catch (...) { \
unit_test::detail::ensures_throw_impl(#Excep, __FILE__, \
__LINE__, __func__); \
} \
} while (0)
#define EnsuresNotThrow(expr, Excep) \
do { \
try { \
expr; \
} catch (const Excep&) { \
unit_test::detail::ensures_not_throw_impl(#Excep, __FILE__, \
__LINE__, \
__func__); \
} catch (...) { \
} \
} while (0)
#endif // #ifndef ORG_VLEPROJECT_UNIT_TEST_HPP
<commit_msg>test: update unit-test<commit_after>/* Copyright (C) 2016 INRA
*
* 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 ORG_VLEPROJECT_UNIT_TEST_HPP
#define ORG_VLEPROJECT_UNIT_TEST_HPP
#include <iostream>
#include <cstdlib>
namespace unit_test {
namespace detail {
struct tester
{
int errors = 0;
bool called_report_function = false;
tester& operator++() noexcept
{
errors++;
return *this;
}
~tester() noexcept
{
if (called_report_function == false) {
std::cerr << "unit_test::report_errors() not called.\n\nUsage:\n"
<< "int main(int argc, char*[] argc)\n"
<< "{\n"
<< " [...]\n"
<< " return unit_test::report_errors();\n"
<< "}\n";
std::abort();
}
}
};
inline tester&
test_errors()
{
static tester t;
return t;
}
inline void
ensures_impl(const char* expr,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr
<< "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_equal_impl(const char* expr1,
const char* expr2,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr1
<< " == " << expr2 << "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_not_equal_impl(const char* expr1,
const char* expr2,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): test '" << expr1
<< " != " << expr2 << "' failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_throw_impl(const char* excep,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): exception '"
<< excep << "' throw failed in function '"
<< function << "'\n";
++test_errors();
}
inline void
ensures_not_throw_impl(const char* excep,
const char* file,
int line,
const char* function)
{
std::cerr << file << "(" << line << "): exception '"
<< excep << "' not throw failed in function '"
<< function << "'\n";
++test_errors();
}
} // namespace details
inline int
report_errors()
{
auto& tester = unit_test::detail::test_errors();
tester.called_report_function = true;
int errors = tester.errors;
if (errors == 0)
std::cerr << "No errors detected.\n";
else
std::cerr << errors << " error" << (errors == 1 ? "": "s")
<< " detected.\n";
return errors;
}
} // namespace unit_test
#define Ensures(expr) \
do { \
if (not (expr)) { \
unit_test::detail::ensures_impl(#expr, __FILE__, \
__LINE__, __func__); \
} \
} while (0)
#define EnsuresEqual(expr1, expr2) \
do { \
if (not ((expr1) == (expr2))) { \
unit_test::detail::ensures_equal_impl(#expr1, #expr2, \
__FILE__, __LINE__, \
__func__); \
} \
} while (0)
#define EnsuresNotEqual(expr1, expr2) \
do { \
if (not ((expr1) != (expr2))) { \
unit_test::detail::ensures_not_equal_impl(#expr1, #expr2, \
__FILE__, \
__LINE__, \
__func__); \
} \
} while (0)
#define EnsuresThrow(expr, Excep) \
do { \
try { \
expr; \
unit_test::detail::ensures_throw_impl(#Excep, __FILE__, \
__LINE__, __func__); \
} catch (const Excep&) { \
} catch (...) { \
unit_test::detail::ensures_throw_impl(#Excep, __FILE__, \
__LINE__, __func__); \
} \
} while (0)
#define EnsuresNotThrow(expr, Excep) \
do { \
try { \
expr; \
} catch (const Excep&) { \
unit_test::detail::ensures_not_throw_impl(#Excep, __FILE__, \
__LINE__, \
__func__); \
} catch (...) { \
} \
} while (0)
#endif // #ifndef ORG_VLEPROJECT_UNIT_TEST_HPP
<|endoftext|> |
<commit_before>#include <iostream>
#include <Utils/utils.h>
#include "numgrind.h"
#include "DeepGrind/deepgrind.h"
#include "Solvers/SGDWithMomentumSolver.h"
#include "Solvers/GradientDescentSolver.h"
#include "Utils/eigenimport.h"
int main()
{
using namespace NumGrind::SymbolicGraph;
const std::string dataDir = "/home/daiver/coding/NumGrind/examples/data/house_prices/";
const auto trainData = NumGrind::Utils::readMatFromTxt(dataDir + "X_train.txt");
const auto trainTargets = NumGrind::Utils::readMatFromTxt(dataDir + "y_train.txt");
const auto testData = NumGrind::Utils::readMatFromTxt(dataDir + "X_test.txt");
const auto testTargets = NumGrind::Utils::readMatFromTxt(dataDir + "y_test.txt");
std::cout << "n Features " << trainData.cols() << std::endl;
std::cout << "n Train samples " << trainData.rows() << std::endl;
std::cout << "n Test samples " << testData.rows() << std::endl;
NumGrind::GraphManager gm;
std::default_random_engine generator;
auto X = gm.constant(trainData);
auto y = gm.constant(trainTargets);
auto w1 = gm.variable(NumGrind::Utils::gaussf(trainData.cols(), 100, 0.0, 0.01, generator));
auto b1 = gm.variable(NumGrind::Utils::gaussf(1, 100, 0.0, 0.01, generator));
auto w2 = gm.variable(NumGrind::Utils::gaussf(100, 1, 0.0, 0.01, generator));
auto b2 = gm.variable(NumGrind::Utils::gaussf(1, 1, 0.0, 0.01, generator));
auto f1 = apply<DeepGrind::relu, DeepGrind::reluDer>(matmult(X, w1) + b1);
auto f2 = matmult(f1, w2) + b2;
auto output = f2;
auto err = sumOfSquares(output - y);
auto vars = gm.initializeVariables();
NumGrind::Solvers::SolverSettings settings;
//settings.verbose = false;
settings.nMaxIterations = 10;
NumGrind::Solvers::gradientDescent(settings, 0.01, gm.funcFromNode(&err), gm.gradFromNode(&err), vars);
NumGrind::Solvers::SGDWithMomentumSolver solver(settings, 0.0001, 0.9, vars);
const int batchSize = 64;
/*Eigen::MatrixXf trainDataSamples(batchSize, trainData.cols());
Eigen::MatrixXf trainLabelsSamples(batchSize, 1);
float bestErr = 1e10;
for(int iterInd = 0; iterInd < 2000001; ++iterInd){
NumGrind::Utils::rowDataTargetRandomSampling<float, float>(trainData, trainTargets, generator, trainDataSamples, trainLabelsSamples);
X.setValue(trainDataSamples);
y.setValue(trainLabelsSamples);
solver.makeStep(gm.funcFromNode(&err),
gm.gradFromNode(&err));
if(iterInd % 10 == 0) std::cout << "Epoch " << iterInd << " err " << err.node()->value() << std::endl;
if(iterInd%100 == 0){
X.setValue(testData);
y.setValue(testTargets);
err.node()->forwardPass(solver.vars());
auto res = err.value();
const float fErr = res / testTargets.rows();
if(fErr < bestErr)
bestErr = fErr;
X.setValue(trainData);
y.setValue(trainTargets);
err.node()->forwardPass(solver.vars());
auto trainErr = err.value()/trainData.rows();
std::cout << std::endl << "Test error " << fErr << ", " << " Train error " << trainErr << ", best " << bestErr << " " << std::endl << std::endl;
}
}*/
return 0;
}
<commit_msg>fix step size. normalization is needed<commit_after>#include <iostream>
#include <Utils/utils.h>
#include "numgrind.h"
#include "DeepGrind/deepgrind.h"
#include "Solvers/SGDWithMomentumSolver.h"
#include "Solvers/GradientDescentSolver.h"
#include "Utils/eigenimport.h"
int main()
{
using namespace NumGrind::SymbolicGraph;
const std::string dataDir = "/home/daiver/coding/NumGrind/examples/data/house_prices/";
const auto trainData = NumGrind::Utils::readMatFromTxt(dataDir + "X_train.txt");
const auto trainTargets = NumGrind::Utils::readMatFromTxt(dataDir + "y_train.txt");
const auto testData = NumGrind::Utils::readMatFromTxt(dataDir + "X_test.txt");
const auto testTargets = NumGrind::Utils::readMatFromTxt(dataDir + "y_test.txt");
std::cout << "n Features " << trainData.cols() << std::endl;
std::cout << "n Train samples " << trainData.rows() << std::endl;
std::cout << "n Test samples " << testData.rows() << std::endl;
NumGrind::GraphManager gm;
std::default_random_engine generator;
auto X = gm.constant(trainData);
auto y = gm.constant(trainTargets);
auto w1 = gm.variable(NumGrind::Utils::gaussf(trainData.cols(), 1, 0.0, 0.01, generator));
//auto w1 = gm.variable(Eigen::MatrixXf::Zero(trainData.cols(), 1));
//auto b1 = gm.variable(0);
auto b1 = gm.variable(NumGrind::Utils::gaussf(1, 1, 0.0, 0.01, generator));
//auto w2 = gm.variable(NumGrind::Utils::gaussf(100, 1, 0.0, 0.01, generator));
//auto b2 = gm.variable(NumGrind::Utils::gaussf(1, 1, 0.0, 0.01, generator));
auto f1 = (matmult(X, w1) + b1);
//auto f1 = apply<DeepGrind::relu, DeepGrind::reluDer>(matmult(X, w1) + b1);
//auto f2 = matmult(f1, w2) + b2;
auto output = f1;
auto err = sumOfSquares(output - y);
auto vars = gm.initializeVariables();
NumGrind::Solvers::SolverSettings settings;
//settings.verbose = false;
settings.nMaxIterations = 10;
//NumGrind::Solvers::gradientDescent(settings, 0.000000001, gm.funcFromNode(&err), gm.gradFromNode(&err), vars);
NumGrind::Solvers::SGDWithMomentumSolver solver(settings, 0.00000001, 0.9, vars);
const int batchSize = 32;
Eigen::MatrixXf trainDataSamples(batchSize, trainData.cols());
Eigen::MatrixXf trainLabelsSamples(batchSize, 1);
float bestErr = 1e10;
for(int iterInd = 0; iterInd < 2001; ++iterInd){
NumGrind::Utils::rowDataTargetRandomSampling<float, float>(trainData, trainTargets, generator, trainDataSamples, trainLabelsSamples);
X.setValue(trainDataSamples);
y.setValue(trainLabelsSamples);
solver.makeStep(gm.funcFromNode(&err),
gm.gradFromNode(&err));
if(iterInd % 10 == 0) std::cout << "Epoch " << iterInd << " err " << err.node()->value() << std::endl;
if(iterInd%100 == 0){
X.setValue(testData);
y.setValue(testTargets);
err.node()->forwardPass(solver.vars());
auto res = err.value();
const float fErr = res / testTargets.rows();
if(fErr < bestErr)
bestErr = fErr;
X.setValue(trainData);
y.setValue(trainTargets);
err.node()->forwardPass(solver.vars());
auto trainErr = err.value()/trainData.rows();
std::cout << std::endl << "Test error " << fErr << ", " << " Train error " << trainErr << ", best " << bestErr << " " << std::endl << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/video_decoder_config.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
namespace media {
VideoDecoderConfig::VideoDecoderConfig()
: codec_(kUnknownVideoCodec),
profile_(VIDEO_CODEC_PROFILE_UNKNOWN),
format_(VideoFrame::INVALID),
extra_data_size_(0),
is_encrypted_(false) {
}
VideoDecoderConfig::VideoDecoderConfig(VideoCodec codec,
VideoCodecProfile profile,
VideoFrame::Format format,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const uint8* extra_data,
size_t extra_data_size,
bool is_encrypted) {
Initialize(codec, profile, format, coded_size, visible_rect, natural_size,
extra_data, extra_data_size, is_encrypted, true);
}
VideoDecoderConfig::~VideoDecoderConfig() {}
// Some videos just want to watch the world burn, with a height of 0; cap the
// "infinite" aspect ratio resulting.
static const int kInfiniteRatio = 99999;
// Common aspect ratios (multiplied by 100 and truncated) used for histogramming
// video sizes. These were taken on 20111103 from
// http://wikipedia.org/wiki/Aspect_ratio_(image)#Previous_and_currently_used_aspect_ratios
static const int kCommonAspectRatios100[] = {
100, 115, 133, 137, 143, 150, 155, 160, 166, 175, 177, 185, 200, 210, 220,
221, 235, 237, 240, 255, 259, 266, 276, 293, 400, 1200, kInfiniteRatio,
};
template<class T> // T has int width() & height() methods.
static void UmaHistogramAspectRatio(const char* name, const T& size) {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
name,
// Intentionally use integer division to truncate the result.
size.height() ? (size.width() * 100) / size.height() : kInfiniteRatio,
base::CustomHistogram::ArrayToCustomRanges(
kCommonAspectRatios100, arraysize(kCommonAspectRatios100)));
}
void VideoDecoderConfig::Initialize(VideoCodec codec,
VideoCodecProfile profile,
VideoFrame::Format format,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const uint8* extra_data,
size_t extra_data_size,
bool is_encrypted,
bool record_stats) {
CHECK((extra_data_size != 0) == (extra_data != NULL));
if (record_stats) {
UMA_HISTOGRAM_ENUMERATION("Media.VideoCodec", codec, kVideoCodecMax + 1);
// Drop UNKNOWN because U_H_E() uses one bucket for all values less than 1.
if (profile >= 0) {
UMA_HISTOGRAM_ENUMERATION("Media.VideoCodecProfile", profile,
VIDEO_CODEC_PROFILE_MAX + 1);
}
UMA_HISTOGRAM_COUNTS_10000("Media.VideoCodedWidth", coded_size.width());
UmaHistogramAspectRatio("Media.VideoCodedAspectRatio", coded_size);
UMA_HISTOGRAM_COUNTS_10000("Media.VideoVisibleWidth", visible_rect.width());
UmaHistogramAspectRatio("Media.VideoVisibleAspectRatio", visible_rect);
}
codec_ = codec;
profile_ = profile;
format_ = format;
coded_size_ = coded_size;
visible_rect_ = visible_rect;
natural_size_ = natural_size;
extra_data_size_ = extra_data_size;
if (extra_data_size_ > 0) {
extra_data_.reset(new uint8[extra_data_size_]);
memcpy(extra_data_.get(), extra_data, extra_data_size_);
} else {
extra_data_.reset();
}
is_encrypted_ = is_encrypted;
}
void VideoDecoderConfig::CopyFrom(const VideoDecoderConfig& video_config) {
Initialize(video_config.codec(),
video_config.profile(),
video_config.format(),
video_config.coded_size(),
video_config.visible_rect(),
video_config.natural_size(),
video_config.extra_data(),
video_config.extra_data_size(),
video_config.is_encrypted(),
false);
}
bool VideoDecoderConfig::IsValidConfig() const {
return codec_ != kUnknownVideoCodec &&
natural_size_.width() > 0 &&
natural_size_.height() > 0 &&
VideoFrame::IsValidConfig(format_, visible_rect().size(), natural_size_);
}
bool VideoDecoderConfig::Matches(const VideoDecoderConfig& config) const {
return ((codec() == config.codec()) &&
(format() == config.format()) &&
(profile() == config.profile()) &&
(coded_size() == config.coded_size()) &&
(visible_rect() == config.visible_rect()) &&
(natural_size() == config.natural_size()) &&
(extra_data_size() == config.extra_data_size()) &&
(!extra_data() || !memcmp(extra_data(), config.extra_data(),
extra_data_size())) &&
(is_encrypted() == config.is_encrypted()));
}
std::string VideoDecoderConfig::AsHumanReadableString() const {
std::ostringstream s;
s << "codec: " << codec()
<< " format: " << format()
<< " coded size: [" << coded_size().width()
<< "," << coded_size().height() << "]"
<< " visible rect: [" << visible_rect().x()
<< "," << visible_rect().y()
<< "," << visible_rect().width()
<< "," << visible_rect().height() << "]"
<< " natural size: [" << natural_size().width()
<< "," << natural_size().height() << "]"
<< " encryption: [" << (is_encrypted() ? "true" : "false") << "]";
return s.str();
}
VideoCodec VideoDecoderConfig::codec() const {
return codec_;
}
VideoCodecProfile VideoDecoderConfig::profile() const {
return profile_;
}
VideoFrame::Format VideoDecoderConfig::format() const {
return format_;
}
gfx::Size VideoDecoderConfig::coded_size() const {
return coded_size_;
}
gfx::Rect VideoDecoderConfig::visible_rect() const {
return visible_rect_;
}
gfx::Size VideoDecoderConfig::natural_size() const {
return natural_size_;
}
uint8* VideoDecoderConfig::extra_data() const {
return extra_data_.get();
}
size_t VideoDecoderConfig::extra_data_size() const {
return extra_data_size_;
}
bool VideoDecoderConfig::is_encrypted() const {
return is_encrypted_;
}
} // namespace media
<commit_msg>Add profile and extra_data info in VideoDecoderConfig::AsHumanReadableString.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/video_decoder_config.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
namespace media {
VideoDecoderConfig::VideoDecoderConfig()
: codec_(kUnknownVideoCodec),
profile_(VIDEO_CODEC_PROFILE_UNKNOWN),
format_(VideoFrame::INVALID),
extra_data_size_(0),
is_encrypted_(false) {
}
VideoDecoderConfig::VideoDecoderConfig(VideoCodec codec,
VideoCodecProfile profile,
VideoFrame::Format format,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const uint8* extra_data,
size_t extra_data_size,
bool is_encrypted) {
Initialize(codec, profile, format, coded_size, visible_rect, natural_size,
extra_data, extra_data_size, is_encrypted, true);
}
VideoDecoderConfig::~VideoDecoderConfig() {}
// Some videos just want to watch the world burn, with a height of 0; cap the
// "infinite" aspect ratio resulting.
static const int kInfiniteRatio = 99999;
// Common aspect ratios (multiplied by 100 and truncated) used for histogramming
// video sizes. These were taken on 20111103 from
// http://wikipedia.org/wiki/Aspect_ratio_(image)#Previous_and_currently_used_aspect_ratios
static const int kCommonAspectRatios100[] = {
100, 115, 133, 137, 143, 150, 155, 160, 166, 175, 177, 185, 200, 210, 220,
221, 235, 237, 240, 255, 259, 266, 276, 293, 400, 1200, kInfiniteRatio,
};
template<class T> // T has int width() & height() methods.
static void UmaHistogramAspectRatio(const char* name, const T& size) {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
name,
// Intentionally use integer division to truncate the result.
size.height() ? (size.width() * 100) / size.height() : kInfiniteRatio,
base::CustomHistogram::ArrayToCustomRanges(
kCommonAspectRatios100, arraysize(kCommonAspectRatios100)));
}
void VideoDecoderConfig::Initialize(VideoCodec codec,
VideoCodecProfile profile,
VideoFrame::Format format,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const uint8* extra_data,
size_t extra_data_size,
bool is_encrypted,
bool record_stats) {
CHECK((extra_data_size != 0) == (extra_data != NULL));
if (record_stats) {
UMA_HISTOGRAM_ENUMERATION("Media.VideoCodec", codec, kVideoCodecMax + 1);
// Drop UNKNOWN because U_H_E() uses one bucket for all values less than 1.
if (profile >= 0) {
UMA_HISTOGRAM_ENUMERATION("Media.VideoCodecProfile", profile,
VIDEO_CODEC_PROFILE_MAX + 1);
}
UMA_HISTOGRAM_COUNTS_10000("Media.VideoCodedWidth", coded_size.width());
UmaHistogramAspectRatio("Media.VideoCodedAspectRatio", coded_size);
UMA_HISTOGRAM_COUNTS_10000("Media.VideoVisibleWidth", visible_rect.width());
UmaHistogramAspectRatio("Media.VideoVisibleAspectRatio", visible_rect);
}
codec_ = codec;
profile_ = profile;
format_ = format;
coded_size_ = coded_size;
visible_rect_ = visible_rect;
natural_size_ = natural_size;
extra_data_size_ = extra_data_size;
if (extra_data_size_ > 0) {
extra_data_.reset(new uint8[extra_data_size_]);
memcpy(extra_data_.get(), extra_data, extra_data_size_);
} else {
extra_data_.reset();
}
is_encrypted_ = is_encrypted;
}
void VideoDecoderConfig::CopyFrom(const VideoDecoderConfig& video_config) {
Initialize(video_config.codec(),
video_config.profile(),
video_config.format(),
video_config.coded_size(),
video_config.visible_rect(),
video_config.natural_size(),
video_config.extra_data(),
video_config.extra_data_size(),
video_config.is_encrypted(),
false);
}
bool VideoDecoderConfig::IsValidConfig() const {
return codec_ != kUnknownVideoCodec &&
natural_size_.width() > 0 &&
natural_size_.height() > 0 &&
VideoFrame::IsValidConfig(format_, visible_rect().size(), natural_size_);
}
bool VideoDecoderConfig::Matches(const VideoDecoderConfig& config) const {
return ((codec() == config.codec()) &&
(format() == config.format()) &&
(profile() == config.profile()) &&
(coded_size() == config.coded_size()) &&
(visible_rect() == config.visible_rect()) &&
(natural_size() == config.natural_size()) &&
(extra_data_size() == config.extra_data_size()) &&
(!extra_data() || !memcmp(extra_data(), config.extra_data(),
extra_data_size())) &&
(is_encrypted() == config.is_encrypted()));
}
std::string VideoDecoderConfig::AsHumanReadableString() const {
std::ostringstream s;
s << "codec: " << codec()
<< " format: " << format()
<< " profile: " << profile()
<< " coded size: [" << coded_size().width()
<< "," << coded_size().height() << "]"
<< " visible rect: [" << visible_rect().x()
<< "," << visible_rect().y()
<< "," << visible_rect().width()
<< "," << visible_rect().height() << "]"
<< " natural size: [" << natural_size().width()
<< "," << natural_size().height() << "]"
<< " has extra data? " << (extra_data() ? "true" : "false")
<< " encrypted? " << (is_encrypted() ? "true" : "false");
return s.str();
}
VideoCodec VideoDecoderConfig::codec() const {
return codec_;
}
VideoCodecProfile VideoDecoderConfig::profile() const {
return profile_;
}
VideoFrame::Format VideoDecoderConfig::format() const {
return format_;
}
gfx::Size VideoDecoderConfig::coded_size() const {
return coded_size_;
}
gfx::Rect VideoDecoderConfig::visible_rect() const {
return visible_rect_;
}
gfx::Size VideoDecoderConfig::natural_size() const {
return natural_size_;
}
uint8* VideoDecoderConfig::extra_data() const {
return extra_data_.get();
}
size_t VideoDecoderConfig::extra_data_size() const {
return extra_data_size_;
}
bool VideoDecoderConfig::is_encrypted() const {
return is_encrypted_;
}
} // namespace media
<|endoftext|> |
<commit_before>#ifndef LOCK_QUEUE
#define LOCK_QUEUE
#include<memory> //allocator, shared_ptr
#include<type_traits>
#include<utility> //move
#include"Node.hpp"
#include"../tool/CAlloc_obj.hpp"
namespace nThread
{
struct Use_pop_if_exist;
struct Do_not_use_pop_if_exist;
template<class T,class PopIfExist,class Mutex,class Alloc=std::allocator<T>>
struct Lock_queue
{
using allocator_type=Alloc;
using element_type=Node<nTool::CAlloc_obj<T,Alloc>>;
using mutex_type=Mutex;
using size_type=typename nTool::CAlloc_obj<T,Alloc>::size_type;
using value_type=T;
static constexpr bool POP_IF_EXIST{std::is_same<PopIfExist,Use_pop_if_exist>::value};
std::shared_ptr<element_type> begin;
std::shared_ptr<element_type> end;
mutex_type mut;
Lock_queue()
:end{std::make_shared<element_type>()}
{
begin=end;
}
Lock_queue(const Lock_queue &)=delete;
void emplace(std::shared_ptr<element_type> &&val)
{
val->next.reset();
std::lock_guard<mutex_type> lock{mut};
emplace_(std::move(val));
}
//do not call other member functions (including const member functions) at same time
inline void emplace_not_ts(std::shared_ptr<element_type> &&val) noexcept
{
emplace_(std::move(val));
}
inline bool empty() const noexcept
{
return !std::atomic_load_explicit(&begin,std::memory_order_acquire)->next;
}
std::shared_ptr<element_type> pop()
{
std::lock_guard<mutex_type> lock{mut};
return pop_(std::integral_constant<bool,POP_IF_EXIST>{});
}
std::shared_ptr<element_type> pop_if_exist()
{
using is_enable=std::enable_if_t<POP_IF_EXIST>;
if(empty())
return std::shared_ptr<element_type>{};
std::lock_guard<mutex_type> lock{mut};
if(empty())
return std::shared_ptr<element_type>{};
return pop_(std::true_type{});
}
//do not call other member functions (including const member functions) at same time
inline std::shared_ptr<element_type> pop_not_ts() noexcept
{
return pop_(std::false_type{});
}
Lock_queue& operator=(const Lock_queue &)=delete;
private:
using check_UsePopIfExist_type=std::enable_if_t<std::is_same<PopIfExist,Use_pop_if_exist>::value||std::is_same<PopIfExist,Do_not_use_pop_if_exist>::value>;
void emplace_(std::shared_ptr<element_type> &&val) noexcept
{
end->next=val;
std::swap(end->data,val->data);
end=std::move(val);
}
std::shared_ptr<element_type> pop_(std::true_type) noexcept
{
const std::shared_ptr<element_type> node{begin};
std::atomic_store_explicit(&begin,node->next,std::memory_order_release);
return node;
}
std::shared_ptr<element_type> pop_(std::false_type) noexcept
{
const std::shared_ptr<element_type> node{std::move(begin)};
begin=node->next;
return node;
}
};
}
#endif<commit_msg>fix pop<commit_after>#ifndef LOCK_QUEUE
#define LOCK_QUEUE
#include<memory> //allocator, shared_ptr
#include<type_traits>
#include<utility> //move
#include"Node.hpp"
#include"../tool/CAlloc_obj.hpp"
namespace nThread
{
struct Use_pop_if_exist;
struct Do_not_use_pop_if_exist;
template<class T,class PopIfExist,class Mutex,class Alloc=std::allocator<T>>
struct Lock_queue
{
using allocator_type=Alloc;
using element_type=Node<nTool::CAlloc_obj<T,Alloc>>;
using mutex_type=Mutex;
using size_type=typename nTool::CAlloc_obj<T,Alloc>::size_type;
using value_type=T;
static constexpr bool POP_IF_EXIST{std::is_same<PopIfExist,Use_pop_if_exist>::value};
std::shared_ptr<element_type> begin;
std::shared_ptr<element_type> end;
mutex_type mut;
Lock_queue()
:end{std::make_shared<element_type>()}
{
begin=end;
}
Lock_queue(const Lock_queue &)=delete;
void emplace(std::shared_ptr<element_type> &&val)
{
val->next.reset();
std::lock_guard<mutex_type> lock{mut};
emplace_(std::move(val));
}
//do not call other member functions (including const member functions) at same time
inline void emplace_not_ts(std::shared_ptr<element_type> &&val) noexcept
{
emplace_(std::move(val));
}
inline bool empty() const noexcept
{
return !std::atomic_load_explicit(&begin,std::memory_order_acquire)->next;
}
std::shared_ptr<element_type> pop()
{
std::lock_guard<mutex_type> lock{mut};
return pop_();
}
std::shared_ptr<element_type> pop_if_exist()
{
using is_enable=std::enable_if_t<POP_IF_EXIST>;
if(empty())
return std::shared_ptr<element_type>{};
std::lock_guard<mutex_type> lock{mut};
if(empty())
return std::shared_ptr<element_type>{};
return pop_();
}
//do not call other member functions (including const member functions) at same time
inline std::shared_ptr<element_type> pop_not_ts() noexcept
{
const std::shared_ptr<element_type> node{std::move(begin)};
begin=node->next;
return node;
}
Lock_queue& operator=(const Lock_queue &)=delete;
private:
using check_UsePopIfExist_type=std::enable_if_t<std::is_same<PopIfExist,Use_pop_if_exist>::value||std::is_same<PopIfExist,Do_not_use_pop_if_exist>::value>;
void emplace_(std::shared_ptr<element_type> &&val) noexcept
{
end->next=val;
std::swap(end->data,val->data);
end=std::move(val);
}
std::shared_ptr<element_type> pop_() noexcept
{
const std::shared_ptr<element_type> node{begin};
std::atomic_store_explicit(&begin,node->next,std::memory_order_release);
return node;
}
};
}
#endif
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Foundations.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Definition of enum lists and constants
//
///////////////////////////////////////////////////////////////////////////////
#ifndef FOUNDATIONS_H
#define FOUNDATIONS_H
#include <string>
namespace Nektar
{
namespace LibUtiltities
{
enum BasisType
{
eOrtho_A, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^a_p(z_i)\f$
eOrtho_B, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^b_{pq}(z_i)\f$
eOrtho_C, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^c_{pqr}(z_i)\f$
eModified_A, //!< Principle Modified Functions \f$ \phi^a_p(z_i) \f$
eModified_B, //!< Principle Modified Functions \f$ \phi^b_{pq}(z_i) \f$
eModified_C, //!< Principle Modified Functions \f$ \phi^c_{pqr}(z_i) \f$
eFourier, //!< Fourier Expansion \f$ \exp(i p\pi z_i)\f$
eGLL_Lagrange,//!< Lagrange for SEM basis \f$ h_p(z_i) \f$
eLegendre, //!< Legendre Polynomials \f$ L_p(z_i) = P^{0,0}_p(z_i)\f$. Same as Ortho_A
eChebyshev, //!< Chebyshev Polynomials \f$ T_p(z_i) = P^{-1/2,-1/2}_p(z_i)\f$
SIZE_BasisType //!< Length of enum list
};
enum PointsType
{
eGauss, //!< 1D Gauss quadrature points
eLobatto, //!< 1D Gauss Lobatto quadrature points
eRadauM, //!< 1D Gauss Radau quadrature points including (z=-1)
eRadauP, //!< 1D Gauss Radau quadrature points including (z=+1)
ePolyEvenSp, //!< 1D Evenly-spaced points using Lagrange polynomial
eFourierEvenSp, //!< 1D Evenly-spaced points using Fourier Fit
eArbitrary, //!< 1D Arbitrary point distribution
eNodalTriElec, //!< 2D Nodal Electrostatic Points on a Triangle
eNodalTriFekete, //!< 2D Nodal Fekete Points on a Triangle
eNodalTetElec, //!< 3D Nodal Electrostatic Points on a Tetrahedron
SIZE_PointsType //!< Length of enum list
};
enum PointsIdentifier
{
eWildcard, //!< Indentifier to use when PointType is sufficient to uniquely specify things
eGaussChebyshevFirstKind, //!< Gauss \f$ \alpha = -1/2, \beta = -1/2} \f$
eGaussChebyshevSecondKind, //!< Gauss \f$ \alpha = 1/2, \beta = 1/2} \f$
eGaussLegendre, //!< Gauss \f$ \alpha = 0, \beta = 0} \f$
eGaussAlpha0Beta1, //!< Gauss \f$ \alpha = 0, \beta = 1} \f$
eGaussAlpha0Beta2, //!< Gauss \f$ \alpha = 0, \beta = 2} \f$
SIZE_PointsIdentifier //!< Length of enum list
};
} // end of namespace
} // end of namespace
#endif //FOUNDATIONS_H
<commit_msg>modified some Doxygen comments typos in the formulae<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Foundations.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Definition of enum lists and constants
//
///////////////////////////////////////////////////////////////////////////////
#ifndef FOUNDATIONS_H
#define FOUNDATIONS_H
#include <string>
namespace Nektar
{
namespace LibUtiltities
{
enum BasisType
{
eOrtho_A, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^a_p(z_i)\f$
eOrtho_B, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^b_{pq}(z_i)\f$
eOrtho_C, //!< Principle Orthogonal Functions \f$\widetilde{\psi}^c_{pqr}(z_i)\f$
eModified_A, //!< Principle Modified Functions \f$ \phi^a_p(z_i) \f$
eModified_B, //!< Principle Modified Functions \f$ \phi^b_{pq}(z_i) \f$
eModified_C, //!< Principle Modified Functions \f$ \phi^c_{pqr}(z_i) \f$
eFourier, //!< Fourier Expansion \f$ \exp(i p\pi z_i)\f$
eGLL_Lagrange,//!< Lagrange for SEM basis \f$ h_p(z_i) \f$
eLegendre, //!< Legendre Polynomials \f$ L_p(z_i) = P^{0,0}_p(z_i)\f$. Same as Ortho_A
eChebyshev, //!< Chebyshev Polynomials \f$ T_p(z_i) = P^{-1/2,-1/2}_p(z_i)\f$
SIZE_BasisType //!< Length of enum list
};
enum PointsType
{
eGauss, //!< 1D Gauss quadrature points
eLobatto, //!< 1D Gauss Lobatto quadrature points
eRadauM, //!< 1D Gauss Radau quadrature points including (z=-1)
eRadauP, //!< 1D Gauss Radau quadrature points including (z=+1)
ePolyEvenSp, //!< 1D Evenly-spaced points using Lagrange polynomial
eFourierEvenSp, //!< 1D Evenly-spaced points using Fourier Fit
eArbitrary, //!< 1D Arbitrary point distribution
eNodalTriElec, //!< 2D Nodal Electrostatic Points on a Triangle
eNodalTriFekete, //!< 2D Nodal Fekete Points on a Triangle
eNodalTetElec, //!< 3D Nodal Electrostatic Points on a Tetrahedron
SIZE_PointsType //!< Length of enum list
};
enum PointsIdentifier
{
eWildcard, //!< Indentifier to use when PointType is sufficient to uniquely specify things
eGaussChebyshevFirstKind, //!< Gauss \f$ \alpha = -1/2, \beta = -1/2 \f$
eGaussChebyshevSecondKind, //!< Gauss \f$ \alpha = 1/2, \beta = 1/2 \f$
eGaussLegendre, //!< Gauss \f$ \alpha = 0, \beta = 0 \f$
eGaussAlpha0Beta1, //!< Gauss \f$ \alpha = 0, \beta = 1 \f$
eGaussAlpha0Beta2, //!< Gauss \f$ \alpha = 0, \beta = 2 \f$
SIZE_PointsIdentifier //!< Length of enum list
};
} // end of namespace
} // end of namespace
#endif //FOUNDATIONS_H
<|endoftext|> |
<commit_before>// Copyright 2016, Dawid Kurek, <dawikur@gmail.com>
#ifdef CROW_CONFIG_
#define ROWS_COUNT 5
#define COLS_COUNT 13
#endif // CROW_CONFIG_
#ifdef CROW_KEYMAP_
{
//
// Layer 0
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |~ |! |@ |# |$ |% |^ |& |* |( |) |_ |+ |BackSp |
// | ` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | - | = | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Tab |Q |W |E |R |T |Y |U |I |O |P |{ |} || |
// | | | | | | | | | | | | [ | ] | \ |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// |CtrlL |A |S |D |F |G |H |J |K |L |: |" |Enter |
// | | | | | | | | | | | ; | ' | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL |Z |X |C |V |B |N |M |< |> |? |ShiftR |
// | | | | | | | | | , | . | / | |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |Layer|GUIL |AltL | |AltR |GUIR |Menu |Layer|
// | 1 | | | | | | | 2 |
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Aqute) , K(1) , K(2) , K(3) , K(4) , K(5) , K(6) , K(7) , K(8) , K(9) , K(0) , K(Minus) , K(Equal) },
{ K(Tab) , K(Q) , K(W) , K(E) , K(R) , K(T) , K(Y) , K(U) , K(I) , K(O) , K(P) , K(OpenBracket) , K(CloseBracket) },
{ M(CtrlL) , K(A) , K(S) , K(D) , K(F) , K(G) , K(H) , K(J) , K(K) , K(L) , K(Semicolon) , K(Apostrophe) , K(Enter) },
{ M(ShiftL) , K(Z) , K(X) , K(C) , K(V) , K(B) , K(N) , K(M) , K(Comma) , K(Dot) , K(ForwardSlash) , M(ShiftR) , K(Slash) },
{ L(0, 1) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , L(0, 2) , K(BackSpace) }
},
//
// Layer 1
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |Esc |F1 |F2 |F3 |F4 |F5 |F6 |F7 |F8 |F9 |F10 |F11 |F12 |Delete |
// | | | | | | | | | | | | | | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Layer | |Pau-| |Ins | | | |Home| | ^ |<-- |--> | |
// | Lock | | se | | CP | | | | | | | | | | |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// |CtrlL |End |Prt-| |PgDn|Home|<-- | | | ^ |--> | | |Enter |
// | | | Sc | | | | | V | | | | | | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL | |Del | | |PgUp| | | | | | |ShiftR |
// | | | | | | | | V | | | | |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |Layer|GUIL |AltL | |AltR |GUIR |Menu |CtrlR|
// |#1###| | | | | | | |
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Esc) , K(F1) , K(F2) , K(F3) , K(F4) , K(F5) , K(F6) , K(F7) , K(F8) , K(F9) , K(F10) , K(F11) , K(F12) },
{ LL(0) , Nop() , K(Pause) , Nop() , K(Ins) , Nop() , Nop() , Nop() , K(Home) , Nop() , K(Up) , K(Left) , K(Right) },
{ M(CtrlL) , K(End) , K(PrtSc) , Nop() , K(PgDn) , Nop() , K(Left) , K(Down) , K(Up) , K(Right) , Nop() , Nop() , K(Enter) },
{ M(ShiftL) , Nop() , K(Delete) , Nop() , Nop() , K(PgUp) , K(Down) , Nop() , Nop() , Nop() , Nop() , ML(ShiftR) , Nop() },
{ L(0, 1) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , M(CtrlR) , K(Delete) }
},
//
// Layer 2
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |Esc | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |BackSp |
// | | | | | | | | | | | | | | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Layer |Mac | ^ | | B |Scr | F | | |Play|Stop|Prev|Next| |
// | Lock | Rec| ^ | | | U | | | | | | | | |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// | | | V | |Scr |Scr |Scr | | |Mute|Vol-|Vol+|Enter |
// | | << | V | >> | L | D | R | | | | | | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL | L | M | R | | | | |-Bri|+Bri| |ShiftR |
// | Lock | | | | | | | | gth| gth| | Lock |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |CtrlL|GUIL |AltL | |AltR |GUIR |Menu |Layer|
// | | | | | | | |#2###|
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Esc) , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() },
{ LL(0) , Nop() , P(Up) , Nop() , PB(Backward) , PS(Up) , PB(Forward) , Nop() , Nop() , C(Play_Pause) , C(Stop) , C(PrevTrack) , C(NextTrack) },
{ Nop() , P(Left) , P(Down) , P(Right) , PS(Left) , PS(Down) , PS(Right) , Nop() , Nop() , C(Mute) , C(VolumeDown) , C(VolumeUp) , K(Enter) },
{ ML(ShiftL) , PB(Left) , PB(Middle) , PB(Right) , Nop() , Nop() , Nop() , Nop() , C(BrightDown) , C(BrightUp) , Nop() , ML(ShiftR) , Nop() },
{ M(CtrlL) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , L(0, 2) , K(BackSpace) }
}
}
#endif // CROW_KEYMAP_
<commit_msg>Cleanup layer 1<commit_after>// Copyright 2016, Dawid Kurek, <dawikur@gmail.com>
#ifdef CROW_CONFIG_
#define ROWS_COUNT 5
#define COLS_COUNT 13
#endif // CROW_CONFIG_
#ifdef CROW_KEYMAP_
{
//
// Layer 0
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |~ |! |@ |# |$ |% |^ |& |* |( |) |_ |+ |BackSp |
// | ` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | - | = | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Tab |Q |W |E |R |T |Y |U |I |O |P |{ |} || |
// | | | | | | | | | | | | [ | ] | \ |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// |CtrlL |A |S |D |F |G |H |J |K |L |: |" |Enter |
// | | | | | | | | | | | ; | ' | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL |Z |X |C |V |B |N |M |< |> |? |ShiftR |
// | | | | | | | | | , | . | / | |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |Layer|GUIL |AltL | |AltR |GUIR |Menu |Layer|
// | 1 | | | | | | | 2 |
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Aqute) , K(1) , K(2) , K(3) , K(4) , K(5) , K(6) , K(7) , K(8) , K(9) , K(0) , K(Minus) , K(Equal) },
{ K(Tab) , K(Q) , K(W) , K(E) , K(R) , K(T) , K(Y) , K(U) , K(I) , K(O) , K(P) , K(OpenBracket) , K(CloseBracket) },
{ M(CtrlL) , K(A) , K(S) , K(D) , K(F) , K(G) , K(H) , K(J) , K(K) , K(L) , K(Semicolon) , K(Apostrophe) , K(Enter) },
{ M(ShiftL) , K(Z) , K(X) , K(C) , K(V) , K(B) , K(N) , K(M) , K(Comma) , K(Dot) , K(ForwardSlash) , M(ShiftR) , K(Slash) },
{ L(0, 1) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , L(0, 2) , K(BackSpace) }
},
//
// Layer 1
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |Esc |F1 |F2 |F3 |F4 |F5 |F6 |F7 |F8 |F9 |F10 |F11 |F12 |Delete |
// | | | | | | | | | | | | | | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Layer | |Pau-| |Ins | | |PgUp|Home| | | | | |
// | Lock | | se | | CP | | | | | | | | | |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// |CtrlL |End |Prt-|PgDn| | |<-- | | | ^ |--> | | |Enter |
// | | | Sc | | | | | V | | | | | | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL | |Del | | | | | | | | |ShiftR |
// | | | | | | | | | | | | |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |Layer|GUIL |AltL | |AltR |GUIR |Menu |CtrlR|
// |#1###| | | | | | | |
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Esc) , K(F1) , K(F2) , K(F3) , K(F4) , K(F5) , K(F6) , K(F7) , K(F8) , K(F9) , K(F10) , K(F11) , K(F12) },
{ LL(0) , Nop() , K(Pause) , Nop() , K(Ins) , Nop() , Nop() , K(PgUp) , K(Home) , Nop() , Nop() , Nop() , Nop() },
{ M(CtrlL) , K(End) , K(PrtSc) , K(PgDn) , Nop() , Nop() , K(Left) , K(Down) , K(Up) , K(Right) , Nop() , Nop() , K(Enter) },
{ M(ShiftL) , Nop() , K(Delete) , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , ML(ShiftR) , Nop() },
{ L(0, 1) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , M(CtrlR) , K(Delete) }
},
//
// Layer 2
//
// ,____,____,____,____,____,____,____,____,____,____,____,____,____,________,
// |Esc | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |BackSp |
// | | | | | | | | | | | | | | |
// ;______,____,____,____,____,____,____,____,____,____,____,____,____,______;
// |Layer |Mac | ^ | | B |Scr | F | | |Play|Stop|Prev|Next| |
// | Lock | Rec| ^ | | | U | | | | | | | | |
// ;_______,____,____,____,____,____,____,____,____,____,____,____,__________;
// | | | V | |Scr |Scr |Scr | | |Mute|Vol-|Vol+|Enter |
// | | << | V | >> | L | D | R | | | | | | |
// ;_________,____,____,____,____,____,____,____,____,____,____,_____________;
// |ShiftL | L | M | R | | | | |-Bri|+Bri| |ShiftR |
// | Lock | | | | | | | | gth| gth| | Lock |
// ;_____,_____,_____ ,______________________________,_____,_____,_____,_____,
// |CtrlL|GUIL |AltL | |AltR |GUIR |Menu |Layer|
// | | | | | | | |#2###|
// `-----`-----`-----`-------------------------------`-----`-----`-----`-----`
{
{ K(Esc) , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() , Nop() },
{ LL(0) , Nop() , P(Up) , Nop() , PB(Backward) , PS(Up) , PB(Forward) , Nop() , Nop() , C(Play_Pause) , C(Stop) , C(PrevTrack) , C(NextTrack) },
{ Nop() , P(Left) , P(Down) , P(Right) , PS(Left) , PS(Down) , PS(Right) , Nop() , Nop() , C(Mute) , C(VolumeDown) , C(VolumeUp) , K(Enter) },
{ ML(ShiftL) , PB(Left) , PB(Middle) , PB(Right) , Nop() , Nop() , Nop() , Nop() , C(BrightDown) , C(BrightUp) , Nop() , ML(ShiftR) , Nop() },
{ M(CtrlL) , M(GUIL) , M(AltL) , Nop() , Nop() , K(SpaceBar) , Nop() , Nop() , M(AltR) , M(GUIR) , K(Application) , L(0, 2) , K(BackSpace) }
}
}
#endif // CROW_KEYMAP_
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/transport/native/server.h"
#include "eventql/transport/native/connection_tcp.h"
#include "eventql/transport/native/frames/query_result.h"
#include "eventql/transport/native/frames/query_progress.h"
#include "eventql/util/logging.h"
#include "eventql/util/MonotonicClock.h"
#include "eventql/util/util/binarymessagereader.h"
#include "eventql/db/database.h"
#include "eventql/server/session.h"
#include "eventql/server/sql_service.h"
#include "eventql/sql/runtime/runtime.h"
#include "eventql/auth/client_auth.h"
namespace eventql {
namespace native_transport {
ReturnCode performOperation_QUERY(
Database* database,
NativeConnection* conn,
const std::string& payload) {
auto session = database->getSession();
auto dbctx = session->getDatabaseContext();
/* read query frame */
std::string q_query;
uint64_t q_flags;
uint64_t q_maxrows;
std::string q_database;
try {
util::BinaryMessageReader q_frame(payload.data(), payload.size());
q_query = q_frame.readLenencString();
q_flags = q_frame.readVarUInt();
q_maxrows = q_frame.readVarUInt();
if (q_flags & EVQL_QUERY_SWITCHDB) {
q_database = q_frame.readLenencString();
}
} catch (const std::exception& e) {
return ReturnCode::error("ERUNTIME", "invalid QUERY frame");
}
if (q_maxrows == 0) {
q_maxrows = 1;
}
/* set heartbeat callback */
session->setHeartbeatCallback([conn] () -> ReturnCode {
return conn->sendHeartbeatFrame();
});
/* switch database */
if (q_flags & EVQL_QUERY_SWITCHDB) {
auto rc = dbctx->client_auth->changeNamespace(session, q_database);
if (!rc.isSuccess()) {
return conn->sendErrorFrame(rc.message());
}
}
if (session->getEffectiveNamespace().empty()) {
return conn->sendErrorFrame("No database selected");
}
/* execute queries */
try {
auto txn = dbctx->sql_service->startTransaction(session);
auto qplan = dbctx->sql_runtime->buildQueryPlan(txn.get(), q_query);
auto progress_interval = dbctx->config->getInt(
"server.query_progress_rate_limit");
auto progress_last = MonotonicClock::now();
/* set progress callback */
qplan->setProgressCallback([
&qplan,
&conn,
&progress_interval,
&progress_last] () -> ReturnCode {
if (!progress_interval.isEmpty()) {
auto now = MonotonicClock::now();
if (now >= progress_last + progress_interval.get()) {
return ReturnCode::success();
}
progress_last = now;
}
auto progress = qplan->getProgress();
QueryProgressFrame progress_frame;
progress_frame.setQueryProgressPermill(progress);
std::string payload;
progress_frame.writeToString(&payload);
if (conn->isOutboxEmpty()) {
return conn->sendFrameAsync(
EVQL_OP_QUERY_PROGRESS,
0,
payload.data(),
payload.size());
} else {
return conn->flushOutbox(false, 0);
}
});
if (qplan->numStatements() > 1 && !(q_flags & EVQL_QUERY_MULTISTMT)) {
return conn->sendErrorFrame(
"you must set EVQL_QUERY_MULTISTMT to enable multiple statements");
}
auto num_statements = qplan->numStatements();
for (int i = 0; i < num_statements; ++i) {
/* execute query */
auto result_cursor = qplan->execute(i);
auto result_ncols = result_cursor->getNumColumns();
/* send response frames */
QueryResultFrame r_frame(qplan->getStatementgetResultColumns(i));
Vector<csql::SValue> row(result_ncols);
while (result_cursor->next(row.data(), row.size())) {
r_frame.addRow(row);
if (r_frame.getRowCount() > q_maxrows ||
r_frame.getRowBytes() > NativeConnection::kMaxFrameSizeSoft) {
{
auto rc = r_frame.writeTo(conn);
if (!rc.isSuccess()) {
return rc;
}
}
r_frame.clear();
/* wait for discard or continue */
uint16_t n_opcode;
uint16_t n_flags;
std::string n_payload;
{
auto rc = conn->recvFrame(
&n_opcode,
&n_flags,
&n_payload,
session->getIdleTimeout());
if (!rc.isSuccess()) {
return rc;
}
}
bool cont = true;
switch (n_opcode) {
case EVQL_OP_QUERY_CONTINUE:
break;
case EVQL_OP_QUERY_DISCARD:
cont = false;
break;
default:
conn->close();
return ReturnCode::error("ERUNTIME", "unexpected opcode");
}
if (!cont) {
break;
}
}
}
bool pending_statement = i + 1 < num_statements;
r_frame.setIsLast(true);
r_frame.setHasPendingStatement(pending_statement);
r_frame.writeTo(conn);
if (!pending_statement) {
break;
}
/* wait for discard or continue (next query) */
uint16_t n_opcode;
uint16_t n_flags;
std::string n_payload;
auto rc = conn->recvFrame(
&n_opcode,
&n_flags,
&n_payload,
session->getIdleTimeout());
if (!rc.isSuccess()) {
return rc;
}
bool cont = true;
switch (n_opcode) {
case EVQL_OP_QUERY_NEXT:
break;
case EVQL_OP_QUERY_DISCARD:
cont = false;
break;
default:
conn->close();
return ReturnCode::error("ERUNTIME", "unexpected opcode");
}
if (!cont) {
break;
}
}
} catch (const StandardException& e) {
return conn->sendErrorFrame(e.what());
}
return ReturnCode::success();
}
} // namespace native_transport
} // namespace eventql
<commit_msg>write progress as permill<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/transport/native/server.h"
#include "eventql/transport/native/connection_tcp.h"
#include "eventql/transport/native/frames/query_result.h"
#include "eventql/transport/native/frames/query_progress.h"
#include "eventql/util/logging.h"
#include "eventql/util/MonotonicClock.h"
#include "eventql/util/util/binarymessagereader.h"
#include "eventql/db/database.h"
#include "eventql/server/session.h"
#include "eventql/server/sql_service.h"
#include "eventql/sql/runtime/runtime.h"
#include "eventql/auth/client_auth.h"
namespace eventql {
namespace native_transport {
ReturnCode performOperation_QUERY(
Database* database,
NativeConnection* conn,
const std::string& payload) {
auto session = database->getSession();
auto dbctx = session->getDatabaseContext();
/* read query frame */
std::string q_query;
uint64_t q_flags;
uint64_t q_maxrows;
std::string q_database;
try {
util::BinaryMessageReader q_frame(payload.data(), payload.size());
q_query = q_frame.readLenencString();
q_flags = q_frame.readVarUInt();
q_maxrows = q_frame.readVarUInt();
if (q_flags & EVQL_QUERY_SWITCHDB) {
q_database = q_frame.readLenencString();
}
} catch (const std::exception& e) {
return ReturnCode::error("ERUNTIME", "invalid QUERY frame");
}
if (q_maxrows == 0) {
q_maxrows = 1;
}
/* set heartbeat callback */
session->setHeartbeatCallback([conn] () -> ReturnCode {
return conn->sendHeartbeatFrame();
});
/* switch database */
if (q_flags & EVQL_QUERY_SWITCHDB) {
auto rc = dbctx->client_auth->changeNamespace(session, q_database);
if (!rc.isSuccess()) {
return conn->sendErrorFrame(rc.message());
}
}
if (session->getEffectiveNamespace().empty()) {
return conn->sendErrorFrame("No database selected");
}
/* execute queries */
try {
auto txn = dbctx->sql_service->startTransaction(session);
auto qplan = dbctx->sql_runtime->buildQueryPlan(txn.get(), q_query);
auto progress_interval = dbctx->config->getInt(
"server.query_progress_rate_limit");
auto progress_last = MonotonicClock::now();
/* set progress callback */
qplan->setProgressCallback([
&qplan,
&conn,
&progress_interval,
&progress_last] () -> ReturnCode {
if (!progress_interval.isEmpty()) {
auto now = MonotonicClock::now();
if (now >= progress_last + progress_interval.get()) {
return ReturnCode::success();
}
progress_last = now;
}
auto progress = qplan->getProgress();
QueryProgressFrame progress_frame;
progress_frame.setQueryProgressPermill(progress * 1000);
std::string payload;
progress_frame.writeToString(&payload);
if (conn->isOutboxEmpty()) {
return conn->sendFrameAsync(
EVQL_OP_QUERY_PROGRESS,
0,
payload.data(),
payload.size());
} else {
return conn->flushOutbox(false, 0);
}
});
if (qplan->numStatements() > 1 && !(q_flags & EVQL_QUERY_MULTISTMT)) {
return conn->sendErrorFrame(
"you must set EVQL_QUERY_MULTISTMT to enable multiple statements");
}
auto num_statements = qplan->numStatements();
for (int i = 0; i < num_statements; ++i) {
/* execute query */
auto result_cursor = qplan->execute(i);
auto result_ncols = result_cursor->getNumColumns();
/* send response frames */
QueryResultFrame r_frame(qplan->getStatementgetResultColumns(i));
Vector<csql::SValue> row(result_ncols);
while (result_cursor->next(row.data(), row.size())) {
r_frame.addRow(row);
if (r_frame.getRowCount() > q_maxrows ||
r_frame.getRowBytes() > NativeConnection::kMaxFrameSizeSoft) {
{
auto rc = r_frame.writeTo(conn);
if (!rc.isSuccess()) {
return rc;
}
}
r_frame.clear();
/* wait for discard or continue */
uint16_t n_opcode;
uint16_t n_flags;
std::string n_payload;
{
auto rc = conn->recvFrame(
&n_opcode,
&n_flags,
&n_payload,
session->getIdleTimeout());
if (!rc.isSuccess()) {
return rc;
}
}
bool cont = true;
switch (n_opcode) {
case EVQL_OP_QUERY_CONTINUE:
break;
case EVQL_OP_QUERY_DISCARD:
cont = false;
break;
default:
conn->close();
return ReturnCode::error("ERUNTIME", "unexpected opcode");
}
if (!cont) {
break;
}
}
}
bool pending_statement = i + 1 < num_statements;
r_frame.setIsLast(true);
r_frame.setHasPendingStatement(pending_statement);
r_frame.writeTo(conn);
if (!pending_statement) {
break;
}
/* wait for discard or continue (next query) */
uint16_t n_opcode;
uint16_t n_flags;
std::string n_payload;
auto rc = conn->recvFrame(
&n_opcode,
&n_flags,
&n_payload,
session->getIdleTimeout());
if (!rc.isSuccess()) {
return rc;
}
bool cont = true;
switch (n_opcode) {
case EVQL_OP_QUERY_NEXT:
break;
case EVQL_OP_QUERY_DISCARD:
cont = false;
break;
default:
conn->close();
return ReturnCode::error("ERUNTIME", "unexpected opcode");
}
if (!cont) {
break;
}
}
} catch (const StandardException& e) {
return conn->sendErrorFrame(e.what());
}
return ReturnCode::success();
}
} // namespace native_transport
} // namespace eventql
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include "triangle.h"
using namespace std;
Triangle::Triangle()
{
}
double Triangle::height()
{
double height = 0.0f;
double tArea = area();
if (tArea > 0) {
// area = 0.5*base*height
// We will use the first side as base
height = tArea / (0.5 * sides_.at(0));
}
return height;
}
void Triangle::addPoint(Point &p)
{
if (points().size() < 3) {
Shape::addPoint(p);
if (points().size() == 3) {
calcTriangle();
}
}
else {
//TODO: throw exception
}
}
double Triangle::area()
{
double area = 0.0f;
// We will use Heron's formula to calc the area of the triangle
if (sides_.size() == 3) {
double s = 0.0f;
for (int i = 0; i < 3; i++) {
s += sides_.at(i);
}
s /= 2;
area = sqrt(s * (s - sides_.at(0)) * (s - sides_.at(1)) * (s - sides_.at(2)));
}
return area;
}
void Triangle::print()
{
//TODO: only go through if we have 3 sides
static const int CAPITAL_A_ASCII_CODE = 'A';
static const int MINUSCULE_A_ASCII_CODE = 'a';
cout << "-----------------------------------------------" << endl;
cout << "I'm a triangle, I have " << numberOfSides() << " sides!" << endl;
cout << "\nThe points that compose me are: " << endl;
for (int i = 0; i < points().size(); i++) {
cout << "P" << i+1 << " = (" << points().at(i).x() << ", "<< points().at(1).y() << ")" << endl;
}
cout << "\nMy side's measures are:" << endl;
for (int i = 0; i < sides_.size(); i++) {
char measureId = MINUSCULE_A_ASCII_CODE + i;
cout << measureId << " = " << sides_.at(i) << endl;
}
cout << "\nMy angles are:" << endl;
for (int i = 0; i < angles_.size(); i++) {
char angleId = CAPITAL_A_ASCII_CODE + i;
cout << angleId << " = " << angles_.at(i) << endl;
}
cout << "I have a height of " << height() << endl;
cout << "Lastly, I have an area of " << area() << endl;
}
void Triangle::calcTriangle()
{
calcSides();
calcAngles();
}
void Triangle::calcSides()
{
if (sides_.size() == 0) {
for (int i = 0; i < 3; i++) {
int j = (i == 2 ? 0 : i + 1);
sides_.push_back(points().at(i) - points().at(j));
}
}
}
void Triangle::calcAngles()
{
int largestAngleIndex = 0;
if (sides_.at(1) > sides_.at(largestAngleIndex)) {
largestAngleIndex = 1;
}
if (sides_.at(2) > sides_.at(largestAngleIndex)) {
largestAngleIndex = 2;
}
double dividend = -1 * pow(sides_.at(largestAngleIndex), 2.0f);
double divisor = 2;
std::vector<int> remainingAnglesIndex;
for (int i = 0; i < 3; i++) {
if (i != largestAngleIndex) {
dividend += pow(sides_.at(i), 2.0f);
divisor *= sides_.at(i);
remainingAnglesIndex.push_back(i);
}
}
double acosLargestAngle = acos(dividend / divisor);
angles_[largestAngleIndex] = convertRadiansToDegress(acosLargestAngle);
dividend = sides_.at(remainingAnglesIndex.at(0)) * sin(convertDegreesToRadians(angles_[largestAngleIndex]));
divisor = sides_.at(largestAngleIndex);
cout << sides_.at(remainingAnglesIndex.at(0)) << endl;
double ordinaryAsinOfNonLargestAngle = asin(dividend / divisor);
angles_[remainingAnglesIndex.at(0)] = convertRadiansToDegress(ordinaryAsinOfNonLargestAngle);
angles_[remainingAnglesIndex.at(1)] = 180.0f;
for (int i = 0; i < 3; i++) {
if (i != remainingAnglesIndex.at(1)) {
angles_[remainingAnglesIndex.at(1)] -= angles_[i];
}
}
}
double Triangle::convertRadiansToDegress(double radians)
{
return radians * (180.0f / M_PI);
}
double Triangle::convertDegreesToRadians(double radians)
{
return radians * (M_PI / 180.0f);
}
<commit_msg>commenting .cc triangle file<commit_after>#include <cmath>
#include <iostream>
#include "triangle.h"
using namespace std;
/********************************************************
******************* PUBLIC METHODS ********************
********************************************************/
/***
* Default constructor
*/
Triangle::Triangle()
{
height_ = 0;
}
/***
* Calculates the height of the triangle
*/
double Triangle::height()
{
// area = 0.5*base*height
// We will use the first side as base
return area() / (0.5 * sides_.at(0));
}
/***
* Adds a new point to the triangle composition
*/
void Triangle::addPoint(Point &p)
{
if (points().size() < 3) {
Shape::addPoint(p);
if (points().size() == 3) {
calcTriangle();
}
}
else {
//TODO: throw exception
}
}
/***
* Calculates the area of the triangle
*/
double Triangle::area()
{
double area = 0.0f;
// We will use Heron's formula to calc the area of the triangle
if (sides_.size() == 3) {
double s = 0.0f;
for (int i = 0; i < 3; i++) {
s += sides_.at(i);
}
s /= 2;
area = sqrt(s * (s - sides_.at(0)) * (s - sides_.at(1)) * (s - sides_.at(2)));
}
else {
//TODO: Throw exception because we dont have 3 sides
}
return area;
}
/***
* Prints out information about the triangle, containing its points, measures, angles, height and area.
*/
void Triangle::print()
{
//TODO: only go through if we have 3 sides
static const int CAPITAL_A_ASCII_CODE = 'A';
static const int MINUSCULE_A_ASCII_CODE = 'a';
cout << "-----------------------------------------------" << endl;
cout << "I'm a triangle, I have " << numberOfSides() << " sides!" << endl;
cout << "\nThe points that compose me are: " << endl;
for (int i = 0; i < points().size(); i++) {
cout << "P" << i+1 << " = (" << points().at(i).x() << ", "<< points().at(1).y() << ")" << endl;
}
cout << "\nMy side's measures are:" << endl;
for (int i = 0; i < sides_.size(); i++) {
char measureId = MINUSCULE_A_ASCII_CODE + i;
cout << measureId << " = " << sides_.at(i) << endl;
}
cout << "\nMy angles are:" << endl;
for (int i = 0; i < angles_.size(); i++) {
char angleId = CAPITAL_A_ASCII_CODE + i;
cout << angleId << " = " << angles_.at(i) << endl;
}
cout << "I have a height of " << height() << endl;
cout << "Lastly, I have an area of " << area() << endl;
}
/********************************************************
******************* PRIVATE METHODS ********************
********************************************************/
void Triangle::calcTriangle()
{
calcSides();
calcAngles();
}
void Triangle::calcSides()
{
if (sides_.size() == 0) {
for (int i = 0; i < 3; i++) {
int j = (i == 2 ? 0 : i + 1);
sides_.push_back(points().at(i) - points().at(j));
}
}
}
void Triangle::calcAngles()
{
int largestAngleIndex = 0;
if (sides_.at(1) > sides_.at(largestAngleIndex)) {
largestAngleIndex = 1;
}
if (sides_.at(2) > sides_.at(largestAngleIndex)) {
largestAngleIndex = 2;
}
double dividend = -1 * pow(sides_.at(largestAngleIndex), 2.0f);
double divisor = 2.0f;
std::vector<int> remainingAnglesIndex;
for (int i = 0; i < 3; i++) {
if (i != largestAngleIndex) {
dividend += pow(sides_.at(i), 2.0f);
divisor *= sides_.at(i);
remainingAnglesIndex.push_back(i);
}
}
double acosLargestAngle = acos(dividend / divisor);
angles_[largestAngleIndex] = convertRadiansToDegress(acosLargestAngle);
dividend = sides_.at(remainingAnglesIndex.at(0)) * sin(convertDegreesToRadians(angles_[largestAngleIndex]));
divisor = sides_.at(largestAngleIndex);
double ordinaryAsinOfNonLargestAngle = asin(dividend / divisor);
angles_[remainingAnglesIndex.at(0)] = convertRadiansToDegress(ordinaryAsinOfNonLargestAngle);
angles_[remainingAnglesIndex.at(1)] = 180.0f;
for (int i = 0; i < 3; i++) {
if (i != remainingAnglesIndex.at(1)) {
angles_[remainingAnglesIndex.at(1)] -= angles_[i];
}
}
}
double Triangle::convertRadiansToDegress(double radians)
{
return radians * (180.0f / M_PI);
}
double Triangle::convertDegreesToRadians(double radians)
{
return radians * (M_PI / 180.0f);
}
<|endoftext|> |
<commit_before>// C++11 (c) 2014 Vladimír Štill
#include "udptools.h"
#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
namespace udp {
struct Socket::_Data {
_Data( Address local, int rcvbufsize ) :
localAddress( local ), rcvbufsize( rcvbufsize ), rcvbuf( new char[ rcvbufsize ] )
{
struct sockaddr_in myaddr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
assert(fd>0, "Cannot create socket\n");
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(localAddress.ip().asInt()); // IP Address
myaddr.sin_port = htons(localAddress.port().get()); // Port numbrt
int bnd = bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr));
assert(bnd==0, "Bind failed");
}
Address localAddress;
int rcvbufsize;
std::unique_ptr< char[] > rcvbuf;
// ... OS specific socket stuff
int fd;
};
Socket::Socket( Address local, int rcvbuf ) : _data( new _Data( local, rcvbuf ) ) { }
// must be here -- where _Data definition is known
Socket::~Socket() = default;
void Socket::setRecvBufferSize( int size ) {
// ...
assert_leq( 1, size, "invalid size" );
_data->rcvbufsize = size;
_data->rcvbuf.reset( new char[ size ] );
}
bool Socket::sendPacket( Packet &packet ) {
// ...
struct sockaddr_in remote;
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(packet.address().ip().asInt()); // IP Address
remote.sin_port = htons(packet.address().port().get()); // Port numbrt
socklen_t l = sizeof(remote);
int snd = sendto(_data->fd,packet.data(),packet.size(),0,(struct sockaddr *)&remote,l);
return snd>=0;
}
Packet Socket::recvPacket() {
// ...
struct sockaddr_in remote;
socklen_t m = sizeof(remote);
int rc = recvfrom(_data->fd,_data->rcvbuf.get(),_data->rcvbufsize,0,(struct sockaddr *)&remote,&m);
assert(rc>=0, "Receive failed");
return Packet(_data->rcvbuf.get(), rc);
}
Address Socket::localAddress() const { return _data->localAddress; }
}
<commit_msg>Error Fixed (I check the lenght of the sent message instead)<commit_after>// C++11 (c) 2014 Vladimír Štill
#include "udptools.h"
#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
namespace udp {
struct Socket::_Data {
_Data( Address local, int rcvbufsize ) :
localAddress( local ), rcvbufsize( rcvbufsize ), rcvbuf( new char[ rcvbufsize ] )
{
struct sockaddr_in myaddr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
assert(fd>0, "Cannot create socket\n");
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(localAddress.ip().asInt()); // IP Address
myaddr.sin_port = htons(localAddress.port().get()); // Port numbrt
int bnd = bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr));
assert(bnd==0, "Bind failed");
}
Address localAddress;
int rcvbufsize;
std::unique_ptr< char[] > rcvbuf;
// ... OS specific socket stuff
int fd;
};
Socket::Socket( Address local, int rcvbuf ) : _data( new _Data( local, rcvbuf ) ) { }
// must be here -- where _Data definition is known
Socket::~Socket() = default;
void Socket::setRecvBufferSize( int size ) {
// ...
assert_leq( 1, size, "invalid size" );
_data->rcvbufsize = size;
_data->rcvbuf.reset( new char[ size ] );
}
bool Socket::sendPacket( Packet &packet ) {
// ...
struct sockaddr_in remote;
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(packet.address().ip().asInt()); // IP Address
remote.sin_port = htons(packet.address().port().get()); // Port numbrt
socklen_t l = sizeof(remote);
int snd = sendto(_data->fd,packet.data(),packet.size(),0,(struct sockaddr *)&remote,l);
return (packet.size()>0);
}
Packet Socket::recvPacket() {
// ...
struct sockaddr_in remote;
socklen_t m = sizeof(remote);
int rc = recvfrom(_data->fd,_data->rcvbuf.get(),_data->rcvbufsize,0,(struct sockaddr *)&remote,&m);
assert(rc>=0, "Receive failed");
return Packet(_data->rcvbuf.get(), rc);
}
Address Socket::localAddress() const { return _data->localAddress; }
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include "viennagrid/meta/typelist.hpp"
template<typename type1, typename type2>
void test_type()
{
bool is_the_same = viennameta::_equal<type1, type2>::value;
std::cout << " " << std::boolalpha << is_the_same << std::endl;
if (!is_the_same) exit(-1);
}
template<int value1, int value2>
void test_value()
{
bool is_the_same = value1 == value2;
std::cout << " " << std::boolalpha << is_the_same << std::endl;
if (!is_the_same) exit(-1);
}
int main()
{
// size
std::cout << "size" << std::endl;
test_value<
viennameta::typelist::result_of::size< VIENNAMETA_MAKE_TYPELIST_5(int, int, int, int, int) >::value,
5
>();
// at
std::cout << "at" << std::endl;
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 2 >::type,
float
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 0 >::type,
int
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 8 >::type,
viennameta::out_of_range
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), -1000 >::type,
viennameta::out_of_range
>();
// find
std::cout << "find" << std::endl;
test_value<
viennameta::typelist::result_of::find< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), float >::value,
2
>();
test_value<
viennameta::typelist::result_of::find< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), unsigned short >::value,
4
>();
test_value<
viennameta::typelist::result_of::find< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), unsigned char >::value,
-1
>();
// push_back
std::cout << "push_back" << std::endl;
test_type<
viennameta::typelist::result_of::push_back< VIENNAMETA_MAKE_TYPELIST_1(int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, float)
>();
test_type<
viennameta::typelist::result_of::push_back< VIENNAMETA_MAKE_TYPELIST_1(int), viennameta::null_type >::type,
VIENNAMETA_MAKE_TYPELIST_1(int)
>();
test_type<
viennameta::typelist::result_of::push_back< viennameta::null_type, int >::type,
VIENNAMETA_MAKE_TYPELIST_1(int)
>();
// push_back_list
std::cout << "push_back_list" << std::endl;
test_type<
viennameta::typelist::result_of::push_back_list< VIENNAMETA_MAKE_TYPELIST_2(int,float), VIENNAMETA_MAKE_TYPELIST_2(char,double) >::type,
VIENNAMETA_MAKE_TYPELIST_4(int, float, char, double)
>();
test_type<
viennameta::typelist::result_of::push_back_list< viennameta::null_type, VIENNAMETA_MAKE_TYPELIST_2(char,double) >::type,
VIENNAMETA_MAKE_TYPELIST_2(char, double)
>();
test_type<
viennameta::typelist::result_of::push_back_list< VIENNAMETA_MAKE_TYPELIST_2(int,float), viennameta::null_type >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, float)
>();
// not valid, should give a compiler error!
// test<
// viennameta::typelist::result_of::push_back_list< int, viennameta::null_type >::type,
// VIENNAMETA_MAKE_TYPELIST_1(int)
// >();
// erase_at
std::cout << "erase_at" << std::endl;
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 0 >::type,
VIENNAMETA_MAKE_TYPELIST_2(float, int)
>();
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 1 >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 8 >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// erase
std::cout << "erase" << std::endl;
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int >::type,
VIENNAMETA_MAKE_TYPELIST_2(float, int)
>();
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// erase_all
std::cout << "erase_all" << std::endl;
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int >::type,
VIENNAMETA_MAKE_TYPELIST_1(float)
>();
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// no_duplicates
std::cout << "no_duplicates" << std::endl;
test_type<
viennameta::typelist::result_of::no_duplicates< VIENNAMETA_MAKE_TYPELIST_8(int, char, float, double, unsigned short, int, float, float) >::type,
VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short)
>();
test_type<
viennameta::typelist::result_of::no_duplicates< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short) >::type,
VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short)
>();
// replace_at
std::cout << "replace_at" << std::endl;
test_type<
viennameta::typelist::result_of::replace_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 0, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, int)
>();
test_type<
viennameta::typelist::result_of::replace_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 5, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
// replace
std::cout << "replace" << std::endl;
test_type<
viennameta::typelist::result_of::replace< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, int)
>();
test_type<
viennameta::typelist::result_of::replace< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
// replace_all
std::cout << "replace_all" << std::endl;
test_type<
viennameta::typelist::result_of::replace_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, double)
>();
test_type<
viennameta::typelist::result_of::replace_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
return 0;
}<commit_msg>moved test function to separate header renamed typelist::find to typelist::index_of<commit_after>#include <iostream>
#include "viennagrid/meta/typelist.hpp"
#include "tests.hpp"
int main()
{
// size
std::cout << "size" << std::endl;
test_value<
viennameta::typelist::result_of::size< VIENNAMETA_MAKE_TYPELIST_5(int, int, int, int, int) >::value,
5
>();
// at
std::cout << "at" << std::endl;
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 2 >::type,
float
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 0 >::type,
int
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), 8 >::type,
viennameta::out_of_range
>();
test_type<
viennameta::typelist::result_of::at< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), -1000 >::type,
viennameta::out_of_range
>();
// index_of
std::cout << "index_of" << std::endl;
test_value<
viennameta::typelist::result_of::index_of< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), float >::value,
2
>();
test_value<
viennameta::typelist::result_of::index_of< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), unsigned short >::value,
4
>();
test_value<
viennameta::typelist::result_of::index_of< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short), unsigned char >::value,
-1
>();
// push_back
std::cout << "push_back" << std::endl;
test_type<
viennameta::typelist::result_of::push_back< VIENNAMETA_MAKE_TYPELIST_1(int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, float)
>();
test_type<
viennameta::typelist::result_of::push_back< VIENNAMETA_MAKE_TYPELIST_1(int), viennameta::null_type >::type,
VIENNAMETA_MAKE_TYPELIST_1(int)
>();
test_type<
viennameta::typelist::result_of::push_back< viennameta::null_type, int >::type,
VIENNAMETA_MAKE_TYPELIST_1(int)
>();
// push_back_list
std::cout << "push_back_list" << std::endl;
test_type<
viennameta::typelist::result_of::push_back_list< VIENNAMETA_MAKE_TYPELIST_2(int,float), VIENNAMETA_MAKE_TYPELIST_2(char,double) >::type,
VIENNAMETA_MAKE_TYPELIST_4(int, float, char, double)
>();
test_type<
viennameta::typelist::result_of::push_back_list< viennameta::null_type, VIENNAMETA_MAKE_TYPELIST_2(char,double) >::type,
VIENNAMETA_MAKE_TYPELIST_2(char, double)
>();
test_type<
viennameta::typelist::result_of::push_back_list< VIENNAMETA_MAKE_TYPELIST_2(int,float), viennameta::null_type >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, float)
>();
// not valid, should give a compiler error!
// test<
// viennameta::typelist::result_of::push_back_list< int, viennameta::null_type >::type,
// VIENNAMETA_MAKE_TYPELIST_1(int)
// >();
// erase_at
std::cout << "erase_at" << std::endl;
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 0 >::type,
VIENNAMETA_MAKE_TYPELIST_2(float, int)
>();
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 1 >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 8 >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// erase
std::cout << "erase" << std::endl;
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int >::type,
VIENNAMETA_MAKE_TYPELIST_2(float, int)
>();
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// erase_all
std::cout << "erase_all" << std::endl;
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int >::type,
VIENNAMETA_MAKE_TYPELIST_1(float)
>();
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), float >::type,
VIENNAMETA_MAKE_TYPELIST_2(int, int)
>();
test_type<
viennameta::typelist::result_of::erase_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double >::type,
VIENNAMETA_MAKE_TYPELIST_3(int, float, int)
>();
// no_duplicates
std::cout << "no_duplicates" << std::endl;
test_type<
viennameta::typelist::result_of::no_duplicates< VIENNAMETA_MAKE_TYPELIST_8(int, char, float, double, unsigned short, int, float, float) >::type,
VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short)
>();
test_type<
viennameta::typelist::result_of::no_duplicates< VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short) >::type,
VIENNAMETA_MAKE_TYPELIST_5(int, char, float, double, unsigned short)
>();
// replace_at
std::cout << "replace_at" << std::endl;
test_type<
viennameta::typelist::result_of::replace_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 0, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, int)
>();
test_type<
viennameta::typelist::result_of::replace_at< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), 5, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
// replace
std::cout << "replace" << std::endl;
test_type<
viennameta::typelist::result_of::replace< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, int)
>();
test_type<
viennameta::typelist::result_of::replace< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
// replace_all
std::cout << "replace_all" << std::endl;
test_type<
viennameta::typelist::result_of::replace_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), int, double >::type,
VIENNAMETA_MAKE_TYPELIST_3(double, float, double)
>();
test_type<
viennameta::typelist::result_of::replace_all< VIENNAMETA_MAKE_TYPELIST_3(int,float,int), double, int >::type,
VIENNAMETA_MAKE_TYPELIST_3(int,float,int)
>();
return 0;
}<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ESP8266HTTPClient.h>
#include <LinkedList.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <BH1750.h>
#define ONE_WIRE_BUS D4
#define SDA D2
#define SCL D1
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
BH1750 lightMeter;
HTTPClient http;
struct measurement {
float temperature;
uint16_t light;
};
LinkedList<struct measurement> measurements;
int counter = 0;
void setup() {
Serial.begin(115200);
Wire.begin(SDA, SCL); // actually pretty important
sensors.begin();
lightMeter.begin();
WiFiManager wifiManager;
wifiManager.autoConnect("Wemos D1 mini");
}
bool sendMeasurementsToApi() {
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& data = root.createNestedArray("measurements");
for (int i = 0; i < measurements.size(); i++) {
JsonObject& nestedObject = data.createNestedObject();
struct measurement m = measurements.get(i);
nestedObject["temperature"] = m.temperature;
nestedObject["light"] = m.light;
}
char buffer[256];
root.printTo(buffer, sizeof(buffer));
int len = root.measureLength();
Serial.print("Buffer is ");
Serial.println(buffer);
http.begin("http://imegumii.space:3030/api/measurement"); //HTTP
http.addHeader("Content-Type", "application/json", true, true);
int httpCode = http.POST(buffer);
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
http.end();
return true;
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
return false;
}
void printMeasurement(struct measurement m, int i) {
Serial.print("Measured: ");
Serial.print(i);
Serial.print(" - ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
}
void loop() {
unsigned long startTime = millis();
uint16_t light = lightMeter.readLightLevel();
sensors.requestTemperatures(); // Send the command to get temperatures
float temperature = sensors.getTempCByIndex(0);
struct measurement m = {temperature, light};
Serial.print("Measured the following: ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
if (m.light > 20000) {
// discard
m.light = 0;
}
measurements.add(m);
counter++;
if (counter >= 6) {
// Serial.print("Measurements contains ");
// Serial.println(measurements.size());
// for (int i = 0; i < measurements.size(); i++) {
// printMeasurement(measurements.get(i), i);
// }
sendMeasurementsToApi();
counter = 0;
measurements.clear();
}
unsigned long delta = millis() - startTime;
delay(5000 - delta);
}
<commit_msg>Changed the way this file enables sensors<commit_after>#include <Arduino.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ESP8266HTTPClient.h>
#include <LinkedList.h>
#include <ArduinoJson.h>
// Uncomment the ones supported.
#define USE_TEMPERATURE
// #define USE_LIGHT
#ifdef USE_TEMPERATURE
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS D4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
#endif
#ifdef USE_LIGHT
#include <Wire.h>
#include <BH1750.h>
#define SDA D2
#define SCL D1
BH1750 lightMeter;
#endif
HTTPClient http;
struct measurement {
float temperature;
uint16_t light;
};
LinkedList<struct measurement> measurements;
int counter = 0;
void setup() {
Serial.begin(115200);
#ifdef USE_LIGHT
Wire.begin(SDA, SCL); // actually pretty important
lightMeter.begin();
#endif
#ifdef USE_TEMPERATURE
sensors.begin();
#endif
WiFiManager wifiManager;
wifiManager.autoConnect("Wemos D1 mini");
}
bool sendMeasurementsToApi() {
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& data = root.createNestedArray("measurements");
for (int i = 0; i < measurements.size(); i++) {
JsonObject& nestedObject = data.createNestedObject();
struct measurement m = measurements.get(i);
nestedObject["temperature"] = m.temperature;
nestedObject["light"] = m.light;
}
char buffer[1024];
root.printTo(buffer, sizeof(buffer));
int len = root.measureLength();
Serial.print("Buffer is ");
Serial.println(buffer);
http.begin("http://imegumii.space:3030/api/measurement"); //HTTP
http.addHeader("Content-Type", "application/json", true, true);
int httpCode = http.POST(buffer);
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
http.end();
return true;
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
return false;
}
void printMeasurement(struct measurement m, int i) {
Serial.print("Measured: ");
Serial.print(i);
Serial.print(" - ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
}
void loop() {
unsigned long startTime = millis();
struct measurement m = { 0.0, 0};
#ifdef USE_TEMPERATURE
sensors.requestTemperatures(); // Send the command to get temperatures
float temperature = sensors.getTempCByIndex(0);
m.temperature = temperature;
#endif
#ifdef USE_LIGHT
uint16_t light = lightMeter.readLightLevel();
m.light = light;
#endif
Serial.print("Measured the following: ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
if (m.light > 20000) {
// discard
m.light = 0;
}
measurements.add(m);
counter++;
if (counter >= 12) { // send 12 measurements, once every 5 seconds
// Serial.print("Measurements contains ");
// Serial.println(measurements.size());
// for (int i = 0; i < measurements.size(); i++) {
// printMeasurement(measurements.get(i), i);
// }
sendMeasurementsToApi();
counter = 0;
measurements.clear();
}
unsigned long delta = millis() - startTime;
delay(5000 - delta);
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Solidity parser shared functionality.
*/
#include <libsolidity/parsing/ParserBase.h>
#include <libsolidity/parsing/Scanner.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
std::shared_ptr<string const> const& ParserBase::sourceName() const
{
return m_scanner->sourceName();
}
int ParserBase::position() const
{
return m_scanner->currentLocation().start;
}
int ParserBase::endPosition() const
{
return m_scanner->currentLocation().end;
}
void ParserBase::expectToken(Token::Value _value)
{
Token::Value tok = m_scanner->currentToken();
if (tok != _value)
{
if (Token::isElementaryTypeName(tok)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected token ") +
string(Token::name(_value)) +
string(" got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected token ") +
string(Token::name(_value)) +
string(" got '") +
string(Token::name(m_scanner->currentToken())) +
string("'")
);
}
m_scanner->next();
}
Token::Value ParserBase::expectAssignmentOperator()
{
Token::Value op = m_scanner->currentToken();
if (!Token::isAssignmentOp(op))
{
if (Token::isElementaryTypeName(op)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected assignment operator, got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected assignment operator, got '") +
string(Token::name(m_scanner->currentToken())) +
string("'")
);
}
m_scanner->next();
return op;
}
ASTPointer<ASTString> ParserBase::expectIdentifierToken()
{
Token::Value id = m_scanner->currentToken();
if (id != Token::Identifier)
{
if (Token::isElementaryTypeName(id)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected identifier, got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected identifier, got '") +
string(Token::name(id)) +
string("'")
);
}
return getLiteralAndAdvance();
}
ASTPointer<ASTString> ParserBase::getLiteralAndAdvance()
{
ASTPointer<ASTString> identifier = make_shared<ASTString>(m_scanner->currentLiteral());
m_scanner->next();
return identifier;
}
void ParserBase::parserError(string const& _description)
{
auto err = make_shared<Error>(Error::Type::ParserError);
*err <<
errinfo_sourceLocation(SourceLocation(position(), position(), sourceName())) <<
errinfo_comment(_description);
m_errors.push_back(err);
}
void ParserBase::fatalParserError(string const& _description)
{
parserError(_description);
BOOST_THROW_EXCEPTION(FatalError());
}
<commit_msg>Raise proper error on reserved keywords<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Solidity parser shared functionality.
*/
#include <libsolidity/parsing/ParserBase.h>
#include <libsolidity/parsing/Scanner.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
std::shared_ptr<string const> const& ParserBase::sourceName() const
{
return m_scanner->sourceName();
}
int ParserBase::position() const
{
return m_scanner->currentLocation().start;
}
int ParserBase::endPosition() const
{
return m_scanner->currentLocation().end;
}
void ParserBase::expectToken(Token::Value _value)
{
Token::Value tok = m_scanner->currentToken();
if (tok != _value)
{
if (Token::isReservedKeyword(tok))
{
fatalParserError(
string("Expected token ") +
string(Token::name(_value)) +
string(" got reserved keyword '") +
string(Token::name(tok)) +
string("'")
);
}
else if (Token::isElementaryTypeName(tok)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected token ") +
string(Token::name(_value)) +
string(" got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected token ") +
string(Token::name(_value)) +
string(" got '") +
string(Token::name(m_scanner->currentToken())) +
string("'")
);
}
m_scanner->next();
}
Token::Value ParserBase::expectAssignmentOperator()
{
Token::Value op = m_scanner->currentToken();
if (!Token::isAssignmentOp(op))
{
if (Token::isElementaryTypeName(op)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected assignment operator, got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected assignment operator, got '") +
string(Token::name(m_scanner->currentToken())) +
string("'")
);
}
m_scanner->next();
return op;
}
ASTPointer<ASTString> ParserBase::expectIdentifierToken()
{
Token::Value id = m_scanner->currentToken();
if (id != Token::Identifier)
{
if (Token::isElementaryTypeName(id)) //for the sake of accuracy in reporting
{
ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken();
fatalParserError(
string("Expected identifier, got '") +
elemTypeName.toString() +
string("'")
);
}
else
fatalParserError(
string("Expected identifier, got '") +
string(Token::name(id)) +
string("'")
);
}
return getLiteralAndAdvance();
}
ASTPointer<ASTString> ParserBase::getLiteralAndAdvance()
{
ASTPointer<ASTString> identifier = make_shared<ASTString>(m_scanner->currentLiteral());
m_scanner->next();
return identifier;
}
void ParserBase::parserError(string const& _description)
{
auto err = make_shared<Error>(Error::Type::ParserError);
*err <<
errinfo_sourceLocation(SourceLocation(position(), position(), sourceName())) <<
errinfo_comment(_description);
m_errors.push_back(err);
}
void ParserBase::fatalParserError(string const& _description)
{
parserError(_description);
BOOST_THROW_EXCEPTION(FatalError());
}
<|endoftext|> |
<commit_before>#include "pending_irob.h"
#include "debug.h"
#include "timeops.h"
#include <functional>
#include <vector>
using std::vector; using std::max;
using std::mem_fun_ref;
using std::bind1st;
#include "pthread_util.h"
static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
ssize_t PendingIROB::obj_count = 0;
PendingIROB::PendingIROB(irob_id_t id_)
: id(id_),
anonymous(false),
complete(false),
placeholder(true)
{
/* this placeholder PendingIROB will be replaced by
the real one, when it arrives. */
}
PendingIROB::PendingIROB(irob_id_t id_, int numdeps, const irob_id_t *deps_array,
size_t datalen, char *data, u_long send_labels_)
: id(id_),
send_labels(send_labels_),
anonymous(false),
complete(false),
placeholder(false)
{
if (numdeps > 0) {
assert(deps_array);
}
for (int i = 0; i < numdeps; i++) {
deps.insert(deps_array[i]);
}
if (datalen > 0) {
anonymous = true;
assert(data);
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = INVALID_IROB_SEQNO;
chunk.datalen = datalen;
chunk.data = data;
(void)add_chunk(chunk);
(void)finish();
}
PthreadScopedLock lock(&count_mutex);
++obj_count;
}
PendingIROB::~PendingIROB()
{
while (!chunks.empty()) {
struct irob_chunk_data chunk = chunks.front();
chunks.pop_front();
delete [] chunk.data;
}
PthreadScopedLock lock(&count_mutex);
--obj_count;
}
ssize_t
PendingIROB::objs()
{
PthreadScopedLock lock(&count_mutex);
return obj_count;
}
bool
PendingIROB::add_chunk(struct irob_chunk_data& irob_chunk)
{
if (is_complete()) {
return false;
}
chunks.push_back(irob_chunk);
return true;
}
bool
PendingIROB::finish(void)
{
if (is_complete()) {
return false;
}
complete = true;
return true;
}
void
PendingIROB::add_dep(irob_id_t id)
{
deps.insert(id);
}
void
PendingIROB::dep_satisfied(irob_id_t id)
{
deps.erase(id);
}
void
PendingIROB::add_dependent(irob_id_t id)
{
dependents.insert(id);
}
bool
PendingIROB::is_complete(void) const
{
return complete;
}
bool
PendingIROB::is_anonymous(void) const
{
return anonymous;
}
bool
PendingIROB::depends_on(irob_id_t that)
{
return (deps.count(that) == 1);
}
PendingIROBLattice::PendingIROBLattice()
: offset(0), last_anon_irob_id(-1)
{
pthread_mutex_init(&membership_lock, NULL);
}
PendingIROBLattice::~PendingIROBLattice()
{
{
PthreadScopedLock lock(&membership_lock);
for (size_t i = 0; i < pending_irobs.size(); i++) {
delete pending_irobs[i];
}
pending_irobs.clear();
offset = 0;
}
pthread_mutex_destroy(&membership_lock);
}
bool
PendingIROBLattice::insert(PendingIROB *pirob, bool infer_deps)
{
PthreadScopedLock lock(&membership_lock);
return insert_locked(pirob, infer_deps);
}
bool
PendingIROBLattice::insert_locked(PendingIROB *pirob, bool infer_deps)
{
assert(pirob);
if (past_irobs.contains(pirob->id)) {
return false;
}
if (pending_irobs.empty()) {
offset = pirob->id;
}
int index = pirob->id - offset;
if (index >= 0 && index < (int)pending_irobs.size() &&
(pending_irobs[index] != NULL &&
!pending_irobs[index]->placeholder)) {
return false;
}
while (index < 0) {
pending_irobs.push_front(NULL);
--offset;
index = pirob->id - offset;
}
if ((int)pending_irobs.size() <= index) {
pending_irobs.resize(index+1, NULL);
}
if (pending_irobs[index]) {
// grab the placeholder's dependents and replace it
// with the real PendingIROB
assert(!pirob->placeholder);
assert(pending_irobs[index]->placeholder);
assert(pending_irobs[index]->id == pirob->id);
pirob->dependents.insert(pending_irobs[index]->dependents.begin(),
pending_irobs[index]->dependents.end());
delete pending_irobs[index];
pending_irobs[index] = pirob;
} else {
pending_irobs[index] = pirob;
}
if (pirob->placeholder) {
// pirob only exists to hold dependents until
// its replacement arrives.
return true;
}
correct_deps(pirob, infer_deps);
dbgprintf("Adding IROB %d as dependent of: [ ", pirob->id);
for (irob_id_set::iterator it = pirob->deps.begin();
it != pirob->deps.end(); it++) {
PendingIROB *dep = find_locked(*it);
if (dep) {
dbgprintf_plain("%ld ", dep->id);
dep->add_dependent(pirob->id);
} else {
dbgprintf_plain("(%ld) ", *it);
dep = new PendingIROB(*it);
insert_locked(dep);
dep->add_dependent(pirob->id);
}
}
dbgprintf_plain("]\n");
return true;
}
void
PendingIROBLattice::clear()
{
PthreadScopedLock lock(&membership_lock);
pending_irobs.clear();
min_dominator_set.clear();
last_anon_irob_id = -1;
}
void
PendingIROBLattice::correct_deps(PendingIROB *pirob, bool infer_deps)
{
/* 1) If pirob is anonymous, add deps on all pending IROBs. */
/* 2) Otherwise, add deps on all pending anonymous IROBs. */
/* we keep around a min-dominator set of IROBs; that is,
* the minimal set of IROBs that the next anonymous IROB
* must depend on. */
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
if (infer_deps) {
// skip this at the receiver. The sender infers and
// communicates deps; the receiver enforces them.
if (pirob->is_anonymous()) {
if (last_anon_irob_id >= 0 && min_dominator_set.empty()) {
pirob->add_dep(last_anon_irob_id);
} else {
pirob->deps.insert(min_dominator_set.begin(),
min_dominator_set.end());
min_dominator_set.clear();
}
last_anon_irob_id = pirob->id;
} else {
// this IROB dominates its deps, so remove them from
// the min_dominator_set before inserting it
vector<irob_id_t> isect(max(pirob->deps.size(),
min_dominator_set.size()));
vector<irob_id_t>::iterator the_end =
set_intersection(pirob->deps.begin(), pirob->deps.end(),
min_dominator_set.begin(),
min_dominator_set.end(),
isect.begin());
if (last_anon_irob_id >= 0 && isect.begin() == the_end) {
pirob->add_dep(last_anon_irob_id);
} // otherwise, it already depends on something
// that depends on the last_anon_irob
for (vector<irob_id_t>::iterator it = isect.begin();
it != the_end; ++it) {
min_dominator_set.erase(*it);
}
min_dominator_set.insert(pirob->id);
}
}
/* 3) Remove already-satisfied deps. */
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
PendingIROB *
PendingIROBLattice::find(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return find_locked(id);
}
PendingIROB *
PendingIROBLattice::find_locked(irob_id_t id)
{
//TimeFunctionBody timer("pending_irobs.find(accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size()) {
return NULL;
}
return pending_irobs[index];
}
bool
PendingIROBLattice::erase(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
//TimeFunctionBody timer("pending_irobs.erase(const_accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size() ||
pending_irobs[index] == NULL) {
return false;
}
past_irobs.insert(id);
min_dominator_set.erase(id);
PendingIROB *victim = pending_irobs[index];
pending_irobs[index] = NULL; // caller must free it
while (!pending_irobs.empty() && pending_irobs[0] == NULL) {
pending_irobs.pop_front();
offset++;
}
dbgprintf("Notifying dependents of IROB %d's release: [ ", id);
for (irob_id_set::iterator it = victim->dependents.begin();
it != victim->dependents.end(); it++) {
PendingIROB *dependent = this->find_locked(*it);
if (dependent == NULL) {
dbgprintf_plain("(%ld) ", *it);
continue;
}
dbgprintf_plain("%ld ", dependent->id);
dependent->dep_satisfied(id);
}
dbgprintf_plain("]\n");
return true;
}
bool
PendingIROBLattice::past_irob_exists(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return past_irobs.contains(id);
}
bool
PendingIROBLattice::empty()
{
PthreadScopedLock lock(&membership_lock);
return pending_irobs.empty();
}
IROBSchedulingData::IROBSchedulingData(irob_id_t id_, u_long seqno_)
: id(id_), seqno(seqno_)
{
/* empty */
}
bool
IROBSchedulingData::operator<(const IROBSchedulingData& other) const
{
// can implement priority here, based on
// any added scheduling hints
return (id < other.id) || (seqno < other.seqno);
}
<commit_msg>past_irobs is really only applicable at the receiver, so don't use it at the sender.<commit_after>#include "pending_irob.h"
#include "debug.h"
#include "timeops.h"
#include <functional>
#include <vector>
using std::vector; using std::max;
using std::mem_fun_ref;
using std::bind1st;
#include "pthread_util.h"
static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
ssize_t PendingIROB::obj_count = 0;
PendingIROB::PendingIROB(irob_id_t id_)
: id(id_),
anonymous(false),
complete(false),
placeholder(true)
{
/* this placeholder PendingIROB will be replaced by
the real one, when it arrives. */
}
PendingIROB::PendingIROB(irob_id_t id_, int numdeps, const irob_id_t *deps_array,
size_t datalen, char *data, u_long send_labels_)
: id(id_),
send_labels(send_labels_),
anonymous(false),
complete(false),
placeholder(false)
{
if (numdeps > 0) {
assert(deps_array);
}
for (int i = 0; i < numdeps; i++) {
deps.insert(deps_array[i]);
}
if (datalen > 0) {
anonymous = true;
assert(data);
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = INVALID_IROB_SEQNO;
chunk.datalen = datalen;
chunk.data = data;
(void)add_chunk(chunk);
(void)finish();
}
PthreadScopedLock lock(&count_mutex);
++obj_count;
}
PendingIROB::~PendingIROB()
{
while (!chunks.empty()) {
struct irob_chunk_data chunk = chunks.front();
chunks.pop_front();
delete [] chunk.data;
}
PthreadScopedLock lock(&count_mutex);
--obj_count;
}
ssize_t
PendingIROB::objs()
{
PthreadScopedLock lock(&count_mutex);
return obj_count;
}
bool
PendingIROB::add_chunk(struct irob_chunk_data& irob_chunk)
{
if (is_complete()) {
return false;
}
chunks.push_back(irob_chunk);
return true;
}
bool
PendingIROB::finish(void)
{
if (is_complete()) {
return false;
}
complete = true;
return true;
}
void
PendingIROB::add_dep(irob_id_t id)
{
deps.insert(id);
}
void
PendingIROB::dep_satisfied(irob_id_t id)
{
deps.erase(id);
}
void
PendingIROB::add_dependent(irob_id_t id)
{
dependents.insert(id);
}
bool
PendingIROB::is_complete(void) const
{
return complete;
}
bool
PendingIROB::is_anonymous(void) const
{
return anonymous;
}
bool
PendingIROB::depends_on(irob_id_t that)
{
return (deps.count(that) == 1);
}
PendingIROBLattice::PendingIROBLattice()
: offset(0), last_anon_irob_id(-1)
{
pthread_mutex_init(&membership_lock, NULL);
}
PendingIROBLattice::~PendingIROBLattice()
{
{
PthreadScopedLock lock(&membership_lock);
for (size_t i = 0; i < pending_irobs.size(); i++) {
delete pending_irobs[i];
}
pending_irobs.clear();
offset = 0;
}
pthread_mutex_destroy(&membership_lock);
}
bool
PendingIROBLattice::insert(PendingIROB *pirob, bool infer_deps)
{
PthreadScopedLock lock(&membership_lock);
return insert_locked(pirob, infer_deps);
}
bool
PendingIROBLattice::insert_locked(PendingIROB *pirob, bool infer_deps)
{
assert(pirob);
if (past_irobs.contains(pirob->id)) {
return false;
}
if (pending_irobs.empty()) {
offset = pirob->id;
}
int index = pirob->id - offset;
if (index >= 0 && index < (int)pending_irobs.size() &&
(pending_irobs[index] != NULL &&
!pending_irobs[index]->placeholder)) {
return false;
}
while (index < 0) {
pending_irobs.push_front(NULL);
--offset;
index = pirob->id - offset;
}
if ((int)pending_irobs.size() <= index) {
pending_irobs.resize(index+1, NULL);
}
if (pending_irobs[index]) {
// grab the placeholder's dependents and replace it
// with the real PendingIROB
assert(!pirob->placeholder);
assert(pending_irobs[index]->placeholder);
assert(pending_irobs[index]->id == pirob->id);
pirob->dependents.insert(pending_irobs[index]->dependents.begin(),
pending_irobs[index]->dependents.end());
delete pending_irobs[index];
pending_irobs[index] = pirob;
} else {
pending_irobs[index] = pirob;
}
if (pirob->placeholder) {
// pirob only exists to hold dependents until
// its replacement arrives.
return true;
}
correct_deps(pirob, infer_deps);
dbgprintf("Adding IROB %d as dependent of: [ ", pirob->id);
for (irob_id_set::iterator it = pirob->deps.begin();
it != pirob->deps.end(); it++) {
PendingIROB *dep = find_locked(*it);
if (dep) {
dbgprintf_plain("%ld ", dep->id);
dep->add_dependent(pirob->id);
} else {
dbgprintf_plain("(%ld) ", *it);
dep = new PendingIROB(*it);
insert_locked(dep);
dep->add_dependent(pirob->id);
}
}
dbgprintf_plain("]\n");
return true;
}
void
PendingIROBLattice::clear()
{
PthreadScopedLock lock(&membership_lock);
pending_irobs.clear();
min_dominator_set.clear();
last_anon_irob_id = -1;
}
void
PendingIROBLattice::correct_deps(PendingIROB *pirob, bool infer_deps)
{
/* 1) If pirob is anonymous, add deps on all pending IROBs. */
/* 2) Otherwise, add deps on all pending anonymous IROBs. */
/* we keep around a min-dominator set of IROBs; that is,
* the minimal set of IROBs that the next anonymous IROB
* must depend on. */
if (!infer_deps) {
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
if (infer_deps) {
// skip this at the receiver. The sender infers and
// communicates deps; the receiver enforces them.
if (pirob->is_anonymous()) {
if (last_anon_irob_id >= 0 && min_dominator_set.empty()) {
pirob->add_dep(last_anon_irob_id);
} else {
pirob->deps.insert(min_dominator_set.begin(),
min_dominator_set.end());
min_dominator_set.clear();
}
last_anon_irob_id = pirob->id;
} else {
// this IROB dominates its deps, so remove them from
// the min_dominator_set before inserting it
vector<irob_id_t> isect(max(pirob->deps.size(),
min_dominator_set.size()));
vector<irob_id_t>::iterator the_end =
set_intersection(pirob->deps.begin(), pirob->deps.end(),
min_dominator_set.begin(),
min_dominator_set.end(),
isect.begin());
if (last_anon_irob_id >= 0 && isect.begin() == the_end) {
pirob->add_dep(last_anon_irob_id);
} // otherwise, it already depends on something
// that depends on the last_anon_irob
for (vector<irob_id_t>::iterator it = isect.begin();
it != the_end; ++it) {
min_dominator_set.erase(*it);
}
min_dominator_set.insert(pirob->id);
}
}
if (!infer_deps) {
/* 3) Remove already-satisfied deps. */
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
}
PendingIROB *
PendingIROBLattice::find(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return find_locked(id);
}
PendingIROB *
PendingIROBLattice::find_locked(irob_id_t id)
{
//TimeFunctionBody timer("pending_irobs.find(accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size()) {
return NULL;
}
return pending_irobs[index];
}
bool
PendingIROBLattice::erase(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
//TimeFunctionBody timer("pending_irobs.erase(const_accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size() ||
pending_irobs[index] == NULL) {
return false;
}
past_irobs.insert(id);
min_dominator_set.erase(id);
PendingIROB *victim = pending_irobs[index];
pending_irobs[index] = NULL; // caller must free it
while (!pending_irobs.empty() && pending_irobs[0] == NULL) {
pending_irobs.pop_front();
offset++;
}
dbgprintf("Notifying dependents of IROB %d's release: [ ", id);
for (irob_id_set::iterator it = victim->dependents.begin();
it != victim->dependents.end(); it++) {
PendingIROB *dependent = this->find_locked(*it);
if (dependent == NULL) {
dbgprintf_plain("(%ld) ", *it);
continue;
}
dbgprintf_plain("%ld ", dependent->id);
dependent->dep_satisfied(id);
}
dbgprintf_plain("]\n");
return true;
}
bool
PendingIROBLattice::past_irob_exists(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return past_irobs.contains(id);
}
bool
PendingIROBLattice::empty()
{
PthreadScopedLock lock(&membership_lock);
return pending_irobs.empty();
}
IROBSchedulingData::IROBSchedulingData(irob_id_t id_, u_long seqno_)
: id(id_), seqno(seqno_)
{
/* empty */
}
bool
IROBSchedulingData::operator<(const IROBSchedulingData& other) const
{
// can implement priority here, based on
// any added scheduling hints
return (id < other.id) || (seqno < other.seqno);
}
<|endoftext|> |
<commit_before>#ifndef STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP
#define STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP
#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/math/prim/scal.hpp>
#include <stan/mcmc/hmc/base_hmc.hpp>
#include <stan/mcmc/hmc/hamiltonians/ps_point.hpp>
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
namespace stan {
namespace mcmc {
/**
* The No-U-Turn sampler (NUTS) with multinomial sampling
*/
template <class Model, template<class, class> class Hamiltonian,
template<class> class Integrator, class BaseRNG>
class base_nuts : public base_hmc<Model, Hamiltonian, Integrator, BaseRNG> {
public:
base_nuts(const Model& model, BaseRNG& rng)
: base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng),
depth_(0), max_depth_(5), max_deltaH_(1000),
n_leapfrog_(0), divergent_(0), energy_(0) {
}
~base_nuts() {}
void set_max_depth(int d) {
if (d > 0)
max_depth_ = d;
}
void set_max_delta(double d) {
max_deltaH_ = d;
}
int get_max_depth() { return this->max_depth_; }
double get_max_delta() { return this->max_deltaH_; }
sample
transition(sample& init_sample,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
// Initialize the algorithm
this->sample_stepsize();
this->seed(init_sample.cont_params());
this->hamiltonian_.sample_p(this->z_, this->rand_int_);
this->hamiltonian_.init(this->z_, info_writer, error_writer);
ps_point z_plus(this->z_);
ps_point z_minus(z_plus);
ps_point z_sample(z_plus);
ps_point z_propose(z_plus);
Eigen::VectorXd p_sharp_plus = this->hamiltonian_.dtau_dp(this->z_);
Eigen::VectorXd p_sharp_minus = this->hamiltonian_.dtau_dp(this->z_);
Eigen::VectorXd rho = this->z_.p;
double log_sum_weight = 0; // log(exp(H0 - H0))
double H0 = this->hamiltonian_.H(this->z_);
int n_leapfrog = 0;
double sum_metro_prob = 1; // exp(H0 - H0)
// Build a trajectory until the NUTS criterion is no longer satisfied
this->depth_ = 0;
this->divergent_ = false;
while (this->depth_ < this->max_depth_) {
// Build a new subtree in a random direction
Eigen::VectorXd rho_subtree(rho.size());
rho_subtree.setZero();
bool valid_subtree = false;
double log_sum_weight_subtree
= -std::numeric_limits<double>::infinity();
if (this->rand_uniform_() > 0.5) {
this->z_.ps_point::operator=(z_plus);
valid_subtree
= build_tree(this->depth_, rho_subtree, z_propose,
H0, 1, n_leapfrog,
log_sum_weight_subtree, sum_metro_prob,
info_writer, error_writer);
z_plus.ps_point::operator=(this->z_);
p_sharp_plus = this->hamiltonian_.dtau_dp(this->z_);
} else {
this->z_.ps_point::operator=(z_minus);
valid_subtree
= build_tree(this->depth_, rho_subtree, z_propose,
H0, -1, n_leapfrog,
log_sum_weight_subtree, sum_metro_prob,
info_writer, error_writer);
z_minus.ps_point::operator=(this->z_);
p_sharp_minus = this->hamiltonian_.dtau_dp(this->z_);
}
if (!valid_subtree) break;
// Sample from an accepted subtree
++(this->depth_);
if (log_sum_weight_subtree > log_sum_weight) {
z_sample = z_propose;
} else {
double accept_prob
= std::exp(log_sum_weight_subtree - log_sum_weight);
if (this->rand_uniform_() < accept_prob)
z_sample = z_propose;
}
log_sum_weight
= math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);
// Break when NUTS criterion is no longer satisfied
rho += rho_subtree;
if (!compute_criterion(p_sharp_minus, p_sharp_plus, rho))
break;
}
this->n_leapfrog_ = n_leapfrog;
// Compute average acceptance probabilty across entire trajectory,
// even over subtrees that may have been rejected
double accept_prob
= sum_metro_prob / static_cast<double>(n_leapfrog + 1);
this->z_.ps_point::operator=(z_sample);
this->energy_ = this->hamiltonian_.H(this->z_);
return sample(this->z_.q, -this->z_.V, accept_prob);
}
void get_sampler_param_names(std::vector<std::string>& names) {
names.push_back("stepsize__");
names.push_back("treedepth__");
names.push_back("n_leapfrog__");
names.push_back("divergent__");
names.push_back("energy__");
}
void get_sampler_params(std::vector<double>& values) {
values.push_back(this->epsilon_);
values.push_back(this->depth_);
values.push_back(this->n_leapfrog_);
values.push_back(this->divergent_);
values.push_back(this->energy_);
}
bool compute_criterion(Eigen::VectorXd& p_sharp_minus,
Eigen::VectorXd& p_sharp_plus,
Eigen::VectorXd& rho) {
return p_sharp_plus.dot(rho) > 0
&& p_sharp_minus.dot(rho) > 0;
}
/**
* Recursively build a new subtree to completion or until
* the subtree becomes invalid. Returns validity of the
* resulting subtree.
*
* @param depth Depth of the desired subtree
* @param rho Summed momentum across trajectory
* @param z_propose State proposed from subtree
* @param H0 Hamiltonian of initial state
* @param sign Direction in time to built subtree
* @param n_leapfrog Summed number of leapfrog evaluations
* @param log_sum_weight Log of summed weights across trajectory
* @param sum_metro_prob Summed Metropolis probabilities across trajectory
* @param info_writer Stream for information messages
* @param error_writer Stream for error messages
*/
bool build_tree(int depth, Eigen::VectorXd& rho, ps_point& z_propose,
double H0, double sign, int& n_leapfrog,
double& log_sum_weight, double& sum_metro_prob,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
// Base case
if (depth == 0) {
this->integrator_.evolve(this->z_, this->hamiltonian_,
sign * this->epsilon_,
info_writer, error_writer);
++n_leapfrog;
double h = this->hamiltonian_.H(this->z_);
if (boost::math::isnan(h))
h = std::numeric_limits<double>::infinity();
if ((h - H0) > this->max_deltaH_) this->divergent_ = true;
log_sum_weight = math::log_sum_exp(log_sum_weight, H0 - h);
if (H0 - h > 0)
sum_metro_prob += 1;
else
sum_metro_prob += std::exp(H0 - h);
z_propose = this->z_;
rho += this->z_.p;
return !this->divergent_;
}
// General recursion
// Build the left subtree
double log_sum_weight_left = -std::numeric_limits<double>::infinity();
Eigen::VectorXd rho_left(rho.size());
rho_left.setZero();
Eigen::VectorXd p_sharp_left = this->hamiltonian_.dtau_dp(this->z_);
bool valid_left
= build_tree(depth - 1, rho_left, z_propose,
H0, sign, n_leapfrog,
log_sum_weight_left, sum_metro_prob,
info_writer, error_writer);
if (!valid_left) return false;
// Build the right subtree
ps_point z_propose_right(this->z_);
double log_sum_weight_right = -std::numeric_limits<double>::infinity();
Eigen::VectorXd rho_right(rho.size());
rho_right.setZero();
bool valid_right
= build_tree(depth - 1, rho_right, z_propose_right,
H0, sign, n_leapfrog,
log_sum_weight_right, sum_metro_prob,
info_writer, error_writer);
if (!valid_right) return false;
// Multinomial sample from right subtree
double log_sum_weight_subtree
= math::log_sum_exp(log_sum_weight_left, log_sum_weight_right);
log_sum_weight
= math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);
if (log_sum_weight_right > log_sum_weight_subtree) {
z_propose = z_propose_right;
} else {
double accept_prob
= std::exp(log_sum_weight_right - log_sum_weight_subtree);
if (this->rand_uniform_() < accept_prob)
z_propose = z_propose_right;
}
Eigen::VectorXd rho_subtree = rho_left + rho_right;
rho += rho_subtree;
Eigen::VectorXd p_sharp_right = this->hamiltonian_.dtau_dp(this->z_);
return compute_criterion(p_sharp_left, p_sharp_right, rho_subtree);
}
int depth_;
int max_depth_;
double max_deltaH_;
int n_leapfrog_;
bool divergent_;
double energy_;
};
} // mcmc
} // stan
#endif
<commit_msg>Fix build tree to return p_sharp at the boundaries to enable valid evaluation of the termination criterion<commit_after>#ifndef STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP
#define STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP
#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/math/prim/scal.hpp>
#include <stan/mcmc/hmc/base_hmc.hpp>
#include <stan/mcmc/hmc/hamiltonians/ps_point.hpp>
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
namespace stan {
namespace mcmc {
/**
* The No-U-Turn sampler (NUTS) with multinomial sampling
*/
template <class Model, template<class, class> class Hamiltonian,
template<class> class Integrator, class BaseRNG>
class base_nuts : public base_hmc<Model, Hamiltonian, Integrator, BaseRNG> {
public:
base_nuts(const Model& model, BaseRNG& rng)
: base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng),
depth_(0), max_depth_(5), max_deltaH_(1000),
n_leapfrog_(0), divergent_(0), energy_(0) {
}
~base_nuts() {}
void set_max_depth(int d) {
if (d > 0)
max_depth_ = d;
}
void set_max_delta(double d) {
max_deltaH_ = d;
}
int get_max_depth() { return this->max_depth_; }
double get_max_delta() { return this->max_deltaH_; }
sample
transition(sample& init_sample,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
// Initialize the algorithm
this->sample_stepsize();
this->seed(init_sample.cont_params());
this->hamiltonian_.sample_p(this->z_, this->rand_int_);
this->hamiltonian_.init(this->z_, info_writer, error_writer);
ps_point z_plus(this->z_);
ps_point z_minus(z_plus);
ps_point z_sample(z_plus);
ps_point z_propose(z_plus);
Eigen::VectorXd p_sharp_plus = this->hamiltonian_.dtau_dp(this->z_);
Eigen::VectorXd p_sharp_dummy = p_sharp_plus;
Eigen::VectorXd p_sharp_minus = p_sharp_plus;
Eigen::VectorXd rho = this->z_.p;
double log_sum_weight = 0; // log(exp(H0 - H0))
double H0 = this->hamiltonian_.H(this->z_);
int n_leapfrog = 0;
double sum_metro_prob = 1; // exp(H0 - H0)
// Build a trajectory until the NUTS criterion is no longer satisfied
this->depth_ = 0;
this->divergent_ = false;
while (this->depth_ < this->max_depth_) {
// Build a new subtree in a random direction
Eigen::VectorXd rho_subtree = Eigen::VectorXd::Zero(rho.size());
bool valid_subtree = false;
double log_sum_weight_subtree
= -std::numeric_limits<double>::infinity();
if (this->rand_uniform_() > 0.5) {
this->z_.ps_point::operator=(z_plus);
valid_subtree
= build_tree(this->depth_, z_propose,
p_sharp_dummy, p_sharp_plus, rho_subtree,
H0, 1, n_leapfrog,
log_sum_weight_subtree, sum_metro_prob,
info_writer, error_writer);
z_plus.ps_point::operator=(this->z_);
} else {
this->z_.ps_point::operator=(z_minus);
valid_subtree
= build_tree(this->depth_, z_propose,
p_sharp_dummy, p_sharp_minus, rho_subtree,
H0, -1, n_leapfrog,
log_sum_weight_subtree, sum_metro_prob,
info_writer, error_writer);
z_minus.ps_point::operator=(this->z_);
}
if (!valid_subtree) break;
// Sample from an accepted subtree
++(this->depth_);
if (log_sum_weight_subtree > log_sum_weight) {
z_sample = z_propose;
} else {
double accept_prob
= std::exp(log_sum_weight_subtree - log_sum_weight);
if (this->rand_uniform_() < accept_prob)
z_sample = z_propose;
}
log_sum_weight
= math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);
// Break when NUTS criterion is no longer satisfied
rho += rho_subtree;
if (!compute_criterion(p_sharp_minus, p_sharp_plus, rho))
break;
}
this->n_leapfrog_ = n_leapfrog;
// Compute average acceptance probabilty across entire trajectory,
// even over subtrees that may have been rejected
double accept_prob
= sum_metro_prob / static_cast<double>(n_leapfrog + 1);
this->z_.ps_point::operator=(z_sample);
this->energy_ = this->hamiltonian_.H(this->z_);
return sample(this->z_.q, -this->z_.V, accept_prob);
}
void get_sampler_param_names(std::vector<std::string>& names) {
names.push_back("stepsize__");
names.push_back("treedepth__");
names.push_back("n_leapfrog__");
names.push_back("divergent__");
names.push_back("energy__");
}
void get_sampler_params(std::vector<double>& values) {
values.push_back(this->epsilon_);
values.push_back(this->depth_);
values.push_back(this->n_leapfrog_);
values.push_back(this->divergent_);
values.push_back(this->energy_);
}
bool compute_criterion(Eigen::VectorXd& p_sharp_minus,
Eigen::VectorXd& p_sharp_plus,
Eigen::VectorXd& rho) {
return p_sharp_plus.dot(rho) > 0
&& p_sharp_minus.dot(rho) > 0;
}
/**
* Recursively build a new subtree to completion or until
* the subtree becomes invalid. Returns validity of the
* resulting subtree.
*
* @param depth Depth of the desired subtree
* @param z_propose State proposed from subtree
* @param p_sharp_left p_sharp from left boundary of returned tree
* @param p_shart_right p_sharp from the right boundary of returned tree
* @param rho Summed momentum across trajectory
* @param H0 Hamiltonian of initial state
* @param sign Direction in time to built subtree
* @param n_leapfrog Summed number of leapfrog evaluations
* @param log_sum_weight Log of summed weights across trajectory
* @param sum_metro_prob Summed Metropolis probabilities across trajectory
* @param info_writer Stream for information messages
* @param error_writer Stream for error messages
*/
bool build_tree(int depth, ps_point& z_propose,
Eigen::VectorXd& p_sharp_left,
Eigen::VectorXd& p_sharp_right,
Eigen::VectorXd& rho,
double H0, double sign, int& n_leapfrog,
double& log_sum_weight, double& sum_metro_prob,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
// Base case
if (depth == 0) {
this->integrator_.evolve(this->z_, this->hamiltonian_,
sign * this->epsilon_,
info_writer, error_writer);
++n_leapfrog;
double h = this->hamiltonian_.H(this->z_);
if (boost::math::isnan(h))
h = std::numeric_limits<double>::infinity();
if ((h - H0) > this->max_deltaH_) this->divergent_ = true;
log_sum_weight = math::log_sum_exp(log_sum_weight, H0 - h);
if (H0 - h > 0)
sum_metro_prob += 1;
else
sum_metro_prob += std::exp(H0 - h);
z_propose = this->z_;
rho += this->z_.p;
p_sharp_left = this->hamiltonian_.dtau_dp(this->z_);
p_sharp_right = p_sharp_left;
return !this->divergent_;
}
// General recursion
Eigen::VectorXd p_sharp_dummy(this->z_.p.size());
// Build the left subtree
double log_sum_weight_left = -std::numeric_limits<double>::infinity();
Eigen::VectorXd rho_left = Eigen::VectorXd::Zero(rho.size());
bool valid_left
= build_tree(depth - 1, z_propose,
p_sharp_left, p_sharp_dummy, rho_left,
H0, sign, n_leapfrog,
log_sum_weight_left, sum_metro_prob,
info_writer, error_writer);
if (!valid_left) return false;
// Build the right subtree
ps_point z_propose_right(this->z_);
double log_sum_weight_right = -std::numeric_limits<double>::infinity();
Eigen::VectorXd rho_right = Eigen::VectorXd::Zero(rho.size());
bool valid_right
= build_tree(depth - 1, z_propose_right,
p_sharp_dummy, p_sharp_right, rho_right,
H0, sign, n_leapfrog,
log_sum_weight_right, sum_metro_prob,
info_writer, error_writer);
if (!valid_right) return false;
// Multinomial sample from right subtree
double log_sum_weight_subtree
= math::log_sum_exp(log_sum_weight_left, log_sum_weight_right);
log_sum_weight
= math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);
if (log_sum_weight_right > log_sum_weight_subtree) {
z_propose = z_propose_right;
} else {
double accept_prob
= std::exp(log_sum_weight_right - log_sum_weight_subtree);
if (this->rand_uniform_() < accept_prob)
z_propose = z_propose_right;
}
Eigen::VectorXd rho_subtree = rho_left + rho_right;
rho += rho_subtree;
return compute_criterion(p_sharp_left, p_sharp_right, rho_subtree);
}
int depth_;
int max_depth_;
double max_deltaH_;
int n_leapfrog_;
bool divergent_;
double energy_;
};
} // mcmc
} // stan
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by: (MA) Mike Avery <averym@uci.edu>, (MB) Michael Beyeler <mbeyeler@uci.edu>,
* (KDC) Kristofor Carlson <kdcarlso@uci.edu>
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARL/CARLsim/
* Ver 2/22/14
*/
#include <carlsim.h>
int main()
{
// simulation details
int N = 1000; // number of neurons
int ithGPU = 0; // run on first GPU
// create a network
CARLsim sim("random",1,42,CPU_MODE,ithGPU);
int g1=sim.createGroup("excit", N*0.8, EXCITATORY_NEURON);
sim.setNeuronParameters(g1, 0.02f, 0.2f, -65.0f, 8.0f);
int g2=sim.createGroup("inhib", N*0.2, INHIBITORY_NEURON);
sim.setNeuronParameters(g2, 0.1f, 0.2f, -65.0f, 2.0f);
int gin=sim.createSpikeGeneratorGroup("input",N*0.1,EXCITATORY_NEURON);
sim.setConductances(ALL,true);
// make random connections with 10% probability
sim.connect(g2,g2,"random",-0.01f,0.1f,1);
// make random connections with 10% probability, and random delays between 1 and 20
sim.connect(g1,g2,"random", 0.0025f, 0.005f, 0.1f, 1, 20, SYN_PLASTIC);
sim.connect(g1,g1,"random", 0.006f, 0.01f, 0.1f, 1, 20, SYN_PLASTIC);
// 5% probability of connection
sim.connect(gin,g1,"random", 1.0f, 1.0f, 0.05f, 1, 20, SYN_FIXED);
// here we define and set the properties of the STDP.
float ALPHA_LTP = 0.10f/100, TAU_LTP = 20.0f, ALPHA_LTD = 0.12f/100, TAU_LTD = 20.0f;
sim.setSTDP(g1, true, ALPHA_LTP, TAU_LTP, ALPHA_LTD, TAU_LTD);
// show logout every 10 secs, enabled with level 1 and output to stdout.
sim.setLogCycle(1, 1, stdout);
// put spike times into spikes.dat
sim.setSpikeMonitor(g1,"results/random/spikes.dat");
// Show basic statistics about g2
sim.setSpikeMonitor(g2);
sim.setSpikeMonitor(gin);
//setup some baseline input
PoissonRate in(N*0.1);
for (int i=0;i<N*0.1;i++) in.rates[i] = 1;
sim.setSpikeRate(gin,&in);
//run for 10 seconds
for(int i=0; i < 10; i++) {
// run the established network for a duration of 1 (sec) and 0 (millisecond)
sim.runNetwork(1,0);
}
FILE* nid = fopen("results/random/network.dat","wb");
sim.writeNetwork(nid);
fclose(nid);
return 0;
}
<commit_msg>main_random.cpp: decreased recurrent exc. weights to lower NMDA currents<commit_after>/*
* Copyright (c) 2013 Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by: (MA) Mike Avery <averym@uci.edu>, (MB) Michael Beyeler <mbeyeler@uci.edu>,
* (KDC) Kristofor Carlson <kdcarlso@uci.edu>
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARL/CARLsim/
* Ver 2/22/14
*/
#include <carlsim.h>
int main()
{
// simulation details
int N = 1000; // number of neurons
int ithGPU = 0; // run on first GPU
// create a network
CARLsim sim("random",1,42,CPU_MODE,ithGPU);
int g1=sim.createGroup("excit", N*0.8, EXCITATORY_NEURON);
sim.setNeuronParameters(g1, 0.02f, 0.2f, -65.0f, 8.0f);
int g2=sim.createGroup("inhib", N*0.2, INHIBITORY_NEURON);
sim.setNeuronParameters(g2, 0.1f, 0.2f, -65.0f, 2.0f);
int gin=sim.createSpikeGeneratorGroup("input",N*0.1,EXCITATORY_NEURON);
sim.setConductances(ALL,true);
// make random connections with 10% probability
sim.connect(g2,g2,"random",-0.01f,0.1f,1);
// make random connections with 10% probability, and random delays between 1 and 20
sim.connect(g1,g2,"random", 0.0025f, 0.005f, 0.1f, 1, 20, SYN_PLASTIC);
sim.connect(g1,g1,"random", 0.006f, 0.01f, 0.1f, 1, 20, SYN_PLASTIC);
// 5% probability of connection
sim.connect(gin,g1,"random", 0.5f, 0.5f, 0.05f, 1, 20, SYN_FIXED);
// here we define and set the properties of the STDP.
float ALPHA_LTP = 0.10f/100, TAU_LTP = 20.0f, ALPHA_LTD = 0.12f/100, TAU_LTD = 20.0f;
sim.setSTDP(g1, true, ALPHA_LTP, TAU_LTP, ALPHA_LTD, TAU_LTD);
// show logout every 10 secs, enabled with level 1 and output to stdout.
sim.setLogCycle(1, 1, stdout);
// put spike times into spikes.dat
sim.setSpikeMonitor(g1,"results/random/spikes.dat");
// Show basic statistics about g2
sim.setSpikeMonitor(g2);
sim.setSpikeMonitor(gin);
//setup some baseline input
PoissonRate in(N*0.1);
for (int i=0;i<N*0.1;i++) in.rates[i] = 1;
sim.setSpikeRate(gin,&in);
//run for 10 seconds
for(int i=0; i < 10; i++) {
// run the established network for a duration of 1 (sec) and 0 (millisecond)
sim.runNetwork(1,0);
}
FILE* nid = fopen("results/random/network.dat","wb");
sim.writeNetwork(nid);
fclose(nid);
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "../connection.h"
#include "view.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(drilldown);
QApplication app(argc, argv);
if (!createConnection())
return 1;
View view("offices", "images");
#ifndef Q_OS_SYMBIAN
view.show();
#else
view.showFullScreen();
#endif
return app.exec();
}
<commit_msg>Enable mouse cursor in drilldown example<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "../connection.h"
#include "view.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(drilldown);
QApplication app(argc, argv);
if (!createConnection())
return 1;
View view("offices", "images");
#ifndef Q_OS_SYMBIAN
view.show();
#else
view.showFullScreen();
#endif
#ifdef QT_KEYPAD_NAVIGATION
QApplication::setNavigationMode(Qt::NavigationModeCursorAuto);
#endif
return app.exec();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* spatializer.cpp: sound reverberation
*****************************************************************************
* Copyright (C) 2004, 2006, 2007 the VideoLAN team
*
* Google Summer of Code 2007
*
* Authors: Biodun Osunkunle <biodun@videolan.org>
*
* Mentor : Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h> /* malloc(), free() */
#include <math.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_aout.h>
#include "revmodel.hpp"
#define SPAT_AMP 0.3
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open ( vlc_object_t * );
static void Close( vlc_object_t * );
#define ROOMSIZE_TEXT N_("Room size")
#define ROOMSIZE_LONGTEXT N_("Defines the virtual surface of the room" \
" emulated by the filter." )
#define WIDTH_TEXT N_("Room width")
#define WIDTH_LONGTEXT N_("Width of the virtual room")
#define WET_TEXT N_("Wet")
#define WET_LONGTEXT NULL
#define DRY_TEXT N_("Dry")
#define DRY_LONGTEXT NULL
#define DAMP_TEXT N_("Damp")
#define DAMP_LONGTEXT NULL
vlc_module_begin ()
set_description( N_("Audio Spatializer") )
set_shortname( N_("Spatializer" ) )
set_capability( "audio filter", 0 )
set_category( CAT_AUDIO )
set_subcategory( SUBCAT_AUDIO_AFILTER )
set_callbacks( Open, Close )
add_shortcut( "spatializer" )
add_float( "spatializer-roomsize", 1.05, NULL, ROOMSIZE_TEXT,
ROOMSIZE_LONGTEXT, true )
add_float( "spatializer-width", 10., NULL, WIDTH_TEXT,WIDTH_LONGTEXT, true )
add_float( "spatializer-wet", 3., NULL, WET_TEXT,WET_LONGTEXT, true )
add_float( "spatializer-dry", 2., NULL, DRY_TEXT,DRY_LONGTEXT, true )
add_float( "spatializer-damp", 1., NULL, DAMP_TEXT,DAMP_LONGTEXT, true )
vlc_module_end ()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
struct aout_filter_sys_t
{
vlc_mutex_t lock;
revmodel *p_reverbm;
};
class CLocker
{
public:
CLocker( vlc_mutex_t *p_lock_to_manage ) : p_lock(p_lock_to_manage)
{
vlc_mutex_lock( p_lock );
}
~CLocker()
{
vlc_mutex_unlock( p_lock );
}
private:
vlc_mutex_t *p_lock;
};
#define DECLARECB(fn) static int fn (vlc_object_t *,char const *, \
vlc_value_t, vlc_value_t, void *)
DECLARECB( RoomCallback );
DECLARECB( WetCallback );
DECLARECB( DryCallback );
DECLARECB( DampCallback );
DECLARECB( WidthCallback );
#undef DECLARECB
struct callback_s {
const char *psz_name;
int (*fp_callback)(vlc_object_t *,const char *,
vlc_value_t,vlc_value_t,void *);
void (revmodel::* fp_set)(float);
};
static const callback_s callbacks[] = {
{ "spatializer-roomsize", RoomCallback, &revmodel::setroomsize },
{ "spatializer-width", WidthCallback, &revmodel::setwidth },
{ "spatializer-wet", WetCallback, &revmodel::setwet },
{ "spatializer-dry", DryCallback, &revmodel::setdry },
{ "spatializer-damp", DampCallback, &revmodel::setdamp }
};
enum { num_callbacks=sizeof(callbacks)/sizeof(callback_s) };
static void DoWork( aout_instance_t *, aout_filter_t *,
aout_buffer_t *, aout_buffer_t * );
static void SpatFilter( aout_instance_t *,aout_filter_t *, float *, float *,
int, int );
/*****************************************************************************
* Open:
*****************************************************************************/
static int Open( vlc_object_t *p_this )
{
aout_filter_t *p_filter = (aout_filter_t *)p_this;
aout_filter_sys_t *p_sys;
aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;
bool b_fit = true;
msg_Dbg( p_this, "Opening filter spatializer" );
if( p_filter->input.i_format != VLC_CODEC_FL32 ||
p_filter->output.i_format != VLC_CODEC_FL32 )
{
b_fit = false;
p_filter->input.i_format = VLC_CODEC_FL32;
p_filter->output.i_format = VLC_CODEC_FL32;
msg_Warn( p_filter, "bad input or output format" );
}
if ( !AOUT_FMTS_SIMILAR( &p_filter->input, &p_filter->output ) )
{
b_fit = false;
memcpy( &p_filter->output, &p_filter->input,
sizeof(audio_sample_format_t) );
msg_Warn( p_filter, "input and output formats are not similar" );
}
if ( ! b_fit )
{
return VLC_EGENERIC;
}
p_filter->pf_do_work = DoWork;
p_filter->b_in_place = true;
/* Allocate structure */
p_sys = p_filter->p_sys = (aout_filter_sys_t*)malloc( sizeof( aout_filter_sys_t ) );
if( !p_sys )
return VLC_ENOMEM;
vlc_mutex_init( &p_sys->lock );
/* Init the variables *//* Add the callbacks */
p_sys->p_reverbm = new revmodel();
for(unsigned i=0;i<num_callbacks;++i)
{
/* NOTE: C++ pointer-to-member function call from table lookup. */
(p_sys->p_reverbm->*(callbacks[i].fp_set))
(var_CreateGetFloatCommand(p_aout,callbacks[i].psz_name));
var_AddCallback( p_aout, callbacks[i].psz_name,
callbacks[i].fp_callback, p_sys );
}
return VLC_SUCCESS;
}
/*****************************************************************************
* Close: close the plugin
*****************************************************************************/
static void Close( vlc_object_t *p_this )
{
aout_filter_t *p_filter = (aout_filter_t *)p_this;
aout_filter_sys_t *p_sys = p_filter->p_sys;
aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;
/* Delete the callbacks */
for(unsigned i=0;i<num_callbacks;++i)
{
var_DelCallback( p_aout, callbacks[i].psz_name,
callbacks[i].fp_callback, p_sys );
}
delete p_sys->p_reverbm;
vlc_mutex_destroy( &p_sys->lock );
free( p_sys );
msg_Dbg( p_this, "Closing filter spatializer" );
}
/*****************************************************************************
* DoWork: process samples buffer
*****************************************************************************/
static void DoWork( aout_instance_t * p_aout, aout_filter_t * p_filter,
aout_buffer_t * p_in_buf, aout_buffer_t * p_out_buf )
{
p_out_buf->i_nb_samples = p_in_buf->i_nb_samples;
p_out_buf->i_nb_bytes = p_in_buf->i_nb_bytes;
SpatFilter( p_aout, p_filter, (float*)p_out_buf->p_buffer,
(float*)p_in_buf->p_buffer, p_in_buf->i_nb_samples,
aout_FormatNbChannels( &p_filter->input ) );
}
static void SpatFilter( aout_instance_t *p_aout,
aout_filter_t *p_filter, float *out, float *in,
int i_samples, int i_channels )
{
aout_filter_sys_t *p_sys = p_filter->p_sys;
CLocker locker( &p_sys->lock );
int i, ch;
for( i = 0; i < i_samples; i++ )
{
for( ch = 0 ; ch < 2; ch++)
{
in[ch] = in[ch] * SPAT_AMP;
}
p_sys->p_reverbm->processreplace( in, out , 1, i_channels);
in += i_channels;
out += i_channels;
}
}
/*****************************************************************************
* Variables callbacks
*****************************************************************************/
static int RoomCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setroomsize(newval.f_float);
msg_Dbg( p_this, "room size is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int WidthCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setwidth(newval.f_float);
msg_Dbg( p_this, "width is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int WetCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setwet(newval.f_float);
msg_Dbg( p_this, "'wet' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int DryCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setdry(newval.f_float);
msg_Dbg( p_this, "'dry' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int DampCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setdamp(newval.f_float);
msg_Dbg( p_this, "'damp' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
<commit_msg>Force new not to throw. Also drop a separate declaration of a static function that's called exactly once, and mark it inline instead.<commit_after>/*****************************************************************************
* spatializer.cpp: sound reverberation
*****************************************************************************
* Copyright (C) 2004, 2006, 2007 the VideoLAN team
*
* Google Summer of Code 2007
*
* Authors: Biodun Osunkunle <biodun@videolan.org>
*
* Mentor : Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h> /* malloc(), free() */
#include <math.h>
#include <new>
using std::nothrow;
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_aout.h>
#include "revmodel.hpp"
#define SPAT_AMP 0.3
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open ( vlc_object_t * );
static void Close( vlc_object_t * );
#define ROOMSIZE_TEXT N_("Room size")
#define ROOMSIZE_LONGTEXT N_("Defines the virtual surface of the room" \
" emulated by the filter." )
#define WIDTH_TEXT N_("Room width")
#define WIDTH_LONGTEXT N_("Width of the virtual room")
#define WET_TEXT N_("Wet")
#define WET_LONGTEXT NULL
#define DRY_TEXT N_("Dry")
#define DRY_LONGTEXT NULL
#define DAMP_TEXT N_("Damp")
#define DAMP_LONGTEXT NULL
vlc_module_begin ()
set_description( N_("Audio Spatializer") )
set_shortname( N_("Spatializer" ) )
set_capability( "audio filter", 0 )
set_category( CAT_AUDIO )
set_subcategory( SUBCAT_AUDIO_AFILTER )
set_callbacks( Open, Close )
add_shortcut( "spatializer" )
add_float( "spatializer-roomsize", 1.05, NULL, ROOMSIZE_TEXT,
ROOMSIZE_LONGTEXT, true )
add_float( "spatializer-width", 10., NULL, WIDTH_TEXT,WIDTH_LONGTEXT, true )
add_float( "spatializer-wet", 3., NULL, WET_TEXT,WET_LONGTEXT, true )
add_float( "spatializer-dry", 2., NULL, DRY_TEXT,DRY_LONGTEXT, true )
add_float( "spatializer-damp", 1., NULL, DAMP_TEXT,DAMP_LONGTEXT, true )
vlc_module_end ()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
struct aout_filter_sys_t
{
vlc_mutex_t lock;
revmodel *p_reverbm;
};
class CLocker
{
public:
CLocker( vlc_mutex_t *p_lock_to_manage ) : p_lock(p_lock_to_manage)
{
vlc_mutex_lock( p_lock );
}
~CLocker()
{
vlc_mutex_unlock( p_lock );
}
private:
vlc_mutex_t *p_lock;
};
#define DECLARECB(fn) static int fn (vlc_object_t *,char const *, \
vlc_value_t, vlc_value_t, void *)
DECLARECB( RoomCallback );
DECLARECB( WetCallback );
DECLARECB( DryCallback );
DECLARECB( DampCallback );
DECLARECB( WidthCallback );
#undef DECLARECB
struct callback_s {
const char *psz_name;
int (*fp_callback)(vlc_object_t *,const char *,
vlc_value_t,vlc_value_t,void *);
void (revmodel::* fp_set)(float);
};
static const callback_s callbacks[] = {
{ "spatializer-roomsize", RoomCallback, &revmodel::setroomsize },
{ "spatializer-width", WidthCallback, &revmodel::setwidth },
{ "spatializer-wet", WetCallback, &revmodel::setwet },
{ "spatializer-dry", DryCallback, &revmodel::setdry },
{ "spatializer-damp", DampCallback, &revmodel::setdamp }
};
enum { num_callbacks=sizeof(callbacks)/sizeof(callback_s) };
static void DoWork( aout_instance_t *, aout_filter_t *,
aout_buffer_t *, aout_buffer_t * );
/*****************************************************************************
* Open:
*****************************************************************************/
static int Open( vlc_object_t *p_this )
{
aout_filter_t *p_filter = (aout_filter_t *)p_this;
aout_filter_sys_t *p_sys;
aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;
bool b_fit = true;
msg_Dbg( p_this, "Opening filter spatializer" );
if( p_filter->input.i_format != VLC_CODEC_FL32 ||
p_filter->output.i_format != VLC_CODEC_FL32 )
{
b_fit = false;
p_filter->input.i_format = VLC_CODEC_FL32;
p_filter->output.i_format = VLC_CODEC_FL32;
msg_Warn( p_filter, "bad input or output format" );
}
if ( !AOUT_FMTS_SIMILAR( &p_filter->input, &p_filter->output ) )
{
b_fit = false;
memcpy( &p_filter->output, &p_filter->input,
sizeof(audio_sample_format_t) );
msg_Warn( p_filter, "input and output formats are not similar" );
}
if ( ! b_fit )
{
return VLC_EGENERIC;
}
p_filter->pf_do_work = DoWork;
p_filter->b_in_place = true;
/* Allocate structure */
p_sys = p_filter->p_sys = (aout_filter_sys_t*)malloc( sizeof( aout_filter_sys_t ) );
if( !p_sys )
return VLC_ENOMEM;
vlc_mutex_init( &p_sys->lock );
/* Force new to return 0 on failure instead of throwing, since we don't
want an exception to leak back to C code. Bad things would happen. */
p_sys->p_reverbm = new (nothrow) revmodel;
if( !p_sys->p_reverbm )
return VLC_ENOMEM;
for(unsigned i=0;i<num_callbacks;++i)
{
/* NOTE: C++ pointer-to-member function call from table lookup. */
(p_sys->p_reverbm->*(callbacks[i].fp_set))
(var_CreateGetFloatCommand(p_aout,callbacks[i].psz_name));
var_AddCallback( p_aout, callbacks[i].psz_name,
callbacks[i].fp_callback, p_sys );
}
return VLC_SUCCESS;
}
/*****************************************************************************
* Close: close the plugin
*****************************************************************************/
static void Close( vlc_object_t *p_this )
{
aout_filter_t *p_filter = (aout_filter_t *)p_this;
aout_filter_sys_t *p_sys = p_filter->p_sys;
aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;
/* Delete the callbacks */
for(unsigned i=0;i<num_callbacks;++i)
{
var_DelCallback( p_aout, callbacks[i].psz_name,
callbacks[i].fp_callback, p_sys );
}
delete p_sys->p_reverbm;
vlc_mutex_destroy( &p_sys->lock );
free( p_sys );
msg_Dbg( p_this, "Closing filter spatializer" );
}
/*****************************************************************************
* SpatFilter: process samples buffer
* DoWork: call SpatFilter
*****************************************************************************/
static inline
void SpatFilter( aout_instance_t *p_aout, aout_filter_t *p_filter,
float *out, float *in, int i_samples, int i_channels )
{
aout_filter_sys_t *p_sys = p_filter->p_sys;
CLocker locker( &p_sys->lock );
int i, ch;
for( i = 0; i < i_samples; i++ )
{
for( ch = 0 ; ch < 2; ch++)
{
in[ch] = in[ch] * SPAT_AMP;
}
p_sys->p_reverbm->processreplace( in, out , 1, i_channels);
in += i_channels;
out += i_channels;
}
}
static void DoWork( aout_instance_t * p_aout, aout_filter_t * p_filter,
aout_buffer_t * p_in_buf, aout_buffer_t * p_out_buf )
{
p_out_buf->i_nb_samples = p_in_buf->i_nb_samples;
p_out_buf->i_nb_bytes = p_in_buf->i_nb_bytes;
SpatFilter( p_aout, p_filter, (float*)p_out_buf->p_buffer,
(float*)p_in_buf->p_buffer, p_in_buf->i_nb_samples,
aout_FormatNbChannels( &p_filter->input ) );
}
/*****************************************************************************
* Variables callbacks
*****************************************************************************/
static int RoomCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setroomsize(newval.f_float);
msg_Dbg( p_this, "room size is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int WidthCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setwidth(newval.f_float);
msg_Dbg( p_this, "width is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int WetCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setwet(newval.f_float);
msg_Dbg( p_this, "'wet' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int DryCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setdry(newval.f_float);
msg_Dbg( p_this, "'dry' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
static int DampCallback( vlc_object_t *p_this, char const *psz_cmd,
vlc_value_t oldval, vlc_value_t newval, void *p_data )
{
(void)psz_cmd; (void)oldval;
aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;
CLocker locker( &p_sys->lock );
p_sys->p_reverbm->setdamp(newval.f_float);
msg_Dbg( p_this, "'damp' value is now %3.1f", newval.f_float );
return VLC_SUCCESS;
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Main driver function for the HMMWV 9-body model, using rigid tire-terrain
// contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "subsys/terrain/RigidTerrain.h"
#include "models/hmmwv/HMMWV.h"
#include "models/hmmwv/vehicle/HMMWV_VehicleReduced.h"
#include "models/hmmwv/tire/HMMWV_RigidTire.h"
#include "models/hmmwv/tire/HMMWV_LugreTire.h"
#include "models/hmmwv/HMMWV_FuncDriver.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
using namespace chrono;
using namespace hmmwv;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Type of tire model (RIGID, PACEJKA, or LUGRE)
TireModelType tire_model = RIGID;
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV9";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// --------------------------
// Create the various modules
// --------------------------
// Create the HMMWV vehicle
HMMWV_VehicleReduced vehicle(false,
hmmwv::PRIMITIVES,
hmmwv::MESH);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the ground
RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
// Create and initialize the tires
ChSharedPtr<ChTire> tire_front_right;
ChSharedPtr<ChTire> tire_front_left;
ChSharedPtr<ChTire> tire_rear_right;
ChSharedPtr<ChTire> tire_rear_left;
switch (tire_model) {
case RIGID:
{
ChSharedPtr<HMMWV_RigidTire> tire_FR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_FL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT));
tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT));
tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT));
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
case LUGRE:
{
ChSharedPtr<HMMWV_LugreTire> tire_FR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_FL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
tire_FR->Initialize();
tire_FL->Initialize();
tire_RR->Initialize();
tire_RL->Initialize();
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
}
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV 9-body demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = false; // shadow map is experimental
if (do_shadows)
application.AddLightWithShadow(irr::core::vector3df(20.f, 20.f, 80.f),
irr::core::vector3df(20.f, 0.f, 0.f),
150, 60, 100, 40, 512, irr::video::SColorf(1, 1, 1));
else
application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5, true);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
double braking_time = 0.3; // time to go from 0 to +1
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetThrottleDelta(render_step_size / throttle_time);
driver.SetBrakingDelta(render_step_size / braking_time);
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
HMMWV_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
// Inter-module communication data
ChTireForces tire_forces(4);
ChWheelState wheel_states[4];
double throttle_input;
double steering_input;
double braking_input;
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
// Collect output data from modules (for inter-module communication)
throttle_input = driver.GetThrottle();
steering_input = driver.GetSteering();
braking_input = driver.GetBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
terrain.Advance(step);
tire_front_right->Advance(step);
tire_front_left->Advance(step);
tire_rear_right->Advance(step);
tire_rear_left->Advance(step);
vehicle.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV_VehicleReduced::ExportMeshPovray(out_dir);
HMMWV_WheelLeft::ExportMeshPovray(out_dir);
HMMWV_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.GetThrottle() << " steering: " << driver.GetSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
// Collect output data from modules (for inter-module communication)
throttle_input = driver.GetThrottle();
steering_input = driver.GetSteering();
braking_input = driver.GetBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
tire_front_right->Advance(step_size);
tire_front_left->Advance(step_size);
tire_rear_right->Advance(step_size);
tire_rear_left->Advance(step_size);
vehicle.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
<commit_msg>Add option of using Pacejka tires (note: this tire model does not work yet)<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Main driver function for the HMMWV 9-body model, using rigid tire-terrain
// contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
#include "subsys/terrain/RigidTerrain.h"
#include "subsys/tire/ChPacejkaTire.h"
#include "models/hmmwv/HMMWV.h"
#include "models/hmmwv/vehicle/HMMWV_VehicleReduced.h"
#include "models/hmmwv/tire/HMMWV_RigidTire.h"
#include "models/hmmwv/tire/HMMWV_LugreTire.h"
#include "models/hmmwv/HMMWV_FuncDriver.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
using namespace chrono;
using namespace hmmwv;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Type of tire model (RIGID, PACEJKA, or LUGRE)
TireModelType tire_model = RIGID;
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV9";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// --------------------------
// Create the various modules
// --------------------------
// Create the HMMWV vehicle
HMMWV_VehicleReduced vehicle(false,
hmmwv::PRIMITIVES,
hmmwv::MESH);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the ground
RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
// Create and initialize the tires
ChSharedPtr<ChTire> tire_front_right;
ChSharedPtr<ChTire> tire_front_left;
ChSharedPtr<ChTire> tire_rear_right;
ChSharedPtr<ChTire> tire_rear_left;
switch (tire_model) {
case RIGID:
{
ChSharedPtr<HMMWV_RigidTire> tire_FR(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_FL(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RR(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RL(new HMMWV_RigidTire(terrain, 0.7f));
tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT));
tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT));
tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT));
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
case LUGRE:
{
ChSharedPtr<HMMWV_LugreTire> tire_FR(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_FL(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RR(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RL(new HMMWV_LugreTire(terrain));
tire_FR->Initialize();
tire_FL->Initialize();
tire_RR->Initialize();
tire_RL->Initialize();
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
case PACEJKA:
{
std::string param_file = utils::GetModelDataFile("hmmwv/pactest.tir");
ChSharedPtr<ChPacejkaTire> tire_FR(new ChPacejkaTire(param_file, terrain));
ChSharedPtr<ChPacejkaTire> tire_FL(new ChPacejkaTire(param_file, terrain));
ChSharedPtr<ChPacejkaTire> tire_RR(new ChPacejkaTire(param_file, terrain));
ChSharedPtr<ChPacejkaTire> tire_RL(new ChPacejkaTire(param_file, terrain));
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
}
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV 9-body demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = false; // shadow map is experimental
if (do_shadows)
application.AddLightWithShadow(irr::core::vector3df(20.f, 20.f, 80.f),
irr::core::vector3df(20.f, 0.f, 0.f),
150, 60, 100, 40, 512, irr::video::SColorf(1, 1, 1));
else
application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5, true);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
double braking_time = 0.3; // time to go from 0 to +1
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetThrottleDelta(render_step_size / throttle_time);
driver.SetBrakingDelta(render_step_size / braking_time);
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
HMMWV_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
// Inter-module communication data
ChTireForces tire_forces(4);
ChWheelState wheel_states[4];
double throttle_input;
double steering_input;
double braking_input;
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
// Collect output data from modules (for inter-module communication)
throttle_input = driver.GetThrottle();
steering_input = driver.GetSteering();
braking_input = driver.GetBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
terrain.Advance(step);
tire_front_right->Advance(step);
tire_front_left->Advance(step);
tire_rear_right->Advance(step);
tire_rear_left->Advance(step);
vehicle.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV_VehicleReduced::ExportMeshPovray(out_dir);
HMMWV_WheelLeft::ExportMeshPovray(out_dir);
HMMWV_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.GetThrottle() << " steering: " << driver.GetSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
// Collect output data from modules (for inter-module communication)
throttle_input = driver.GetThrottle();
steering_input = driver.GetSteering();
braking_input = driver.GetBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
tire_front_right->Advance(step_size);
tire_front_left->Advance(step_size);
tire_rear_right->Advance(step_size);
tire_rear_left->Advance(step_size);
vehicle.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "GasMeter.h"
#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/IntrinsicInst.h>
#include "preprocessor/llvm_includes_end.h"
#include "Ext.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
namespace // Helper functions
{
int64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20};
int64_t const c_expByteGas = 10;
int64_t const c_sha3Gas = 30;
int64_t const c_sha3WordGas = 6;
int64_t const c_sloadGas = 50;
int64_t const c_sstoreSetGas = 20000;
int64_t const c_sstoreResetGas = 5000;
int64_t const c_jumpdestGas = 1;
int64_t const c_logGas = 375;
int64_t const c_logTopicGas = 375;
int64_t const c_logDataGas = 8;
int64_t const c_callGas = 40;
int64_t const c_createGas = 32000;
int64_t const c_memoryGas = 3;
int64_t const c_copyGas = 3;
int64_t getStepCost(Instruction inst)
{
switch (inst)
{
// Tier 0
case Instruction::STOP:
case Instruction::RETURN:
case Instruction::SUICIDE:
case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore()
return c_stepGas[0];
// Tier 1
case Instruction::ADDRESS:
case Instruction::ORIGIN:
case Instruction::CALLER:
case Instruction::CALLVALUE:
case Instruction::CALLDATASIZE:
case Instruction::CODESIZE:
case Instruction::GASPRICE:
case Instruction::COINBASE:
case Instruction::TIMESTAMP:
case Instruction::NUMBER:
case Instruction::DIFFICULTY:
case Instruction::GASLIMIT:
case Instruction::POP:
case Instruction::PC:
case Instruction::MSIZE:
case Instruction::GAS:
return c_stepGas[1];
// Tier 2
case Instruction::ADD:
case Instruction::SUB:
case Instruction::LT:
case Instruction::GT:
case Instruction::SLT:
case Instruction::SGT:
case Instruction::EQ:
case Instruction::ISZERO:
case Instruction::AND:
case Instruction::OR:
case Instruction::XOR:
case Instruction::NOT:
case Instruction::BYTE:
case Instruction::CALLDATALOAD:
case Instruction::CALLDATACOPY:
case Instruction::CODECOPY:
case Instruction::MLOAD:
case Instruction::MSTORE:
case Instruction::MSTORE8:
case Instruction::ANY_PUSH:
case Instruction::ANY_DUP:
case Instruction::ANY_SWAP:
return c_stepGas[2];
// Tier 3
case Instruction::MUL:
case Instruction::DIV:
case Instruction::SDIV:
case Instruction::MOD:
case Instruction::SMOD:
case Instruction::SIGNEXTEND:
return c_stepGas[3];
// Tier 4
case Instruction::ADDMOD:
case Instruction::MULMOD:
case Instruction::JUMP:
return c_stepGas[4];
// Tier 5
case Instruction::EXP:
case Instruction::JUMPI:
return c_stepGas[5];
// Tier 6
case Instruction::BALANCE:
case Instruction::EXTCODESIZE:
case Instruction::EXTCODECOPY:
case Instruction::BLOCKHASH:
return c_stepGas[6];
case Instruction::SHA3:
return c_sha3Gas;
case Instruction::SLOAD:
return c_sloadGas;
case Instruction::JUMPDEST:
return c_jumpdestGas;
case Instruction::LOG0:
case Instruction::LOG1:
case Instruction::LOG2:
case Instruction::LOG3:
case Instruction::LOG4:
{
auto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0);
return c_logGas + numTopics * c_logTopicGas;
}
case Instruction::CALL:
case Instruction::CALLCODE:
return c_callGas;
case Instruction::CREATE:
return c_createGas;
}
return 0; // TODO: Add UNREACHABLE macro
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :
CompilerHelper(_builder),
m_runtimeManager(_runtimeManager)
{
llvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr};
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", getModule());
m_gasCheckFunc->setDoesNotThrow();
m_gasCheckFunc->setDoesNotCapture(1);
auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);
auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
auto gasPtr = &m_gasCheckFunc->getArgumentList().front();
gasPtr->setName("gasPtr");
auto cost = gasPtr->getNextNode();
cost->setName("cost");
auto jmpBuf = cost->getNextNode();
jmpBuf->setName("jmpBuf");
InsertPointGuard guard(m_builder);
m_builder.SetInsertPoint(checkBB);
auto gas = m_builder.CreateLoad(gasPtr, "gas");
auto gasUpdated = m_builder.CreateNSWSub(gas, cost, "gasUpdated");
auto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), "gasOk"); // gas >= 0, with gas == 0 we can still do 0 cost instructions
m_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue);
m_builder.SetInsertPoint(updateBB);
m_builder.CreateStore(gasUpdated, gasPtr);
m_builder.CreateRetVoid();
m_builder.SetInsertPoint(outOfGasBB);
m_runtimeManager.abort(jmpBuf);
m_builder.CreateUnreachable();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()});
}
m_blockCost += getStepCost(_inst);
}
void GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)
{
if (_cost->getType() == Type::Word)
{
auto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word);
auto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, "costTooHigh");
auto cost64 = m_builder.CreateTrunc(_cost, Type::Gas);
_cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, "cost");
}
assert(_cost->getType() == Type::Gas);
createCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()});
}
void GasMeter::countExp(llvm::Value* _exponent)
{
// Additional cost is 1 per significant byte of exponent
// lz - leading zeros
// cost = ((256 - lz) + 7) / 8
// OPT: Can gas update be done in exp algorithm?
auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);
auto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));
auto lz = m_builder.CreateTrunc(lz256, Type::Gas, "lz");
auto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, "sigBits");
auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8));
count(m_builder.CreateNUWMul(sigBytes, m_builder.getInt64(c_expByteGas)));
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
auto oldValue = _ext.sload(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert");
auto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDelete");
auto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), "cost");
cost = m_builder.CreateSelect(isDelete, m_builder.getInt64(0), cost, "cost");
count(cost);
}
void GasMeter::countLogData(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // LOGn instruction is already counted
static_assert(c_logDataGas != 1, "Log data gas cost has changed. Update GasMeter.");
count(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); // TODO: Use i64
}
void GasMeter::countSha3Data(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // SHA3 instruction is already counted
// TODO: This round ups to 32 happens in many places
static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter");
auto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas);
auto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32));
auto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64);
count(cost64);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
assert(_gas->getType() == Type::Gas);
m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));
}
void GasMeter::commitCostBlock()
{
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
m_checkCall = nullptr;
return;
}
m_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)
{
static_assert(c_memoryGas != 1, "Memory gas cost has changed. Update GasMeter.");
count(_additionalMemoryInWords, _jmpBuf, _gasPtr);
}
void GasMeter::countCopy(llvm::Value* _copyWords)
{
static_assert(c_copyGas != 1, "Copy gas cost has changed. Update GasMeter.");
count(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas)));
}
}
}
}
<commit_msg>Update gas costs for PoC-9: set nonzero storage clear cost<commit_after>#include "GasMeter.h"
#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/IntrinsicInst.h>
#include "preprocessor/llvm_includes_end.h"
#include "Ext.h"
#include "RuntimeManager.h"
namespace dev
{
namespace eth
{
namespace jit
{
namespace // Helper functions
{
int64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20};
int64_t const c_expByteGas = 10;
int64_t const c_sha3Gas = 30;
int64_t const c_sha3WordGas = 6;
int64_t const c_sloadGas = 50;
int64_t const c_sstoreSetGas = 20000;
int64_t const c_sstoreResetGas = 5000;
int64_t const c_sstoreClearGas = 5000;
int64_t const c_jumpdestGas = 1;
int64_t const c_logGas = 375;
int64_t const c_logTopicGas = 375;
int64_t const c_logDataGas = 8;
int64_t const c_callGas = 40;
int64_t const c_createGas = 32000;
int64_t const c_memoryGas = 3;
int64_t const c_copyGas = 3;
int64_t getStepCost(Instruction inst)
{
switch (inst)
{
// Tier 0
case Instruction::STOP:
case Instruction::RETURN:
case Instruction::SUICIDE:
case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore()
return c_stepGas[0];
// Tier 1
case Instruction::ADDRESS:
case Instruction::ORIGIN:
case Instruction::CALLER:
case Instruction::CALLVALUE:
case Instruction::CALLDATASIZE:
case Instruction::CODESIZE:
case Instruction::GASPRICE:
case Instruction::COINBASE:
case Instruction::TIMESTAMP:
case Instruction::NUMBER:
case Instruction::DIFFICULTY:
case Instruction::GASLIMIT:
case Instruction::POP:
case Instruction::PC:
case Instruction::MSIZE:
case Instruction::GAS:
return c_stepGas[1];
// Tier 2
case Instruction::ADD:
case Instruction::SUB:
case Instruction::LT:
case Instruction::GT:
case Instruction::SLT:
case Instruction::SGT:
case Instruction::EQ:
case Instruction::ISZERO:
case Instruction::AND:
case Instruction::OR:
case Instruction::XOR:
case Instruction::NOT:
case Instruction::BYTE:
case Instruction::CALLDATALOAD:
case Instruction::CALLDATACOPY:
case Instruction::CODECOPY:
case Instruction::MLOAD:
case Instruction::MSTORE:
case Instruction::MSTORE8:
case Instruction::ANY_PUSH:
case Instruction::ANY_DUP:
case Instruction::ANY_SWAP:
return c_stepGas[2];
// Tier 3
case Instruction::MUL:
case Instruction::DIV:
case Instruction::SDIV:
case Instruction::MOD:
case Instruction::SMOD:
case Instruction::SIGNEXTEND:
return c_stepGas[3];
// Tier 4
case Instruction::ADDMOD:
case Instruction::MULMOD:
case Instruction::JUMP:
return c_stepGas[4];
// Tier 5
case Instruction::EXP:
case Instruction::JUMPI:
return c_stepGas[5];
// Tier 6
case Instruction::BALANCE:
case Instruction::EXTCODESIZE:
case Instruction::EXTCODECOPY:
case Instruction::BLOCKHASH:
return c_stepGas[6];
case Instruction::SHA3:
return c_sha3Gas;
case Instruction::SLOAD:
return c_sloadGas;
case Instruction::JUMPDEST:
return c_jumpdestGas;
case Instruction::LOG0:
case Instruction::LOG1:
case Instruction::LOG2:
case Instruction::LOG3:
case Instruction::LOG4:
{
auto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0);
return c_logGas + numTopics * c_logTopicGas;
}
case Instruction::CALL:
case Instruction::CALLCODE:
return c_callGas;
case Instruction::CREATE:
return c_createGas;
}
return 0; // TODO: Add UNREACHABLE macro
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :
CompilerHelper(_builder),
m_runtimeManager(_runtimeManager)
{
llvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr};
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", getModule());
m_gasCheckFunc->setDoesNotThrow();
m_gasCheckFunc->setDoesNotCapture(1);
auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);
auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
auto gasPtr = &m_gasCheckFunc->getArgumentList().front();
gasPtr->setName("gasPtr");
auto cost = gasPtr->getNextNode();
cost->setName("cost");
auto jmpBuf = cost->getNextNode();
jmpBuf->setName("jmpBuf");
InsertPointGuard guard(m_builder);
m_builder.SetInsertPoint(checkBB);
auto gas = m_builder.CreateLoad(gasPtr, "gas");
auto gasUpdated = m_builder.CreateNSWSub(gas, cost, "gasUpdated");
auto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), "gasOk"); // gas >= 0, with gas == 0 we can still do 0 cost instructions
m_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue);
m_builder.SetInsertPoint(updateBB);
m_builder.CreateStore(gasUpdated, gasPtr);
m_builder.CreateRetVoid();
m_builder.SetInsertPoint(outOfGasBB);
m_runtimeManager.abort(jmpBuf);
m_builder.CreateUnreachable();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()});
}
m_blockCost += getStepCost(_inst);
}
void GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)
{
if (_cost->getType() == Type::Word)
{
auto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word);
auto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, "costTooHigh");
auto cost64 = m_builder.CreateTrunc(_cost, Type::Gas);
_cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, "cost");
}
assert(_cost->getType() == Type::Gas);
createCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()});
}
void GasMeter::countExp(llvm::Value* _exponent)
{
// Additional cost is 1 per significant byte of exponent
// lz - leading zeros
// cost = ((256 - lz) + 7) / 8
// OPT: Can gas update be done in exp algorithm?
auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);
auto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));
auto lz = m_builder.CreateTrunc(lz256, Type::Gas, "lz");
auto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, "sigBits");
auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8));
count(m_builder.CreateNUWMul(sigBytes, m_builder.getInt64(c_expByteGas)));
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
auto oldValue = _ext.sload(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert");
static_assert(c_sstoreResetGas == c_sstoreClearGas, "Update SSTORE gas cost");
auto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), "cost");
count(cost);
}
void GasMeter::countLogData(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // LOGn instruction is already counted
static_assert(c_logDataGas != 1, "Log data gas cost has changed. Update GasMeter.");
count(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); // TODO: Use i64
}
void GasMeter::countSha3Data(llvm::Value* _dataLength)
{
assert(m_checkCall);
assert(m_blockCost > 0); // SHA3 instruction is already counted
// TODO: This round ups to 32 happens in many places
static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter");
auto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas);
auto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32));
auto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64);
count(cost64);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
assert(_gas->getType() == Type::Gas);
m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));
}
void GasMeter::commitCostBlock()
{
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
m_checkCall = nullptr;
return;
}
m_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)
{
static_assert(c_memoryGas != 1, "Memory gas cost has changed. Update GasMeter.");
count(_additionalMemoryInWords, _jmpBuf, _gasPtr);
}
void GasMeter::countCopy(llvm::Value* _copyWords)
{
static_assert(c_copyGas != 1, "Copy gas cost has changed. Update GasMeter.");
count(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas)));
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef IMAP__H__
#define IMAP__H__
#include "zip.hpp"
#include <utility>
#include <type_traits>
namespace iter {
// Everything in detail namespace
// modified from http://stackoverflow.com/questions/10766112/
// Question by Thomas http://stackoverflow.com/users/115355/thomas
// Answer by Kerrek SB http://stackoverflow.com/users/596781/kerrek-sb
namespace detail
{
// implementation details, users never invoke these directly
template <typename F, typename Tuple, bool Done, int Total, int... N>
struct call_impl
{
static auto call(F f, Tuple && t) ->
decltype(call_impl<F,
Tuple,
Total == 1 + sizeof...(N),
Total,
N...,
sizeof...(N)>::call(f, std::forward<Tuple>(t)))
{
return call_impl<F,
Tuple,
Total == 1 + sizeof...(N),
Total,
N...,
sizeof...(N)>::call(f, std::forward<Tuple>(t));
}
};
template <typename F, typename Tuple, int Total, int... N>
struct call_impl<F, Tuple, true, Total, N...>
{
static auto call(F f, Tuple && t) ->
decltype(f(std::get<N>(std::forward<Tuple>(t))...))
{
return f(std::get<N>(std::forward<Tuple>(t))...);
}
};
// user invokes this
template <typename F, typename Tuple>
auto call(F f, Tuple && t) ->
decltype(call_impl<F,
Tuple,
0 == std::tuple_size<typename std::decay<Tuple>::type>::value,
std::tuple_size<typename std::decay<Tuple>::type>::value>
::call(f,std::forward<Tuple>(t)))
{
typedef typename std::decay<Tuple>::type ttype;
return call_impl<F,
Tuple,
0 == std::tuple_size<ttype>::value,
std::tuple_size<ttype>::value>::call(f,std::forward<Tuple>(t));
}
}
//Forward declarations of IMap and imap
template <typename MapFunc, typename... Containers>
class IMap;
template <typename MapFunc, typename... Containers>
IMap<MapFunc, Containers...> imap(MapFunc, Containers &&...);
template <typename MapFunc, typename... Containers>
class IMap {
// The imap function is the only thing allowed to create a IMap
friend IMap imap<MapFunc, Containers...>(MapFunc, Containers && ...);
// The type returned when dereferencing the Containers...::Iterator
// XXX depends on zip using iterator_range. would be nice if it didn't
using Zipped =
iterator_range<zip_iter<decltype(std::declval<Containers>().begin())...>>;
using ZippedIterType = decltype(std::declval<Zipped>().begin());
//typename std::remove_const<decltype(std::declval<Zipped>().begin())>::type;
private:
MapFunc map_func;
Zipped zipped;
// Value constructor for use only in the imap function
IMap(MapFunc map_func, Containers && ... containers) :
map_func(map_func),
zipped(zip(std::forward<Containers>(containers)...))
{ }
IMap () = delete;
IMap & operator=(const IMap &) = delete;
public:
IMap (const IMap &) = default;
class Iterator {
private:
MapFunc map_func;
mutable ZippedIterType zipiter;
public:
Iterator (MapFunc map_func, ZippedIterType zipiter) :
map_func(map_func),
zipiter(zipiter)
{ }
auto operator*() const ->
decltype(detail::call(this->map_func, *(this->zipiter)))
{
return detail::call(this->map_func, *(this->zipiter));
}
Iterator & operator++() {
++this->zipiter;
return *this;
}
bool operator!=(const Iterator & other) const {
return this->zipiter != other.zipiter;
}
};
Iterator begin() const {
return Iterator(this->map_func, this->zipped.begin());
}
Iterator end() const {
return Iterator(this->map_func, this->zipped.end());
}
};
// Helper function to instantiate a IMap
template <typename MapFunc, typename... Containers>
IMap<MapFunc, Containers...> imap(
MapFunc map_func, Containers && ... containers) {
return IMap<MapFunc, Containers...>(
map_func,
std::forward<Containers>(containers)...);
}
}
#endif //ifndef IMAP__H__
<commit_msg>uniform initialization updates<commit_after>#ifndef IMAP__H__
#define IMAP__H__
#include "zip.hpp"
#include <utility>
#include <type_traits>
namespace iter {
// Everything in detail namespace
// modified from http://stackoverflow.com/questions/10766112/
// Question by Thomas http://stackoverflow.com/users/115355/thomas
// Answer by Kerrek SB http://stackoverflow.com/users/596781/kerrek-sb
namespace detail
{
// implementation details, users never invoke these directly
template <typename F, typename Tuple, bool Done, int Total, int... N>
struct call_impl
{
static auto call(F f, Tuple && t) ->
decltype(call_impl<F,
Tuple,
Total == 1 + sizeof...(N),
Total,
N...,
sizeof...(N)>::call(f, std::forward<Tuple>(t)))
{
return call_impl<F,
Tuple,
Total == 1 + sizeof...(N),
Total,
N...,
sizeof...(N)>::call(f, std::forward<Tuple>(t));
}
};
template <typename F, typename Tuple, int Total, int... N>
struct call_impl<F, Tuple, true, Total, N...>
{
static auto call(F f, Tuple && t) ->
decltype(f(std::get<N>(std::forward<Tuple>(t))...))
{
return f(std::get<N>(std::forward<Tuple>(t))...);
}
};
// user invokes this
template <typename F, typename Tuple>
auto call(F f, Tuple && t) ->
decltype(call_impl<F,
Tuple,
0 == std::tuple_size<typename std::decay<Tuple>::type>::value,
std::tuple_size<typename std::decay<Tuple>::type>::value>
::call(f,std::forward<Tuple>(t)))
{
typedef typename std::decay<Tuple>::type ttype;
return call_impl<F,
Tuple,
0 == std::tuple_size<ttype>::value,
std::tuple_size<ttype>::value>::call(f,std::forward<Tuple>(t));
}
}
//Forward declarations of IMap and imap
template <typename MapFunc, typename... Containers>
class IMap;
template <typename MapFunc, typename... Containers>
IMap<MapFunc, Containers...> imap(MapFunc, Containers &&...);
template <typename MapFunc, typename... Containers>
class IMap {
// The imap function is the only thing allowed to create a IMap
friend IMap imap<MapFunc, Containers...>(MapFunc, Containers && ...);
// The type returned when dereferencing the Containers...::Iterator
// XXX depends on zip using iterator_range. would be nice if it didn't
using Zipped =
iterator_range<zip_iter<decltype(std::declval<Containers>().begin())...>>;
using ZippedIterType = decltype(std::declval<Zipped>().begin());
//typename std::remove_const<decltype(std::declval<Zipped>().begin())>::type;
private:
MapFunc map_func;
Zipped zipped;
// Value constructor for use only in the imap function
IMap(MapFunc map_func, Containers && ... containers) :
map_func(map_func),
zipped(zip(std::forward<Containers>(containers)...))
{ }
IMap () = delete;
IMap & operator=(const IMap &) = delete;
public:
IMap (const IMap &) = default;
class Iterator {
private:
MapFunc map_func;
mutable ZippedIterType zipiter;
public:
Iterator (MapFunc map_func, ZippedIterType zipiter) :
map_func(map_func),
zipiter(zipiter)
{ }
auto operator*() const ->
decltype(detail::call(this->map_func, *(this->zipiter)))
{
return detail::call(this->map_func, *(this->zipiter));
}
Iterator & operator++() {
++this->zipiter;
return *this;
}
bool operator!=(const Iterator & other) const {
return this->zipiter != other.zipiter;
}
};
Iterator begin() const {
return {this->map_func, this->zipped.begin()};
}
Iterator end() const {
return {this->map_func, this->zipped.end()};
}
};
// Helper function to instantiate a IMap
template <typename MapFunc, typename... Containers>
IMap<MapFunc, Containers...> imap(
MapFunc map_func, Containers && ... containers) {
return {map_func, std::forward<Containers>(containers)...};
}
}
#endif //ifndef IMAP__H__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2013 by KO Myung-Hun <komh@chollian.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the copyright holder nor the names
* of any other contributors may be used to endorse or
* promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
#define INCL_WIN
#include <os2.h>
#include <sstream>
#include <KPMLib.h>
#include <libssh2.h>
#include "KSCPClient.h"
#include "kscp.h"
int KSCP::Run()
{
int rc;
rc = libssh2_init( 0 );
if( rc != 0 )
{
stringstream ssMsg;
ssMsg << "libssh2 initialization failed : rc = " << rc;
MessageBox( KWND_DESKTOP, ssMsg.str(), "KSCP", MB_OK | MB_ERROR );
return 1;
}
KSCPClient kclient;
kclient.RegisterClass( _hab, WC_KSCP, CS_SIZEREDRAW, sizeof( PVOID ));
ULONG flFrameFlags;
flFrameFlags = FCF_SYSMENU | FCF_TITLEBAR | FCF_MINMAX | FCF_SIZEBORDER |
FCF_SHELLPOSITION | FCF_TASKLIST | FCF_MENU |
FCF_ACCELTABLE;
KFrameWindow kframe;
kframe.CreateStdWindow( KWND_DESKTOP, // parent window handle
WS_VISIBLE, // frame window style
&flFrameFlags, // window style
KSCP_TITLE, // window title
0, // default client style
0, // resource in exe file
ID_KSCP, // frame window id
kclient // client window handle
);
if( kframe.GetHWND())
{
bool fShow = false;
ULONG ulBufMax;
ulBufMax = sizeof( fShow );
PrfQueryProfileData( HINI_USERPROFILE, KSCP_PRF_APP,
KSCP_PRF_KEY_SHOW, &fShow, &ulBufMax );
if( fShow )
kclient.PostMsg( WM_COMMAND, MPFROMSHORT( IDM_FILE_ADDRBOOK ),
MPFROM2SHORT( CMDSRC_MENU, false ));
KPMApp::Run();
kframe.DestroyWindow();
}
libssh2_exit();
return 0;
}
int main( void )
{
KSCP kscp;
return kscp.Run();
}
<commit_msg>KSCP: use GetHAB() to get a hab handle in according to KPMLib changes<commit_after>/*
* Copyright (c) 2012-2013 by KO Myung-Hun <komh@chollian.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the copyright holder nor the names
* of any other contributors may be used to endorse or
* promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
#define INCL_WIN
#include <os2.h>
#include <sstream>
#include <KPMLib.h>
#include <libssh2.h>
#include "KSCPClient.h"
#include "kscp.h"
int KSCP::Run()
{
int rc;
rc = libssh2_init( 0 );
if( rc != 0 )
{
stringstream ssMsg;
ssMsg << "libssh2 initialization failed : rc = " << rc;
MessageBox( KWND_DESKTOP, ssMsg.str(), "KSCP", MB_OK | MB_ERROR );
return 1;
}
KSCPClient kclient;
kclient.RegisterClass( GetHAB(), WC_KSCP, CS_SIZEREDRAW, sizeof( PVOID ));
ULONG flFrameFlags;
flFrameFlags = FCF_SYSMENU | FCF_TITLEBAR | FCF_MINMAX | FCF_SIZEBORDER |
FCF_SHELLPOSITION | FCF_TASKLIST | FCF_MENU |
FCF_ACCELTABLE;
KFrameWindow kframe;
kframe.CreateStdWindow( KWND_DESKTOP, // parent window handle
WS_VISIBLE, // frame window style
&flFrameFlags, // window style
KSCP_TITLE, // window title
0, // default client style
0, // resource in exe file
ID_KSCP, // frame window id
kclient // client window handle
);
if( kframe.GetHWND())
{
bool fShow = false;
ULONG ulBufMax;
ulBufMax = sizeof( fShow );
PrfQueryProfileData( HINI_USERPROFILE, KSCP_PRF_APP,
KSCP_PRF_KEY_SHOW, &fShow, &ulBufMax );
if( fShow )
kclient.PostMsg( WM_COMMAND, MPFROMSHORT( IDM_FILE_ADDRBOOK ),
MPFROM2SHORT( CMDSRC_MENU, false ));
KPMApp::Run();
kframe.DestroyWindow();
}
libssh2_exit();
return 0;
}
int main( void )
{
KSCP kscp;
return kscp.Run();
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
void parse_data(std::ifstream &instream_data,std::map<std::string, std::vector <std::string> > & map_data){
int count=0;
while (instream_data){
std::string s;
if (!getline( instream_data, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
std::string full_name= record[1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_data.insert(std::make_pair(modified_name, record));
count++;
}
}
//int main(int argc, char** argv)
int main(){
std::map<std::string, std::vector <std::string> > map_salary;
std::map<std::string, std::vector <std::string> > map_pitcher_player;
std::map<std::string, std::vector <std::string> > map_batter_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
// std::string user_option = "";
// std::cout << "Would you like to view a particular player's value or a list of players ranked by value?: ";
// getline(std::cin, player_name);
// std::cout << "You entered: " << player_name << std::endl;
// std::cin.clear();
std::string player_name = "";
std::cout << "Please enter a players name: ";
getline(std::cin, player_name);
std::cout << "You entered: " << player_name << std::endl;
std::cin.clear();
std::string player_position = "";
std::cout << "Is "<< player_name<< " a Pitcher or Batter?: ";
getline(std::cin, player_position);
std::cout << "You entered: " << player_position << std::endl;
//parse_data for salary info
parse_data(infile, map_salary);
if(map_salary.find("Yoenis Cespedes")!=map_salary.end()){
std::cout<< "Yoenis Cespedes's Salary: "<< map_salary.find("Yoenis Cespedes")->second[21]<<std::endl;
}
//parse data for pitcher info
parse_data(infile_pitcher, map_pitcher_player);
if(map_pitcher_player.find("Tim Adleman")!=map_pitcher_player.end()){
std::cout<<"Tim Adleman's ERA: "<<map_pitcher_player.find("Tim Adleman")->second[8]<<std::endl;
}
// //parse data for batter info
// parse_data(infile_batter, map_batter_player);
// if(map_batter_player.find("Ryan Zimmerman")!=map_batter_player.end()){
// std::cout<<"Ryan Zimmerman's BA: "<< map_batter_player.find("Ryan Zimmerman")->second[18]<<std::endl;
// // std::cout<<"map works!!"<<std::endl;
// }
float run_creation=0.0;
//Run Creation = ((Hits + Walks)* TotalBases)/(AtBats + Walks)
parse_data(infile_batter, map_batter_player);
if(map_batter_player.find("LgAvg per 600 PA")!=map_batter_player.end()){
run_creation= (map_batter_player.find("LgAvg per 600 PA")->second[9] + map_batter_player.find("LgAvg per 600 PA")->second[9])
//std::cout<<"Ryan Zimmerman's BA: "<< map_batter_player.find("Ryan Zimmerman")->second[18]<<std::endl;
}
return 0;
}
<commit_msg>Keeping batter info<commit_after>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
void parse_data(std::ifstream &instream_data,std::map<std::string, std::vector <std::string> > & map_data){
int count=0;
while (instream_data){
std::string s;
if (!getline( instream_data, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
std::string full_name= record[1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_data.insert(std::make_pair(modified_name, record));
count++;
}
}
//int main(int argc, char** argv)
int main(){
std::map<std::string, std::vector <std::string> > map_salary;
std::map<std::string, std::vector <std::string> > map_pitcher_player;
std::map<std::string, std::vector <std::string> > map_batter_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
// std::string user_option = "";
// std::cout << "Would you like to view a particular player's value or a list of players ranked by value?: ";
// getline(std::cin, player_name);
// std::cout << "You entered: " << player_name << std::endl;
// std::cin.clear();
std::string player_name = "";
std::cout << "Please enter a players name: ";
getline(std::cin, player_name);
std::cout << "You entered: " << player_name << std::endl;
std::cin.clear();
std::string player_position = "";
std::cout << "Is "<< player_name<< " a Pitcher or Batter?: ";
getline(std::cin, player_position);
std::cout << "You entered: " << player_position << std::endl;
//parse_data for salary info
parse_data(infile, map_salary);
if(map_salary.find("Yoenis Cespedes")!=map_salary.end()){
std::cout<< "Yoenis Cespedes's Salary: "<< map_salary.find("Yoenis Cespedes")->second[21]<<std::endl;
}
//parse data for pitcher info
parse_data(infile_pitcher, map_pitcher_player);
if(map_pitcher_player.find("Tim Adleman")!=map_pitcher_player.end()){
std::cout<<"Tim Adleman's ERA: "<<map_pitcher_player.find("Tim Adleman")->second[8]<<std::endl;
}
//parse data for batter info
parse_data(infile_batter, map_batter_player);
if(map_batter_player.find("Ryan Zimmerman")!=map_batter_player.end()){
std::cout<<"Ryan Zimmerman's BA: "<< map_batter_player.find("Ryan Zimmerman")->second[18]<<std::endl;
// std::cout<<"map works!!"<<std::endl;
}
float run_creation=0.0;
//Run Creation = ((Hits + Walks)* TotalBases)/(AtBats + Walks)
parse_data(infile_batter, map_batter_player);
if(map_batter_player.find("LgAvg per 600 PA")!=map_batter_player.end()){
run_creation= (map_batter_player.find("LgAvg per 600 PA")->second[9] + map_batter_player.find("LgAvg per 600 PA")->second[9])
//std::cout<<"Ryan Zimmerman's BA: "<< map_batter_player.find("Ryan Zimmerman")->second[18]<<std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>8778f45e-4b02-11e5-9441-28cfe9171a43<commit_msg>update testing<commit_after>8783870c-4b02-11e5-8c31-28cfe9171a43<|endoftext|> |
<commit_before>8562796c-2d15-11e5-af21-0401358ea401<commit_msg>8562796d-2d15-11e5-af21-0401358ea401<commit_after>8562796d-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>dcb15e3d-313a-11e5-885f-3c15c2e10482<commit_msg>dcb83326-313a-11e5-a527-3c15c2e10482<commit_after>dcb83326-313a-11e5-a527-3c15c2e10482<|endoftext|> |
<commit_before>#include <memory>
#include <iostream>
#include <exception>
#include <appgrm.h>
#ifdef _OPENMP
extern "C" {
int omp_get_num_procs();
int omp_get_max_threads();
void omp_set_num_threads(int);
}
#endif
int main(int argc, char *argv[])
{
#ifdef _OPENMP
int num_procs = omp_get_num_procs();
if (num_procs < omp_get_max_threads() * 2)
omp_set_num_threads(num_procs < 4 ? 1 : num_procs / 2);
#endif
try {
return std::make_shared<AppGRM>()->run(argc, argv);
}
catch (const std::exception &e) {
std::cerr << "FATAL: exception caught: " << e.what() << "\n";
return 1;
}
catch (...) {
std::cerr << "FATAL: unknown exception caught\n";
return 1;
}
return 0;
}
<commit_msg>Fixed typos<commit_after>#include <memory>
#include <iostream>
#include <exception>
#include "appgrm.h"
#ifdef _OPENMP
extern "C" {
int omp_get_num_procs();
int omp_get_max_threads();
void omp_set_num_threads(int);
}
#endif
int main(int argc, char *argv[])
{
#ifdef _OPENMP
int num_procs = omp_get_num_procs();
if (num_procs < omp_get_max_threads() * 2)
omp_set_num_threads(num_procs < 4 ? 1 : num_procs / 2);
#endif
try {
return std::make_shared<AppGRM>()->run(argc, argv);
}
catch (const std::exception &e) {
std::cerr << "FATAL: exception caught: " << e.what() << "\n";
return 1;
}
catch (...) {
std::cerr << "FATAL: unknown exception caught\n";
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>8431fc8d-2d15-11e5-af21-0401358ea401<commit_msg>8431fc8e-2d15-11e5-af21-0401358ea401<commit_after>8431fc8e-2d15-11e5-af21-0401358ea401<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.