text
stringlengths 54
60.6k
|
|---|
<commit_before><commit_msg>Remove commented out code<commit_after><|endoftext|>
|
<commit_before><commit_msg>SwPagePreView: fix some scrollbar bugs (still not perfect, just a quick fix)<commit_after><|endoftext|>
|
<commit_before>#include <queue>
#include <vector>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <time.h>
//#include <malloc.h>
using namespace std;
#define DEBUG 0
#define MAX_T 100
#define MAX_2 801
#define MAX_S 100001
int count[MAX_T];
int len_two[MAX_2];
vector<string> str_two(MAX_2);
void init() {
for (size_t i = 0; i < MAX_2; i++) {
if (0 == i) {
str_two[i] = '1';
}
else {
int carry = 0;
int val = 0;
for (size_t j = 0; j < str_two[i - 1].length(); j++) {
val = (str_two[i - 1][j] - '0') * 2 + carry;
if (9 < val) {
str_two[i] += '0' + val - 10;
carry = 1;
}
else {
str_two[i] += '0' + val;
carry = 0;
}
}
if (0 < carry) {
str_two[i] += '1';
}
}
}
}
int two_two(string& s) {
int ret = 0;
return ret;
}
int main() {
int t;
#if DEBUG
ifstream fin("input.txt");
if (!fin.is_open()) {
printf("open file error!\n");
return -1;
}
fin >> t;
#else
cin >> t;
#endif
init();
string s;
for (size_t i = 0; i < t; i++) {
#if DEBUG
fin >> s;
#else
cin >> s;
#endif
count[i] = two_two(s);
}
for (size_t i = 0; i < t; i++) {
cout << count[i];
}
return 0;
}
<commit_msg>150.00 points<commit_after>#include <queue>
#include <vector>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <time.h>
#include <algorithm>
using namespace std;
#define DEBUG 0
#define MAX_T 100
#define MAX_2 801
#define MAX_S 100001
int cnt[MAX_T];
// Max number of states in the matching machine.
// Should be equal to the sum of the length of all keywords.
//const int MAXS = 2000000;
int maxs;
vector<string> str_two(MAX_2);
// Maximum number of characters in input alphabet
const int MAXC = 10;
const int MAXM = 512;
const int ONE_MB = 1000000;
struct output {
int value;
struct output * next;
};
// OUTPUT FUNCTION IS IMPLEMENTED USING out[]
// Bit i in this mask is one if the word with index i
// appears when the machine enters this state.
//vector<int> out[MAXS];
struct output * * out;
struct output * * last;
struct output * mem[MAXM];
// FAILURE FUNCTION IS IMPLEMENTED USING f[]
int * f;
// GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING g[][]
//int g[MAXS][MAXC];
int * * g;
int index_in_mem = 0;
int index_in_1mb = 0;
struct output * getOneOutput() {
struct output * ret = NULL;
if (ONE_MB == index_in_1mb) {
index_in_mem ++;
}
if (MAXM > index_in_mem) {
if (NULL == mem[index_in_mem]) {
mem[index_in_mem] = (struct output *)malloc(ONE_MB * sizeof(struct output));
index_in_1mb = 0;
}
ret = &mem[index_in_mem][index_in_1mb];
ret->value = 0;
ret->next = 0;
index_in_1mb ++;
}
return ret;
}
//void addToOutput(struct output * * l, int value) {
void addToOutput(int index, int value) {
struct output * tmp = getOneOutput();
tmp->value = value;
if (NULL == out[index]) {
out[index] = tmp;
}
else {
last[index]->next = tmp;
}
last[index] = tmp;
}
void mergeOutput(struct output * * l_a, struct output * * l_b) {
if (*l_b) {
struct output * p_a = * l_a;
struct output * pp_a = NULL;
struct output * p_b = * l_b;
if (NULL == (*l_a)) {
*l_a = getOneOutput();
(*l_a)->value = p_b->value;
p_a = *l_a;
p_b = p_b->next;
}
while (p_a && p_b) {
if (p_b->value == p_a->value) {
p_a = p_a->next;
p_b = p_b->next;
if (pp_a) {
pp_a = pp_a->next;
}
else {
pp_a = *l_a;
}
}
else if (p_b->value < p_a->value) {
struct output * tmp = getOneOutput();
tmp->value = p_b->value;
tmp->next = p_a;
if (pp_a) {
pp_a->next = tmp;
}
else {
* l_a = tmp;
}
pp_a = tmp;
p_b = p_b->next;
}
else {
p_a = p_a->next;
if (pp_a) {
pp_a = pp_a->next;
}
else {
pp_a = *l_a;
}
}
}
while (p_b){
struct output * tmp = getOneOutput();
tmp->value = p_b->value;
pp_a->next = tmp;
pp_a = tmp;
p_b = p_b->next;
}
}
}
// Builds the string matching machine.
// arr - array of words. The index of each keyword is important:
// "out[state] & (1 << i)" is > 0 if we just found word[i]
// in the text.
// Returns the number of states that the built machine has.
// States are numbered 0 up to the return value - 1, inclusive.
int buildMatchingMachine(vector<string>& arr, int k)
{
// Initialize all values in output function as 0.
// memset(out, 0, sizeof out);
// Initially, we just have the 0 state
int states = 1;
// Construct values for goto function, i.e., fill g[][]
// This is same as building a Trie for arr[]
for (int i = 0; i < k; ++i)
{
const string &word = arr[i];
int currentState = 0;
// Insert all characters of current word in arr[]
for (int j = 0; j < word.size(); ++j)
{
int ch = word[j] - '0';
// Allocate a new node (create a new state) if a
// node for ch doesn't exist.
if (g[currentState][ch] == -1)
g[currentState][ch] = states++;
currentState = g[currentState][ch];
}
// Add current word in output function
// out[currentState] |= (1 << i);
// addToOutput(&out[currentState], i);
addToOutput(currentState, i);
}
// For all characters which don't have an edge from
// root (or state 0) in Trie, add a goto edge to state
// 0 itself
for (int ch = 0; ch < MAXC; ++ch)
if (g[0][ch] == -1)
g[0][ch] = 0;
// Now, let's build the failure function
// Failure function is computed in breadth first order
// using a queue
queue<int> q;
// Iterate over every possible input
for (int ch = 0; ch < MAXC; ++ch)
{
// All nodes of depth 1 have failure function value
// as 0. For example, in above diagram we move to 0
// from states 1 and 3.
if (g[0][ch] != 0)
{
f[g[0][ch]] = 0;
q.push(g[0][ch]);
}
}
// Now queue has states 1 and 3
while (q.size())
{
// Remove the front state from queue
int state = q.front();
q.pop();
// For the removed state, find failure function for
// all those characters for which goto function is
// not defined.
for (int ch = 0; ch < MAXC; ++ch)
{
// If goto function is defined for character 'ch'
// and 'state'
if (g[state][ch] != -1)
{
// Find failure state of removed state
int failure = f[state];
// Find the deepest node labeled by proper
// suffix of string from root to current
// state.
while (g[failure][ch] == -1)
failure = f[failure];
failure = g[failure][ch];
f[g[state][ch]] = failure;
// Merge output values
mergeOutput(&out[g[state][ch]], &out[failure]);
// out[g[state][ch]] |= out[failure];
// Insert the next level node (of Trie) in Queue
q.push(g[state][ch]);
}
}
}
return states;
}
// Returns the next state the machine will transition to using goto
// and failure functions.
// currentState - The current state of the machine. Must be between
// 0 and the Nnumber of states - 1, inclusive.
// nextInput - The next character that enters into the machine.
int findNextState(int currentState, char nextInput)
{
int answer = currentState;
int ch = nextInput - '0';
// If goto is not defined, use failure function
while (g[answer][ch] == -1)
answer = f[answer];
return g[answer][ch];
}
void init() {
for (size_t i = 0; i < MAX_2; i++) {
if (0 == i) {
str_two[i] = '1';
}
else {
int carry = 0;
int val = 0;
for (size_t j = 0; j < str_two[i - 1].length(); j++) {
val = (str_two[i - 1][j] - '0') * 2 + carry;
if (9 < val) {
str_two[i] += '0' + val - 10;
carry = 1;
}
else {
str_two[i] += '0' + val;
carry = 0;
}
}
if (0 < carry) {
str_two[i] += '1';
}
}
maxs += str_two[i].length();
}
// buildMatchingMachine
f = (int *)malloc(maxs * sizeof(int));
memset(f, -1, sizeof(maxs * sizeof(int)));
g = (int * *)malloc(maxs * sizeof(int *));
for (size_t i = 0; i < maxs; i++) {
g[i] = (int *)malloc(MAXC * sizeof(int));
memset(g[i], -1, MAXC * sizeof(int));
}
out = (struct output * *)malloc(maxs * sizeof(struct output *));
memset(out, 0 , maxs * sizeof(struct output *));
last = (struct output * *)malloc(maxs * sizeof(struct output *));
memset(last, 0 , maxs * sizeof(struct output *));
buildMatchingMachine(str_two, MAX_2);
}
int two_two(string& s) {
int ret = 0;
// reverse
reverse(s.begin(), s.end());
// Initialize current state
int currentState = 0;
// Traverse the text through the nuilt machine to find
// all occurrences of words in arr[]
for (int i = 0; i < s.size(); ++i)
{
currentState = findNextState(currentState, s[i]);
// Match found, print all matching words of arr[]
// using output function.
struct output * p = out[currentState];
while (p) {
ret ++;
p = p->next;
}
}
return ret;
}
int main() {
int t;
#if DEBUG
ifstream fin("input.txt");
if (!fin.is_open()) {
printf("open file error!\n");
return -1;
}
fin >> t;
#else
cin >> t;
#endif
init();
string s;
for (size_t i = 0; i < t; i++) {
#if DEBUG
fin >> s;
#else
cin >> s;
#endif
cnt[i] = two_two(s);
}
for (size_t i = 0; i < t; i++) {
cout << cnt[i] << "\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
#ifndef __WINDOWS__
#include <fts.h>
#endif // __WINDOWS__
#include <mesos/type_utils.hpp>
#include <mesos/docker/spec.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/process.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/os.hpp>
#include <stout/stringify.hpp>
#include <stout/uuid.hpp>
#include "slave/paths.hpp"
#include "slave/containerizer/mesos/provisioner/backend.hpp"
#include "slave/containerizer/mesos/provisioner/paths.hpp"
#include "slave/containerizer/mesos/provisioner/provisioner.hpp"
#include "slave/containerizer/mesos/provisioner/store.hpp"
using namespace process;
namespace spec = docker::spec;
using std::list;
using std::string;
using std::vector;
using mesos::slave::ContainerState;
namespace mesos {
namespace internal {
namespace slave {
Try<Owned<Provisioner>> Provisioner::create(const Flags& flags)
{
string _rootDir = slave::paths::getProvisionerDir(flags.work_dir);
Try<Nothing> mkdir = os::mkdir(_rootDir);
if (mkdir.isError()) {
return Error(
"Failed to create provisioner root directory '" +
_rootDir + "': " + mkdir.error());
}
Result<string> rootDir = os::realpath(_rootDir);
if (rootDir.isError()) {
return Error(
"Failed to resolve the realpath of provisioner root directory '" +
_rootDir + "': " + rootDir.error());
}
CHECK_SOME(rootDir); // Can't be None since we just created it.
Try<hashmap<Image::Type, Owned<Store>>> stores = Store::create(flags);
if (stores.isError()) {
return Error("Failed to create image stores: " + stores.error());
}
hashmap<string, Owned<Backend>> backends = Backend::create(flags);
if (backends.empty()) {
return Error("No usable provisioner backend created");
}
if (!backends.contains(flags.image_provisioner_backend)) {
return Error(
"The specified provisioner backend '" +
flags.image_provisioner_backend + "' is unsupported");
}
return Owned<Provisioner>(new Provisioner(
Owned<ProvisionerProcess>(new ProvisionerProcess(
flags,
rootDir.get(),
stores.get(),
backends))));
}
Provisioner::Provisioner(Owned<ProvisionerProcess> _process)
: process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Provisioner::~Provisioner()
{
if (process.get() != nullptr) {
terminate(process.get());
wait(process.get());
}
}
Future<Nothing> Provisioner::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::recover,
states,
orphans);
}
Future<ProvisionInfo> Provisioner::provision(
const ContainerID& containerId,
const Image& image)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::provision,
containerId,
image);
}
Future<bool> Provisioner::destroy(const ContainerID& containerId)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::destroy,
containerId);
}
ProvisionerProcess::ProvisionerProcess(
const Flags& _flags,
const string& _rootDir,
const hashmap<Image::Type, Owned<Store>>& _stores,
const hashmap<string, Owned<Backend>>& _backends)
: flags(_flags),
rootDir(_rootDir),
stores(_stores),
backends(_backends) {}
Future<Nothing> ProvisionerProcess::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
// Register living containers, including the ones that do not
// provision images.
hashset<ContainerID> alive;
foreach (const ContainerState& state, states) {
alive.insert(state.container_id());
}
// List provisioned containers; recover living ones; destroy unknown
// orphans. Note that known orphan containers are recovered as well
// and they will be destroyed by the containerizer using the normal
// cleanup path. See MESOS-2367 for details.
Try<hashset<ContainerID>> containers =
provisioner::paths::listContainers(rootDir);
if (containers.isError()) {
return Failure(
"Failed to list the containers managed by the provisioner: " +
containers.error());
}
// Scan the list of containers, register all of them with 'infos'
// but mark unknown orphans for immediate cleanup.
hashset<ContainerID> unknownOrphans;
foreach (const ContainerID& containerId, containers.get()) {
Owned<Info> info = Owned<Info>(new Info());
Try<hashmap<string, hashset<string>>> rootfses =
provisioner::paths::listContainerRootfses(rootDir, containerId);
if (rootfses.isError()) {
return Failure(
"Unable to list rootfses belonged to container " +
stringify(containerId) + ": " + rootfses.error());
}
foreachkey (const string& backend, rootfses.get()) {
if (!backends.contains(backend)) {
return Failure(
"Found rootfses managed by an unrecognized backend: " + backend);
}
info->rootfses.put(backend, rootfses.get()[backend]);
}
infos.put(containerId, info);
if (alive.contains(containerId) || orphans.contains(containerId)) {
LOG(INFO) << "Recovered container " << containerId;
continue;
} else {
// For immediate cleanup below.
unknownOrphans.insert(containerId);
}
}
// Cleanup unknown orphan containers' rootfses.
list<Future<bool>> cleanups;
foreach (const ContainerID& containerId, unknownOrphans) {
LOG(INFO) << "Cleaning up unknown orphan container " << containerId;
cleanups.push_back(destroy(containerId));
}
Future<Nothing> cleanup = collect(cleanups)
.then([]() -> Future<Nothing> { return Nothing(); });
// Recover stores.
list<Future<Nothing>> recovers;
foreachvalue (const Owned<Store>& store, stores) {
recovers.push_back(store->recover());
}
Future<Nothing> recover = collect(recovers)
.then([]() -> Future<Nothing> { return Nothing(); });
// A successful provisioner recovery depends on:
// 1) Recovery of living containers and known orphans (done above).
// 2) Successful cleanup of unknown orphans.
// 3) Successful store recovery.
//
// TODO(jieyu): Do not recover 'store' before unknown orphans are
// cleaned up. In the future, we may want to cleanup unused rootfses
// in 'store', which might fail if there still exist unknown orphans
// holding references to them.
return collect(cleanup, recover)
.then([=]() -> Future<Nothing> {
LOG(INFO) << "Provisioner recovery complete";
return Nothing();
});
}
Future<ProvisionInfo> ProvisionerProcess::provision(
const ContainerID& containerId,
const Image& image)
{
if (!stores.contains(image.type())) {
return Failure(
"Unsupported container image type: " +
stringify(image.type()));
}
// Get and then provision image layers from the store.
return stores.get(image.type()).get()->get(image)
.then(defer(self(), &Self::_provision, containerId, image, lambda::_1));
}
Future<ProvisionInfo> ProvisionerProcess::_provision(
const ContainerID& containerId,
const Image& image,
const ImageInfo& imageInfo)
{
// TODO(jieyu): Choose a backend smartly. For instance, if there is
// only one layer returned from the store. prefer to use bind
// backend because it's the simplest.
const string& backend = flags.image_provisioner_backend;
CHECK(backends.contains(backend));
string rootfsId = UUID::random().toString();
string rootfs = provisioner::paths::getContainerRootfsDir(
rootDir,
containerId,
backend,
rootfsId);
LOG(INFO) << "Provisioning image rootfs '" << rootfs
<< "' for container " << containerId;
// NOTE: It's likely that the container ID already exists in 'infos'
// because one container might provision multiple images.
if (!infos.contains(containerId)) {
infos.put(containerId, Owned<Info>(new Info()));
}
infos[containerId]->rootfses[backend].insert(rootfsId);
string backendDir = provisioner::paths::getBackendDir(
rootDir,
containerId,
backend);
return backends.get(backend).get()->provision(
imageInfo.layers,
rootfs,
backendDir)
.then(defer(self(), &Self::__provision, rootfs, image, imageInfo));
}
// This function is currently docker image specific. Depending
// on docker v1 spec, a docker image may include filesystem
// changeset, which may need to delete directories or files.
// The file/dir to be deleted will be labeled by creating a
// 'whiteout' file, which is at the same location and with the
// basename of the deleted file or directory prefixed with
// '.wh.'. Please see:
// https://github.com/docker/docker/blob/master/image/spec/v1.md
Future<ProvisionInfo> ProvisionerProcess::__provision(
const string& rootfs,
const Image& image,
const ImageInfo& imageInfo)
{
// Skip single-layered images since no 'whiteout' files needs
// to be handled, and this excludes any image using the bind
// backend.
if (imageInfo.layers.size() == 1 || image.type() != Image::DOCKER) {
return ProvisionInfo{rootfs, imageInfo.dockerManifest};
}
#ifndef __WINDOWS__
char* _rootfs[] = {const_cast<char*>(rootfs.c_str()), nullptr};
FTS* tree = ::fts_open(_rootfs, FTS_NOCHDIR | FTS_PHYSICAL, nullptr);
if (tree == nullptr) {
return Failure("Failed to open '" + rootfs + "': " + os::strerror(errno));
}
vector<string> whiteout;
for (FTSENT *node = ::fts_read(tree);
node != nullptr; node = ::fts_read(tree)) {
if (node->fts_info == FTS_F &&
strings::startsWith(node->fts_name, string(spec::WHITEOUT_PREFIX))) {
Path path = Path(node->fts_path);
whiteout.push_back(path::join(path.dirname(), path.basename().substr(
strlen(spec::WHITEOUT_PREFIX))));
Try<Nothing> rm = os::rm(path.value);
if (rm.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove the whiteout '.wh.' file '" +
path.value + "': " + rm.error());
}
}
}
if (errno != 0) {
Error error = ErrnoError();
::fts_close(tree);
return Failure(error);
}
if (::fts_close(tree) != 0) {
return Failure(
"Failed to stop traversing file system: " + os::strerror(errno));
}
foreach (const string& path, whiteout) {
if (os::stat::isdir(path)) {
Try<Nothing> rmdir = os::rmdir(path);
if (rmdir.isError()) {
return Failure(
"Failed to remove whiteout directory '" +
path + "': " + rmdir.error());
}
} else {
Try<Nothing> rm = os::rm(path);
if (rm.isError()) {
return Failure(
"Failed to remove whiteout file '" +
path + "': " + rm.error());
}
}
}
return ProvisionInfo{rootfs, imageInfo.dockerManifest};
#else
return ProvisionInfo{ rootfs, imageInfo.dockerManifest };
#endif // __WINDOWS__
}
Future<bool> ProvisionerProcess::destroy(const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
VLOG(1) << "Ignoring destroy request for unknown container " << containerId;
return false;
}
// Unregister the container first. If destroy() fails, we can rely
// on recover() to retry it later.
Owned<Info> info = infos[containerId];
infos.erase(containerId);
list<Future<bool>> futures;
foreachkey (const string& backend, info->rootfses) {
if (!backends.contains(backend)) {
return Failure("Unknown backend '" + backend + "'");
}
foreach (const string& rootfsId, info->rootfses[backend]) {
string rootfs = provisioner::paths::getContainerRootfsDir(
rootDir,
containerId,
backend,
rootfsId);
LOG(INFO) << "Destroying container rootfs at '" << rootfs
<< "' for container " << containerId;
futures.push_back(backends.get(backend).get()->destroy(rootfs));
}
}
// TODO(xujyan): Revisit the usefulness of this return value.
return collect(futures)
.then(defer(self(), &ProvisionerProcess::_destroy, containerId));
}
Future<bool> ProvisionerProcess::_destroy(const ContainerID& containerId)
{
// This should be fairly cheap as the directory should only
// contain a few empty sub-directories at this point.
//
// TODO(jieyu): Currently, it's possible that some directories
// cannot be removed due to EBUSY. EBUSY is caused by the race
// between cleaning up this container and new containers copying
// the host mount table. It's OK to ignore them. The cleanup
// will be retried during slave recovery.
string containerDir =
provisioner::paths::getContainerDir(rootDir, containerId);
Try<Nothing> rmdir = os::rmdir(containerDir);
if (rmdir.isError()) {
LOG(ERROR) << "Failed to remove the provisioned container directory "
<< "at '" << containerDir << "': " << rmdir.error();
++metrics.remove_container_errors;
}
return true;
}
ProvisionerProcess::Metrics::Metrics()
: remove_container_errors(
"containerizer/mesos/provisioner/remove_container_errors")
{
process::metrics::add(remove_container_errors);
}
ProvisionerProcess::Metrics::~Metrics()
{
process::metrics::remove(remove_container_errors);
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Added TODO to support Docker 'whiteout' deletions on Windows.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
#ifndef __WINDOWS__
#include <fts.h>
#endif // __WINDOWS__
#include <mesos/type_utils.hpp>
#include <mesos/docker/spec.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/process.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/os.hpp>
#include <stout/stringify.hpp>
#include <stout/uuid.hpp>
#include "slave/paths.hpp"
#include "slave/containerizer/mesos/provisioner/backend.hpp"
#include "slave/containerizer/mesos/provisioner/paths.hpp"
#include "slave/containerizer/mesos/provisioner/provisioner.hpp"
#include "slave/containerizer/mesos/provisioner/store.hpp"
using namespace process;
namespace spec = docker::spec;
using std::list;
using std::string;
using std::vector;
using mesos::slave::ContainerState;
namespace mesos {
namespace internal {
namespace slave {
Try<Owned<Provisioner>> Provisioner::create(const Flags& flags)
{
string _rootDir = slave::paths::getProvisionerDir(flags.work_dir);
Try<Nothing> mkdir = os::mkdir(_rootDir);
if (mkdir.isError()) {
return Error(
"Failed to create provisioner root directory '" +
_rootDir + "': " + mkdir.error());
}
Result<string> rootDir = os::realpath(_rootDir);
if (rootDir.isError()) {
return Error(
"Failed to resolve the realpath of provisioner root directory '" +
_rootDir + "': " + rootDir.error());
}
CHECK_SOME(rootDir); // Can't be None since we just created it.
Try<hashmap<Image::Type, Owned<Store>>> stores = Store::create(flags);
if (stores.isError()) {
return Error("Failed to create image stores: " + stores.error());
}
hashmap<string, Owned<Backend>> backends = Backend::create(flags);
if (backends.empty()) {
return Error("No usable provisioner backend created");
}
if (!backends.contains(flags.image_provisioner_backend)) {
return Error(
"The specified provisioner backend '" +
flags.image_provisioner_backend + "' is unsupported");
}
return Owned<Provisioner>(new Provisioner(
Owned<ProvisionerProcess>(new ProvisionerProcess(
flags,
rootDir.get(),
stores.get(),
backends))));
}
Provisioner::Provisioner(Owned<ProvisionerProcess> _process)
: process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Provisioner::~Provisioner()
{
if (process.get() != nullptr) {
terminate(process.get());
wait(process.get());
}
}
Future<Nothing> Provisioner::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::recover,
states,
orphans);
}
Future<ProvisionInfo> Provisioner::provision(
const ContainerID& containerId,
const Image& image)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::provision,
containerId,
image);
}
Future<bool> Provisioner::destroy(const ContainerID& containerId)
{
return dispatch(
CHECK_NOTNULL(process.get()),
&ProvisionerProcess::destroy,
containerId);
}
ProvisionerProcess::ProvisionerProcess(
const Flags& _flags,
const string& _rootDir,
const hashmap<Image::Type, Owned<Store>>& _stores,
const hashmap<string, Owned<Backend>>& _backends)
: flags(_flags),
rootDir(_rootDir),
stores(_stores),
backends(_backends) {}
Future<Nothing> ProvisionerProcess::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
// Register living containers, including the ones that do not
// provision images.
hashset<ContainerID> alive;
foreach (const ContainerState& state, states) {
alive.insert(state.container_id());
}
// List provisioned containers; recover living ones; destroy unknown
// orphans. Note that known orphan containers are recovered as well
// and they will be destroyed by the containerizer using the normal
// cleanup path. See MESOS-2367 for details.
Try<hashset<ContainerID>> containers =
provisioner::paths::listContainers(rootDir);
if (containers.isError()) {
return Failure(
"Failed to list the containers managed by the provisioner: " +
containers.error());
}
// Scan the list of containers, register all of them with 'infos'
// but mark unknown orphans for immediate cleanup.
hashset<ContainerID> unknownOrphans;
foreach (const ContainerID& containerId, containers.get()) {
Owned<Info> info = Owned<Info>(new Info());
Try<hashmap<string, hashset<string>>> rootfses =
provisioner::paths::listContainerRootfses(rootDir, containerId);
if (rootfses.isError()) {
return Failure(
"Unable to list rootfses belonged to container " +
stringify(containerId) + ": " + rootfses.error());
}
foreachkey (const string& backend, rootfses.get()) {
if (!backends.contains(backend)) {
return Failure(
"Found rootfses managed by an unrecognized backend: " + backend);
}
info->rootfses.put(backend, rootfses.get()[backend]);
}
infos.put(containerId, info);
if (alive.contains(containerId) || orphans.contains(containerId)) {
LOG(INFO) << "Recovered container " << containerId;
continue;
} else {
// For immediate cleanup below.
unknownOrphans.insert(containerId);
}
}
// Cleanup unknown orphan containers' rootfses.
list<Future<bool>> cleanups;
foreach (const ContainerID& containerId, unknownOrphans) {
LOG(INFO) << "Cleaning up unknown orphan container " << containerId;
cleanups.push_back(destroy(containerId));
}
Future<Nothing> cleanup = collect(cleanups)
.then([]() -> Future<Nothing> { return Nothing(); });
// Recover stores.
list<Future<Nothing>> recovers;
foreachvalue (const Owned<Store>& store, stores) {
recovers.push_back(store->recover());
}
Future<Nothing> recover = collect(recovers)
.then([]() -> Future<Nothing> { return Nothing(); });
// A successful provisioner recovery depends on:
// 1) Recovery of living containers and known orphans (done above).
// 2) Successful cleanup of unknown orphans.
// 3) Successful store recovery.
//
// TODO(jieyu): Do not recover 'store' before unknown orphans are
// cleaned up. In the future, we may want to cleanup unused rootfses
// in 'store', which might fail if there still exist unknown orphans
// holding references to them.
return collect(cleanup, recover)
.then([=]() -> Future<Nothing> {
LOG(INFO) << "Provisioner recovery complete";
return Nothing();
});
}
Future<ProvisionInfo> ProvisionerProcess::provision(
const ContainerID& containerId,
const Image& image)
{
if (!stores.contains(image.type())) {
return Failure(
"Unsupported container image type: " +
stringify(image.type()));
}
// Get and then provision image layers from the store.
return stores.get(image.type()).get()->get(image)
.then(defer(self(), &Self::_provision, containerId, image, lambda::_1));
}
Future<ProvisionInfo> ProvisionerProcess::_provision(
const ContainerID& containerId,
const Image& image,
const ImageInfo& imageInfo)
{
// TODO(jieyu): Choose a backend smartly. For instance, if there is
// only one layer returned from the store. prefer to use bind
// backend because it's the simplest.
const string& backend = flags.image_provisioner_backend;
CHECK(backends.contains(backend));
string rootfsId = UUID::random().toString();
string rootfs = provisioner::paths::getContainerRootfsDir(
rootDir,
containerId,
backend,
rootfsId);
LOG(INFO) << "Provisioning image rootfs '" << rootfs
<< "' for container " << containerId;
// NOTE: It's likely that the container ID already exists in 'infos'
// because one container might provision multiple images.
if (!infos.contains(containerId)) {
infos.put(containerId, Owned<Info>(new Info()));
}
infos[containerId]->rootfses[backend].insert(rootfsId);
string backendDir = provisioner::paths::getBackendDir(
rootDir,
containerId,
backend);
return backends.get(backend).get()->provision(
imageInfo.layers,
rootfs,
backendDir)
.then(defer(self(), &Self::__provision, rootfs, image, imageInfo));
}
// This function is currently docker image specific. Depending
// on docker v1 spec, a docker image may include filesystem
// changeset, which may need to delete directories or files.
// The file/dir to be deleted will be labeled by creating a
// 'whiteout' file, which is at the same location and with the
// basename of the deleted file or directory prefixed with
// '.wh.'. Please see:
// https://github.com/docker/docker/blob/master/image/spec/v1.md
Future<ProvisionInfo> ProvisionerProcess::__provision(
const string& rootfs,
const Image& image,
const ImageInfo& imageInfo)
{
// Skip single-layered images since no 'whiteout' files needs
// to be handled, and this excludes any image using the bind
// backend.
if (imageInfo.layers.size() == 1 || image.type() != Image::DOCKER) {
return ProvisionInfo{rootfs, imageInfo.dockerManifest};
}
#ifndef __WINDOWS__
// TODO(hausdorff): The FTS API is not available on some platforms, such as
// Windows. We will need to either (1) prove that this is not necessary for
// Windows Containers, which use much of the Docker spec themselves, or (2)
// make this code compatible with Windows, as we did with other code that
// depended on FTS, such as `os::rmdir`. See MESOS-5610.
char* _rootfs[] = {const_cast<char*>(rootfs.c_str()), nullptr};
FTS* tree = ::fts_open(_rootfs, FTS_NOCHDIR | FTS_PHYSICAL, nullptr);
if (tree == nullptr) {
return Failure("Failed to open '" + rootfs + "': " + os::strerror(errno));
}
vector<string> whiteout;
for (FTSENT *node = ::fts_read(tree);
node != nullptr; node = ::fts_read(tree)) {
if (node->fts_info == FTS_F &&
strings::startsWith(node->fts_name, string(spec::WHITEOUT_PREFIX))) {
Path path = Path(node->fts_path);
whiteout.push_back(path::join(path.dirname(), path.basename().substr(
strlen(spec::WHITEOUT_PREFIX))));
Try<Nothing> rm = os::rm(path.value);
if (rm.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove the whiteout '.wh.' file '" +
path.value + "': " + rm.error());
}
}
}
if (errno != 0) {
Error error = ErrnoError();
::fts_close(tree);
return Failure(error);
}
if (::fts_close(tree) != 0) {
return Failure(
"Failed to stop traversing file system: " + os::strerror(errno));
}
foreach (const string& path, whiteout) {
if (os::stat::isdir(path)) {
Try<Nothing> rmdir = os::rmdir(path);
if (rmdir.isError()) {
return Failure(
"Failed to remove whiteout directory '" +
path + "': " + rmdir.error());
}
} else {
Try<Nothing> rm = os::rm(path);
if (rm.isError()) {
return Failure(
"Failed to remove whiteout file '" +
path + "': " + rm.error());
}
}
}
return ProvisionInfo{rootfs, imageInfo.dockerManifest};
#else
return ProvisionInfo{ rootfs, imageInfo.dockerManifest };
#endif // __WINDOWS__
}
Future<bool> ProvisionerProcess::destroy(const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
VLOG(1) << "Ignoring destroy request for unknown container " << containerId;
return false;
}
// Unregister the container first. If destroy() fails, we can rely
// on recover() to retry it later.
Owned<Info> info = infos[containerId];
infos.erase(containerId);
list<Future<bool>> futures;
foreachkey (const string& backend, info->rootfses) {
if (!backends.contains(backend)) {
return Failure("Unknown backend '" + backend + "'");
}
foreach (const string& rootfsId, info->rootfses[backend]) {
string rootfs = provisioner::paths::getContainerRootfsDir(
rootDir,
containerId,
backend,
rootfsId);
LOG(INFO) << "Destroying container rootfs at '" << rootfs
<< "' for container " << containerId;
futures.push_back(backends.get(backend).get()->destroy(rootfs));
}
}
// TODO(xujyan): Revisit the usefulness of this return value.
return collect(futures)
.then(defer(self(), &ProvisionerProcess::_destroy, containerId));
}
Future<bool> ProvisionerProcess::_destroy(const ContainerID& containerId)
{
// This should be fairly cheap as the directory should only
// contain a few empty sub-directories at this point.
//
// TODO(jieyu): Currently, it's possible that some directories
// cannot be removed due to EBUSY. EBUSY is caused by the race
// between cleaning up this container and new containers copying
// the host mount table. It's OK to ignore them. The cleanup
// will be retried during slave recovery.
string containerDir =
provisioner::paths::getContainerDir(rootDir, containerId);
Try<Nothing> rmdir = os::rmdir(containerDir);
if (rmdir.isError()) {
LOG(ERROR) << "Failed to remove the provisioned container directory "
<< "at '" << containerDir << "': " << rmdir.error();
++metrics.remove_container_errors;
}
return true;
}
ProvisionerProcess::Metrics::Metrics()
: remove_container_errors(
"containerizer/mesos/provisioner/remove_container_errors")
{
process::metrics::add(remove_container_errors);
}
ProvisionerProcess::Metrics::~Metrics()
{
process::metrics::remove(remove_container_errors);
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include "kernel/register.h"
#include "kernel/rtlil.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SynthIntelPass : public ScriptPass {
SynthIntelPass() : ScriptPass("synth_intel", "synthesis for Intel (Altera) FPGAs.") {}
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_intel [options]\n");
log("\n");
log("This command runs synthesis for Intel FPGAs.\n");
log("\n");
log(" -family < max10 | a10gx | cyclone10 | cyclonev | cycloneiv | cycloneive>\n");
log(" generate the synthesis netlist for the specified family.\n");
log(" MAX10 is the default target if not family argument specified.\n");
log(" For Cyclone GX devices, use cycloneiv argument; For Cyclone E, use cycloneive.\n");
log(" Cyclone V and Arria 10 GX devices are experimental, use it with a10gx argument.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module (default='top')\n");
log("\n");
log(" -vqm <file>\n");
log(" write the design to the specified Verilog Quartus Mapping File. Writing of an\n");
log(" output file is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr <file>\n");
log(" write BLIF files for VPR flow experiments. The synthesized BLIF output file is not\n");
log(" compatible with the Quartus flow. Writing of an\n");
log(" output file is omitted if this parameter is not specified.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -noiopads\n");
log(" do not use altsyncram cells in output netlist\n");
log("\n");
log(" -nobram\n");
log(" do not use altsyncram cells in output netlist\n");
log("\n");
log(" -noflatten\n");
log(" do not flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
string top_opt, family_opt, vout_file, blif_file;
bool retime, flatten, nobram, noiopads;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
family_opt = "max10";
vout_file = "";
blif_file = "";
retime = false;
flatten = true;
nobram = false;
noiopads = false;
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-family" && argidx + 1 < args.size()) {
family_opt = args[++argidx];
continue;
}
if (args[argidx] == "-top" && argidx + 1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-vqm" && argidx + 1 < args.size()) {
vout_file = args[++argidx];
continue;
}
if (args[argidx] == "-vpr" && argidx + 1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx + 1 < args.size()) {
size_t pos = args[argidx + 1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos + 1);
continue;
}
if (args[argidx] == "-noiopads") {
noiopads = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-noflatten") {
flatten = false;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
if (family_opt != "max10" && family_opt != "a10gx" && family_opt != "cyclonev" && family_opt != "cycloneiv" &&
family_opt != "cycloneive" && family_opt != "cyclone10")
log_cmd_error("Invalid or not family specified: '%s'\n", family_opt.c_str());
log_header(design, "Executing SYNTH_INTEL pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (check_label("family") && family_opt == "max10")
run("read_verilog -sv -lib +/intel/max10/cells_sim.v");
else if (check_label("family") && family_opt == "a10gx")
run("read_verilog -sv -lib +/intel/a10gx/cells_sim.v");
else if (check_label("family") && family_opt == "cyclonev")
run("read_verilog -sv -lib +/intel/cyclonev/cells_sim.v");
else if (check_label("family") && family_opt == "cyclone10")
run("read_verilog -sv -lib +/intel/cyclone10/cells_sim.v");
else if (check_label("family") && family_opt == "cycloneiv")
run("read_verilog -sv -lib +/intel/cycloneiv/cells_sim.v");
else
run("read_verilog -sv -lib +/intel/cycloneive/cells_sim.v");
// Misc and common cells
run("read_verilog -sv -lib +/intel/common/m9k_bb.v");
run("read_verilog -sv -lib +/intel/common/altpll_bb.v");
run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
}
if (flatten && check_label("flatten", "(unless -noflatten)")) {
run("proc");
run("flatten");
run("tribuf -logic");
run("deminout");
}
if (check_label("coarse")) {
run("synth -run coarse");
}
if (!nobram && check_label("bram", "(skip if -nobram)")) {
run("memory_bram -rules +/intel/common/brams.txt");
run("techmap -map +/intel/common/brams_map.v");
}
if (check_label("fine")) {
run("opt -fast -mux_undef -undriven -fine -full");
run("memory_map");
run("opt -undriven -fine");
run("dffsr2dff");
run("dff2dffe -direct-match $_DFF_*");
run("opt -fine");
run("techmap -map +/techmap.v");
run("opt -full");
run("clean -purge");
run("setundef -undriven -zero");
if (retime || help_mode)
run("abc -markgroups -dff", "(only if -retime)");
}
if (check_label("map_luts")) {
if (family_opt == "a10gx" || family_opt == "cyclonev")
run("abc -luts 2:2,3,6:5" + string(retime ? " -dff" : ""));
else
run("abc -lut 4" + string(retime ? " -dff" : ""));
run("clean");
}
if (check_label("map_cells")) {
if (!noiopads)
run("iopadmap -bits -outpad $__outpad I:O -inpad $__inpad O:I", "(unless -noiopads)");
if (family_opt == "max10")
run("techmap -map +/intel/max10/cells_map.v");
else if (family_opt == "a10gx")
run("techmap -map +/intel/a10gx/cells_map.v");
else if (family_opt == "cyclonev")
run("techmap -map +/intel/cyclonev/cells_map.v");
else if (family_opt == "cyclone10")
run("techmap -map +/intel/cyclone10/cells_map.v");
else if (family_opt == "cycloneiv")
run("techmap -map +/intel/cycloneiv/cells_map.v");
else
run("techmap -map +/intel/cycloneive/cells_map.v");
run("dffinit -highlow -ff dffeas q power_up");
run("clean -purge");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat");
run("check -noinit");
}
if (check_label("vqm")) {
if (!vout_file.empty() || help_mode)
run(stringf("write_verilog -attr2comment -defparam -nohex -decimal -renameprefix syn_ %s",
help_mode ? "<file-name>" : vout_file.c_str()));
}
if (check_label("vpr")) {
if (!blif_file.empty() || help_mode) {
run(stringf("opt_clean -purge"));
run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()));
}
}
}
} SynthIntelPass;
PRIVATE_NAMESPACE_END
<commit_msg>synth_intel: Warn about untested Quartus backend<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include "kernel/register.h"
#include "kernel/rtlil.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SynthIntelPass : public ScriptPass {
SynthIntelPass() : ScriptPass("synth_intel", "synthesis for Intel (Altera) FPGAs.") {}
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_intel [options]\n");
log("\n");
log("This command runs synthesis for Intel FPGAs.\n");
log("\n");
log(" -family < max10 | a10gx | cyclone10 | cyclonev | cycloneiv | cycloneive>\n");
log(" generate the synthesis netlist for the specified family.\n");
log(" MAX10 is the default target if not family argument specified.\n");
log(" For Cyclone GX devices, use cycloneiv argument; For Cyclone E, use cycloneive.\n");
log(" Cyclone V and Arria 10 GX devices are experimental, use it with a10gx argument.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module (default='top')\n");
log("\n");
log(" -vqm <file>\n");
log(" write the design to the specified Verilog Quartus Mapping File. Writing of an\n");
log(" output file is omitted if this parameter is not specified.\n");
log(" Note that this backend has not been tested and is likely incompatible\n");
log(" with recent versions of Quartus.\n");
log("\n");
log(" -vpr <file>\n");
log(" write BLIF files for VPR flow experiments. The synthesized BLIF output file is not\n");
log(" compatible with the Quartus flow. Writing of an\n");
log(" output file is omitted if this parameter is not specified.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -noiopads\n");
log(" do not use altsyncram cells in output netlist\n");
log("\n");
log(" -nobram\n");
log(" do not use altsyncram cells in output netlist\n");
log("\n");
log(" -noflatten\n");
log(" do not flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
string top_opt, family_opt, vout_file, blif_file;
bool retime, flatten, nobram, noiopads;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
family_opt = "max10";
vout_file = "";
blif_file = "";
retime = false;
flatten = true;
nobram = false;
noiopads = false;
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-family" && argidx + 1 < args.size()) {
family_opt = args[++argidx];
continue;
}
if (args[argidx] == "-top" && argidx + 1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-vqm" && argidx + 1 < args.size()) {
vout_file = args[++argidx];
log_warning("The Quartus backend has not been tested recently and is likely incompatible with modern versions of Quartus.\n");
continue;
}
if (args[argidx] == "-vpr" && argidx + 1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx + 1 < args.size()) {
size_t pos = args[argidx + 1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos + 1);
continue;
}
if (args[argidx] == "-noiopads") {
noiopads = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-noflatten") {
flatten = false;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
if (family_opt != "max10" && family_opt != "a10gx" && family_opt != "cyclonev" && family_opt != "cycloneiv" &&
family_opt != "cycloneive" && family_opt != "cyclone10")
log_cmd_error("Invalid or not family specified: '%s'\n", family_opt.c_str());
log_header(design, "Executing SYNTH_INTEL pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (check_label("family") && family_opt == "max10")
run("read_verilog -sv -lib +/intel/max10/cells_sim.v");
else if (check_label("family") && family_opt == "a10gx")
run("read_verilog -sv -lib +/intel/a10gx/cells_sim.v");
else if (check_label("family") && family_opt == "cyclonev")
run("read_verilog -sv -lib +/intel/cyclonev/cells_sim.v");
else if (check_label("family") && family_opt == "cyclone10")
run("read_verilog -sv -lib +/intel/cyclone10/cells_sim.v");
else if (check_label("family") && family_opt == "cycloneiv")
run("read_verilog -sv -lib +/intel/cycloneiv/cells_sim.v");
else
run("read_verilog -sv -lib +/intel/cycloneive/cells_sim.v");
// Misc and common cells
run("read_verilog -sv -lib +/intel/common/m9k_bb.v");
run("read_verilog -sv -lib +/intel/common/altpll_bb.v");
run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
}
if (flatten && check_label("flatten", "(unless -noflatten)")) {
run("proc");
run("flatten");
run("tribuf -logic");
run("deminout");
}
if (check_label("coarse")) {
run("synth -run coarse");
}
if (!nobram && check_label("bram", "(skip if -nobram)")) {
run("memory_bram -rules +/intel/common/brams.txt");
run("techmap -map +/intel/common/brams_map.v");
}
if (check_label("fine")) {
run("opt -fast -mux_undef -undriven -fine -full");
run("memory_map");
run("opt -undriven -fine");
run("dffsr2dff");
run("dff2dffe -direct-match $_DFF_*");
run("opt -fine");
run("techmap -map +/techmap.v");
run("opt -full");
run("clean -purge");
run("setundef -undriven -zero");
if (retime || help_mode)
run("abc -markgroups -dff", "(only if -retime)");
}
if (check_label("map_luts")) {
if (family_opt == "a10gx" || family_opt == "cyclonev")
run("abc -luts 2:2,3,6:5" + string(retime ? " -dff" : ""));
else
run("abc -lut 4" + string(retime ? " -dff" : ""));
run("clean");
}
if (check_label("map_cells")) {
if (!noiopads)
run("iopadmap -bits -outpad $__outpad I:O -inpad $__inpad O:I", "(unless -noiopads)");
if (family_opt == "max10")
run("techmap -map +/intel/max10/cells_map.v");
else if (family_opt == "a10gx")
run("techmap -map +/intel/a10gx/cells_map.v");
else if (family_opt == "cyclonev")
run("techmap -map +/intel/cyclonev/cells_map.v");
else if (family_opt == "cyclone10")
run("techmap -map +/intel/cyclone10/cells_map.v");
else if (family_opt == "cycloneiv")
run("techmap -map +/intel/cycloneiv/cells_map.v");
else
run("techmap -map +/intel/cycloneive/cells_map.v");
run("dffinit -highlow -ff dffeas q power_up");
run("clean -purge");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat");
run("check -noinit");
}
if (check_label("vqm")) {
if (!vout_file.empty() || help_mode)
run(stringf("write_verilog -attr2comment -defparam -nohex -decimal -renameprefix syn_ %s",
help_mode ? "<file-name>" : vout_file.c_str()));
}
if (check_label("vpr")) {
if (!blif_file.empty() || help_mode) {
run(stringf("opt_clean -purge"));
run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()));
}
}
}
} SynthIntelPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>#ifndef TEST_POLYGON_HPP
#define TEST_POLYGON_HPP
#include <gtest/gtest.h>
#include <DO/Core/EigenExtension.hpp>
using namespace DO;
class TestPolygon : public testing::Test
{
protected:
int w;
int h;
double a;
double b;
Point2d p1;
Point2d p2;
Point2d center;
TestPolygon()
{
w = 512;
h = 512;
a = 0.25*w;
b = 0.75*h;
p1 = Point2d(a, a);
p2 = Point2d(b, b);
center = Point2d(w/2., h/2.);
}
template <typename TestPred, typename GroundTruth>
void sweep_check(const TestPred& pred, const GroundTruth& ground_truth)
{
for (int y = -h; y < h; ++y)
{
for (int x = -w; x < w; ++x)
{
Point2d p(x,y);
EXPECT_EQ(ground_truth(p), pred(p));
}
}
}
template <typename TestPred>
int sweep_count_pixels(const TestPred& pred)
{
int quantity = 0;
for (int y = -h; y < h; ++y)
{
for (int x = -w; x < w; ++x)
{
Point2d p(x,y);
if (pred(p))
++quantity;
}
}
return quantity;
}
};
#endif /* TEST_POLYGON_HPP */<commit_msg>Rename data members in test fixture.<commit_after>#ifndef TEST_POLYGON_HPP
#define TEST_POLYGON_HPP
#include <gtest/gtest.h>
#include <DO/Core/EigenExtension.hpp>
using namespace DO;
class TestPolygon : public testing::Test
{
protected:
int _width;
int _height;
double _a;
double _b;
Point2d _p1;
Point2d _p2;
Point2d _center;
TestPolygon()
{
_width = 10;
_height = 10;
_a = 0.25*_width;
_b = 0.75*_height;
_p1 = Point2d(_a, _a);
_p2 = Point2d(_b, _b);
_center = Point2d(_width/2., _height/2.);
}
template <typename TestPred, typename GroundTruth>
void sweep_check(const TestPred& pred, const GroundTruth& ground_truth)
{
for (int y = -_height; y < _height; ++y)
{
for (int x = -_width; x < _width; ++x)
{
Point2d p(x,y);
EXPECT_EQ(ground_truth(p), pred(p));
}
}
}
template <typename TestPred>
int sweep_count_pixels(const TestPred& pred)
{
int quantity = 0;
for (int y = -_height; y < _height; ++y)
{
for (int x = -_width; x < _width; ++x)
{
Point2d p(x,y);
if (pred(p))
++quantity;
}
}
return quantity;
}
};
#endif /* TEST_POLYGON_HPP */<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/common_runtime/eager/kernel_and_device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/platform/fingerprint.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/tensor_slice_reader_cache.h"
namespace tensorflow {
// static
Status KernelAndDevice::InitOp(Device* device, const NodeDef& ndef,
KernelAndDevice* out) {
OpKernel* k = nullptr;
Status s = CreateOpKernel(device->device_type().c_str(), device,
device->GetAllocator(AllocatorAttributes()),
nullptr, ndef, TF_GRAPH_DEF_VERSION, &k);
out->device_ = device;
out->kernel_.reset(k);
out->flib_ = nullptr;
return s;
}
// static
Status KernelAndDevice::Init(const NodeDef& ndef, FunctionLibraryRuntime* flib,
KernelAndDevice* out) {
OpKernel* k = nullptr;
Status s = flib->CreateKernel(ndef, &k);
out->device_ = flib->device();
out->kernel_.reset(k);
out->flib_ = flib;
return s;
}
Status KernelAndDevice::Run(std::vector<Tensor>* input_tensors,
std::vector<Tensor>* output_tensors,
NodeExecStats* stats) {
gtl::InlinedVector<TensorValue, 4> inputs;
for (Tensor& t : *input_tensors) {
inputs.push_back(TensorValue(&t));
}
std::vector<AllocatorAttributes> out_attrs(kernel_->num_outputs());
for (size_t i = 0; i < out_attrs.size(); ++i) {
out_attrs[i].set_on_host(kernel_->output_memory_types()[i] ==
tensorflow::HOST_MEMORY);
}
OpKernelContext::Params params;
params.device = device_;
params.frame_iter = FrameAndIter(0, 0);
params.inputs = &inputs;
params.op_kernel = kernel_.get();
params.resource_manager = device_->resource_manager();
params.output_attr_array = gtl::vector_as_array(&out_attrs);
params.function_library = flib_;
params.slice_reader_cache = &slice_reader_cache_;
params.rendezvous = rendez_;
if (stats != nullptr) {
params.track_allocations = true;
}
// TODO(apassos): use a thread pool.
std::function<void(std::function<void()>)> runner =
[](std::function<void()> f) { f(); };
params.runner = &runner;
OpKernelContext context(¶ms);
if (kernel_->def().op() == "_Recv") {
// TODO(apassos) do not special-case _Recv. Currently the GPU device fails
// if trying to run _Recv->Compute(), specifically checking for _Recv. To go
// around this we call _Recv->ComputeAsync, to mimic graph mode behavior.
AsyncOpKernel* async = kernel_->AsAsync();
Notification done;
device_->ComputeAsync(async, &context, [&done]() { done.Notify(); });
done.WaitForNotification();
} else {
device_->Compute(kernel_.get(), &context);
}
if (!context.status().ok()) return context.status();
output_tensors->clear();
for (int i = 0; i < context.num_outputs(); ++i) {
output_tensors->push_back(Tensor(*context.mutable_output(i)));
}
if (stats != nullptr) {
for (const auto& allocator_pair : context.wrapped_allocators()) {
AllocatorMemoryUsed* memory = stats->add_memory();
memory->set_allocator_name(allocator_pair.first->Name());
auto sizes = allocator_pair.second->GetSizes();
memory->set_total_bytes(std::get<0>(sizes));
memory->set_peak_bytes(std::get<1>(sizes));
memory->set_live_bytes(std::get<2>(sizes));
AllocatorStats allocator_stats;
allocator_pair.first->GetStats(&allocator_stats);
memory->set_allocator_bytes_in_use(allocator_stats.bytes_in_use);
allocator_pair.second->GetRecordsAndUnRef();
}
auto* ms = stats->mutable_memory_stats();
ms->set_temp_memory_size(context.temp_memory_allocated());
for (const auto& alloc_id : context.persistent_alloc_ids()) {
ms->mutable_persistent_tensor_alloc_ids()->Add(alloc_id);
}
ms->set_persistent_memory_size(context.persistent_memory_allocated());
}
return Status::OK();
}
} // namespace tensorflow
<commit_msg>Provide a step container to OpKernelContexts when running eagerly.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/common_runtime/eager/kernel_and_device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/platform/fingerprint.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/tensor_slice_reader_cache.h"
namespace tensorflow {
// static
Status KernelAndDevice::InitOp(Device* device, const NodeDef& ndef,
KernelAndDevice* out) {
OpKernel* k = nullptr;
Status s = CreateOpKernel(device->device_type().c_str(), device,
device->GetAllocator(AllocatorAttributes()),
nullptr, ndef, TF_GRAPH_DEF_VERSION, &k);
out->device_ = device;
out->kernel_.reset(k);
out->flib_ = nullptr;
return s;
}
// static
Status KernelAndDevice::Init(const NodeDef& ndef, FunctionLibraryRuntime* flib,
KernelAndDevice* out) {
OpKernel* k = nullptr;
Status s = flib->CreateKernel(ndef, &k);
out->device_ = flib->device();
out->kernel_.reset(k);
out->flib_ = flib;
return s;
}
Status KernelAndDevice::Run(std::vector<Tensor>* input_tensors,
std::vector<Tensor>* output_tensors,
NodeExecStats* stats) {
gtl::InlinedVector<TensorValue, 4> inputs;
for (Tensor& t : *input_tensors) {
inputs.push_back(TensorValue(&t));
}
std::vector<AllocatorAttributes> out_attrs(kernel_->num_outputs());
for (size_t i = 0; i < out_attrs.size(); ++i) {
out_attrs[i].set_on_host(kernel_->output_memory_types()[i] ==
tensorflow::HOST_MEMORY);
}
OpKernelContext::Params params;
params.device = device_;
params.frame_iter = FrameAndIter(0, 0);
params.inputs = &inputs;
params.op_kernel = kernel_.get();
params.resource_manager = device_->resource_manager();
params.output_attr_array = gtl::vector_as_array(&out_attrs);
params.function_library = flib_;
params.slice_reader_cache = &slice_reader_cache_;
params.rendezvous = rendez_;
if (stats != nullptr) {
params.track_allocations = true;
}
// TODO(apassos): use a thread pool.
std::function<void(std::function<void()>)> runner =
[](std::function<void()> f) { f(); };
params.runner = &runner;
ScopedStepContainer step_container(0, [this](const string& name) {
device_->resource_manager()->Cleanup(name).IgnoreError();
});
params.step_container = &step_container;
OpKernelContext context(¶ms);
if (kernel_->def().op() == "_Recv") {
// TODO(apassos) do not special-case _Recv. Currently the GPU device fails
// if trying to run _Recv->Compute(), specifically checking for _Recv. To go
// around this we call _Recv->ComputeAsync, to mimic graph mode behavior.
AsyncOpKernel* async = kernel_->AsAsync();
Notification done;
device_->ComputeAsync(async, &context, [&done]() { done.Notify(); });
done.WaitForNotification();
} else {
device_->Compute(kernel_.get(), &context);
}
if (!context.status().ok()) return context.status();
output_tensors->clear();
for (int i = 0; i < context.num_outputs(); ++i) {
output_tensors->push_back(Tensor(*context.mutable_output(i)));
}
if (stats != nullptr) {
for (const auto& allocator_pair : context.wrapped_allocators()) {
AllocatorMemoryUsed* memory = stats->add_memory();
memory->set_allocator_name(allocator_pair.first->Name());
auto sizes = allocator_pair.second->GetSizes();
memory->set_total_bytes(std::get<0>(sizes));
memory->set_peak_bytes(std::get<1>(sizes));
memory->set_live_bytes(std::get<2>(sizes));
AllocatorStats allocator_stats;
allocator_pair.first->GetStats(&allocator_stats);
memory->set_allocator_bytes_in_use(allocator_stats.bytes_in_use);
allocator_pair.second->GetRecordsAndUnRef();
}
auto* ms = stats->mutable_memory_stats();
ms->set_temp_memory_size(context.temp_memory_allocated());
for (const auto& alloc_id : context.persistent_alloc_ids()) {
ms->mutable_persistent_tensor_alloc_ids()->Add(alloc_id);
}
ms->set_persistent_memory_size(context.persistent_memory_allocated());
}
return Status::OK();
}
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:58:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef FRM_STRINGS_HXX
#include "frm_strings.hxx"
#endif
#ifndef _FRM_PROPERTY_HXX_
#include "property.hxx"
#endif
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#include <algorithm>
//... namespace frm .......................................................
namespace frm
{
//.........................................................................
//==================================================================
//= PropertyInfoService
//==================================================================
PropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;
//------------------------------------------------------------------
sal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)
{
initialize();
PropertyAssignment aCompareName(_rName, -1);
::std::pair<PropertyMapIterator,PropertyMapIterator> aPair = equal_range(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
aCompareName,
PropertyAssignmentNameCompareLess());
sal_Int32 nHandle = -1;
if (aPair.first != aPair.second)
{ // we found something _and_ we have an identity
nHandle = aPair.first->nHandle;
}
return nHandle;
}
//------------------------------------------------------------------
sal_Int32 ConcretInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)
{
return PropertyInfoService::getPropertyId(_rName);
}
//------------------------------------------------------------------
#define ADD_PROP_ASSIGNMENT(varname) \
s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))
//..................................................................
void PropertyInfoService::initialize()
{
if (!s_AllKnownProperties.empty())
return;
s_AllKnownProperties.reserve(220);
ADD_PROP_ASSIGNMENT(NAME);
ADD_PROP_ASSIGNMENT(TAG);
ADD_PROP_ASSIGNMENT(TABINDEX);
ADD_PROP_ASSIGNMENT(CLASSID);
ADD_PROP_ASSIGNMENT(ALIGN);
ADD_PROP_ASSIGNMENT(FETCHSIZE);
ADD_PROP_ASSIGNMENT(VALUE);
ADD_PROP_ASSIGNMENT(VALUEMIN);
ADD_PROP_ASSIGNMENT(VALUEMAX);
ADD_PROP_ASSIGNMENT(VALUESTEP);
ADD_PROP_ASSIGNMENT(TEXT);
ADD_PROP_ASSIGNMENT(LABEL);
ADD_PROP_ASSIGNMENT(NAVIGATION);
ADD_PROP_ASSIGNMENT(CYCLE);
ADD_PROP_ASSIGNMENT(CONTROLSOURCE);
ADD_PROP_ASSIGNMENT(ENABLED);
ADD_PROP_ASSIGNMENT(SPIN);
ADD_PROP_ASSIGNMENT(READONLY);
ADD_PROP_ASSIGNMENT(FILTER);
ADD_PROP_ASSIGNMENT(WIDTH);
ADD_PROP_ASSIGNMENT(SEARCHABLE);
ADD_PROP_ASSIGNMENT(MULTILINE);
ADD_PROP_ASSIGNMENT(TARGET_URL);
ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);
ADD_PROP_ASSIGNMENT(MAXTEXTLEN);
ADD_PROP_ASSIGNMENT(SIZE);
ADD_PROP_ASSIGNMENT(DATE);
ADD_PROP_ASSIGNMENT(TIME);
ADD_PROP_ASSIGNMENT(STATE);
ADD_PROP_ASSIGNMENT(TRISTATE);
ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);
ADD_PROP_ASSIGNMENT(TARGET_FRAME);
ADD_PROP_ASSIGNMENT(BUTTONTYPE);
ADD_PROP_ASSIGNMENT(STRINGITEMLIST);
ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);
ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);
ADD_PROP_ASSIGNMENT(DEFAULT_DATE);
ADD_PROP_ASSIGNMENT(DEFAULT_TIME);
ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);
ADD_PROP_ASSIGNMENT(FORMATKEY);
ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);
ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);
ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);
ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);
ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);
ADD_PROP_ASSIGNMENT(IMAGE_URL);
ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);
ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);
ADD_PROP_ASSIGNMENT(LISTSOURCE);
ADD_PROP_ASSIGNMENT(SELECT_SEQ);
ADD_PROP_ASSIGNMENT(VALUE_SEQ);
ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);
ADD_PROP_ASSIGNMENT(MULTISELECTION);
ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);
ADD_PROP_ASSIGNMENT(EDITMASK);
ADD_PROP_ASSIGNMENT(ISREADONLY);
ADD_PROP_ASSIGNMENT(FIELDTYPE);
ADD_PROP_ASSIGNMENT(DECIMALS);
ADD_PROP_ASSIGNMENT(REFVALUE);
ADD_PROP_ASSIGNMENT(STRICTFORMAT);
ADD_PROP_ASSIGNMENT(DATASOURCE);
ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);
ADD_PROP_ASSIGNMENT(ALLOWEDITS);
ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);
ADD_PROP_ASSIGNMENT(MASTERFIELDS);
ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);
ADD_PROP_ASSIGNMENT(QUERY);
ADD_PROP_ASSIGNMENT(LITERALMASK);
ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);
ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);
ADD_PROP_ASSIGNMENT(DATEFORMAT);
ADD_PROP_ASSIGNMENT(DATEMIN);
ADD_PROP_ASSIGNMENT(DATEMAX);
ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);
ADD_PROP_ASSIGNMENT(TIMEFORMAT);
ADD_PROP_ASSIGNMENT(TIMEMIN);
ADD_PROP_ASSIGNMENT(TIMEMAX);
ADD_PROP_ASSIGNMENT(LINECOUNT);
ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);
ADD_PROP_ASSIGNMENT(HASNAVIGATION);
ADD_PROP_ASSIGNMENT(FONT);
ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);
ADD_PROP_ASSIGNMENT(FILLCOLOR);
ADD_PROP_ASSIGNMENT(TEXTCOLOR);
ADD_PROP_ASSIGNMENT(LINECOLOR);
ADD_PROP_ASSIGNMENT(BORDER);
ADD_PROP_ASSIGNMENT(DROPDOWN);
ADD_PROP_ASSIGNMENT(HSCROLL);
ADD_PROP_ASSIGNMENT(VSCROLL);
ADD_PROP_ASSIGNMENT(TABSTOP);
ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);
ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);
ADD_PROP_ASSIGNMENT(PRINTABLE);
ADD_PROP_ASSIGNMENT(ECHO_CHAR);
ADD_PROP_ASSIGNMENT(ROWHEIGHT);
ADD_PROP_ASSIGNMENT(HELPTEXT);
ADD_PROP_ASSIGNMENT(FONT_NAME);
ADD_PROP_ASSIGNMENT(FONT_STYLENAME);
ADD_PROP_ASSIGNMENT(FONT_FAMILY);
ADD_PROP_ASSIGNMENT(FONT_CHARSET);
ADD_PROP_ASSIGNMENT(FONT_HEIGHT);
ADD_PROP_ASSIGNMENT(FONT_WEIGHT);
ADD_PROP_ASSIGNMENT(FONT_SLANT);
ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);
ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);
ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);
ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);
ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);
ADD_PROP_ASSIGNMENT(FONTRELIEF);
ADD_PROP_ASSIGNMENT(HELPURL);
ADD_PROP_ASSIGNMENT(RECORDMARKER);
ADD_PROP_ASSIGNMENT(BOUNDFIELD);
ADD_PROP_ASSIGNMENT(TREATASNUMERIC);
ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);
ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);
ADD_PROP_ASSIGNMENT(HIDDEN);
ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);
ADD_PROP_ASSIGNMENT(FIELDSOURCE);
ADD_PROP_ASSIGNMENT(TABLENAME);
ADD_PROP_ASSIGNMENT(CONTROLLABEL);
ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);
ADD_PROP_ASSIGNMENT(CURSORCOLOR);
ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);
ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);
ADD_PROP_ASSIGNMENT(ISMODIFIED);
ADD_PROP_ASSIGNMENT(ISNEW);
ADD_PROP_ASSIGNMENT(PRIVILEGES);
ADD_PROP_ASSIGNMENT(DETAILFIELDS);
ADD_PROP_ASSIGNMENT(COMMAND);
ADD_PROP_ASSIGNMENT(COMMANDTYPE);
ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);
ADD_PROP_ASSIGNMENT(INSERTONLY);
ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);
ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);
ADD_PROP_ASSIGNMENT(APPLYFILTER);
ADD_PROP_ASSIGNMENT(ISNULLABLE);
ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);
ADD_PROP_ASSIGNMENT(ISCURRENCY);
ADD_PROP_ASSIGNMENT(URL);
ADD_PROP_ASSIGNMENT(TITLE);
ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);
ADD_PROP_ASSIGNMENT(SCALE);
ADD_PROP_ASSIGNMENT(SORT);
ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);
ADD_PROP_ASSIGNMENT(SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(SPIN_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);
// now sort the array by name
std::sort(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
PropertyAssignmentNameCompareLess()
);
}
//.........................................................................
}
//... namespace frm .......................................................
<commit_msg>INTEGRATION: CWS dba23a (1.16.58); FILE MERGED 2007/03/14 14:44:52 fs 1.16.58.1: #i74087# outsourced the PropertyBag handling into an own class, which is now used by both OControlModel and ODatabaseForm<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2007-05-10 09:59:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef FRM_STRINGS_HXX
#include "frm_strings.hxx"
#endif
#ifndef _FRM_PROPERTY_HXX_
#include "property.hxx"
#endif
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#include <algorithm>
//... namespace frm .......................................................
namespace frm
{
//.........................................................................
//==================================================================
//= PropertyInfoService
//==================================================================
PropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;
//------------------------------------------------------------------
sal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)
{
initialize();
PropertyAssignment aCompareName(_rName, -1);
::std::pair<PropertyMapIterator,PropertyMapIterator> aPair = equal_range(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
aCompareName,
PropertyAssignmentNameCompareLess());
sal_Int32 nHandle = -1;
if (aPair.first != aPair.second)
{ // we found something _and_ we have an identity
nHandle = aPair.first->nHandle;
}
return nHandle;
}
//------------------------------------------------------------------
sal_Int32 ConcreteInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)
{
return PropertyInfoService::getPropertyId(_rName);
}
//------------------------------------------------------------------
#define ADD_PROP_ASSIGNMENT(varname) \
s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))
//..................................................................
void PropertyInfoService::initialize()
{
if (!s_AllKnownProperties.empty())
return;
s_AllKnownProperties.reserve(220);
ADD_PROP_ASSIGNMENT(NAME);
ADD_PROP_ASSIGNMENT(TAG);
ADD_PROP_ASSIGNMENT(TABINDEX);
ADD_PROP_ASSIGNMENT(CLASSID);
ADD_PROP_ASSIGNMENT(ALIGN);
ADD_PROP_ASSIGNMENT(FETCHSIZE);
ADD_PROP_ASSIGNMENT(VALUE);
ADD_PROP_ASSIGNMENT(VALUEMIN);
ADD_PROP_ASSIGNMENT(VALUEMAX);
ADD_PROP_ASSIGNMENT(VALUESTEP);
ADD_PROP_ASSIGNMENT(TEXT);
ADD_PROP_ASSIGNMENT(LABEL);
ADD_PROP_ASSIGNMENT(NAVIGATION);
ADD_PROP_ASSIGNMENT(CYCLE);
ADD_PROP_ASSIGNMENT(CONTROLSOURCE);
ADD_PROP_ASSIGNMENT(ENABLED);
ADD_PROP_ASSIGNMENT(SPIN);
ADD_PROP_ASSIGNMENT(READONLY);
ADD_PROP_ASSIGNMENT(FILTER);
ADD_PROP_ASSIGNMENT(WIDTH);
ADD_PROP_ASSIGNMENT(SEARCHABLE);
ADD_PROP_ASSIGNMENT(MULTILINE);
ADD_PROP_ASSIGNMENT(TARGET_URL);
ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);
ADD_PROP_ASSIGNMENT(MAXTEXTLEN);
ADD_PROP_ASSIGNMENT(SIZE);
ADD_PROP_ASSIGNMENT(DATE);
ADD_PROP_ASSIGNMENT(TIME);
ADD_PROP_ASSIGNMENT(STATE);
ADD_PROP_ASSIGNMENT(TRISTATE);
ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);
ADD_PROP_ASSIGNMENT(TARGET_FRAME);
ADD_PROP_ASSIGNMENT(BUTTONTYPE);
ADD_PROP_ASSIGNMENT(STRINGITEMLIST);
ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);
ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);
ADD_PROP_ASSIGNMENT(DEFAULT_DATE);
ADD_PROP_ASSIGNMENT(DEFAULT_TIME);
ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);
ADD_PROP_ASSIGNMENT(FORMATKEY);
ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);
ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);
ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);
ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);
ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);
ADD_PROP_ASSIGNMENT(IMAGE_URL);
ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);
ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);
ADD_PROP_ASSIGNMENT(LISTSOURCE);
ADD_PROP_ASSIGNMENT(SELECT_SEQ);
ADD_PROP_ASSIGNMENT(VALUE_SEQ);
ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);
ADD_PROP_ASSIGNMENT(MULTISELECTION);
ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);
ADD_PROP_ASSIGNMENT(EDITMASK);
ADD_PROP_ASSIGNMENT(ISREADONLY);
ADD_PROP_ASSIGNMENT(FIELDTYPE);
ADD_PROP_ASSIGNMENT(DECIMALS);
ADD_PROP_ASSIGNMENT(REFVALUE);
ADD_PROP_ASSIGNMENT(STRICTFORMAT);
ADD_PROP_ASSIGNMENT(DATASOURCE);
ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);
ADD_PROP_ASSIGNMENT(ALLOWEDITS);
ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);
ADD_PROP_ASSIGNMENT(MASTERFIELDS);
ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);
ADD_PROP_ASSIGNMENT(QUERY);
ADD_PROP_ASSIGNMENT(LITERALMASK);
ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);
ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);
ADD_PROP_ASSIGNMENT(DATEFORMAT);
ADD_PROP_ASSIGNMENT(DATEMIN);
ADD_PROP_ASSIGNMENT(DATEMAX);
ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);
ADD_PROP_ASSIGNMENT(TIMEFORMAT);
ADD_PROP_ASSIGNMENT(TIMEMIN);
ADD_PROP_ASSIGNMENT(TIMEMAX);
ADD_PROP_ASSIGNMENT(LINECOUNT);
ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);
ADD_PROP_ASSIGNMENT(HASNAVIGATION);
ADD_PROP_ASSIGNMENT(FONT);
ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);
ADD_PROP_ASSIGNMENT(FILLCOLOR);
ADD_PROP_ASSIGNMENT(TEXTCOLOR);
ADD_PROP_ASSIGNMENT(LINECOLOR);
ADD_PROP_ASSIGNMENT(BORDER);
ADD_PROP_ASSIGNMENT(DROPDOWN);
ADD_PROP_ASSIGNMENT(HSCROLL);
ADD_PROP_ASSIGNMENT(VSCROLL);
ADD_PROP_ASSIGNMENT(TABSTOP);
ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);
ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);
ADD_PROP_ASSIGNMENT(PRINTABLE);
ADD_PROP_ASSIGNMENT(ECHO_CHAR);
ADD_PROP_ASSIGNMENT(ROWHEIGHT);
ADD_PROP_ASSIGNMENT(HELPTEXT);
ADD_PROP_ASSIGNMENT(FONT_NAME);
ADD_PROP_ASSIGNMENT(FONT_STYLENAME);
ADD_PROP_ASSIGNMENT(FONT_FAMILY);
ADD_PROP_ASSIGNMENT(FONT_CHARSET);
ADD_PROP_ASSIGNMENT(FONT_HEIGHT);
ADD_PROP_ASSIGNMENT(FONT_WEIGHT);
ADD_PROP_ASSIGNMENT(FONT_SLANT);
ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);
ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);
ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);
ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);
ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);
ADD_PROP_ASSIGNMENT(FONTRELIEF);
ADD_PROP_ASSIGNMENT(HELPURL);
ADD_PROP_ASSIGNMENT(RECORDMARKER);
ADD_PROP_ASSIGNMENT(BOUNDFIELD);
ADD_PROP_ASSIGNMENT(TREATASNUMERIC);
ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);
ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);
ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);
ADD_PROP_ASSIGNMENT(HIDDEN);
ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);
ADD_PROP_ASSIGNMENT(FIELDSOURCE);
ADD_PROP_ASSIGNMENT(TABLENAME);
ADD_PROP_ASSIGNMENT(CONTROLLABEL);
ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);
ADD_PROP_ASSIGNMENT(CURSORCOLOR);
ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);
ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);
ADD_PROP_ASSIGNMENT(ISMODIFIED);
ADD_PROP_ASSIGNMENT(ISNEW);
ADD_PROP_ASSIGNMENT(PRIVILEGES);
ADD_PROP_ASSIGNMENT(DETAILFIELDS);
ADD_PROP_ASSIGNMENT(COMMAND);
ADD_PROP_ASSIGNMENT(COMMANDTYPE);
ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);
ADD_PROP_ASSIGNMENT(INSERTONLY);
ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);
ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);
ADD_PROP_ASSIGNMENT(APPLYFILTER);
ADD_PROP_ASSIGNMENT(ISNULLABLE);
ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);
ADD_PROP_ASSIGNMENT(ISCURRENCY);
ADD_PROP_ASSIGNMENT(URL);
ADD_PROP_ASSIGNMENT(TITLE);
ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);
ADD_PROP_ASSIGNMENT(SCALE);
ADD_PROP_ASSIGNMENT(SORT);
ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);
ADD_PROP_ASSIGNMENT(SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(SPIN_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);
ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);
// now sort the array by name
std::sort(
s_AllKnownProperties.begin(),
s_AllKnownProperties.end(),
PropertyAssignmentNameCompareLess()
);
}
//.........................................................................
}
//... namespace frm .......................................................
<|endoftext|>
|
<commit_before>/**
* 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.
*/
#ifndef __STOUT_CACHE_HPP__
#define __STOUT_CACHE_HPP__
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <boost/unordered_map.hpp>
#include "none.hpp"
#include "option.hpp"
// Forward declaration.
template <typename Key, typename Value>
class cache;
// Outputs the key/value pairs from least to most-recently used.
template <typename Key, typename Value>
std::ostream& operator << (
std::ostream& stream,
const cache<Key, Value>& c);
// Provides a least-recently used (LRU) cache of some predefined
// capacity. A "write" and a "read" both count as uses.
template <typename Key, typename Value>
class cache
{
public:
typedef std::list<Key> list;
typedef boost::unordered_map<
Key, std::pair<Value, typename list::iterator> > map;
explicit cache(int _capacity) : capacity(_capacity) {}
void put(const Key& key, const Value& value)
{
typename map::iterator i = values.find(key);
if (i == values.end()) {
insert(key, value);
} else {
(*i).second.first = value;
use(i);
}
}
Option<Value> get(const Key& key)
{
typename map::iterator i = values.find(key);
if (i != values.end()) {
use(i);
return (*i).second.first;
}
return None();
}
private:
// Not copyable, not assignable.
cache(const cache&);
cache& operator = (const cache&);
// Give the operator access to our internals.
friend std::ostream& operator << <>(
std::ostream& stream,
const cache<Key, Value>& c);
// Insert key/value into the cache.
void insert(const Key& key, const Value& value)
{
if (keys.size() == capacity) {
evict();
}
// Get a "pointer" into the lru list for efficient update.
typename list::iterator i = keys.insert(keys.end(), key);
// Save key/value and "pointer" into lru list.
values.insert(std::make_pair(key, std::make_pair(value, i)));
}
// Updates the LRU ordering in the cache for the given iterator.
void use(const typename map::iterator& i)
{
// Move the "pointer" to the end of the lru list.
keys.splice(keys.end(), keys, (*i).second.second);
// Now update the "pointer" so we can do this again.
(*i).second.second = --keys.end();
}
// Evict the least-recently used element from the cache.
void evict()
{
const typename map::iterator& i = values.find(keys.front());
CHECK(i != values.end());
values.erase(i);
keys.pop_front();
}
// Size of the cache.
int capacity;
// Cache of values and "pointers" into the least-recently used list.
map values;
// Keys ordered by least-recently used.
list keys;
};
template <typename Key, typename Value>
std::ostream& operator << (
std::ostream& stream,
const cache<Key, Value>& c)
{
typename cache<Key, Value>::list::const_iterator i1;
for (i1 = c.keys.begin(); i1 != c.keys.end(); i1++) {
stream << *i1 << ": ";
typename cache<Key, Value>::map::const_iterator i2;
i2 = c.values.find(*i1);
CHECK(i2 != c.values.end());
stream << *i2 << std::endl;
}
return stream;
}
#endif // __STOUT_CACHE_HPP__
<commit_msg>Renamed cache to Cache.<commit_after>/**
* 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.
*/
#ifndef __STOUT_CACHE_HPP__
#define __STOUT_CACHE_HPP__
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <boost/unordered_map.hpp>
#include "none.hpp"
#include "option.hpp"
// Forward declaration.
template <typename Key, typename Value>
class Cache;
// Outputs the key/value pairs from least to most-recently used.
template <typename Key, typename Value>
std::ostream& operator << (
std::ostream& stream,
const Cache<Key, Value>& c);
// Provides a least-recently used (LRU) cache of some predefined
// capacity. A "write" and a "read" both count as uses.
template <typename Key, typename Value>
class Cache
{
public:
typedef std::list<Key> list;
typedef boost::unordered_map<
Key, std::pair<Value, typename list::iterator> > map;
explicit Cache(int _capacity) : capacity(_capacity) {}
void put(const Key& key, const Value& value)
{
typename map::iterator i = values.find(key);
if (i == values.end()) {
insert(key, value);
} else {
(*i).second.first = value;
use(i);
}
}
Option<Value> get(const Key& key)
{
typename map::iterator i = values.find(key);
if (i != values.end()) {
use(i);
return (*i).second.first;
}
return None();
}
private:
// Not copyable, not assignable.
Cache(const Cache&);
Cache& operator = (const Cache&);
// Give the operator access to our internals.
friend std::ostream& operator << <>(
std::ostream& stream,
const Cache<Key, Value>& c);
// Insert key/value into the cache.
void insert(const Key& key, const Value& value)
{
if (keys.size() == capacity) {
evict();
}
// Get a "pointer" into the lru list for efficient update.
typename list::iterator i = keys.insert(keys.end(), key);
// Save key/value and "pointer" into lru list.
values.insert(std::make_pair(key, std::make_pair(value, i)));
}
// Updates the LRU ordering in the cache for the given iterator.
void use(const typename map::iterator& i)
{
// Move the "pointer" to the end of the lru list.
keys.splice(keys.end(), keys, (*i).second.second);
// Now update the "pointer" so we can do this again.
(*i).second.second = --keys.end();
}
// Evict the least-recently used element from the cache.
void evict()
{
const typename map::iterator& i = values.find(keys.front());
CHECK(i != values.end());
values.erase(i);
keys.pop_front();
}
// Size of the cache.
int capacity;
// Cache of values and "pointers" into the least-recently used list.
map values;
// Keys ordered by least-recently used.
list keys;
};
template <typename Key, typename Value>
std::ostream& operator << (
std::ostream& stream,
const Cache<Key, Value>& c)
{
typename Cache<Key, Value>::list::const_iterator i1;
for (i1 = c.keys.begin(); i1 != c.keys.end(); i1++) {
stream << *i1 << ": ";
typename Cache<Key, Value>::map::const_iterator i2;
i2 = c.values.find(*i1);
CHECK(i2 != c.values.end());
stream << *i2 << std::endl;
}
return stream;
}
#endif // __STOUT_CACHE_HPP__
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChangeRequestQueueProcessor.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-04-03 15:44:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef SD_FRAMEWORK_CHANGE_REQUEST_QUEUE_PROCESSOR_HXX
#define SD_FRAMEWORK_CHANGE_REQUEST_QUEUE_PROCESSOR_HXX
#include "ChangeRequestQueue.hxx"
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include <rtl/ref.hxx>
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCHANGEREQUEST_HPP_
#include <com/sun/star/drawing/framework/XConfigurationChangeRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_CONFIGURATIONCHANGEEVENT_HPP_
#include <com/sun/star/drawing/framework/ConfigurationChangeEvent.hpp>
#endif
#include <cppuhelper/interfacecontainer.hxx>
#include <tools/link.hxx>
#include <boost/shared_ptr.hpp>
namespace sd { namespace framework {
class ConfigurationController;
class ConfigurationUpdater;
/** The ChangeRequestQueueProcessor ownes the ChangeRequestQueue and
processes the configuration change requests.
When after processing one entry the queue is empty then the
XConfigurationController::update() method is called so that the changes
made to the local XConfiguration reference are reflected by the UI.
Queue entries are processed asynchronously by calling PostUserEvent().
*/
class ChangeRequestQueueProcessor
{
public:
/** The queue processor is created with a reference to an
ConfigurationController so that its UpdateConfiguration() method can
be called when the queue becomes empty.
*/
ChangeRequestQueueProcessor (
const ::rtl::Reference<ConfigurationController>& rxController,
const ::boost::shared_ptr<ConfigurationUpdater>& rpUpdater);
~ChangeRequestQueueProcessor (void);
/** Sets the configuration who will be changed by subsequent change
requests. This method should be called only by the configuration
controller who owns the configuration.
*/
void SetConfiguration (
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfiguration>& rxConfiguration);
/** The given request is appended to the end of the queue and will
eventually be processed when all other entries in front of it have
been processed.
*/
void AddRequest (const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfigurationChangeRequest>& rxRequest);
/** Returns </TRUE> when the queue is empty.
*/
bool IsEmpty (void) const;
private:
mutable ::osl::Mutex maMutex;
ChangeRequestQueue maQueue;
/** The id returned by the last PostUserEvent() call. This id is stored
so that a pending user event can be removed whent he queue processor
is destroyed.
*/
sal_uInt32 mnUserEventId;
::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfiguration> mxConfiguration;
::rtl::Reference<ConfigurationController> mpConfigurationController;
::boost::shared_ptr<ConfigurationUpdater> mpConfigurationUpdater;
/** Initiate the processing of the entries in the queue. The actual
processing starts asynchronously.
*/
void StartProcessing (void);
/** Callback function for the PostUserEvent() call.
*/
DECL_LINK(ProcessOneEvent,void*);
};
} } // end of namespace sd::framework
#endif
<commit_msg>INTEGRATION: CWS hr45_SRC680 (1.2.114); FILE MERGED 2007/08/22 14:09:59 hr 1.2.114.1: #i80944#: ChangeRequestQueueProcessor: member mnUserEventId is a pointer in camouflage, change from type sal_uInt32 to sal_uIntPtr for the benefit of LP64 platforms<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChangeRequestQueueProcessor.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-08-28 11:15:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef SD_FRAMEWORK_CHANGE_REQUEST_QUEUE_PROCESSOR_HXX
#define SD_FRAMEWORK_CHANGE_REQUEST_QUEUE_PROCESSOR_HXX
#include "ChangeRequestQueue.hxx"
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include <rtl/ref.hxx>
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCHANGEREQUEST_HPP_
#include <com/sun/star/drawing/framework/XConfigurationChangeRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_CONFIGURATIONCHANGEEVENT_HPP_
#include <com/sun/star/drawing/framework/ConfigurationChangeEvent.hpp>
#endif
#include <cppuhelper/interfacecontainer.hxx>
#include <tools/link.hxx>
#include <boost/shared_ptr.hpp>
namespace sd { namespace framework {
class ConfigurationController;
class ConfigurationUpdater;
/** The ChangeRequestQueueProcessor ownes the ChangeRequestQueue and
processes the configuration change requests.
When after processing one entry the queue is empty then the
XConfigurationController::update() method is called so that the changes
made to the local XConfiguration reference are reflected by the UI.
Queue entries are processed asynchronously by calling PostUserEvent().
*/
class ChangeRequestQueueProcessor
{
public:
/** The queue processor is created with a reference to an
ConfigurationController so that its UpdateConfiguration() method can
be called when the queue becomes empty.
*/
ChangeRequestQueueProcessor (
const ::rtl::Reference<ConfigurationController>& rxController,
const ::boost::shared_ptr<ConfigurationUpdater>& rpUpdater);
~ChangeRequestQueueProcessor (void);
/** Sets the configuration who will be changed by subsequent change
requests. This method should be called only by the configuration
controller who owns the configuration.
*/
void SetConfiguration (
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfiguration>& rxConfiguration);
/** The given request is appended to the end of the queue and will
eventually be processed when all other entries in front of it have
been processed.
*/
void AddRequest (const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfigurationChangeRequest>& rxRequest);
/** Returns </TRUE> when the queue is empty.
*/
bool IsEmpty (void) const;
private:
mutable ::osl::Mutex maMutex;
ChangeRequestQueue maQueue;
/** The id returned by the last PostUserEvent() call. This id is stored
so that a pending user event can be removed whent he queue processor
is destroyed.
*/
sal_uIntPtr mnUserEventId;
::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XConfiguration> mxConfiguration;
::rtl::Reference<ConfigurationController> mpConfigurationController;
::boost::shared_ptr<ConfigurationUpdater> mpConfigurationUpdater;
/** Initiate the processing of the entries in the queue. The actual
processing starts asynchronously.
*/
void StartProcessing (void);
/** Callback function for the PostUserEvent() call.
*/
DECL_LINK(ProcessOneEvent,void*);
};
} } // end of namespace sd::framework
#endif
<|endoftext|>
|
<commit_before>// @(#)root/gpad:$Id$
// Author: Rene Brun 01/07/96
/*************************************************************************
* 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. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TButton.h"
#include "TCanvas.h"
#include "TLatex.h"
#include <string.h>
ClassImp(TButton)
/** \class TButton
\ingroup gpad
A TButton object is a user interface object.
A TButton has a name and an associated action.
When the button is clicked with the left mouse button, the corresponding
action is executed.
A TButton can be created by direct invocation of the constructors
or via the graphics editor.
The action can be set via TButton::SetMethod.
The action can be any command. Examples of actions:
- "34+78" When the button is clicked, the result of addition is printed.
- ".x macro.C" . Clicking the button executes the macro macro.C
The action can be modified at any time via TButton::SetMethod.
To modify the layout/size/contents of one or several buttons
in a canvas, you must set the canvas editable via TCanvas::SetEditable.
By default a TCanvas is editable.
By default a TDialogCanvas is not editable.
TButtons are in general placed in a TDialogCanvas.
A TButton being a TPad, one can draw graphics primitives in it
when the TCanvas/TDialogCanvas is editable.
Example of a macro creating a dialog canvas with buttons:
~~~ {.cpp}
void but() {
// example of a dialog canvas with a few buttons
TDialogCanvas *dialog = new TDialogCanvas("dialog","",200,300);
// Create first button. Clicking on this button will execute 34+56
TButton *but1 = new TButton("button1","34+56",.05,.8,.45,.88);
but1->Draw();
// Create second button. Clicking on this button will create a new canvas
TButton *but2 = new TButton("canvas","c2 = new TCanvas(\"c2\")",.55,.8,.95,.88);
but2->Draw();
// Create third button. Clicking on this button will invoke the browser
but3 = new TButton("Browser","br = new TBrowser(\"br\")",0.25,0.54,0.75,0.64);
but3->SetFillColor(42);
but3->Draw();
// Create last button with no name. Instead a graph is draw inside the button
// Clicking on this button will invoke the macro $ROOTSYS/tutorials/graphs/graph.C
button = new TButton("",".x tutorials/graphs/graph.C",0.15,0.15,0.85,0.38);
button->SetFillColor(42);
button->Draw();
button->SetEditable(kTRUE);
button->cd();
Double_t x[8] = {0.08,0.21,0.34,0.48,0.61,0.7,0.81,0.92};
Double_t y[8] = {0.2,0.65,0.4,0.34,0.24,0.43,0.75,0.52};
TGraph *graph = new TGraph(8,x,y);
graph->SetMarkerColor(4);
graph->SetMarkerStyle(21);
graph->Draw("lp");
dialog->cd();
}
~~~
Executing the macro above produces the following dialog canvas:
\image html gpad_dialogbuttons.png
*/
////////////////////////////////////////////////////////////////////////////////
/// Button default constructor.
TButton::TButton(): TPad()
{
fFraming = 0;
fMethod = "";
fLogx = kFALSE;
fLogy = kFALSE;
SetEditable(kFALSE);
fFocused = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Button normal constructor.
///
/// Note that the button coordinates x1,y1,x2,y2 are always in the range [0,1]
TButton::TButton(const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t y2)
:TPad("button",title,x1,y1,x2,y2,18,2,1), TAttText(22,0,1,61,0.65)
{
fFraming=0;
SetBit(kCanDelete);
fModified = kTRUE;
fMethod = method;
if (strlen(title)) {
TLatex *text = new TLatex(0.5*(fX1+fX2),0.5*(fY1+fY2),title);
fPrimitives->Add(text);
}
fLogx = kFALSE;
fLogy = kFALSE;
SetEditable(kFALSE);
fFocused = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Button default destructor.
TButton::~TButton()
{
if (fPrimitives) fPrimitives->Delete();
}
////////////////////////////////////////////////////////////////////////////////
/// Draw this button with its current attributes.
void TButton::Draw(Option_t *option)
{
if (fCanvas) AppendPad(option);
}
////////////////////////////////////////////////////////////////////////////////
/// Execute action corresponding to one event.
///
/// This member function is called when a Button object is clicked.
void TButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
//check case where pressing a button deletes itself
if (!TestBit(kNotDeleted)) return;
if (IsEditable()) {
TPad::ExecuteEvent(event,px,py);
return;
}
TPad *cdpad = (TPad*)gROOT->GetSelectedPad();
HideToolTip(event);
switch (event) {
case kMouseEnter:
TPad::ExecuteEvent(event,px,py);
break;
case kButton1Down:
SetBorderMode(-1);
fFocused=1;
Modified();
Update();
break;
case kMouseMotion:
break;
case kButton1Motion:
if (px<XtoAbsPixel(1) && px>XtoAbsPixel(0) &&
py<YtoAbsPixel(0) && py>YtoAbsPixel(1)) {
if (!fFocused) {
SetBorderMode(-1);
fFocused=1;
Modified();
GetCanvas()->Modified();
Update();
}
} else if (fFocused) {
SetBorderMode(1);
fFocused=0;
Modified();
GetCanvas()->Modified();
Update();
}
break;
case kButton1Up:
SetCursor(kWatch);
if (fFocused) {
if (cdpad) cdpad->cd();
gROOT->ProcessLine(GetMethod());
}
//check case where pressing a button deletes itself
if (!TestBit(kNotDeleted)) return;
SetBorderMode(1);
Modified();
Update();
SetCursor(kCross);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Paint this button with its current attributes.
void TButton::Paint(Option_t *option)
{
TPad::Paint(option); //only called for Postscript print
}
////////////////////////////////////////////////////////////////////////////////
/// Paint is modified.
void TButton::PaintModified()
{
if (!fCanvas) return;
if (!fPrimitives) fPrimitives = new TList();
TObject *obj = GetListOfPrimitives()->First();
if (obj && obj->InheritsFrom(TText::Class())) {
TLatex *text = (TLatex*)obj;
text->SetTitle(GetTitle());
text->SetTextSize(GetTextSize());
text->SetTextFont(GetTextFont());
text->SetTextAlign(GetTextAlign());
text->SetTextColor(GetTextColor());
text->SetTextAngle(GetTextAngle());
}
SetLogx(0);
SetLogy(0);
TPad::PaintModified();
}
////////////////////////////////////////////////////////////////////////////////
/// Set world coordinate system for the pad.
void TButton::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
TPad::Range(x1,y1,x2,y2);
}
////////////////////////////////////////////////////////////////////////////////
/// Save primitive as a C++ statement(s) on output stream out
void TButton::SavePrimitive(std::ostream &out, Option_t * /*= ""*/)
{
TPad *padsav = (TPad*)gPad;
char quote = '"';
if (gROOT->ClassSaved(TButton::Class())) {
out<<" ";
} else {
out<<" TButton *";
}
char *cm = (char*)GetMethod();
Int_t nch = strlen(cm);
char *cmethod = new char[nch+10];
Int_t i = 0;
while(*cm) {
if (*cm == '"') {
cmethod[i] = '\\';
i++;
}
cmethod[i] = *cm;
i++;
cm++;
}
cmethod[i] = 0;
out<<"button = new TButton("<<quote<<GetTitle()
<<quote<<","<<quote<<cmethod<<quote
<<","<<fXlowNDC
<<","<<fYlowNDC
<<","<<fXlowNDC+fWNDC
<<","<<fYlowNDC+fHNDC
<<");"<<std::endl;
delete [] cmethod;
SaveFillAttributes(out,"button",0,1001);
SaveLineAttributes(out,"button",1,1,1);
SaveTextAttributes(out,"button",22,0,1,61,.65);
if (GetBorderSize() != 2) {
out<<" button->SetBorderSize("<<GetBorderSize()<<");"<<std::endl;
}
if (GetBorderMode() != 1) {
out<<" button->SetBorderMode("<<GetBorderMode()<<");"<<std::endl;
}
if (GetFraming()) out<<"button->SetFraming();"<<std::endl;
if (IsEditable()) out<<"button->SetEditable(kTRUE);"<<std::endl;
out<<" button->Draw();"<<std::endl;
TIter next(GetListOfPrimitives());
TObject *obj = next(); //do not save first primitive
Int_t nprim = 0;
while ((obj = next())) {
if (!nprim) out<<" button->cd();"<<std::endl;
nprim++;
obj->SavePrimitive(out, (Option_t *)next.GetOption());
}
if (nprim) out<<" "<<padsav->GetName()<<"->cd();"<<std::endl;
padsav->cd();
}
////////////////////////////////////////////////////////////////////////////////
/// if framing is set, button will be highlighted
void TButton::SetFraming(Bool_t f)
{
fFraming=f;
if (f) SetBit(kFraming);
else ResetBit(kFraming);
}
<commit_msg>Set the Text attributes in Paint like in PaintModified. This fix the issue mentioned here: https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=21435&p=93481&sid=cfe798cdb4bfc583e082f980033d913a#p93481<commit_after>// @(#)root/gpad:$Id$
// Author: Rene Brun 01/07/96
/*************************************************************************
* 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. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TButton.h"
#include "TCanvas.h"
#include "TLatex.h"
#include <string.h>
ClassImp(TButton)
/** \class TButton
\ingroup gpad
A TButton object is a user interface object.
A TButton has a name and an associated action.
When the button is clicked with the left mouse button, the corresponding
action is executed.
A TButton can be created by direct invocation of the constructors
or via the graphics editor.
The action can be set via TButton::SetMethod.
The action can be any command. Examples of actions:
- "34+78" When the button is clicked, the result of addition is printed.
- ".x macro.C" . Clicking the button executes the macro macro.C
The action can be modified at any time via TButton::SetMethod.
To modify the layout/size/contents of one or several buttons
in a canvas, you must set the canvas editable via TCanvas::SetEditable.
By default a TCanvas is editable.
By default a TDialogCanvas is not editable.
TButtons are in general placed in a TDialogCanvas.
A TButton being a TPad, one can draw graphics primitives in it
when the TCanvas/TDialogCanvas is editable.
Example of a macro creating a dialog canvas with buttons:
~~~ {.cpp}
void but() {
// example of a dialog canvas with a few buttons
TDialogCanvas *dialog = new TDialogCanvas("dialog","",200,300);
// Create first button. Clicking on this button will execute 34+56
TButton *but1 = new TButton("button1","34+56",.05,.8,.45,.88);
but1->Draw();
// Create second button. Clicking on this button will create a new canvas
TButton *but2 = new TButton("canvas","c2 = new TCanvas(\"c2\")",.55,.8,.95,.88);
but2->Draw();
// Create third button. Clicking on this button will invoke the browser
but3 = new TButton("Browser","br = new TBrowser(\"br\")",0.25,0.54,0.75,0.64);
but3->SetFillColor(42);
but3->Draw();
// Create last button with no name. Instead a graph is draw inside the button
// Clicking on this button will invoke the macro $ROOTSYS/tutorials/graphs/graph.C
button = new TButton("",".x tutorials/graphs/graph.C",0.15,0.15,0.85,0.38);
button->SetFillColor(42);
button->Draw();
button->SetEditable(kTRUE);
button->cd();
Double_t x[8] = {0.08,0.21,0.34,0.48,0.61,0.7,0.81,0.92};
Double_t y[8] = {0.2,0.65,0.4,0.34,0.24,0.43,0.75,0.52};
TGraph *graph = new TGraph(8,x,y);
graph->SetMarkerColor(4);
graph->SetMarkerStyle(21);
graph->Draw("lp");
dialog->cd();
}
~~~
Executing the macro above produces the following dialog canvas:
\image html gpad_dialogbuttons.png
*/
////////////////////////////////////////////////////////////////////////////////
/// Button default constructor.
TButton::TButton(): TPad()
{
fFraming = 0;
fMethod = "";
fLogx = kFALSE;
fLogy = kFALSE;
SetEditable(kFALSE);
fFocused = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Button normal constructor.
///
/// Note that the button coordinates x1,y1,x2,y2 are always in the range [0,1]
TButton::TButton(const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t y2)
:TPad("button",title,x1,y1,x2,y2,18,2,1), TAttText(22,0,1,61,0.65)
{
fFraming=0;
SetBit(kCanDelete);
fModified = kTRUE;
fMethod = method;
if (strlen(title)) {
TLatex *text = new TLatex(0.5*(fX1+fX2),0.5*(fY1+fY2),title);
fPrimitives->Add(text);
}
fLogx = kFALSE;
fLogy = kFALSE;
SetEditable(kFALSE);
fFocused = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Button default destructor.
TButton::~TButton()
{
if (fPrimitives) fPrimitives->Delete();
}
////////////////////////////////////////////////////////////////////////////////
/// Draw this button with its current attributes.
void TButton::Draw(Option_t *option)
{
if (fCanvas) AppendPad(option);
}
////////////////////////////////////////////////////////////////////////////////
/// Execute action corresponding to one event.
///
/// This member function is called when a Button object is clicked.
void TButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
//check case where pressing a button deletes itself
if (!TestBit(kNotDeleted)) return;
if (IsEditable()) {
TPad::ExecuteEvent(event,px,py);
return;
}
TPad *cdpad = (TPad*)gROOT->GetSelectedPad();
HideToolTip(event);
switch (event) {
case kMouseEnter:
TPad::ExecuteEvent(event,px,py);
break;
case kButton1Down:
SetBorderMode(-1);
fFocused=1;
Modified();
Update();
break;
case kMouseMotion:
break;
case kButton1Motion:
if (px<XtoAbsPixel(1) && px>XtoAbsPixel(0) &&
py<YtoAbsPixel(0) && py>YtoAbsPixel(1)) {
if (!fFocused) {
SetBorderMode(-1);
fFocused=1;
Modified();
GetCanvas()->Modified();
Update();
}
} else if (fFocused) {
SetBorderMode(1);
fFocused=0;
Modified();
GetCanvas()->Modified();
Update();
}
break;
case kButton1Up:
SetCursor(kWatch);
if (fFocused) {
if (cdpad) cdpad->cd();
gROOT->ProcessLine(GetMethod());
}
//check case where pressing a button deletes itself
if (!TestBit(kNotDeleted)) return;
SetBorderMode(1);
Modified();
Update();
SetCursor(kCross);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Paint this button with its current attributes.
void TButton::Paint(Option_t *option)
{
if (!fCanvas) return;
if (!fPrimitives) fPrimitives = new TList();
TObject *obj = GetListOfPrimitives()->First();
if (obj && obj->InheritsFrom(TText::Class())) {
TLatex *text = (TLatex*)obj;
text->SetTitle(GetTitle());
text->SetTextSize(GetTextSize());
text->SetTextFont(GetTextFont());
text->SetTextAlign(GetTextAlign());
text->SetTextColor(GetTextColor());
text->SetTextAngle(GetTextAngle());
}
SetLogx(0);
SetLogy(0);
TPad::Paint(option); //only called for Postscript print
}
////////////////////////////////////////////////////////////////////////////////
/// Paint is modified.
void TButton::PaintModified()
{
if (!fCanvas) return;
if (!fPrimitives) fPrimitives = new TList();
TObject *obj = GetListOfPrimitives()->First();
if (obj && obj->InheritsFrom(TText::Class())) {
TLatex *text = (TLatex*)obj;
text->SetTitle(GetTitle());
text->SetTextSize(GetTextSize());
text->SetTextFont(GetTextFont());
text->SetTextAlign(GetTextAlign());
text->SetTextColor(GetTextColor());
text->SetTextAngle(GetTextAngle());
}
SetLogx(0);
SetLogy(0);
TPad::PaintModified();
}
////////////////////////////////////////////////////////////////////////////////
/// Set world coordinate system for the pad.
void TButton::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
TPad::Range(x1,y1,x2,y2);
}
////////////////////////////////////////////////////////////////////////////////
/// Save primitive as a C++ statement(s) on output stream out
void TButton::SavePrimitive(std::ostream &out, Option_t * /*= ""*/)
{
TPad *padsav = (TPad*)gPad;
char quote = '"';
if (gROOT->ClassSaved(TButton::Class())) {
out<<" ";
} else {
out<<" TButton *";
}
char *cm = (char*)GetMethod();
Int_t nch = strlen(cm);
char *cmethod = new char[nch+10];
Int_t i = 0;
while(*cm) {
if (*cm == '"') {
cmethod[i] = '\\';
i++;
}
cmethod[i] = *cm;
i++;
cm++;
}
cmethod[i] = 0;
out<<"button = new TButton("<<quote<<GetTitle()
<<quote<<","<<quote<<cmethod<<quote
<<","<<fXlowNDC
<<","<<fYlowNDC
<<","<<fXlowNDC+fWNDC
<<","<<fYlowNDC+fHNDC
<<");"<<std::endl;
delete [] cmethod;
SaveFillAttributes(out,"button",0,1001);
SaveLineAttributes(out,"button",1,1,1);
SaveTextAttributes(out,"button",22,0,1,61,.65);
if (GetBorderSize() != 2) {
out<<" button->SetBorderSize("<<GetBorderSize()<<");"<<std::endl;
}
if (GetBorderMode() != 1) {
out<<" button->SetBorderMode("<<GetBorderMode()<<");"<<std::endl;
}
if (GetFraming()) out<<"button->SetFraming();"<<std::endl;
if (IsEditable()) out<<"button->SetEditable(kTRUE);"<<std::endl;
out<<" button->Draw();"<<std::endl;
TIter next(GetListOfPrimitives());
TObject *obj = next(); //do not save first primitive
Int_t nprim = 0;
while ((obj = next())) {
if (!nprim) out<<" button->cd();"<<std::endl;
nprim++;
obj->SavePrimitive(out, (Option_t *)next.GetOption());
}
if (nprim) out<<" "<<padsav->GetName()<<"->cd();"<<std::endl;
padsav->cd();
}
////////////////////////////////////////////////////////////////////////////////
/// if framing is set, button will be highlighted
void TButton::SetFraming(Bool_t f)
{
fFraming=f;
if (f) SetBit(kFraming);
else ResetBit(kFraming);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* 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
*/
#include "gameitemsmodel.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <QtCore/QHash>
#include <QtCore/QByteArray>
using namespace GluonPlayer;
GameViewItem::GameViewItem(const QString &gameName, const QString &gameDescription,
const QString &projectFileName, const QString &id)
: m_gameName(gameName)
, m_gameDescription(gameDescription)
, m_projectFileName(projectFileName)
, m_id(id)
{
}
QString GameViewItem::gameName() const
{
return m_gameName;
}
QString GameViewItem::gameDescription() const
{
return m_gameDescription;
}
QString GameViewItem::projectFileName() const
{
return m_projectFileName;
}
QString GameViewItem::id() const
{
return m_id;
}
GameItemsModel::GameItemsModel( QObject* parent )
: QAbstractListModel( parent )
{
QDir m_dir;
m_dir.cd( GluonCore::Global::dataDirectory() + "/gluon/games" );
QStringList gameDirNameList;
gameDirNameList = m_dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot );
foreach( const QString& gameDirName, gameDirNameList)
{
QDir gameDir = m_dir;
gameDir.cd( gameDirName );
QStringList gluonProjectFiles = gameDir.entryList( QStringList( GluonEngine::projectFilename ) );
if( !gluonProjectFiles.isEmpty() )
{
QString projectFileName = gameDir.absoluteFilePath( gluonProjectFiles.at( 0 ) );
GluonEngine::GameProject project;
project.loadFromFile( projectFileName );
GameViewItem gameViewItem(project.name(), project.description(),
projectFileName, project.property("id").toString());
m_gameViewItems.append(gameViewItem);
}
}
QHash<int, QByteArray> roles;
roles[GameNameRole] = "gameName";
roles[GameDescriptionRole] = "gameDescription";
roles[ProjectFileNameRole] = "projectFileName";
roles[IDRole] = "id";
setRoleNames(roles);
}
QVariant GameItemsModel::data( const QModelIndex& index, int role ) const
{
if (index.row() < 0 || index.row() > m_gameViewItems.count())
return QVariant();
switch (role) {
case Qt::UserRole:
break;
case GameNameRole:
return m_gameViewItems.at( index.row() ).gameName();
case GameDescriptionRole:
return m_gameViewItems.at( index.row() ).gameDescription();
case Qt::DisplayRole:
case ProjectFileNameRole:
return m_gameViewItems.at( index.row() ).projectFileName();
case IDRole:
return m_gameViewItems.at( index.row() ).id();
default:
break;
}
return QVariant();
}
int GameItemsModel::rowCount( const QModelIndex& /* parent */ ) const
{
return m_gameViewItems.count();
}
int GameItemsModel::columnCount( const QModelIndex& /* parent */ ) const
{
return 1;
}
QVariant GameItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( section == 0 )
{
return QString( "Game" );
}
return QAbstractItemModel::headerData( section, orientation, role );
}
#include "gameitemsmodel.moc"
<commit_msg>Fix the game dir management after the gamebinding change.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* 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
*/
#include "gameitemsmodel.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <QtCore/QHash>
#include <QtCore/QByteArray>
using namespace GluonPlayer;
GameViewItem::GameViewItem(const QString &gameName, const QString &gameDescription,
const QString &projectFileName, const QString &id)
: m_gameName(gameName)
, m_gameDescription(gameDescription)
, m_projectFileName(projectFileName)
, m_id(id)
{
}
QString GameViewItem::gameName() const
{
return m_gameName;
}
QString GameViewItem::gameDescription() const
{
return m_gameDescription;
}
QString GameViewItem::projectFileName() const
{
return m_projectFileName;
}
QString GameViewItem::id() const
{
return m_id;
}
GameItemsModel::GameItemsModel( QObject* parent )
: QAbstractListModel( parent )
{
QDir m_dir;
m_dir.cd( GluonCore::Global::dataDirectory() + "/gluon/games" );
QStringList gameDirNameList = m_dir.entryList( QStringList() << QString("*" + GluonEngine::projectSuffix), QDir::Dirs | QDir::NoDotAndDotDot );
foreach( const QString& gameDirName, gameDirNameList)
{
QDir gameDir = m_dir;
gameDir.cd( gameDirName );
QStringList gluonProjectFiles = gameDir.entryList( QStringList( GluonEngine::projectFilename ) );
if( !gluonProjectFiles.isEmpty() )
{
QString projectFileName = gameDir.absoluteFilePath( gluonProjectFiles.at( 0 ) );
GluonEngine::GameProject project;
project.loadFromFile( projectFileName );
GameViewItem gameViewItem(project.name(), project.description(),
projectFileName, project.property("id").toString());
m_gameViewItems.append(gameViewItem);
}
}
QHash<int, QByteArray> roles;
roles[GameNameRole] = "gameName";
roles[GameDescriptionRole] = "gameDescription";
roles[ProjectFileNameRole] = "projectFileName";
roles[IDRole] = "id";
setRoleNames(roles);
}
QVariant GameItemsModel::data( const QModelIndex& index, int role ) const
{
if (index.row() < 0 || index.row() > m_gameViewItems.count())
return QVariant();
switch (role) {
case Qt::UserRole:
break;
case GameNameRole:
return m_gameViewItems.at( index.row() ).gameName();
case GameDescriptionRole:
return m_gameViewItems.at( index.row() ).gameDescription();
case Qt::DisplayRole:
case ProjectFileNameRole:
return m_gameViewItems.at( index.row() ).projectFileName();
case IDRole:
return m_gameViewItems.at( index.row() ).id();
default:
break;
}
return QVariant();
}
int GameItemsModel::rowCount( const QModelIndex& /* parent */ ) const
{
return m_gameViewItems.count();
}
int GameItemsModel::columnCount( const QModelIndex& /* parent */ ) const
{
return 1;
}
QVariant GameItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( section == 0 )
{
return QString( "Game" );
}
return QAbstractItemModel::headerData( section, orientation, role );
}
#include "gameitemsmodel.moc"
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* 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 "test/core/util/test_config.h"
#include <grpc/impl/codegen/gpr_types.h>
#include <inttypes.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/examine_stack.h"
#include "src/core/lib/surface/init.h"
#include "test/core/util/stack_tracer.h"
#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
int64_t g_fixture_slowdown_factor = 1;
int64_t g_poller_slowdown_factor = 1;
#if GPR_GETPID_IN_UNISTD_H
#include <unistd.h>
static unsigned seed(void) { return static_cast<unsigned>(getpid()); }
#endif
#if GPR_GETPID_IN_PROCESS_H
#include <process.h>
static unsigned seed(void) { return (unsigned)_getpid(); }
#endif
#if GPR_WINDOWS_CRASH_HANDLER
#include <windows.h>
#include <tchar.h>
// disable warning 4091 - dbghelp.h is broken for msvc2015
#pragma warning(disable : 4091)
#define DBGHELP_TRANSLATE_TCHAR
#include <dbghelp.h>
#ifdef _MSC_VER
#pragma comment(lib, "dbghelp.lib")
#endif
static void print_stack_from_context(HANDLE thread, CONTEXT c) {
STACKFRAME s; // in/out stackframe
memset(&s, 0, sizeof(s));
DWORD imageType;
#ifdef _M_IX86
// normally, call ImageNtHeader() and use machine info from PE header
imageType = IMAGE_FILE_MACHINE_I386;
s.AddrPC.Offset = c.Eip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Ebp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Esp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
imageType = IMAGE_FILE_MACHINE_AMD64;
s.AddrPC.Offset = c.Rip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Rbp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Rsp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_IA64
imageType = IMAGE_FILE_MACHINE_IA64;
s.AddrPC.Offset = c.StIIP;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.IntSp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrBStore.Offset = c.RsBSP;
s.AddrBStore.Mode = AddrModeFlat;
s.AddrStack.Offset = c.IntSp;
s.AddrStack.Mode = AddrModeFlat;
#else
#error "Platform not supported!"
#endif
HANDLE process = GetCurrentProcess();
SYMBOL_INFOW* symbol =
(SYMBOL_INFOW*)calloc(sizeof(SYMBOL_INFOW) + 256 * sizeof(wchar_t), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFOW);
const unsigned short MAX_CALLERS_SHOWN =
8192; // avoid flooding the stderr if stacktrace is way too long
for (int frame = 0; frame < MAX_CALLERS_SHOWN &&
StackWalk(imageType, process, thread, &s, &c, 0,
SymFunctionTableAccess, SymGetModuleBase, 0);
frame++) {
PWSTR symbol_name = L"<<no symbol>>";
DWORD64 symbol_address = 0;
if (SymFromAddrW(process, (DWORD64)(s.AddrPC.Offset), 0, symbol)) {
symbol_name = symbol->Name;
symbol_address = (DWORD64)symbol->Address;
}
PWSTR file_name = L"<<no line info>>";
int line_number = 0;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD displacement = 0;
if (SymGetLineFromAddrW64(process, (DWORD64)(s.AddrPC.Offset),
&displacement, &line)) {
file_name = line.FileName;
line_number = (int)line.LineNumber;
}
fwprintf(stderr, L"*** %d: %016I64X %ls - %016I64X (%ls:%d)\n", frame,
(DWORD64)(s.AddrPC.Offset), symbol_name, symbol_address, file_name,
line_number);
fflush(stderr);
}
free(symbol);
}
static void print_current_stack() {
CONTEXT context;
RtlCaptureContext(&context);
print_stack_from_context(GetCurrentThread(), context);
}
static LONG crash_handler(struct _EXCEPTION_POINTERS* ex_info) {
fprintf(stderr, "Exception handler called, dumping information\n");
bool try_to_print_stack = true;
PEXCEPTION_RECORD exrec = ex_info->ExceptionRecord;
while (exrec) {
DWORD code = exrec->ExceptionCode;
DWORD flgs = exrec->ExceptionFlags;
PVOID addr = exrec->ExceptionAddress;
if (code == EXCEPTION_STACK_OVERFLOW) try_to_print_stack = false;
fprintf(stderr, "code: %x - flags: %d - address: %p\n", code, flgs, addr);
exrec = exrec->ExceptionRecord;
}
if (try_to_print_stack) {
print_stack_from_context(GetCurrentThread(), *ex_info->ContextRecord);
}
if (IsDebuggerPresent()) {
__debugbreak();
} else {
_exit(1);
}
return EXCEPTION_EXECUTE_HANDLER;
}
static void abort_handler(int sig) {
fprintf(stderr, "Abort handler called.\n");
print_current_stack();
if (IsDebuggerPresent()) {
__debugbreak();
} else {
_exit(1);
}
}
static void install_crash_handler() {
if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
fprintf(stderr, "SymInitialize failed: %d\n", GetLastError());
}
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)crash_handler);
_set_abort_behavior(0, _WRITE_ABORT_MSG);
_set_abort_behavior(0, _CALL_REPORTFAULT);
signal(SIGABRT, abort_handler);
}
#elif GPR_POSIX_CRASH_HANDLER
#include <errno.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#define SIGNAL_NAMES_LENGTH 32
static const char* const signal_names[] = {
nullptr, "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
"SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV",
"SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD",
"SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG",
"SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO",
"SIGPWR", "SIGSYS"};
static char g_alt_stack[GPR_MAX(MINSIGSTKSZ, 65536)];
#define MAX_FRAMES 32
/* signal safe output */
static void output_string(const char* string) {
size_t len = strlen(string);
ssize_t r;
do {
r = write(STDERR_FILENO, string, len);
} while (r == -1 && errno == EINTR);
}
static void output_num(long num) {
char buf[GPR_LTOA_MIN_BUFSIZE];
gpr_ltoa(num, buf);
output_string(buf);
}
static void crash_handler(int signum, siginfo_t* /*info*/, void* /*data*/) {
void* addrlist[MAX_FRAMES + 1];
int addrlen;
output_string("\n\n\n*******************************\nCaught signal ");
if (signum > 0 && signum < SIGNAL_NAMES_LENGTH) {
output_string(signal_names[signum]);
} else {
output_num(signum);
}
output_string("\n");
addrlen = backtrace(addrlist, GPR_ARRAY_SIZE(addrlist));
if (addrlen == 0) {
output_string(" no backtrace\n");
} else {
backtrace_symbols_fd(addrlist, addrlen, STDERR_FILENO);
}
/* try to get a core dump for SIGTERM */
if (signum == SIGTERM) signum = SIGQUIT;
raise(signum);
}
static void install_crash_handler() {
stack_t ss;
struct sigaction sa;
memset(&ss, 0, sizeof(ss));
memset(&sa, 0, sizeof(sa));
ss.ss_size = sizeof(g_alt_stack);
ss.ss_sp = g_alt_stack;
GPR_ASSERT(sigaltstack(&ss, nullptr) == 0);
sa.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_RESETHAND);
sa.sa_sigaction = crash_handler;
GPR_ASSERT(sigaction(SIGILL, &sa, nullptr) == 0);
GPR_ASSERT(sigaction(SIGABRT, &sa, nullptr) == 0);
GPR_ASSERT(sigaction(SIGBUS, &sa, nullptr) == 0);
GPR_ASSERT(sigaction(SIGSEGV, &sa, nullptr) == 0);
GPR_ASSERT(sigaction(SIGTERM, &sa, nullptr) == 0);
GPR_ASSERT(sigaction(SIGQUIT, &sa, nullptr) == 0);
}
#else
static void install_crash_handler() {}
#endif
bool BuiltUnderValgrind() {
#ifdef RUNNING_ON_VALGRIND
return true;
#else
return false;
#endif
}
bool BuiltUnderTsan() {
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef THREAD_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderAsan() {
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef ADDRESS_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderMsan() {
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef MEMORY_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderUbsan() {
#ifdef GRPC_UBSAN
return true;
#else
return false;
#endif
}
int64_t grpc_test_sanitizer_slowdown_factor() {
int64_t sanitizer_multiplier = 1;
if (BuiltUnderValgrind()) {
sanitizer_multiplier = 20;
} else if (BuiltUnderTsan()) {
sanitizer_multiplier = 5;
} else if (BuiltUnderAsan()) {
sanitizer_multiplier = 3;
} else if (BuiltUnderMsan()) {
sanitizer_multiplier = 4;
} else if (BuiltUnderUbsan()) {
sanitizer_multiplier = 5;
}
return sanitizer_multiplier;
}
int64_t grpc_test_slowdown_factor() {
return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor *
g_poller_slowdown_factor;
}
gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) {
return gpr_time_add(
gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_millis(
grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s,
GPR_TIMESPAN));
}
gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) {
return gpr_time_add(
gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_micros(
grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms,
GPR_TIMESPAN));
}
void grpc_test_init(int argc, char** argv) {
#if GPR_WINDOWS
// Windows cannot use absl::InitializeSymbolizer until it fixes mysterious
// SymInitialize failure using Bazel RBE on Windows
// https://github.com/grpc/grpc/issues/24178
install_crash_handler();
#else
grpc_core::testing::InitializeStackTracer(argv[0]);
absl::FailureSignalHandlerOptions options;
absl::InstallFailureSignalHandler(options);
#endif
gpr_log(GPR_DEBUG,
"test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64
", poller=%" PRId64 ", total=%" PRId64,
grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor,
g_poller_slowdown_factor, grpc_test_slowdown_factor());
/* seed rng with pid, so we don't end up with the same random numbers as a
concurrently running test binary */
srand(seed());
}
bool grpc_wait_until_shutdown(int64_t time_s) {
gpr_timespec deadline = grpc_timeout_seconds_to_deadline(time_s);
while (grpc_is_initialized()) {
grpc_maybe_wait_for_async_shutdown();
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(1, GPR_TIMESPAN)));
if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) > 0) {
return false;
}
}
return true;
}
namespace grpc {
namespace testing {
TestEnvironment::TestEnvironment(int argc, char** argv) {
grpc_test_init(argc, argv);
}
TestEnvironment::~TestEnvironment() {
// This will wait until gRPC shutdown has actually happened to make sure
// no gRPC resources (such as thread) are active. (timeout = 10s)
if (!grpc_wait_until_shutdown(10)) {
gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
}
if (BuiltUnderMsan()) {
// This is a workaround for MSAN. MSAN doesn't like having shutdown thread
// running. Although the code above waits until shutdown is done, chances
// are that thread itself is still alive. To workaround this problem, this
// is going to wait for 0.5 sec to give a chance to the shutdown thread to
// exit. https://github.com/grpc/grpc/issues/23695
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN)));
}
gpr_log(GPR_INFO, "TestEnvironment ends");
}
TestGrpcScope::TestGrpcScope() { grpc_init(); }
TestGrpcScope::~TestGrpcScope() {
grpc_shutdown();
if (!grpc_wait_until_shutdown(10)) {
gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
}
}
} // namespace testing
} // namespace grpc
<commit_msg>Enable Abseil crash handler on Windows<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* 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 "test/core/util/test_config.h"
#include <grpc/impl/codegen/gpr_types.h>
#include <inttypes.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/examine_stack.h"
#include "src/core/lib/surface/init.h"
#include "test/core/util/stack_tracer.h"
#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
int64_t g_fixture_slowdown_factor = 1;
int64_t g_poller_slowdown_factor = 1;
#if GPR_GETPID_IN_UNISTD_H
#include <unistd.h>
static unsigned seed(void) { return static_cast<unsigned>(getpid()); }
#endif
#if GPR_GETPID_IN_PROCESS_H
#include <process.h>
static unsigned seed(void) { return (unsigned)_getpid(); }
#endif
bool BuiltUnderValgrind() {
#ifdef RUNNING_ON_VALGRIND
return true;
#else
return false;
#endif
}
bool BuiltUnderTsan() {
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef THREAD_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderAsan() {
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef ADDRESS_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderMsan() {
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
return true;
#else
return false;
#endif
#else
#ifdef MEMORY_SANITIZER
return true;
#else
return false;
#endif
#endif
}
bool BuiltUnderUbsan() {
#ifdef GRPC_UBSAN
return true;
#else
return false;
#endif
}
int64_t grpc_test_sanitizer_slowdown_factor() {
int64_t sanitizer_multiplier = 1;
if (BuiltUnderValgrind()) {
sanitizer_multiplier = 20;
} else if (BuiltUnderTsan()) {
sanitizer_multiplier = 5;
} else if (BuiltUnderAsan()) {
sanitizer_multiplier = 3;
} else if (BuiltUnderMsan()) {
sanitizer_multiplier = 4;
} else if (BuiltUnderUbsan()) {
sanitizer_multiplier = 5;
}
return sanitizer_multiplier;
}
int64_t grpc_test_slowdown_factor() {
return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor *
g_poller_slowdown_factor;
}
gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) {
return gpr_time_add(
gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_millis(
grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s,
GPR_TIMESPAN));
}
gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) {
return gpr_time_add(
gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_micros(
grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms,
GPR_TIMESPAN));
}
void grpc_test_init(int argc, char** argv) {
grpc_core::testing::InitializeStackTracer(argv[0]);
absl::FailureSignalHandlerOptions options;
absl::InstallFailureSignalHandler(options);
gpr_log(GPR_DEBUG,
"test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64
", poller=%" PRId64 ", total=%" PRId64,
grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor,
g_poller_slowdown_factor, grpc_test_slowdown_factor());
/* seed rng with pid, so we don't end up with the same random numbers as a
concurrently running test binary */
srand(seed());
}
bool grpc_wait_until_shutdown(int64_t time_s) {
gpr_timespec deadline = grpc_timeout_seconds_to_deadline(time_s);
while (grpc_is_initialized()) {
grpc_maybe_wait_for_async_shutdown();
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(1, GPR_TIMESPAN)));
if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) > 0) {
return false;
}
}
return true;
}
namespace grpc {
namespace testing {
TestEnvironment::TestEnvironment(int argc, char** argv) {
grpc_test_init(argc, argv);
}
TestEnvironment::~TestEnvironment() {
// This will wait until gRPC shutdown has actually happened to make sure
// no gRPC resources (such as thread) are active. (timeout = 10s)
if (!grpc_wait_until_shutdown(10)) {
gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
}
if (BuiltUnderMsan()) {
// This is a workaround for MSAN. MSAN doesn't like having shutdown thread
// running. Although the code above waits until shutdown is done, chances
// are that thread itself is still alive. To workaround this problem, this
// is going to wait for 0.5 sec to give a chance to the shutdown thread to
// exit. https://github.com/grpc/grpc/issues/23695
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(500, GPR_TIMESPAN)));
}
gpr_log(GPR_INFO, "TestEnvironment ends");
}
TestGrpcScope::TestGrpcScope() { grpc_init(); }
TestGrpcScope::~TestGrpcScope() {
grpc_shutdown();
if (!grpc_wait_until_shutdown(10)) {
gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
}
}
} // namespace testing
} // namespace grpc
<|endoftext|>
|
<commit_before>/* Autogenerated with kurento-module-creator */
#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <gst/gst.h>
#include <KurentoException.hpp>
#include <vector>
#include <string>
#define GST_CAT_DEFAULT kurento_telmate_frame_grabber_opencv_impl
GST_DEBUG_CATEGORY_STATIC(GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoTelmateFrameGrabberOpenCVImpl"
namespace kurento {
TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() {
GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
this->thrLoop = true;
this->snapInterval = 1000;
this->epName = "EP_NAME_UNINITIALIZED";
this->storagePath = "/tmp";
this->framesCounter = 0;
this->outputFormat = FGFMT_JPEG;
this->lastQueueTimeStamp = 0;
this->queueLength = 0;
this->frameQueue = new avis_blocking_queue<VideoFrame*>;
this->thr = new boost::thread(boost::bind(
&TelmateFrameGrabberOpenCVImpl::queueHandler, this));
this->thr->detach();
GST_INFO("Constructor was called for %s", this->epName.c_str());
}
TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() {
GST_INFO("Destructor was called for %s", this->epName.c_str());
}
void TelmateFrameGrabberOpenCVImpl::cleanup() {
VideoFrame *ptrVf;
while(!this->frameQueue->empty()) {
this->frameQueue->pop(ptrVf); // blocks
--this->queueLength;
delete ptrVf;
ptrVf = NULL;
}
this->thrLoop = false;
boost::this_thread::sleep_for(boost::chrono::milliseconds(250)); /* Give the processing thread some time to exit() */
GST_INFO("Called release() for %s :: Dequeue completed.", this->epName.c_str());
delete this->frameQueue;
this->frameQueue = NULL;
return;
}
/*
* This function will be called with each new frame. mat variable
* contains the current frame. You should insert your image processing code
* here. Any changes in mat, will be sent through the Media Pipeline.
*/
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat) {
if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) >= this->snapInterval) {
if(this->thrLoop) { // do not push into the queue if the destructor was called.
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
VideoFrame *ptrVf = new VideoFrame();
ptrVf->mat = mat.clone();
ptrVf->ts = std::to_string(this->lastQueueTimeStamp);
this->frameQueue->push(ptrVf);
++this->queueLength;
++this->framesCounter;
}
}
}
/*
* This function is executed inside the queueHandler thread as a main() function.
* It pops a VideoFrame from the framequeue and saves it to disk.
* a boost scoped_lock is implemented to ensure the queue is emptied to disk before
* the destructor is executed. a 1 second sleep is implemented inside the while() loop
* to ensure the cpu isn't exhausted while the queue is empty.
*/
void TelmateFrameGrabberOpenCVImpl::queueHandler() {
VideoFrame *ptrVf;
cv::Mat image;
std::vector<int> params;
std::string image_extension;
while (this->thrLoop) {
this->frameQueue->pop(ptrVf); // blocks
params.clear(); // clear the vector since the last iteration.
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
--this->queueLength;
switch (this->outputFormat) {
case FGFMT_JPEG:
/* Set jpeg params */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
case FGFMT_PNG:
/* Set PNG parameters, compression etc. */
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(FG_PNG_QUALITY);
image_extension = ".png";
break;
default:
/* Defaults to jpeg */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
}
std::string filename =
std::to_string((long) this->framesCounter) + "_" + ptrVf->ts + image_extension;
if (this->storagePathSubdir.empty()) {
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
boost::filesystem::path dir(this->storagePathSubdir.c_str());
if (!boost::filesystem::create_directories(dir)) {
GST_ERROR("%s create_directories() failed for: %s", this->epName.c_str(),
this->storagePathSubdir.c_str());
}
}
std::string fullpath = this->storagePathSubdir + "/" + filename;
try {
cv::imwrite(fullpath.c_str(), ptrVf->mat, params);
}
catch (...) {
GST_ERROR("::queueHandler() imgwrite() failed.");
throw KurentoException(NOT_IMPLEMENTED,
"TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed. \n");
}
ptrVf->mat.release(); // release internal memory allocations
delete ptrVf;
ptrVf = NULL;
}
}
/* This function provides the ability to update the storage path for
* snapshot storage per endpoint
*/
void TelmateFrameGrabberOpenCVImpl::setStoragePath(std::string storagePath) {
this->storagePath = storagePath;
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
boost::filesystem::path dir(this->storagePathSubdir.c_str());
if (!boost::filesystem::create_directories(dir)) {
GST_ERROR("%s create_directories() failed for: %s", this->epName.c_str(),
this->storagePathSubdir.c_str());
}
GST_INFO("Storage path has been updated to %s for %s", this->storagePath.c_str(), this->epName.c_str());
}
std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString() {
struct timeval tp;
long int ms;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
sstr_ts << ms;
return sstr_ts.str();
}
long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}
} // namespace kurento
<commit_msg>allways create directories<commit_after>/* Autogenerated with kurento-module-creator */
#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <gst/gst.h>
#include <KurentoException.hpp>
#include <vector>
#include <string>
#define GST_CAT_DEFAULT kurento_telmate_frame_grabber_opencv_impl
GST_DEBUG_CATEGORY_STATIC(GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoTelmateFrameGrabberOpenCVImpl"
namespace kurento {
TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() {
GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
this->thrLoop = true;
this->snapInterval = 1000;
this->epName = "EP_NAME_UNINITIALIZED";
this->storagePath = "/tmp/";
this->framesCounter = 0;
this->outputFormat = FGFMT_JPEG;
this->lastQueueTimeStamp = 0;
this->queueLength = 0;
this->frameQueue = new avis_blocking_queue<VideoFrame*>;
this->thr = new boost::thread(boost::bind(
&TelmateFrameGrabberOpenCVImpl::queueHandler, this));
this->thr->detach();
GST_INFO("Constructor was called for %s", this->epName.c_str());
}
TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() {
GST_INFO("Destructor was called for %s", this->epName.c_str());
}
void TelmateFrameGrabberOpenCVImpl::cleanup() {
VideoFrame *ptrVf;
while(!this->frameQueue->empty()) {
this->frameQueue->pop(ptrVf); // blocks
--this->queueLength;
delete ptrVf;
ptrVf = NULL;
}
this->thrLoop = false;
boost::this_thread::sleep_for(boost::chrono::milliseconds(250)); /* Give the processing thread some time to exit() */
GST_INFO("Called release() for %s :: Dequeue completed.", this->epName.c_str());
delete this->frameQueue;
this->frameQueue = NULL;
return;
}
/*
* This function will be called with each new frame. mat variable
* contains the current frame. You should insert your image processing code
* here. Any changes in mat, will be sent through the Media Pipeline.
*/
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat) {
if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) >= this->snapInterval) {
if(this->thrLoop) { // do not push into the queue if the destructor was called.
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
VideoFrame *ptrVf = new VideoFrame();
ptrVf->mat = mat.clone();
ptrVf->ts = std::to_string(this->lastQueueTimeStamp);
this->frameQueue->push(ptrVf);
++this->queueLength;
++this->framesCounter;
}
}
}
/*
* This function is executed inside the queueHandler thread as a main() function.
* It pops a VideoFrame from the framequeue and saves it to disk.
* a boost scoped_lock is implemented to ensure the queue is emptied to disk before
* the destructor is executed. a 1 second sleep is implemented inside the while() loop
* to ensure the cpu isn't exhausted while the queue is empty.
*/
void TelmateFrameGrabberOpenCVImpl::queueHandler() {
VideoFrame *ptrVf;
cv::Mat image;
std::vector<int> params;
std::string image_extension;
while (this->thrLoop) {
this->frameQueue->pop(ptrVf); // blocks
params.clear(); // clear the vector since the last iteration.
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
--this->queueLength;
switch (this->outputFormat) {
case FGFMT_JPEG:
/* Set jpeg params */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
case FGFMT_PNG:
/* Set PNG parameters, compression etc. */
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(FG_PNG_QUALITY);
image_extension = ".png";
break;
default:
/* Defaults to jpeg */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
}
std::string filename =
std::to_string((long) this->framesCounter) + "_" + ptrVf->ts + image_extension;
//if (this->storagePathSubdir.empty()) {
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
boost::filesystem::path dir(this->storagePathSubdir.c_str());
if (!boost::filesystem::create_directories(dir)) {
GST_INFO("%s create_directories() failed for: %s", this->epName.c_str(),
this->storagePathSubdir.c_str());
}
//}
std::string fullpath = this->storagePathSubdir + "/" + filename;
try {
cv::imwrite(fullpath.c_str(), ptrVf->mat, params);
}
catch (...) {
GST_ERROR("::queueHandler() imgwrite() failed.");
throw KurentoException(NOT_IMPLEMENTED,
"TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed. \n");
}
ptrVf->mat.release(); // release internal memory allocations
delete ptrVf;
ptrVf = NULL;
}
}
/* This function provides the ability to update the storage path for
* snapshot storage per endpoint
*/
void TelmateFrameGrabberOpenCVImpl::setStoragePath(std::string storagePath) {
this->storagePath = storagePath;
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
boost::filesystem::path dir(this->storagePathSubdir.c_str());
if (!boost::filesystem::create_directories(dir)) {
GST_INFO("%s create_directories() failed for: %s", this->epName.c_str(),
this->storagePathSubdir.c_str());
}
GST_INFO("Storage path has been updated to %s for %s", this->storagePath.c_str(), this->epName.c_str());
}
std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString() {
struct timeval tp;
long int ms;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
sstr_ts << ms;
return sstr_ts.str();
}
long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}
} // namespace kurento
<|endoftext|>
|
<commit_before>
// Copyright (c) 2010 libmv authors.
//
// 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.
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/multiview/projection.hpp"
namespace openMVG {
/// Compute P = K[R|t]
void P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t, Mat34 *P)
{
assert(P != nullptr);
*P = P_From_KRt(K, R, t);
}
Mat34 P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t)
{
return K * HStack(R,t);
}
void KRt_From_P(const Mat34 &P, Mat3 *Kp, Mat3 *Rp, Vec3 *tp)
{
assert(Kp != nullptr);
assert(Rp != nullptr);
assert(tp != nullptr);
// Decompose using the RQ decomposition HZ A4.1.1 pag.579.
Mat3 K = P.block(0, 0, 3, 3);
Mat3 Q;
Q.setIdentity();
// Set K(2,1) to zero.
if (K(2,1) != 0)
{
double c = -K(2,2);
double s = K(2,1);
const double l = sqrt(c * c + s * s);
c /= l;
s /= l;
Mat3 Qx;
Qx << 1, 0, 0,
0, c, -s,
0, s, c;
K = K * Qx;
Q = Qx.transpose() * Q;
}
// Set K(2,0) to zero.
if (K(2,0) != 0)
{
double c = K(2,2);
double s = K(2,0);
const double l = sqrt(c * c + s * s);
c /= l;
s /= l;
Mat3 Qy;
Qy << c, 0, s,
0, 1, 0,
-s, 0, c;
K = K * Qy;
Q = Qy.transpose() * Q;
}
// Set K(1,0) to zero.
if (K(1,0) != 0)
{
double c = -K(1,1);
double s = K(1,0);
const double l = sqrt(c * c + s * s);
c /= l;
s /= l;
Mat3 Qz;
Qz << c,-s, 0,
s, c, 0,
0, 0, 1;
K = K * Qz;
Q = Qz.transpose() * Q;
}
Mat3 R = Q;
//Mat3 H = P.block(0, 0, 3, 3);
// RQ decomposition
//Eigen::HouseholderQR<Mat3> qr(H);
//Mat3 K = qr.matrixQR().triangularView<Eigen::Upper>();
//Mat3 R = qr.householderQ();
// Ensure that the diagonal is positive and R determinant == 1.
if (K(2,2) < 0)
{
K = -K;
R = -R;
}
if (K(1,1) < 0)
{
Mat3 S;
S << 1, 0, 0,
0,-1, 0,
0, 0, 1;
K = K * S;
R = S * R;
}
if (K(0,0) < 0)
{
Mat3 S;
S << -1, 0, 0,
0, 1, 0,
0, 0, 1;
K = K * S;
R = S * R;
}
// Compute translation.
Eigen::PartialPivLU<Mat3> lu(K);
Vec3 t = lu.solve(P.col(3));
if(R.determinant() < 0)
{
R = -R;
t = -t;
}
// scale K so that K(2,2) = 1
K = K / K(2,2);
*Kp = K;
*Rp = R;
*tp = t;
}
Mat3 F_from_P(const Mat34 & P1, const Mat34 & P2)
{
Mat3 F12;
typedef Eigen::Matrix<double, 2, 4> Mat24;
Mat24 X1 = P1.block<2, 4>(1, 0);
Mat24 X2;
X2 << P1.row(2), P1.row(0);
Mat24 X3 = P1.block<2, 4>(0, 0);
Mat24 Y1 = P2.block<2, 4>(1, 0);
Mat24 Y2;
Y2 << P2.row(2), P2.row(0);
Mat24 Y3 = P2.block<2, 4>(0, 0);
Mat4 X1Y1, X2Y1, X3Y1, X1Y2, X2Y2, X3Y2, X1Y3, X2Y3, X3Y3;
X1Y1 << X1, Y1;
X2Y1 << X2, Y1;
X3Y1 << X3, Y1;
X1Y2 << X1, Y2;
X2Y2 << X2, Y2;
X3Y2 << X3, Y2;
X1Y3 << X1, Y3;
X2Y3 << X2, Y3;
X3Y3 << X3, Y3;
F12 << X1Y1.determinant(), X2Y1.determinant(), X3Y1.determinant(),
X1Y2.determinant(), X2Y2.determinant(), X3Y2.determinant(),
X1Y3.determinant(), X2Y3.determinant(), X3Y3.determinant();
return F12;
}
Vec2 Project(const Mat34 &P, const Vec3 &X)
{
return Vec3(P * X.homogeneous()).hnormalized();
}
void Project(const Mat34 &P, const Mat3X &X, Mat2X *x)
{
assert(x != nullptr);
Project(P, Mat4X(X.colwise().homogeneous()), x);
}
void Project(const Mat34 &P, const Mat4X &X, Mat2X *x)
{
assert(x != nullptr);
*x = Project(P, X);
}
Mat2X Project(const Mat34 &P, const Mat3X &X)
{
return Project(P, Mat4X(X.colwise().homogeneous()));
}
Mat2X Project(const Mat34 &P, const Mat4X &X)
{
return Mat3X(P * X).colwise().hnormalized();
}
void HomogeneousToEuclidean(const Vec4 &H, Vec3 *X)
{
assert(X != nullptr);
*X = H.hnormalized();
}
void EuclideanToHomogeneous(const Mat &X, Mat *H)
{
assert(H != nullptr);
*H = X.colwise().homogeneous();
}
double Depth(const Mat3 &R, const Vec3 &t, const Vec3 &X)
{
return (R*X)[2] + t[2];
}
Vec3 EuclideanToHomogeneous(const Vec2 &x)
{
return x.homogeneous();
}
void HomogeneousToEuclidean(const Mat &H, Mat *X)
{
assert(X != nullptr);
*X = H.colwise().hnormalized();
}
Mat3X EuclideanToHomogeneous(const Mat2X &x)
{
return x.colwise().homogeneous();
}
void EuclideanToHomogeneous(const Mat2X &x, Mat3X *h)
{
assert(h != nullptr);
*h = x.colwise().homogeneous();
}
void HomogeneousToEuclidean(const Mat3X &h, Mat2X *e)
{
assert(e != nullptr);
*e = h.colwise().hnormalized();
}
void EuclideanToNormalizedCamera(const Mat2X &x, const Mat3 &K, Mat2X *n)
{
assert(n != nullptr);
HomogeneousToNormalizedCamera(x.colwise().homogeneous(), K, n);
}
void HomogeneousToNormalizedCamera(const Mat3X &x, const Mat3 &K, Mat2X *n)
{
assert(n != nullptr);
*n = (K.inverse() * x).colwise().hnormalized();
}
/// Estimates the root mean square error (2D)
double reprojectionErrorRMSE(const Mat2X &x_image,
const Mat4X &X_world,
const Mat34 &P)
{
const std::size_t num_points = x_image.cols();
const Mat2X dx = Project(P, X_world) - x_image;
return std::sqrt(dx.squaredNorm() / num_points);
}
/// Estimates the root mean square error (2D)
double reprojectionErrorRMSE(const Mat2X &x_image,
const Mat3X &X_world,
const Mat3 &K,
const Mat3 &R,
const Vec3 &t)
{
Mat34 P;
P_From_KRt(K, R, t, &P);
return reprojectionErrorRMSE(x_image, X_world.colwise().homogeneous(), P);
}
} // namespace openMVG
<commit_msg>[multiview] renaming<commit_after>
// Copyright (c) 2010 libmv authors.
//
// 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.
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <openMVG/multiview/projection.hpp>
#include <cmath>
namespace openMVG {
/// Compute P = K[R|t]
void P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t, Mat34 *P)
{
assert(P != nullptr);
*P = P_From_KRt(K, R, t);
}
Mat34 P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t)
{
return K * HStack(R,t);
}
void KRt_From_P(const Mat34 &P, Mat3 *Kp, Mat3 *Rp, Vec3 *tp)
{
assert(Kp != nullptr);
assert(Rp != nullptr);
assert(tp != nullptr);
// Decompose using the RQ decomposition HZ A4.1.1 pag.579.
Mat3 K = P.block(0, 0, 3, 3);
Mat3 Q;
Q.setIdentity();
// Set K(2,1) to zero.
if (K(2,1) != 0)
{
double c = -K(2,2);
double s = K(2,1);
const double lenght = std::sqrt(c * c + s * s);
c /= lenght;
s /= lenght;
Mat3 Qx;
Qx << 1, 0, 0,
0, c, -s,
0, s, c;
K = K * Qx;
Q = Qx.transpose() * Q;
}
// Set K(2,0) to zero.
if (K(2,0) != 0)
{
double c = K(2,2);
double s = K(2,0);
const double length = std::sqrt(c * c + s * s);
c /= length;
s /= length;
Mat3 Qy;
Qy << c, 0, s,
0, 1, 0,
-s, 0, c;
K = K * Qy;
Q = Qy.transpose() * Q;
}
// Set K(1,0) to zero.
if (K(1,0) != 0)
{
double c = -K(1,1);
double s = K(1,0);
const double length = sqrt(c * c + s * s);
c /= length;
s /= length;
Mat3 Qz;
Qz << c,-s, 0,
s, c, 0,
0, 0, 1;
K = K * Qz;
Q = Qz.transpose() * Q;
}
Mat3 R = Q;
//Mat3 H = P.block(0, 0, 3, 3);
// RQ decomposition
//Eigen::HouseholderQR<Mat3> qr(H);
//Mat3 K = qr.matrixQR().triangularView<Eigen::Upper>();
//Mat3 R = qr.householderQ();
// Ensure that the diagonal is positive and R determinant == 1.
if (K(2,2) < 0)
{
K = -K;
R = -R;
}
if (K(1,1) < 0)
{
Mat3 S;
S << 1, 0, 0,
0,-1, 0,
0, 0, 1;
K = K * S;
R = S * R;
}
if (K(0,0) < 0)
{
Mat3 S;
S << -1, 0, 0,
0, 1, 0,
0, 0, 1;
K = K * S;
R = S * R;
}
// Compute translation.
Eigen::PartialPivLU<Mat3> lu(K);
Vec3 t = lu.solve(P.col(3));
if(R.determinant() < 0)
{
R = -R;
t = -t;
}
// scale K so that K(2,2) = 1
K = K / K(2,2);
*Kp = K;
*Rp = R;
*tp = t;
}
Mat3 F_from_P(const Mat34 & P1, const Mat34 & P2)
{
Mat3 F12;
typedef Eigen::Matrix<double, 2, 4> Mat24;
Mat24 X1 = P1.block<2, 4>(1, 0);
Mat24 X2;
X2 << P1.row(2), P1.row(0);
Mat24 X3 = P1.block<2, 4>(0, 0);
Mat24 Y1 = P2.block<2, 4>(1, 0);
Mat24 Y2;
Y2 << P2.row(2), P2.row(0);
Mat24 Y3 = P2.block<2, 4>(0, 0);
Mat4 X1Y1, X2Y1, X3Y1, X1Y2, X2Y2, X3Y2, X1Y3, X2Y3, X3Y3;
X1Y1 << X1, Y1;
X2Y1 << X2, Y1;
X3Y1 << X3, Y1;
X1Y2 << X1, Y2;
X2Y2 << X2, Y2;
X3Y2 << X3, Y2;
X1Y3 << X1, Y3;
X2Y3 << X2, Y3;
X3Y3 << X3, Y3;
F12 << X1Y1.determinant(), X2Y1.determinant(), X3Y1.determinant(),
X1Y2.determinant(), X2Y2.determinant(), X3Y2.determinant(),
X1Y3.determinant(), X2Y3.determinant(), X3Y3.determinant();
return F12;
}
Vec2 Project(const Mat34 &P, const Vec3 &X)
{
return Vec3(P * X.homogeneous()).hnormalized();
}
void Project(const Mat34 &P, const Mat3X &X, Mat2X *x)
{
assert(x != nullptr);
Project(P, Mat4X(X.colwise().homogeneous()), x);
}
void Project(const Mat34 &P, const Mat4X &X, Mat2X *x)
{
assert(x != nullptr);
*x = Project(P, X);
}
Mat2X Project(const Mat34 &P, const Mat3X &X)
{
return Project(P, Mat4X(X.colwise().homogeneous()));
}
Mat2X Project(const Mat34 &P, const Mat4X &X)
{
return Mat3X(P * X).colwise().hnormalized();
}
void HomogeneousToEuclidean(const Vec4 &H, Vec3 *X)
{
assert(X != nullptr);
*X = H.hnormalized();
}
void EuclideanToHomogeneous(const Mat &X, Mat *H)
{
assert(H != nullptr);
*H = X.colwise().homogeneous();
}
double Depth(const Mat3 &R, const Vec3 &t, const Vec3 &X)
{
return (R*X)[2] + t[2];
}
Vec3 EuclideanToHomogeneous(const Vec2 &x)
{
return x.homogeneous();
}
void HomogeneousToEuclidean(const Mat &H, Mat *X)
{
assert(X != nullptr);
*X = H.colwise().hnormalized();
}
Mat3X EuclideanToHomogeneous(const Mat2X &x)
{
return x.colwise().homogeneous();
}
void EuclideanToHomogeneous(const Mat2X &x, Mat3X *h)
{
assert(h != nullptr);
*h = x.colwise().homogeneous();
}
void HomogeneousToEuclidean(const Mat3X &h, Mat2X *e)
{
assert(e != nullptr);
*e = h.colwise().hnormalized();
}
void EuclideanToNormalizedCamera(const Mat2X &x, const Mat3 &K, Mat2X *n)
{
assert(n != nullptr);
HomogeneousToNormalizedCamera(x.colwise().homogeneous(), K, n);
}
void HomogeneousToNormalizedCamera(const Mat3X &x, const Mat3 &K, Mat2X *n)
{
assert(n != nullptr);
*n = (K.inverse() * x).colwise().hnormalized();
}
/// Estimates the root mean square error (2D)
double reprojectionErrorRMSE(const Mat2X &x_image,
const Mat4X &X_world,
const Mat34 &P)
{
const std::size_t num_points = x_image.cols();
const Mat2X dx = Project(P, X_world) - x_image;
return std::sqrt(dx.squaredNorm() / num_points);
}
/// Estimates the root mean square error (2D)
double reprojectionErrorRMSE(const Mat2X &x_image,
const Mat3X &X_world,
const Mat3 &K,
const Mat3 &R,
const Vec3 &t)
{
Mat34 P;
P_From_KRt(K, R, t, &P);
return reprojectionErrorRMSE(x_image, X_world.colwise().homogeneous(), P);
}
} // namespace openMVG
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2001 by Norman Krmer
This library 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 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
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "oggdata.h"
#include "isound/loader.h"
#include "iutil/comp.h"
CS_IMPLEMENT_PLUGIN
SCF_IMPLEMENT_IBASE (csOggSoundData)
SCF_IMPLEMENTS_INTERFACE (iSoundData)
SCF_IMPLEMENT_IBASE_END
static size_t cs_ogg_read (void *ptr, size_t size, size_t nmemb, void *datasource)
{
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
size_t br = MIN (size*nmemb, ds->length-ds->pos);
memcpy (ptr, ds->data+ds->pos, br);
ds->pos +=br;
return br;
}
static int cs_ogg_seek (void *datasource, int64_t offset, int whence)
{
size_t np;
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
if (whence == SEEK_SET)
np = offset;
else if (whence == SEEK_CUR)
np = ds->pos + offset;
else if (whence == SEEK_END)
np = ds->length + offset;
else
return -1;
if (np > ds->length)
return -1;
ds->pos = np;
return 0;
}
static int cs_ogg_close (void *)
{
return 0;
}
static long cs_ogg_tell (void *datasource)
{
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
return ds->pos;
}
csOggSoundData::cs_ov_callbacks::cs_ov_callbacks ()
{
read_func = cs_ogg_read;
seek_func = cs_ogg_seek;
close_func = cs_ogg_close;
tell_func = cs_ogg_tell;
}
CS_IMPLEMENT_STATIC_VAR (GetCallbacks, csOggSoundData::cs_ov_callbacks, ())
csOggSoundData::csOggSoundData (iBase *parent, uint8 *data, size_t len)
{
SCF_CONSTRUCT_IBASE (parent);
#ifdef CS_LITTLE_ENDIAN
endian = 0;
#else
endian = 1;
#endif
ds = new datastore (data, len, true);
ogg_ok = false;
buf = NULL;
len = 0;
current_section = 0;
fmt.Bits = 16;
fmt.Channels = 2;
}
csOggSoundData::~csOggSoundData ()
{
ov_clear (&vf);
delete [] buf;
delete ds;
}
bool csOggSoundData::Initialize(const csSoundFormat *fmt)
{
if (!ogg_ok)
{
ogg_ok = ov_open_callbacks(ds, &vf, NULL, 0, *(ov_callbacks*)GetCallbacks ()) == 0;
if (fmt->Channels != -1)
this->fmt.Channels = fmt->Channels;
if (fmt->Freq != -1)
this->fmt.Freq = fmt->Freq;
}
return ogg_ok;
}
bool csOggSoundData::IsOgg (void *Buffer, size_t len)
{
datastore *dd = new datastore ((uint8*)Buffer, len, false);
OggVorbis_File f;
bool ok = ov_open_callbacks(dd, &f, NULL, 0, *(ov_callbacks*)GetCallbacks ()) == 0;
ov_clear (&f);
delete dd;
return ok;
}
const csSoundFormat* csOggSoundData::GetFormat()
{
return &fmt;
}
bool csOggSoundData::IsStatic()
{
return false;
}
long csOggSoundData::GetStaticSampleCount()
{
return -1;
}
void *csOggSoundData::GetStaticData()
{
return NULL;
}
void csOggSoundData::ResetStreamed()
{
ogg_ok = ov_raw_seek (&vf, 0) == 0;
}
void *csOggSoundData::ReadStreamed(long &NumSamples)
{
if (ogg_ok)
{
long buffersize = NumSamples * (fmt.Bits >> 3) * fmt.Channels;
if (buffersize > len)
{
buf = (uint8*) realloc (buf, buffersize);
len = buffersize;
}
long bytes_read = ov_read (&vf, (char*)buf, buffersize, endian,
fmt.Bits>>3, 1, ¤t_section);
NumSamples = bytes_read / ((fmt.Bits >> 3) * fmt.Channels);
return buf;
}
NumSamples = 0;
return NULL;
}
// ogg loader
class csOggLoader : public iSoundLoader
{
public:
SCF_DECLARE_IBASE;
struct eiComponent : public iComponent
{
SCF_DECLARE_EMBEDDED_IBASE (csOggLoader);
virtual bool Initialize (iObjectRegistry *){return true;}
}scfiComponent;
csOggLoader (iBase *parent)
{
SCF_CONSTRUCT_IBASE (parent);
SCF_CONSTRUCT_EMBEDDED_IBASE (scfiComponent);
}
virtual csPtr<iSoundData> LoadSound (void *Buffer, unsigned long Size) const
{
csOggSoundData *sd=NULL;
if (csOggSoundData::IsOgg (Buffer, Size))
sd = new csOggSoundData ((iBase*)this, (uint8*)Buffer, Size);
return csPtr<iSoundData> (sd);
}
};
SCF_IMPLEMENT_IBASE (csOggLoader)
SCF_IMPLEMENTS_INTERFACE (iSoundLoader)
SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)
SCF_IMPLEMENT_IBASE_END
SCF_IMPLEMENT_EMBEDDED_IBASE (csOggLoader::eiComponent)
SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
SCF_IMPLEMENT_FACTORY (csOggLoader);
SCF_EXPORT_CLASS_TABLE (sndogg)
SCF_EXPORT_CLASS (csOggLoader, "crystalspace.sound.loader.ogg", "Ogg Vorbis Sound Loader")
SCF_EXPORT_CLASS_TABLE_END
<commit_msg>fix ogg loader crash when sound hasn't been initialized<commit_after>/*
Copyright (C) 2001 by Norman Krmer
This library 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 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
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "oggdata.h"
#include "isound/loader.h"
#include "iutil/comp.h"
CS_IMPLEMENT_PLUGIN
SCF_IMPLEMENT_IBASE (csOggSoundData)
SCF_IMPLEMENTS_INTERFACE (iSoundData)
SCF_IMPLEMENT_IBASE_END
static size_t cs_ogg_read (void *ptr, size_t size, size_t nmemb, void *datasource)
{
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
size_t br = MIN (size*nmemb, ds->length-ds->pos);
memcpy (ptr, ds->data+ds->pos, br);
ds->pos +=br;
return br;
}
static int cs_ogg_seek (void *datasource, int64_t offset, int whence)
{
size_t np;
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
if (whence == SEEK_SET)
np = offset;
else if (whence == SEEK_CUR)
np = ds->pos + offset;
else if (whence == SEEK_END)
np = ds->length + offset;
else
return -1;
if (np > ds->length)
return -1;
ds->pos = np;
return 0;
}
static int cs_ogg_close (void *)
{
return 0;
}
static long cs_ogg_tell (void *datasource)
{
csOggSoundData::datastore *ds = (csOggSoundData::datastore*)datasource;
return ds->pos;
}
csOggSoundData::cs_ov_callbacks::cs_ov_callbacks ()
{
read_func = cs_ogg_read;
seek_func = cs_ogg_seek;
close_func = cs_ogg_close;
tell_func = cs_ogg_tell;
}
CS_IMPLEMENT_STATIC_VAR (GetCallbacks, csOggSoundData::cs_ov_callbacks, ())
csOggSoundData::csOggSoundData (iBase *parent, uint8 *data, size_t len)
{
SCF_CONSTRUCT_IBASE (parent);
#ifdef CS_LITTLE_ENDIAN
endian = 0;
#else
endian = 1;
#endif
ds = new datastore (data, len, true);
ogg_ok = false;
buf = NULL;
len = 0;
current_section = 0;
fmt.Bits = 16;
fmt.Channels = 2;
memset (&vf, 0, sizeof(vf));
}
csOggSoundData::~csOggSoundData ()
{
ov_clear (&vf);
delete [] buf;
delete ds;
}
bool csOggSoundData::Initialize(const csSoundFormat *fmt)
{
if (!ogg_ok)
{
ogg_ok = ov_open_callbacks(ds, &vf, NULL, 0, *(ov_callbacks*)GetCallbacks ()) == 0;
if (fmt->Channels != -1)
this->fmt.Channels = fmt->Channels;
if (fmt->Freq != -1)
this->fmt.Freq = fmt->Freq;
}
return ogg_ok;
}
bool csOggSoundData::IsOgg (void *Buffer, size_t len)
{
datastore *dd = new datastore ((uint8*)Buffer, len, false);
OggVorbis_File f;
bool ok = ov_open_callbacks(dd, &f, NULL, 0, *(ov_callbacks*)GetCallbacks ()) == 0;
ov_clear (&f);
delete dd;
return ok;
}
const csSoundFormat* csOggSoundData::GetFormat()
{
return &fmt;
}
bool csOggSoundData::IsStatic()
{
return false;
}
long csOggSoundData::GetStaticSampleCount()
{
return -1;
}
void *csOggSoundData::GetStaticData()
{
return NULL;
}
void csOggSoundData::ResetStreamed()
{
ogg_ok = ov_raw_seek (&vf, 0) == 0;
}
void *csOggSoundData::ReadStreamed(long &NumSamples)
{
if (ogg_ok)
{
long buffersize = NumSamples * (fmt.Bits >> 3) * fmt.Channels;
if (buffersize > len)
{
buf = (uint8*) realloc (buf, buffersize);
len = buffersize;
}
long bytes_read = ov_read (&vf, (char*)buf, buffersize, endian,
fmt.Bits>>3, 1, ¤t_section);
NumSamples = bytes_read / ((fmt.Bits >> 3) * fmt.Channels);
return buf;
}
NumSamples = 0;
return NULL;
}
// ogg loader
class csOggLoader : public iSoundLoader
{
public:
SCF_DECLARE_IBASE;
struct eiComponent : public iComponent
{
SCF_DECLARE_EMBEDDED_IBASE (csOggLoader);
virtual bool Initialize (iObjectRegistry *){return true;}
}scfiComponent;
csOggLoader (iBase *parent)
{
SCF_CONSTRUCT_IBASE (parent);
SCF_CONSTRUCT_EMBEDDED_IBASE (scfiComponent);
}
virtual csPtr<iSoundData> LoadSound (void *Buffer, unsigned long Size) const
{
csOggSoundData *sd=NULL;
if (csOggSoundData::IsOgg (Buffer, Size))
sd = new csOggSoundData ((iBase*)this, (uint8*)Buffer, Size);
return csPtr<iSoundData> (sd);
}
};
SCF_IMPLEMENT_IBASE (csOggLoader)
SCF_IMPLEMENTS_INTERFACE (iSoundLoader)
SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)
SCF_IMPLEMENT_IBASE_END
SCF_IMPLEMENT_EMBEDDED_IBASE (csOggLoader::eiComponent)
SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
SCF_IMPLEMENT_FACTORY (csOggLoader);
SCF_EXPORT_CLASS_TABLE (sndogg)
SCF_EXPORT_CLASS (csOggLoader, "crystalspace.sound.loader.ogg", "Ogg Vorbis Sound Loader")
SCF_EXPORT_CLASS_TABLE_END
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@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.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
*/
#include "offsetcachefile.h"
#include "file.h"
#include "wordentry.h"
#include <QtCore/QVector>
#include <QtCore/QFile>
#include <QtCore/QtGlobal>
#include <QtCore/QDir>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QDesktopServices>
#include <arpa/inet.h>
using namespace MulaPluginStarDict;
class OffsetCacheFile::Private
{
public:
Private()
: wordCount(0)
, pageIndex(-1)
, cacheMagicString("StarDict's Cache, Version: 0.1")
, mappedData(0)
{
}
~Private()
{
}
// The length of "word_str" should be less than 256, and then offset, size
static const int wordEntrySize = 256 + sizeof(quint32)*2;
static const int pageEntryNumber = 32;
QVector<quint32> pageOffsetList;
QFile indexFile;
ulong wordCount;
// index/date based key and value pair
QPair<int, QByteArray> first;
QPair<int, QByteArray> last;
QPair<int, QByteArray> middle;
QPair<int, QByteArray> realLast;
long pageIndex;
QList<WordEntry> wordEntryList;
QByteArray cacheMagicString;
QFile mapFile;
uchar *mappedData;
};
OffsetCacheFile::OffsetCacheFile()
: d(new Private)
{
}
OffsetCacheFile::~OffsetCacheFile()
{
}
QByteArray
OffsetCacheFile::readFirstWordDataOnPage(long pageIndex)
{
int pageSize = d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex);
int wordEntrySize = d->wordEntrySize;
d->indexFile.seek(d->pageOffsetList.at(pageIndex));
return d->indexFile.read(qMin(wordEntrySize, pageSize)); //TODO: check returned values, deal with word entry that strlen>255.
}
QByteArray
OffsetCacheFile::firstWordDataOnPage(long pageIndex)
{
if (pageIndex < d->middle.first)
{
if (pageIndex == d->first.first)
return d->first.second;
return readFirstWordDataOnPage(pageIndex);
}
else if (pageIndex > d->middle.first)
{
if (pageIndex == d->last.first)
return d->last.second;
return readFirstWordDataOnPage(pageIndex);
}
else
{
return d->middle.second;
}
}
QStringList
OffsetCacheFile::cacheLocations(const QString& completeFilePath)
{
QStringList result;
result.append(completeFilePath + ".oft");
QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
QFileInfo cacheLocationFileInfo(cacheLocation);
QDir cacheLocationDir;
if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false)
return result;
if (!cacheLocationFileInfo.isDir())
return result;
result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(completeFilePath).fileName() + ".oft");
return result;
}
bool
OffsetCacheFile::loadCache(const QString& completeFilePath)
{
foreach (const QString& cacheLocation, cacheLocations(completeFilePath))
{
QFileInfo fileInfoIndex(completeFilePath);
QFileInfo fileInfoCache(cacheLocation);
if (fileInfoCache.lastModified() < fileInfoIndex.lastModified())
continue;
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(cacheLocation);
if( !d->mapFile.open( QIODevice::ReadOnly ) )
{
qDebug() << "Failed to open file:" << cacheLocation;
return false;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation);
return false;
}
if (d->cacheMagicString != d->mappedData)
continue;
memcpy(d->pageOffsetList.data(), d->mappedData + d->cacheMagicString.size(), d->pageOffsetList.size()*sizeof(d->pageOffsetList.at(0)));
return true;
}
return false;
}
bool
OffsetCacheFile::saveCache(const QString& completeFilePath)
{
foreach (const QString& cacheLocation, cacheLocations(completeFilePath))
{
QFile file(cacheLocation);
if( !file.open( QIODevice::WriteOnly ) )
{
qDebug() << "Failed to open file for writing:" << cacheLocation;
return false;
}
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(cacheLocation);
if( !d->mapFile.open( QIODevice::ReadOnly ) )
{
qDebug() << "Failed to open file:" << cacheLocation;
return false;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation);
return false;
}
if (file.write(d->cacheMagicString) != d->cacheMagicString.size())
continue;
if (file.write(reinterpret_cast<const char*>(d->pageOffsetList.data()), sizeof(d->pageOffsetList.at(0))*d->pageOffsetList.size())
!= d->pageOffsetList.at(0)*d->pageOffsetList.size())
continue;
file.close();
qDebug() << "Save to cache" << completeFilePath;
return true;
}
return false;
}
int
OffsetCacheFile::loadPage(int pageIndex)
{
int wordEntryCountOnPage;
if (pageIndex == (d->pageOffsetList.size() - 2) && (d->wordCount % d->pageEntryNumber) != 0)
wordEntryCountOnPage = d->wordCount % d->pageEntryNumber;
else
wordEntryCountOnPage = d->pageEntryNumber;
if (pageIndex != d->pageIndex)
{
d->pageIndex = pageIndex;
d->indexFile.seek(d->pageOffsetList.at(pageIndex));
QByteArray pageData = d->indexFile.read(d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex));
ulong position = 0;
d->wordEntryList.clear();
d->wordEntryList.reserve(wordEntryCountOnPage);
for (int i = 0; i < wordEntryCountOnPage; ++i)
{
WordEntry wordEntry;
wordEntry.setData(pageData.mid(position));
position = qstrlen(pageData.mid(position)) + 1;
wordEntry.setDataOffset(ntohl(*reinterpret_cast<quint32 *>(pageData.mid(position).data())));
position += sizeof(quint32);
wordEntry.setDataSize(ntohl(*reinterpret_cast<quint32 *>(pageData.mid(position).data())));
position += sizeof(quint32);
d->wordEntryList.append(wordEntry);
}
}
return wordEntryCountOnPage;
}
QByteArray
OffsetCacheFile::key(long index)
{
loadPage(index / d->pageEntryNumber);
ulong indexInPage = index % d->pageEntryNumber;
setWordEntryOffset(d->wordEntryList.at(indexInPage).dataOffset());
setWordEntrySize(d->wordEntryList.at(indexInPage).dataSize());
return d->wordEntryList.at(indexInPage).data();
}
bool
OffsetCacheFile::load(const QString& completeFilePath, qulonglong fileSize, int wordCount)
{
d->wordCount = wordCount;
if (!loadCache(completeFilePath))
{ //map file will close after finish of block
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(completeFilePath);
if (!d->mapFile.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open file:" << completeFilePath;
return -1;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath);
return false;
}
QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), fileSize);
int position = 0;
d->pageOffsetList.clear();
int wordTerminatorOffsetSizeLength = 1 + 2 * sizeof(quint32);
for (int i = 0; i < wordCount; ++i)
{
if (i % d->pageEntryNumber == 0)
d->pageOffsetList.append(position);
position += qstrlen(byteArray.mid(position)) + wordTerminatorOffsetSizeLength;
}
d->pageOffsetList.append(position);
if (!saveCache(completeFilePath))
qDebug() << "Cache update failed";
}
d->indexFile.setFileName(completeFilePath);
if (!d->indexFile.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open file:" << completeFilePath;
d->pageOffsetList.clear();
return false;
}
d->first = qMakePair(0, readFirstWordDataOnPage(0));
d->last = qMakePair(d->pageOffsetList.size() - 2, readFirstWordDataOnPage(d->pageOffsetList.size() - 2));
d->middle = qMakePair((d->pageOffsetList.size() - 2) / 2, readFirstWordDataOnPage((d->pageOffsetList.size() - 2) / 2));
d->realLast = qMakePair(wordCount - 1, key(wordCount - 1));
return true;
}
bool
OffsetCacheFile::lookupPage(const QByteArray& word, int& pageIndex)
{
bool found = false;
if (stardictStringCompare(word, d->first.second) < 0)
{
pageIndex = invalidIndex;
return false;
}
else if (stardictStringCompare(word, d->realLast.second) > 0)
{
pageIndex = invalidIndex;
return false;
}
else
{
int indexTo = d->pageOffsetList.size() - 2;
int indexFrom = 0;
int indexThisIndex = 0;
int cmpint;
while (indexFrom <= indexTo)
{
indexThisIndex = (indexFrom + indexTo) / 2;
cmpint = stardictStringCompare(word, firstWordDataOnPage(indexThisIndex));
if (cmpint > 0)
indexFrom = indexThisIndex + 1;
else if (cmpint < 0)
indexTo = indexThisIndex - 1;
else
{
found = true;
break;
}
}
if (!found)
pageIndex = indexTo; //prev
else
pageIndex = indexThisIndex;
}
return found;
}
bool
OffsetCacheFile::lookup(const QByteArray& word, int &index)
{
bool found = false;
int indexFrom;
int cmpint;
int indexThisIndex;
int pageIndex;
found = lookupPage(word, pageIndex);
if (!found)
{
ulong netr = loadPage(index);
indexFrom = 1; // Needn't search the first word anymore.
int indexTo = netr - 1;
indexThisIndex = 0;
while (indexFrom <= indexTo)
{
indexThisIndex = (indexFrom + indexTo) / 2;
cmpint = stardictStringCompare(word, d->wordEntryList.at(indexThisIndex).data());
if (cmpint > 0)
indexFrom = indexThisIndex + 1;
else if (cmpint < 0)
indexTo = indexThisIndex - 1;
else
{
found = true;
break;
}
}
index *= d->pageEntryNumber;
if (!found)
index += indexFrom; //next
else
index += indexThisIndex;
}
else
{
index *= d->pageEntryNumber;
}
return found;
}
quint32
OffsetCacheFile::wordEntryOffset() const
{
return AbstractIndexFile::wordEntryOffset();
}
void
OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset)
{
AbstractIndexFile::setWordEntryOffset(wordEntryOffset);
}
quint32
OffsetCacheFile::wordEntrySize() const
{
return AbstractIndexFile::wordEntrySize();
}
void
OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize)
{
AbstractIndexFile::setWordEntrySize(wordEntrySize);
}
<commit_msg>Just use one index instead of mixing up the situation by using two separate ones<commit_after>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@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.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
*/
#include "offsetcachefile.h"
#include "file.h"
#include "wordentry.h"
#include <QtCore/QVector>
#include <QtCore/QFile>
#include <QtCore/QtGlobal>
#include <QtCore/QDir>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QDesktopServices>
#include <arpa/inet.h>
using namespace MulaPluginStarDict;
class OffsetCacheFile::Private
{
public:
Private()
: wordCount(0)
, pageIndex(-1)
, cacheMagicString("StarDict's Cache, Version: 0.1")
, mappedData(0)
{
}
~Private()
{
}
// The length of "word_str" should be less than 256, and then offset, size
static const int wordEntrySize = 256 + sizeof(quint32)*2;
static const int pageEntryNumber = 32;
QVector<quint32> pageOffsetList;
QFile indexFile;
ulong wordCount;
// index/date based key and value pair
QPair<int, QByteArray> first;
QPair<int, QByteArray> last;
QPair<int, QByteArray> middle;
QPair<int, QByteArray> realLast;
long pageIndex;
QList<WordEntry> wordEntryList;
QByteArray cacheMagicString;
QFile mapFile;
uchar *mappedData;
};
OffsetCacheFile::OffsetCacheFile()
: d(new Private)
{
}
OffsetCacheFile::~OffsetCacheFile()
{
}
QByteArray
OffsetCacheFile::readFirstWordDataOnPage(long pageIndex)
{
int pageSize = d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex);
int wordEntrySize = d->wordEntrySize;
d->indexFile.seek(d->pageOffsetList.at(pageIndex));
return d->indexFile.read(qMin(wordEntrySize, pageSize)); //TODO: check returned values, deal with word entry that strlen>255.
}
QByteArray
OffsetCacheFile::firstWordDataOnPage(long pageIndex)
{
if (pageIndex < d->middle.first)
{
if (pageIndex == d->first.first)
return d->first.second;
return readFirstWordDataOnPage(pageIndex);
}
else if (pageIndex > d->middle.first)
{
if (pageIndex == d->last.first)
return d->last.second;
return readFirstWordDataOnPage(pageIndex);
}
else
{
return d->middle.second;
}
}
QStringList
OffsetCacheFile::cacheLocations(const QString& completeFilePath)
{
QStringList result;
result.append(completeFilePath + ".oft");
QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
QFileInfo cacheLocationFileInfo(cacheLocation);
QDir cacheLocationDir;
if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false)
return result;
if (!cacheLocationFileInfo.isDir())
return result;
result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(completeFilePath).fileName() + ".oft");
return result;
}
bool
OffsetCacheFile::loadCache(const QString& completeFilePath)
{
foreach (const QString& cacheLocation, cacheLocations(completeFilePath))
{
QFileInfo fileInfoIndex(completeFilePath);
QFileInfo fileInfoCache(cacheLocation);
if (fileInfoCache.lastModified() < fileInfoIndex.lastModified())
continue;
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(cacheLocation);
if( !d->mapFile.open( QIODevice::ReadOnly ) )
{
qDebug() << "Failed to open file:" << cacheLocation;
return false;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation);
return false;
}
if (d->cacheMagicString != d->mappedData)
continue;
memcpy(d->pageOffsetList.data(), d->mappedData + d->cacheMagicString.size(), d->pageOffsetList.size()*sizeof(d->pageOffsetList.at(0)));
return true;
}
return false;
}
bool
OffsetCacheFile::saveCache(const QString& completeFilePath)
{
foreach (const QString& cacheLocation, cacheLocations(completeFilePath))
{
QFile file(cacheLocation);
if( !file.open( QIODevice::WriteOnly ) )
{
qDebug() << "Failed to open file for writing:" << cacheLocation;
return false;
}
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(cacheLocation);
if( !d->mapFile.open( QIODevice::ReadOnly ) )
{
qDebug() << "Failed to open file:" << cacheLocation;
return false;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation);
return false;
}
if (file.write(d->cacheMagicString) != d->cacheMagicString.size())
continue;
if (file.write(reinterpret_cast<const char*>(d->pageOffsetList.data()), sizeof(d->pageOffsetList.at(0))*d->pageOffsetList.size())
!= d->pageOffsetList.at(0)*d->pageOffsetList.size())
continue;
file.close();
qDebug() << "Save to cache" << completeFilePath;
return true;
}
return false;
}
int
OffsetCacheFile::loadPage(int pageIndex)
{
int wordEntryCountOnPage;
if (pageIndex == (d->pageOffsetList.size() - 2) && (d->wordCount % d->pageEntryNumber) != 0)
wordEntryCountOnPage = d->wordCount % d->pageEntryNumber;
else
wordEntryCountOnPage = d->pageEntryNumber;
if (pageIndex != d->pageIndex)
{
d->pageIndex = pageIndex;
d->indexFile.seek(d->pageOffsetList.at(pageIndex));
QByteArray pageData = d->indexFile.read(d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex));
ulong position = 0;
d->wordEntryList.clear();
d->wordEntryList.reserve(wordEntryCountOnPage);
for (int i = 0; i < wordEntryCountOnPage; ++i)
{
WordEntry wordEntry;
wordEntry.setData(pageData.mid(position));
position = qstrlen(pageData.mid(position)) + 1;
wordEntry.setDataOffset(ntohl(*reinterpret_cast<quint32 *>(pageData.mid(position).data())));
position += sizeof(quint32);
wordEntry.setDataSize(ntohl(*reinterpret_cast<quint32 *>(pageData.mid(position).data())));
position += sizeof(quint32);
d->wordEntryList.append(wordEntry);
}
}
return wordEntryCountOnPage;
}
QByteArray
OffsetCacheFile::key(long index)
{
loadPage(index / d->pageEntryNumber);
ulong indexInPage = index % d->pageEntryNumber;
setWordEntryOffset(d->wordEntryList.at(indexInPage).dataOffset());
setWordEntrySize(d->wordEntryList.at(indexInPage).dataSize());
return d->wordEntryList.at(indexInPage).data();
}
bool
OffsetCacheFile::load(const QString& completeFilePath, qulonglong fileSize, int wordCount)
{
d->wordCount = wordCount;
if (!loadCache(completeFilePath))
{ //map file will close after finish of block
d->mapFile.unmap(d->mappedData);
d->mapFile.setFileName(completeFilePath);
if (!d->mapFile.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open file:" << completeFilePath;
return -1;
}
d->mappedData = d->mapFile.map(0, d->mapFile.size());
if (d->mappedData == NULL)
{
qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath);
return false;
}
QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), fileSize);
int position = 0;
d->pageOffsetList.clear();
int wordTerminatorOffsetSizeLength = 1 + 2 * sizeof(quint32);
for (int i = 0; i < wordCount; ++i)
{
if (i % d->pageEntryNumber == 0)
d->pageOffsetList.append(position);
position += qstrlen(byteArray.mid(position)) + wordTerminatorOffsetSizeLength;
}
d->pageOffsetList.append(position);
if (!saveCache(completeFilePath))
qDebug() << "Cache update failed";
}
d->indexFile.setFileName(completeFilePath);
if (!d->indexFile.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to open file:" << completeFilePath;
d->pageOffsetList.clear();
return false;
}
d->first = qMakePair(0, readFirstWordDataOnPage(0));
d->last = qMakePair(d->pageOffsetList.size() - 2, readFirstWordDataOnPage(d->pageOffsetList.size() - 2));
d->middle = qMakePair((d->pageOffsetList.size() - 2) / 2, readFirstWordDataOnPage((d->pageOffsetList.size() - 2) / 2));
d->realLast = qMakePair(wordCount - 1, key(wordCount - 1));
return true;
}
bool
OffsetCacheFile::lookupPage(const QByteArray& word, int& pageIndex)
{
bool found = false;
if (stardictStringCompare(word, d->first.second) < 0)
{
pageIndex = invalidIndex;
return false;
}
else if (stardictStringCompare(word, d->realLast.second) > 0)
{
pageIndex = invalidIndex;
return false;
}
else
{
int indexTo = d->pageOffsetList.size() - 2;
int indexFrom = 0;
int indexThisIndex = 0;
int cmpint;
while (indexFrom <= indexTo)
{
indexThisIndex = (indexFrom + indexTo) / 2;
cmpint = stardictStringCompare(word, firstWordDataOnPage(indexThisIndex));
if (cmpint > 0)
indexFrom = indexThisIndex + 1;
else if (cmpint < 0)
indexTo = indexThisIndex - 1;
else
{
found = true;
break;
}
}
if (!found)
pageIndex = indexTo; //prev
else
pageIndex = indexThisIndex;
}
return found;
}
bool
OffsetCacheFile::lookup(const QByteArray& word, int &index)
{
bool found = false;
int indexFrom;
int cmpint;
int indexThisIndex;
found = lookupPage(word, index);
if (!found)
{
ulong netr = loadPage(index);
indexFrom = 1; // Needn't search the first word anymore.
int indexTo = netr - 1;
indexThisIndex = 0;
while (indexFrom <= indexTo)
{
indexThisIndex = (indexFrom + indexTo) / 2;
cmpint = stardictStringCompare(word, d->wordEntryList.at(indexThisIndex).data());
if (cmpint > 0)
indexFrom = indexThisIndex + 1;
else if (cmpint < 0)
indexTo = indexThisIndex - 1;
else
{
found = true;
break;
}
}
index *= d->pageEntryNumber;
if (!found)
index += indexFrom; //next
else
index += indexThisIndex;
}
else
{
index *= d->pageEntryNumber;
}
return found;
}
quint32
OffsetCacheFile::wordEntryOffset() const
{
return AbstractIndexFile::wordEntryOffset();
}
void
OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset)
{
AbstractIndexFile::setWordEntryOffset(wordEntryOffset);
}
quint32
OffsetCacheFile::wordEntrySize() const
{
return AbstractIndexFile::wordEntrySize();
}
void
OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize)
{
AbstractIndexFile::setWordEntrySize(wordEntrySize);
}
<|endoftext|>
|
<commit_before>#ifdef PARTICLES
#include<stdio.h>
#include<stdlib.h>
#include"math.h"
#include <iostream>
#include"../global.h"
#include"../grid3D.h"
#include"particles_3D.h"
#ifdef PARALLEL_OMP
#include"../parallel_omp.h"
#endif
Real Grid3D::Calc_Particles_dt( ){
Real dt_particles;
#ifndef PARALLEL_OMP
dt_particles = Calc_Particles_dt_function( 0, Particles.n_local );
#else
dt_particles = 1e100;
Real dt_particles_all[N_OMP_THREADS];
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
dt_particles_all[omp_id] = Calc_Particles_dt_function( p_start, p_end );
}
for ( int i=0; i<N_OMP_THREADS; i++ ){
dt_particles = fmin( dt_particles, dt_particles_all[i]);
}
#endif
Real dt_particles_global;
#ifdef MPI_CHOLLA
dt_particles_global = ReduceRealMin( dt_particles );
#else
dt_particles_global = dt_particles;
#endif
return dt_particles_global;
}
Real Grid3D::Calc_Particles_dt_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt, dt_min, vel;
dt_min = 1e100;
for ( pID=p_start; pID<p_end; pID++ ){
vel = fabs(Particles.vel_x[pID]);
if ( vel > 0){
dt = Particles.G.dx / vel;
dt_min = std::min( dt_min, dt);
}
vel = fabs(Particles.vel_y[pID]);
if ( vel > 0){
dt = Particles.G.dy / vel;
dt_min = std::min( dt_min, dt);
}
vel = fabs(Particles.vel_z[pID]);
if ( vel > 0){
dt = Particles.G.dz / vel;
dt_min = std::min( dt_min, dt);
}
}
return Particles.C_cfl * dt_min;
}
void Grid3D::Advance_Particles( int N_KDK_step ){
#ifdef CPU_TIME
Timer.Start_Timer();
#endif
if ( N_KDK_step == 1 ) Advance_Particles_KDK_Step1();
if ( N_KDK_step == 2 ){
Get_Particles_Accelration();
Advance_Particles_KDK_Step2();
}
#ifdef CPU_TIME
if ( N_KDK_step == 1) Timer.End_and_Record_Time(6);
if ( N_KDK_step == 2) Timer.End_and_Record_Time(7);
#endif
}
void Grid3D::Get_Particles_Accelration(){
// Get the accteleration for all the particles
Get_Gravity_Field_Particles();
Get_Gravity_CIC();
}
void Grid3D::Advance_Particles_KDK_Step1( ){
#ifndef PARALLEL_OMP
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step1_function( 0, Particles.n_local );
#else
Advance_Particles_KDK_Step1_function( 0, Particles.n_local );
#endif//COSMOLOGY
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step1_function( p_start, p_end );
#else
Advance_Particles_KDK_Step1_function( p_start, p_end );
#endif//COSMOLOGY
}
#endif
}
void Grid3D::Advance_Particles_KDK_Step2( ){
#ifndef PARALLEL_OMP
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step2_function( 0, Particles.n_local );
#else
Advance_Particles_KDK_Step2_function( 0, Particles.n_local );
#endif//COSMOLOGY
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step2_function( p_start, p_end );
#else
Advance_Particles_KDK_Step2_function( p_start, p_end );
#endif//COSMOLOGY
}
#endif
}
void Grid3D::Advance_Particles_KDK_Step1_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt = Particles.dt;
// Advance velocities by half a step
for ( pID=p_start; pID<p_end; pID++ ){
Particles.vel_x[pID] += 0.5 * dt * Particles.grav_x[pID];
Particles.vel_y[pID] += 0.5 * dt * Particles.grav_y[pID];
Particles.vel_z[pID] += 0.5 * dt * Particles.grav_z[pID];
}
//Advance Posiotions using advanced velocities
for ( pID=p_start; pID<p_end; pID++ ){
Particles.pos_x[pID] += dt * Particles.vel_x[pID];
Particles.pos_y[pID] += dt * Particles.vel_y[pID];
Particles.pos_z[pID] += dt * Particles.vel_z[pID];
}
}
void Grid3D::Advance_Particles_KDK_Step2_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt = Particles.dt;
// Advance velocities by the second half a step
for ( pID=p_start; pID<p_end; pID++ ){
Particles.vel_x[pID] += 0.5 * dt * Particles.grav_x[pID];
Particles.vel_y[pID] += 0.5 * dt * Particles.grav_y[pID];
Particles.vel_z[pID] += 0.5 * dt * Particles.grav_z[pID];
}
}
#ifdef COSMOLOGY
Real Grid3D::Calc_Particles_dt_Cosmo(){
Real dt_particles;
#ifndef PARALLEL_OMP
dt_particles = Calc_Particles_dt_Cosmo_function( 0, Particles.n_local );
#else
dt_particles = 1e100;
Real dt_particles_all[N_OMP_THREADS];
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
dt_particles_all[omp_id] = Calc_Particles_dt_Cosmo_function( p_start, p_end );
}
for ( int i=0; i<N_OMP_THREADS; i++ ){
dt_particles = fmin( dt_particles, dt_particles_all[i]);
}
#endif
Real dt_particles_global;
#ifdef MPI_CHOLLA
dt_particles_global = ReduceRealMin( dt_particles );
#else
dt_particles_global = dt_particles;
#endif
return dt_particles_global;
}
Real Grid3D::Calc_Particles_dt_Cosmo_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real da, da_min, vel, dt_min;
da_min = 1e100;
Real scale_factor = Cosmo.Scale_Function( Cosmo.current_a , Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real a2 = ( Cosmo.current_a )*( Cosmo.current_a );
Real vel_factor = a2 / scale_factor;
for ( pID=0; pID<Particles.n_local; pID++ ){
vel = fabs(Particles.vel_x[pID]);
if ( vel > 0){
da = Particles.G.dx * vel_factor / vel;
da_min = std::min( da_min, da);
}
vel = fabs(Particles.vel_y[pID]);
if ( vel > 0){
da = Particles.G.dy * vel_factor / vel;
da_min = std::min( da_min, da);
}
vel = fabs(Particles.vel_z[pID]);
if ( vel > 0){
da = Particles.G.dz * vel_factor / vel;
da_min = std::min( da_min, da);
}
}
dt_min = Cosmo.Get_dt_from_da( da_min );
return Particles.C_cfl * dt_min;
}
void Grid3D::Advance_Particles_KDK_Cosmo_Step1_function( part_int_t p_start, part_int_t p_end ){
part_int_t pIndx;
Real da = Cosmo.delta_a;
Real current_a = Cosmo.current_a;
Real scale_factor = Cosmo.Scale_Function( current_a, Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real scale_factor_1 = Cosmo.Scale_Function( current_a + 0.5*da, Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real a2_inv = 1./( ( current_a + 0.5*da )*( current_a + 0.5*da ));
// Advance velocities by half a step
Real pos_x, vel_x, grav_x;
Real pos_y, vel_y, grav_y;
Real pos_z, vel_z, grav_z;
for ( pIndx=p_start; pIndx<p_end; pIndx++ ){
pos_x = Particles.pos_x[pIndx];
pos_y = Particles.pos_y[pIndx];
pos_z = Particles.pos_z[pIndx];
vel_x = Particles.vel_x[pIndx];
vel_y = Particles.vel_y[pIndx];
vel_z = Particles.vel_z[pIndx];
grav_x = Particles.grav_x[pIndx];
grav_y = Particles.grav_y[pIndx];
grav_z = Particles.grav_z[pIndx];
vel_x += scale_factor * 0.5 * da * grav_x;
vel_y += scale_factor * 0.5 * da * grav_y;
vel_z += scale_factor * 0.5 * da * grav_z;
pos_x += a2_inv * scale_factor_1 * da * vel_x;
pos_y += a2_inv * scale_factor_1 * da * vel_y;
pos_z += a2_inv * scale_factor_1 * da * vel_z;
Particles.pos_x[pIndx] = pos_x;
Particles.pos_y[pIndx] = pos_y;
Particles.pos_z[pIndx] = pos_z;
Particles.vel_x[pIndx] = vel_x;
Particles.vel_y[pIndx] = vel_y;
Particles.vel_z[pIndx] = vel_z;
}
}
void Grid3D::Advance_Particles_KDK_Cosmo_Step2_function( part_int_t p_start, part_int_t p_end ){
part_int_t pIndx;
Real da = Cosmo.delta_a;
Real current_a = Cosmo.current_a;
Real scale_factor = Cosmo.Scale_Function( current_a , Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
// Advance velocities by half a step
Real grav_x;
Real grav_y;
Real grav_z;
for ( pIndx=p_start; pIndx<p_end; pIndx++ ){
grav_x = Particles.grav_x[pIndx];
grav_y = Particles.grav_y[pIndx];
grav_z = Particles.grav_z[pIndx];
Particles.vel_x[pIndx] += scale_factor * 0.5 * da * grav_x;
Particles.vel_y[pIndx] += scale_factor * 0.5 * da * grav_y;
Particles.vel_z[pIndx] += scale_factor * 0.5 * da * grav_z;
}
}
#endif
#endif//PARTICLES<commit_msg>optimized dt_particles<commit_after>#ifdef PARTICLES
#include<stdio.h>
#include<stdlib.h>
#include"math.h"
#include <iostream>
#include"../global.h"
#include"../grid3D.h"
#include"particles_3D.h"
#ifdef PARALLEL_OMP
#include"../parallel_omp.h"
#endif
Real Grid3D::Calc_Particles_dt( ){
Real dt_particles;
#ifndef PARALLEL_OMP
dt_particles = Calc_Particles_dt_function( 0, Particles.n_local );
#else
dt_particles = 1e100;
Real dt_particles_all[N_OMP_THREADS];
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
dt_particles_all[omp_id] = Calc_Particles_dt_function( p_start, p_end );
}
for ( int i=0; i<N_OMP_THREADS; i++ ){
dt_particles = fmin( dt_particles, dt_particles_all[i]);
}
#endif
Real dt_particles_global;
#ifdef MPI_CHOLLA
dt_particles_global = ReduceRealMin( dt_particles );
#else
dt_particles_global = dt_particles;
#endif
return dt_particles_global;
}
Real Grid3D::Calc_Particles_dt_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt, dt_min, vel;
dt_min = 1e100;
for ( pID=p_start; pID<p_end; pID++ ){
vel = fabs(Particles.vel_x[pID]);
if ( vel > 0){
dt = Particles.G.dx / vel;
dt_min = std::min( dt_min, dt);
}
vel = fabs(Particles.vel_y[pID]);
if ( vel > 0){
dt = Particles.G.dy / vel;
dt_min = std::min( dt_min, dt);
}
vel = fabs(Particles.vel_z[pID]);
if ( vel > 0){
dt = Particles.G.dz / vel;
dt_min = std::min( dt_min, dt);
}
}
return Particles.C_cfl * dt_min;
}
void Grid3D::Advance_Particles( int N_KDK_step ){
#ifdef CPU_TIME
Timer.Start_Timer();
#endif
if ( N_KDK_step == 1 ) Advance_Particles_KDK_Step1();
if ( N_KDK_step == 2 ){
Get_Particles_Accelration();
Advance_Particles_KDK_Step2();
}
#ifdef CPU_TIME
if ( N_KDK_step == 1) Timer.End_and_Record_Time(6);
if ( N_KDK_step == 2) Timer.End_and_Record_Time(7);
#endif
}
void Grid3D::Get_Particles_Accelration(){
// Get the accteleration for all the particles
Get_Gravity_Field_Particles();
Get_Gravity_CIC();
}
void Grid3D::Advance_Particles_KDK_Step1( ){
#ifndef PARALLEL_OMP
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step1_function( 0, Particles.n_local );
#else
Advance_Particles_KDK_Step1_function( 0, Particles.n_local );
#endif//COSMOLOGY
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step1_function( p_start, p_end );
#else
Advance_Particles_KDK_Step1_function( p_start, p_end );
#endif//COSMOLOGY
}
#endif
}
void Grid3D::Advance_Particles_KDK_Step2( ){
#ifndef PARALLEL_OMP
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step2_function( 0, Particles.n_local );
#else
Advance_Particles_KDK_Step2_function( 0, Particles.n_local );
#endif//COSMOLOGY
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
#ifdef COSMOLOGY
Advance_Particles_KDK_Cosmo_Step2_function( p_start, p_end );
#else
Advance_Particles_KDK_Step2_function( p_start, p_end );
#endif//COSMOLOGY
}
#endif
}
void Grid3D::Advance_Particles_KDK_Step1_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt = Particles.dt;
// Advance velocities by half a step
for ( pID=p_start; pID<p_end; pID++ ){
Particles.vel_x[pID] += 0.5 * dt * Particles.grav_x[pID];
Particles.vel_y[pID] += 0.5 * dt * Particles.grav_y[pID];
Particles.vel_z[pID] += 0.5 * dt * Particles.grav_z[pID];
}
//Advance Posiotions using advanced velocities
for ( pID=p_start; pID<p_end; pID++ ){
Particles.pos_x[pID] += dt * Particles.vel_x[pID];
Particles.pos_y[pID] += dt * Particles.vel_y[pID];
Particles.pos_z[pID] += dt * Particles.vel_z[pID];
}
}
void Grid3D::Advance_Particles_KDK_Step2_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real dt = Particles.dt;
// Advance velocities by the second half a step
for ( pID=p_start; pID<p_end; pID++ ){
Particles.vel_x[pID] += 0.5 * dt * Particles.grav_x[pID];
Particles.vel_y[pID] += 0.5 * dt * Particles.grav_y[pID];
Particles.vel_z[pID] += 0.5 * dt * Particles.grav_z[pID];
}
}
#ifdef COSMOLOGY
Real Grid3D::Calc_Particles_dt_Cosmo(){
Real dt_particles;
#ifndef PARALLEL_OMP
dt_particles = Calc_Particles_dt_Cosmo_function( 0, Particles.n_local );
#else
dt_particles = 1e100;
Real dt_particles_all[N_OMP_THREADS];
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t p_start, p_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Particles_Indxs( Particles.n_local, N_OMP_THREADS, omp_id, &p_start, &p_end );
dt_particles_all[omp_id] = Calc_Particles_dt_Cosmo_function( p_start, p_end );
}
for ( int i=0; i<N_OMP_THREADS; i++ ){
dt_particles = fmin( dt_particles, dt_particles_all[i]);
}
#endif
Real dt_particles_global;
#ifdef MPI_CHOLLA
dt_particles_global = ReduceRealMin( dt_particles );
#else
dt_particles_global = dt_particles;
#endif
return dt_particles_global;
}
Real Grid3D::Calc_Particles_dt_Cosmo_function( part_int_t p_start, part_int_t p_end ){
part_int_t pID;
Real da, da_min, vel, dt_min;
da_min = 1e100;
Real scale_factor = Cosmo.Scale_Function( Cosmo.current_a , Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real a2 = ( Cosmo.current_a )*( Cosmo.current_a );
Real vel_factor = a2 / scale_factor;
Real vx_max, vy_max, vz_max;
vx_max = 0;
vy_max = 0;
vz_max = 0;
for ( pID=p_start; pID<p_end; pID++ ){
vx_max = fmax( vx_max, fabs(Particles.vel_x[pID]) );
vy_max = fmax( vy_max, fabs(Particles.vel_y[pID]) );
vz_max = fmax( vz_max, fabs(Particles.vel_z[pID]) );
}
da_min = fmin( Particles.G.dx / vx_max, Particles.G.dy / vy_max );
da_min = fmin( Particles.G.dz / vz_max, da_min );
da_min *= vel_factor;
dt_min = Cosmo.Get_dt_from_da( da_min );
// for ( pID=0; pID<Particles.n_local; pID++ ){
// vel = fabs(Particles.vel_x[pID]);
// if ( vel > 0){
// da = Particles.G.dx * vel_factor / vel;
// da_min = std::min( da_min, da);
// }
// vel = fabs(Particles.vel_y[pID]);
// if ( vel > 0){
// da = Particles.G.dy * vel_factor / vel;
// da_min = std::min( da_min, da);
// }
// vel = fabs(Particles.vel_z[pID]);
// if ( vel > 0){
// da = Particles.G.dz * vel_factor / vel;
// da_min = std::min( da_min, da);
// }
// }
// dt_min = Cosmo.Get_dt_from_da( da_min );
return Particles.C_cfl * dt_min;
}
void Grid3D::Advance_Particles_KDK_Cosmo_Step1_function( part_int_t p_start, part_int_t p_end ){
part_int_t pIndx;
Real da = Cosmo.delta_a;
Real current_a = Cosmo.current_a;
Real scale_factor = Cosmo.Scale_Function( current_a, Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real scale_factor_1 = Cosmo.Scale_Function( current_a + 0.5*da, Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
Real a2_inv = 1./( ( current_a + 0.5*da )*( current_a + 0.5*da ));
// Advance velocities by half a step
Real pos_x, vel_x, grav_x;
Real pos_y, vel_y, grav_y;
Real pos_z, vel_z, grav_z;
for ( pIndx=p_start; pIndx<p_end; pIndx++ ){
pos_x = Particles.pos_x[pIndx];
pos_y = Particles.pos_y[pIndx];
pos_z = Particles.pos_z[pIndx];
vel_x = Particles.vel_x[pIndx];
vel_y = Particles.vel_y[pIndx];
vel_z = Particles.vel_z[pIndx];
grav_x = Particles.grav_x[pIndx];
grav_y = Particles.grav_y[pIndx];
grav_z = Particles.grav_z[pIndx];
vel_x += scale_factor * 0.5 * da * grav_x;
vel_y += scale_factor * 0.5 * da * grav_y;
vel_z += scale_factor * 0.5 * da * grav_z;
pos_x += a2_inv * scale_factor_1 * da * vel_x;
pos_y += a2_inv * scale_factor_1 * da * vel_y;
pos_z += a2_inv * scale_factor_1 * da * vel_z;
Particles.pos_x[pIndx] = pos_x;
Particles.pos_y[pIndx] = pos_y;
Particles.pos_z[pIndx] = pos_z;
Particles.vel_x[pIndx] = vel_x;
Particles.vel_y[pIndx] = vel_y;
Particles.vel_z[pIndx] = vel_z;
}
}
void Grid3D::Advance_Particles_KDK_Cosmo_Step2_function( part_int_t p_start, part_int_t p_end ){
part_int_t pIndx;
Real da = Cosmo.delta_a;
Real current_a = Cosmo.current_a;
Real scale_factor = Cosmo.Scale_Function( current_a , Cosmo.Omega_M, Cosmo.Omega_L, Cosmo.Omega_K ) / Cosmo.H0 * Cosmo.cosmo_h;
// Advance velocities by half a step
Real grav_x;
Real grav_y;
Real grav_z;
for ( pIndx=p_start; pIndx<p_end; pIndx++ ){
grav_x = Particles.grav_x[pIndx];
grav_y = Particles.grav_y[pIndx];
grav_z = Particles.grav_z[pIndx];
Particles.vel_x[pIndx] += scale_factor * 0.5 * da * grav_x;
Particles.vel_y[pIndx] += scale_factor * 0.5 * da * grav_y;
Particles.vel_z[pIndx] += scale_factor * 0.5 * da * grav_z;
}
}
#endif
#endif//PARTICLES<|endoftext|>
|
<commit_before>/*
* File: SensorSymbols.cpp
* Author: thomas
*
* Created on 9. April 2009, 18:10
*/
#include "SensorSymbols.h"
void SensorSymbols::registerSymbols(xabsl::Engine& engine)
{
engine.registerDecimalInputSymbol("sensor.gyro.x", &getGyrometerData().data.x);
engine.registerDecimalInputSymbol("sensor.gyro.y", &getGyrometerData().data.y);
engine.registerDecimalInputSymbol("sensor.inertial.x", &getInertialSensorX);
engine.registerDecimalInputSymbol("sensor.inertial.y", &getInertialSensorY);
engine.registerBooleanInputSymbol("sensor.inertial.calibrated", &getCalibrationData().calibrated);
engine.registerDecimalInputSymbol("sensor.ultrasound", &getUltraSoundReceiveData().rawdata);
engine.registerDecimalInputSymbol("sensor.ultrasound.left", &simplePassLeftSensor);
engine.registerDecimalInputSymbol("sensor.ultrasound.right", &simplePassRightSensor);
//engine.registerDecimalInputSymbol("platform.battery", &getBatteryData().charge);
engine.registerDecimalInputSymbol("platform.battery", &getBodyState().batteryCharge);
engine.registerEnumElement("fall_down_state", "fall_down_state.undefined", BodyState::undefined);
engine.registerEnumElement("fall_down_state", "fall_down_state.upright", BodyState::upright);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_front", BodyState::lying_on_front);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_back", BodyState::lying_on_back);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_left_side", BodyState::lying_on_left_side);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_right_side", BodyState::lying_on_right_side);
engine.registerEnumeratedInputSymbol("fall_down_state", "fall_down_state", &getFallDownState);
engine.registerDecimalInputSymbol("body.temperature.leg.left", &getBodyState().temperatureLeftLeg);
engine.registerDecimalInputSymbol("body.temperature.leg.right", &getBodyState().temperatureRightLeg);
engine.registerBooleanInputSymbol("body.foot.groundcontact.left", &getBodyState().standByLeftFoot);
engine.registerBooleanInputSymbol("body.foot.groundcontact.right", &getBodyState().standByRightFoot);
engine.registerDecimalInputSymbol("body.foot.groundcontact.statetime", &getFootStateTime);
engine.registerBooleanInputSymbol("body.lifted_up", &getBodyState().isLiftedUp);
engine.registerBooleanInputSymbol("body.collision.arm.left", &getCollisionArmLeft);
engine.registerBooleanInputSymbol("body.collision.arm.right", &getCollisionArmRight);
engine.registerDecimalInputSymbol("platform.frameNumber", &getFrameNumber);
engine.registerDecimalInputSymbol("obstacle.ultrasound.distance", &getObstacleDistance);
engine.registerDecimalInputSymbol("obstacle.ultrasound.left.distance", &getObstacleDistanceLeft);
engine.registerDecimalInputSymbol("obstacle.ultrasound.right.distance", &getObstacleDistanceRight);
engine.registerDecimalInputSymbol("obstacle.ultrasound.blockedtime", &getBlockedTime);
engine.registerBooleanInputSymbol("button.bumper.pressed.left", &getBumperLeftPressed);
engine.registerBooleanInputSymbol("button.bumper.pressed.right", &getBumperRightPressed);
engine.registerBooleanInputSymbol("button.head.pressed.front", &getButtonHeadFront);
engine.registerBooleanInputSymbol("button.head.pressed.middle", &getButtonHeadMiddle);
engine.registerBooleanInputSymbol("button.head.pressed.rear", &getButtonHeadRear);
// deprecated?
engine.registerBooleanInputSymbol("battery.isDischarging", &getBodyState().isDischarging);
engine.registerBooleanInputSymbol("battery.isCharging", &getBodyState().isCharging);
engine.registerBooleanOutputSymbol("audio.capture", &getAudioControl().capture);
}//end registerSymbols
SensorSymbols* SensorSymbols::theInstance = NULL;
SensorSymbols::~SensorSymbols()
{
}
void SensorSymbols::execute()
{
}//end execute
bool SensorSymbols::getBumperLeftPressed()
{
return theInstance->getButtonData().isPressed[ButtonData::LeftFootLeft] || theInstance->getButtonData().isPressed[ButtonData::LeftFootRight];
/*return (theInstance->getButtonData().eventCounter[ButtonData::LeftFootLeft] > 0) ||
(theInstance->getButtonData().eventCounter[ButtonData::LeftFootRight] > 0);*/
}
bool SensorSymbols::getBumperLeftPressed()
{
return theInstance->getButtonData().isPressed[ButtonData::LeftFootLeft] || theInstance->getButtonData().isPressed[ButtonData::LeftFootRight];
/*return (theInstance->getButtonData().eventCounter[ButtonData::LeftFootLeft] > 0) ||
(theInstance->getButtonData().eventCounter[ButtonData::LeftFootRight] > 0);*/
}
bool SensorSymbols::getButtonHeadFront()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadFront]);
}
bool SensorSymbols::getButtonHeadMiddle()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadMiddle]);
}
bool SensorSymbols::getButtonHeadRear()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadRear]);
}
double SensorSymbols::getFrameNumber()
{
return (double) (theInstance->getFrameInfo().getFrameNumber());
}
double SensorSymbols::getFootStateTime()
{
return (double) theInstance->getFrameInfo().getTimeSince(theInstance->getBodyState().foot_state_time);
}
int SensorSymbols::getFallDownState()
{
return (int)(theInstance->getBodyState().fall_down_state);
}
// returns whether some data is received or not
double SensorSymbols::simplePassLeftSensor()
{
double r = 2550.0;
// return minimum measurement = closest object
for(size_t i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++)
{
if((theInstance->getUltraSoundReceiveData().dataLeft[i] * 1000) < r && theInstance->getUltraSoundReceiveData().dataLeft[i] > 0.2)
{
r = theInstance->getUltraSoundReceiveData().dataLeft[i] * 1000;
}
}
return r;
} // end simpleLeftUSSensor
double SensorSymbols::simplePassRightSensor()
{
double r = 2550.0;
// return minimum measurement = closest object
for(size_t i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++)
{
if((theInstance->getUltraSoundReceiveData().dataRight[i] * 1000) < r && theInstance->getUltraSoundReceiveData().dataRight[i] > 0.2)
{
r = theInstance->getUltraSoundReceiveData().dataRight[i] * 1000;
}
}
return r;
} // end simpleRightUSSensor
double SensorSymbols::getObstacleDistance()
{
return theInstance->getObstacleModel().frontDistance;
}
double SensorSymbols::getObstacleDistanceLeft()
{
return theInstance->getObstacleModel().leftDistance;
}
double SensorSymbols::getObstacleDistanceRight()
{
return theInstance->getObstacleModel().rightDistance;
}
double SensorSymbols::getBlockedTime()
{
return theInstance->getObstacleModel().blockedTime;
}
double SensorSymbols::getInertialSensorX()
{
return Math::toDegrees(theInstance->getInertialSensorData().data.x);
}
double SensorSymbols::getInertialSensorY()
{
return Math::toDegrees(theInstance->getInertialSensorData().data.y);
}
bool SensorSymbols::getCollisionArmLeft()
{
return
theInstance->getCollisionPercept().timeCollisionArmLeft > 0 &&
theInstance->getFrameInfo().getTimeSince(theInstance->getCollisionPercept().timeCollisionArmLeft) < 100;
}
bool SensorSymbols::getCollisionArmRight()
{
return
theInstance->getCollisionPercept().timeCollisionArmRight > 0 &&
theInstance->getFrameInfo().getTimeSince(theInstance->getCollisionPercept().timeCollisionArmRight) < 100;
}
<commit_msg>forgot small thing<commit_after>/*
* File: SensorSymbols.cpp
* Author: thomas
*
* Created on 9. April 2009, 18:10
*/
#include "SensorSymbols.h"
void SensorSymbols::registerSymbols(xabsl::Engine& engine)
{
engine.registerDecimalInputSymbol("sensor.gyro.x", &getGyrometerData().data.x);
engine.registerDecimalInputSymbol("sensor.gyro.y", &getGyrometerData().data.y);
engine.registerDecimalInputSymbol("sensor.inertial.x", &getInertialSensorX);
engine.registerDecimalInputSymbol("sensor.inertial.y", &getInertialSensorY);
engine.registerBooleanInputSymbol("sensor.inertial.calibrated", &getCalibrationData().calibrated);
engine.registerDecimalInputSymbol("sensor.ultrasound", &getUltraSoundReceiveData().rawdata);
engine.registerDecimalInputSymbol("sensor.ultrasound.left", &simplePassLeftSensor);
engine.registerDecimalInputSymbol("sensor.ultrasound.right", &simplePassRightSensor);
//engine.registerDecimalInputSymbol("platform.battery", &getBatteryData().charge);
engine.registerDecimalInputSymbol("platform.battery", &getBodyState().batteryCharge);
engine.registerEnumElement("fall_down_state", "fall_down_state.undefined", BodyState::undefined);
engine.registerEnumElement("fall_down_state", "fall_down_state.upright", BodyState::upright);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_front", BodyState::lying_on_front);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_back", BodyState::lying_on_back);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_left_side", BodyState::lying_on_left_side);
engine.registerEnumElement("fall_down_state", "fall_down_state.lying_on_right_side", BodyState::lying_on_right_side);
engine.registerEnumeratedInputSymbol("fall_down_state", "fall_down_state", &getFallDownState);
engine.registerDecimalInputSymbol("body.temperature.leg.left", &getBodyState().temperatureLeftLeg);
engine.registerDecimalInputSymbol("body.temperature.leg.right", &getBodyState().temperatureRightLeg);
engine.registerBooleanInputSymbol("body.foot.groundcontact.left", &getBodyState().standByLeftFoot);
engine.registerBooleanInputSymbol("body.foot.groundcontact.right", &getBodyState().standByRightFoot);
engine.registerDecimalInputSymbol("body.foot.groundcontact.statetime", &getFootStateTime);
engine.registerBooleanInputSymbol("body.lifted_up", &getBodyState().isLiftedUp);
engine.registerBooleanInputSymbol("body.collision.arm.left", &getCollisionArmLeft);
engine.registerBooleanInputSymbol("body.collision.arm.right", &getCollisionArmRight);
engine.registerDecimalInputSymbol("platform.frameNumber", &getFrameNumber);
engine.registerDecimalInputSymbol("obstacle.ultrasound.distance", &getObstacleDistance);
engine.registerDecimalInputSymbol("obstacle.ultrasound.left.distance", &getObstacleDistanceLeft);
engine.registerDecimalInputSymbol("obstacle.ultrasound.right.distance", &getObstacleDistanceRight);
engine.registerDecimalInputSymbol("obstacle.ultrasound.blockedtime", &getBlockedTime);
engine.registerBooleanInputSymbol("button.bumper.pressed.left", &getBumperLeftPressed);
engine.registerBooleanInputSymbol("button.bumper.pressed.right", &getBumperRightPressed);
engine.registerBooleanInputSymbol("button.head.pressed.front", &getButtonHeadFront);
engine.registerBooleanInputSymbol("button.head.pressed.middle", &getButtonHeadMiddle);
engine.registerBooleanInputSymbol("button.head.pressed.rear", &getButtonHeadRear);
// deprecated?
engine.registerBooleanInputSymbol("battery.isDischarging", &getBodyState().isDischarging);
engine.registerBooleanInputSymbol("battery.isCharging", &getBodyState().isCharging);
engine.registerBooleanOutputSymbol("audio.capture", &getAudioControl().capture);
}//end registerSymbols
SensorSymbols* SensorSymbols::theInstance = NULL;
SensorSymbols::~SensorSymbols()
{
}
void SensorSymbols::execute()
{
}//end execute
bool SensorSymbols::getBumperLeftPressed()
{
return theInstance->getButtonData().isPressed[ButtonData::LeftFootLeft] || theInstance->getButtonData().isPressed[ButtonData::LeftFootRight];
/*return (theInstance->getButtonData().eventCounter[ButtonData::LeftFootLeft] > 0) ||
(theInstance->getButtonData().eventCounter[ButtonData::LeftFootRight] > 0);*/
}
bool SensorSymbols::getBumperRightPressed()
{
return theInstance->getButtonData().isPressed[ButtonData::LeftFootLeft] || theInstance->getButtonData().isPressed[ButtonData::LeftFootRight];
/*return (theInstance->getButtonData().eventCounter[ButtonData::LeftFootLeft] > 0) ||
(theInstance->getButtonData().eventCounter[ButtonData::LeftFootRight] > 0);*/
}
bool SensorSymbols::getButtonHeadFront()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadFront]);
}
bool SensorSymbols::getButtonHeadMiddle()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadMiddle]);
}
bool SensorSymbols::getButtonHeadRear()
{
return (theInstance->getButtonData().isPressed[ButtonData::HeadRear]);
}
double SensorSymbols::getFrameNumber()
{
return (double) (theInstance->getFrameInfo().getFrameNumber());
}
double SensorSymbols::getFootStateTime()
{
return (double) theInstance->getFrameInfo().getTimeSince(theInstance->getBodyState().foot_state_time);
}
int SensorSymbols::getFallDownState()
{
return (int)(theInstance->getBodyState().fall_down_state);
}
// returns whether some data is received or not
double SensorSymbols::simplePassLeftSensor()
{
double r = 2550.0;
// return minimum measurement = closest object
for(size_t i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++)
{
if((theInstance->getUltraSoundReceiveData().dataLeft[i] * 1000) < r && theInstance->getUltraSoundReceiveData().dataLeft[i] > 0.2)
{
r = theInstance->getUltraSoundReceiveData().dataLeft[i] * 1000;
}
}
return r;
} // end simpleLeftUSSensor
double SensorSymbols::simplePassRightSensor()
{
double r = 2550.0;
// return minimum measurement = closest object
for(size_t i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++)
{
if((theInstance->getUltraSoundReceiveData().dataRight[i] * 1000) < r && theInstance->getUltraSoundReceiveData().dataRight[i] > 0.2)
{
r = theInstance->getUltraSoundReceiveData().dataRight[i] * 1000;
}
}
return r;
} // end simpleRightUSSensor
double SensorSymbols::getObstacleDistance()
{
return theInstance->getObstacleModel().frontDistance;
}
double SensorSymbols::getObstacleDistanceLeft()
{
return theInstance->getObstacleModel().leftDistance;
}
double SensorSymbols::getObstacleDistanceRight()
{
return theInstance->getObstacleModel().rightDistance;
}
double SensorSymbols::getBlockedTime()
{
return theInstance->getObstacleModel().blockedTime;
}
double SensorSymbols::getInertialSensorX()
{
return Math::toDegrees(theInstance->getInertialSensorData().data.x);
}
double SensorSymbols::getInertialSensorY()
{
return Math::toDegrees(theInstance->getInertialSensorData().data.y);
}
bool SensorSymbols::getCollisionArmLeft()
{
return
theInstance->getCollisionPercept().timeCollisionArmLeft > 0 &&
theInstance->getFrameInfo().getTimeSince(theInstance->getCollisionPercept().timeCollisionArmLeft) < 100;
}
bool SensorSymbols::getCollisionArmRight()
{
return
theInstance->getCollisionPercept().timeCollisionArmRight > 0 &&
theInstance->getFrameInfo().getTimeSince(theInstance->getCollisionPercept().timeCollisionArmRight) < 100;
}
<|endoftext|>
|
<commit_before>#include "ROOT/TDataFrame.hxx"
#include "Compression.h"
#include "TFile.h"
#include "TInterpreter.h"
#include "TRandom.h"
#include "gtest/gtest.h"
using namespace ROOT::Experimental;
namespace TEST_CATEGORY {
int DefineFunction()
{
return 1;
}
struct DefineStruct {
int operator()() { return 1; }
};
void FillTree(const char *filename, const char *treeName, int nevents = 0)
{
TFile f(filename, "RECREATE");
TTree t(treeName, treeName);
t.SetAutoFlush(1); // yes, one event per cluster: to make MT more meaningful
double b1;
int b2;
t.Branch("b1", &b1);
t.Branch("b2", &b2);
for (int i = 0; i < nevents; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
}
}
TEST(TEST_CATEGORY, CreateEmpty)
{
TDataFrame tdf(10);
auto c = tdf.Count();
EXPECT_EQ(10U, *c);
}
TEST(TEST_CATEGORY, CreateZeroEntries)
{
TDataFrame tdf(0);
auto c = tdf.Count();
EXPECT_EQ(0U, *c);
}
TEST(TEST_CATEGORY, CreateZeroEntriesWithBranches)
{
auto filename = "dataframe_simple_0.root";
auto treename = "t";
#ifndef testTDF_simple_0_CREATED
#define testTDF_simple_0_CREATED
TEST_CATEGORY::FillTree(filename, treename);
#endif
TDataFrame tdf(treename, filename);
auto c = tdf.Count();
auto m = tdf.Mean("b1");
EXPECT_EQ(0U, *c);
EXPECT_EQ(0., *m);
}
TEST(TEST_CATEGORY, BuildWithTDirectory)
{
auto filename = "dataframe_simple_1.root";
auto treename = "t";
#ifndef testTDF_simple_1_CREATED
#define testTDF_simple_1_CREATED
TEST_CATEGORY::FillTree(filename, treename, 50);
#endif
TFile f(filename);
TDataFrame tdf(treename, &f);
auto c = tdf.Count();
EXPECT_EQ(50U, *c);
}
// Jitting of column types
TEST(TEST_CATEGORY, TypeGuessing)
{
auto filename = "dataframe_simple_2.root";
auto treename = "t";
#ifndef testTDF_simple_2_CREATED
#define testTDF_simple_2_CREATED
TEST_CATEGORY::FillTree(filename, treename, 50);
#endif
TDataFrame tdf(treename, filename, {"b1"});
auto hcompiled = tdf.Histo1D<double>();
auto hjitted = tdf.Histo1D();
EXPECT_EQ(50, hcompiled->GetEntries());
EXPECT_EQ(50, hjitted->GetEntries());
EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean());
}
// Define
TEST(TEST_CATEGORY, Define_lambda)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", []() { return 1; });
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_function)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", TEST_CATEGORY::DefineFunction);
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_functor)
{
TDataFrame tdf(10);
TEST_CATEGORY::DefineStruct def;
auto d = tdf.Define("i", def);
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_jitted)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", "1");
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_jitted_complex)
{
// The test can be run in sequential and MT mode.
#ifndef RNDM_GEN_CREATED
#define RNDM_GEN_CREATED
gInterpreter->ProcessLine("TRandom r;");
#endif
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("i", "r.Uniform(0.,8.)");
auto m = d.Max("i");
EXPECT_EQ(7.867497533559811628, *m);
}
// Define + Filters
TEST(TEST_CATEGORY, Define_Filter)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter([](double x) { return x > 5; }, {"r"});
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_jitted)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter("r>5");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_named)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_named_jitted)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter("r>5", "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
// jitted Define + Filters
TEST(TEST_CATEGORY, Define_jitted_Filter)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter([](double x) { return x > 5; }, {"r"});
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_jitted)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter("r>5");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_named)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter("r>5", "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Snapshot_update)
{
using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;
SnapshotOptions opts;
opts.fMode = "UPDATE";
TDataFrame tdf1(1000);
auto s1 = tdf1.Define("one", []() { return 1.0; })
.Snapshot<double>("mytree1", "snapshot_test_update.root", {"one"});
EXPECT_EQ(1000U, *s1.Count());
EXPECT_EQ(1.0, *s1.Min("one"));
EXPECT_EQ(1.0, *s1.Max("one"));
EXPECT_EQ(1.0, *s1.Mean("one"));
TDataFrame tdf2(1000);
auto s2 = tdf2.Define("two", []() { return 2.0; })
.Snapshot<double>("mytree2", "snapshot_test_update.root", {"two"}, opts);
EXPECT_EQ(1000U, *s2.Count());
EXPECT_EQ(2.0, *s2.Min("two"));
EXPECT_EQ(2.0, *s2.Max("two"));
EXPECT_EQ(2.0, *s2.Mean("two"));
TFile *f = TFile::Open("snapshot_test_update.root", "READ");
auto mytree1 = (TTree*) f->Get("mytree1");
auto mytree2 = (TTree*) f->Get("mytree2");
EXPECT_NE(nullptr, mytree1);
EXPECT_NE(nullptr, mytree2);
f->Close();
delete f;
}
TEST(TEST_CATEGORY, Snapshot_action_with_options)
{
using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;
SnapshotOptions opts;
opts.fAutoFlush = 10;
opts.fMode = "RECREATE";
for (auto algorithm : { ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4 }) {
TDataFrame tdf(1000);
opts.fCompressionLevel = 6;
opts.fCompressionAlgorithm = algorithm;
auto s = tdf.Define("one", []() { return 1.0; })
.Snapshot<double>("mytree", "snapshot_test_opts.root", {"one"}, opts);
EXPECT_EQ(1000U, *s.Count());
EXPECT_EQ(1.0, *s.Min("one"));
EXPECT_EQ(1.0, *s.Max("one"));
EXPECT_EQ(1.0, *s.Mean("one"));
TFile *f = TFile::Open("snapshot_test_opts.root", "READ");
EXPECT_EQ(algorithm, f->GetCompressionAlgorithm());
EXPECT_EQ(6, f->GetCompressionLevel());
f->Close();
delete f;
}
}
// This tests the interface but we need to run it both w/ and w/o implicit mt
#ifdef R__USE_IMT
TEST(TEST_CATEGORY, GetNSlots)
{
EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots());
}
#endif
<commit_msg>[TDF] Add gtest for `DefineSlot` transformation<commit_after>#include "ROOT/TDataFrame.hxx"
#include "Compression.h"
#include "TFile.h"
#include "TInterpreter.h"
#include "TRandom.h"
#include "gtest/gtest.h"
using namespace ROOT::Experimental;
namespace TEST_CATEGORY {
int DefineFunction()
{
return 1;
}
struct DefineStruct {
int operator()() { return 1; }
};
void FillTree(const char *filename, const char *treeName, int nevents = 0)
{
TFile f(filename, "RECREATE");
TTree t(treeName, treeName);
t.SetAutoFlush(1); // yes, one event per cluster: to make MT more meaningful
double b1;
int b2;
t.Branch("b1", &b1);
t.Branch("b2", &b2);
for (int i = 0; i < nevents; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
}
}
TEST(TEST_CATEGORY, CreateEmpty)
{
TDataFrame tdf(10);
auto c = tdf.Count();
EXPECT_EQ(10U, *c);
}
TEST(TEST_CATEGORY, CreateZeroEntries)
{
TDataFrame tdf(0);
auto c = tdf.Count();
EXPECT_EQ(0U, *c);
}
TEST(TEST_CATEGORY, CreateZeroEntriesWithBranches)
{
auto filename = "dataframe_simple_0.root";
auto treename = "t";
#ifndef testTDF_simple_0_CREATED
#define testTDF_simple_0_CREATED
TEST_CATEGORY::FillTree(filename, treename);
#endif
TDataFrame tdf(treename, filename);
auto c = tdf.Count();
auto m = tdf.Mean("b1");
EXPECT_EQ(0U, *c);
EXPECT_EQ(0., *m);
}
TEST(TEST_CATEGORY, BuildWithTDirectory)
{
auto filename = "dataframe_simple_1.root";
auto treename = "t";
#ifndef testTDF_simple_1_CREATED
#define testTDF_simple_1_CREATED
TEST_CATEGORY::FillTree(filename, treename, 50);
#endif
TFile f(filename);
TDataFrame tdf(treename, &f);
auto c = tdf.Count();
EXPECT_EQ(50U, *c);
}
// Jitting of column types
TEST(TEST_CATEGORY, TypeGuessing)
{
auto filename = "dataframe_simple_2.root";
auto treename = "t";
#ifndef testTDF_simple_2_CREATED
#define testTDF_simple_2_CREATED
TEST_CATEGORY::FillTree(filename, treename, 50);
#endif
TDataFrame tdf(treename, filename, {"b1"});
auto hcompiled = tdf.Histo1D<double>();
auto hjitted = tdf.Histo1D();
EXPECT_EQ(50, hcompiled->GetEntries());
EXPECT_EQ(50, hjitted->GetEntries());
EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean());
}
// Define
TEST(TEST_CATEGORY, Define_lambda)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", []() { return 1; });
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_function)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", TEST_CATEGORY::DefineFunction);
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_functor)
{
TDataFrame tdf(10);
TEST_CATEGORY::DefineStruct def;
auto d = tdf.Define("i", def);
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_jitted)
{
TDataFrame tdf(10);
auto d = tdf.Define("i", "1");
auto m = d.Mean("i");
EXPECT_DOUBLE_EQ(1., *m);
}
TEST(TEST_CATEGORY, Define_jitted_complex)
{
// The test can be run in sequential and MT mode.
#ifndef RNDM_GEN_CREATED
#define RNDM_GEN_CREATED
gInterpreter->ProcessLine("TRandom r;");
#endif
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("i", "r.Uniform(0.,8.)");
auto m = d.Max("i");
EXPECT_EQ(7.867497533559811628, *m);
}
// Define + Filters
TEST(TEST_CATEGORY, Define_Filter)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter([](double x) { return x > 5; }, {"r"});
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_jitted)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter("r>5");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_named)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_Filter_named_jitted)
{
TRandom r(1);
TDataFrame tdf(50);
auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); });
auto df = d.Filter("r>5", "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
// jitted Define + Filters
TEST(TEST_CATEGORY, Define_jitted_Filter)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter([](double x) { return x > 5; }, {"r"});
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_jitted)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter("r>5");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_named)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted)
{
gInterpreter->ProcessLine("r.SetSeed(1);");
TDataFrame tdf(50);
auto d = tdf.Define("r", "r.Uniform(0.,8.)");
auto df = d.Filter("r>5", "myFilter");
auto m = df.Max("r");
EXPECT_EQ(7.867497533559811628, *m);
}
TEST(TEST_CATEGORY, DefineSlot)
{
std::array<int, NSLOTS> values;
for (auto i = 0u; i < NSLOTS; ++i)
values[i] = i;
TDataFrame df(NSLOTS);
auto ddf = df.DefineSlot("s", [values](unsigned int slot) { return values[slot]; });
auto m = ddf.Max("s");
EXPECT_EQ(*m, NSLOTS-1); // no matter the order of processing, the higher slot number is always taken at least once
}
TEST(TEST_CATEGORY, Snapshot_update)
{
using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;
SnapshotOptions opts;
opts.fMode = "UPDATE";
TDataFrame tdf1(1000);
auto s1 = tdf1.Define("one", []() { return 1.0; })
.Snapshot<double>("mytree1", "snapshot_test_update.root", {"one"});
EXPECT_EQ(1000U, *s1.Count());
EXPECT_EQ(1.0, *s1.Min("one"));
EXPECT_EQ(1.0, *s1.Max("one"));
EXPECT_EQ(1.0, *s1.Mean("one"));
TDataFrame tdf2(1000);
auto s2 = tdf2.Define("two", []() { return 2.0; })
.Snapshot<double>("mytree2", "snapshot_test_update.root", {"two"}, opts);
EXPECT_EQ(1000U, *s2.Count());
EXPECT_EQ(2.0, *s2.Min("two"));
EXPECT_EQ(2.0, *s2.Max("two"));
EXPECT_EQ(2.0, *s2.Mean("two"));
TFile *f = TFile::Open("snapshot_test_update.root", "READ");
auto mytree1 = (TTree*) f->Get("mytree1");
auto mytree2 = (TTree*) f->Get("mytree2");
EXPECT_NE(nullptr, mytree1);
EXPECT_NE(nullptr, mytree2);
f->Close();
delete f;
}
TEST(TEST_CATEGORY, Snapshot_action_with_options)
{
using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;
SnapshotOptions opts;
opts.fAutoFlush = 10;
opts.fMode = "RECREATE";
for (auto algorithm : { ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4 }) {
TDataFrame tdf(1000);
opts.fCompressionLevel = 6;
opts.fCompressionAlgorithm = algorithm;
auto s = tdf.Define("one", []() { return 1.0; })
.Snapshot<double>("mytree", "snapshot_test_opts.root", {"one"}, opts);
EXPECT_EQ(1000U, *s.Count());
EXPECT_EQ(1.0, *s.Min("one"));
EXPECT_EQ(1.0, *s.Max("one"));
EXPECT_EQ(1.0, *s.Mean("one"));
TFile *f = TFile::Open("snapshot_test_opts.root", "READ");
EXPECT_EQ(algorithm, f->GetCompressionAlgorithm());
EXPECT_EQ(6, f->GetCompressionLevel());
f->Close();
delete f;
}
}
// This tests the interface but we need to run it both w/ and w/o implicit mt
#ifdef R__USE_IMT
TEST(TEST_CATEGORY, GetNSlots)
{
EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots());
}
#endif
<|endoftext|>
|
<commit_before>//=============================================================================
// ■ audio.cpp
//-----------------------------------------------------------------------------
// 提供声音支持。
//=============================================================================
#include "global.hpp"
namespace Audio {
//-------------------------------------------------------------------------
// ● 全局变量
//-------------------------------------------------------------------------
const size_t vf_buffer_size = 4096;
PaStream* wave_stream;
struct callback_data data;
struct active_sound* active_sounds[16] = {NULL};
size_t active_sound_count = 0;
// 为了避免反复计算,将正弦值存储在这里。其分布为
// [0] = sin 0
// [64] = sin ⅛π
// [128] = sin ¼π
// [192] = sin ⅜π
float sine_table[256];
const size_t sine_table_size = ARRAY_SIZE(sine_table);
//-------------------------------------------------------------------------
// ● 初始化
//-------------------------------------------------------------------------
void init() {
ensure_no_error(Pa_Initialize());
populate_sine_table();
data.type = 0;
// 44100Hz
data.sample_rate = 44100.0d;
ensure_no_error(Pa_OpenDefaultStream(
&wave_stream,
// 无声输入 - 立体声输出、32位浮点数
0, 2, paFloat32,
data.sample_rate,
// 256格缓冲区
256,
play_callback, &data
));
ensure_no_error(Pa_StartStream(wave_stream));
}
//-------------------------------------------------------------------------
// ● 释放
//-------------------------------------------------------------------------
void wobuzhidaozhegefangfayinggaijiaoshenmemingzi() {
ensure_no_error(Pa_StopStream(wave_stream));
ensure_no_error(Pa_CloseStream(wave_stream));
Pa_Terminate();
}
//-------------------------------------------------------------------------
// ● 统一处理错误
//-------------------------------------------------------------------------
void ensure_no_error(PaError err) {
if (err >= 0) return;
Pa_Terminate();
rb_raise(
rb_eRuntimeError,
"PortAudio error %d: %s",
err, Pa_GetErrorText(err)
);
}
//-------------------------------------------------------------------------
// ● 内部使用的回调函数
//-------------------------------------------------------------------------
int play_callback(
const void* input_buffer UNUSED,
void* output_buffer,
unsigned long frame_count,
const PaStreamCallbackTimeInfo* time_info UNUSED,
PaStreamCallbackFlags status_flags UNUSED,
void* user_data
) {
float* output = (float*) output_buffer;
struct callback_data* data = (struct callback_data*) user_data;
// Magic. 吔屎啦PortAudio!
#define FEED_AUDIO_DATA(value) do { \
*output++ = (value); \
*output++ = (value); \
frame_count--; \
} while (false)
while (frame_count > 0) switch (data->type) {
case 0:
FEED_AUDIO_DATA(.0f);
break;
case 1:
get_next_triangle_value(&data->data.triangle);
FEED_AUDIO_DATA(data->data.triangle.value);
break;
case 2:
default:
get_next_sine_value(&data->data.sine);
FEED_AUDIO_DATA(data->data.sine.value);
break;
case 3:
*((float*) 0) = .0f; // 音频就是爆炸!
FEED_AUDIO_DATA(.0f);
break;
case 4:
FEED_AUDIO_DATA((float) (
(double) rand() / (double) RAND_MAX * 2.0d - 1.0d
));
break;
}
#undef FEED_AUDIO_DATA
return paContinue;
}
//-------------------------------------------------------------------------
// ● 停止播放
//-------------------------------------------------------------------------
void stop() {
data.type = 0;
}
//-------------------------------------------------------------------------
// ● 播放三角波
// freq : 频率(Hz)
//-------------------------------------------------------------------------
void play_triangle(float freq) {
data.data.triangle.value = -1.0f;
data.data.triangle.delta = 2.0f / ((float) data.sample_rate / freq / 2);
data.type = 1;
}
//-------------------------------------------------------------------------
// ● 计算下一个值使输出呈三角波形
//-------------------------------------------------------------------------
void get_next_triangle_value(struct triangle_data* data) {
data->value += data->delta;
if (data->value > 1.0f) {
data->value = 2.0f - data->value;
data->delta = -data->delta;
} else if (data->value < -1.0f) {
data->value = -2.0f - data->value;
data->delta = -data->delta;
}
}
//-------------------------------------------------------------------------
// ● 播放正弦波
// freq : 频率(Hz)
//-------------------------------------------------------------------------
void play_sine(float freq) {
data.data.sine.index = .0f;
data.data.sine.index_delta =
sine_table_size / ((float) data.sample_rate / 4 / freq);
data.data.sine.minus = false;
data.type = 2;
}
//-------------------------------------------------------------------------
// ● 向正弦表中填充数据
//-------------------------------------------------------------------------
void populate_sine_table() {
float k = 0.5f / (float) sine_table_size * Util::PIf;
for (size_t i = 0; i < sine_table_size; i++) sine_table[i] = sin(i * k);
}
//-------------------------------------------------------------------------
// ● 计算正弦函数的下一值
//-------------------------------------------------------------------------
void get_next_sine_value(struct sine_data* data) {
data->index += data->index_delta;
if (data->index > (float) sine_table_size) {
data->index = sine_table_size * 2.0f - data->index;
data->index_delta = -data->index_delta;
} else if (data->index < 0) {
data->index = -data->index;
data->index_delta = -data->index_delta;
data->minus = !data->minus;
}
data->value = sine_table[(size_t) (int) data->index];
if (data->minus) data->value = -data->value;
}
//-------------------------------------------------------------------------
// ● 播放声音
//-------------------------------------------------------------------------
void play_sound(const char* filename) {
compact_active_sounds_array();
log("play sound %s", filename);
struct active_sound* sound = new struct active_sound;
sound->stream = NULL;
// sound->file
sound->file = fopen(filename, "rb");
if (!sound->file) {
delete sound;
rb_raise(rb_eIOError, "can't open this file: %s", filename);
}
// sound->vf
if (ov_open_callbacks(
sound->file, &sound->vf,
NULL, 0, OV_CALLBACKS_NOCLOSE
) < 0) {
delete sound;
fclose(sound->file);
rb_raise(rb_eRuntimeError, "can't open ogg vorbis file: %s", filename);
}
// sound->stream
ensure_no_error(Pa_OpenDefaultStream(
&sound->stream, 0, 2, paFloat32, 44100,
256, play_sound_callback, sound
));
// sound->*_head
sound->play_head = 0;
sound->load_head = 0;
// etc
sound->eof = false;
active_sounds[active_sound_count] = sound;
active_sound_count++;
decode_vorbis(sound);
// sound->decode_thread
sound->decode_thread = new thread(decode_vorbis_thread, sound);
ensure_no_error(Pa_StartStream(sound->stream));
}
//-------------------------------------------------------------------------
// ● 扔掉active_sounds中已经播放完的条目
//-------------------------------------------------------------------------
void compact_active_sounds_array() {
size_t size = ARRAY_SIZE(active_sounds);
for (size_t i = 0; i < size; i++) {
if (!active_sounds[i]) continue;
PaError active = Pa_IsStreamActive(active_sounds[i]->stream);
ensure_no_error(active);
if (!active) {
Pa_CloseStream(active_sounds[i]->stream);
ov_clear(&active_sounds[i]->vf);
fclose(active_sounds[i]->file);
delete active_sounds[i]->decode_thread;
delete active_sounds[i];
active_sounds[i] = NULL;
}
}
}
//-------------------------------------------------------------------------
// ● 播放声音的回调函数
//-------------------------------------------------------------------------
int play_sound_callback(
const void* input_buffer UNUSED,
void* output_buffer,
unsigned long frame_count,
const PaStreamCallbackTimeInfo* time_info UNUSED,
PaStreamCallbackFlags status_flags UNUSED,
void* user_data
) {
float* output = (float*) output_buffer;
struct active_sound* sound = (struct active_sound*) user_data;
while (frame_count > 0) {
if (sound->play_head < sound->load_head) {
size_t index = sound->play_head % vf_buffer_size;
//log("%f %f", sound->vf_buffer[0][index], sound->vf_buffer[1][index]);
*output++ = sound->vf_buffer[0][index];
*output++ = sound->vf_buffer[1][index];
sound->play_head++;
} else {
TWICE *output++ = .0f;
}
frame_count--;
}
return sound->eof ? paComplete : paContinue;
}
//-------------------------------------------------------------------------
// ● 解码文件来填active_sound结构中的缓冲区
//-------------------------------------------------------------------------
void decode_vorbis(struct active_sound* sound) {
while (sound->load_head - sound->play_head < vf_buffer_size) {
// After ov_read_float(), tmp_buffer will be changed.
float** tmp_buffer;
long ret = ov_read_float(
&sound->vf,
&tmp_buffer,
vf_buffer_size,
&sound->bitstream
);
if (ret > 0) {
for (long i = 0; i < ret; i++) {
size_t j = (sound->load_head + i) % vf_buffer_size;
sound->vf_buffer[0][j] = tmp_buffer[0][i];
sound->vf_buffer[1][j] = tmp_buffer[1][i];
}
sound->load_head += ret;
} else if (ret == 0) {
while (sound->load_head - sound->play_head < vf_buffer_size) {
size_t j = sound->load_head % vf_buffer_size;
sound->vf_buffer[0][j] = .0f;
sound->vf_buffer[1][j] = .0f;
sound->load_head++;
}
sound->eof = true;
break;
} else if (ret == OV_EBADLINK) {
rb_raise(rb_eIOError, "bad vorbis data (OV_EBADLINK)");
} else if (ret == OV_EINVAL) {
rb_raise(rb_eIOError, "bad vorbis data (OV_EINVAL)");
}
// We must not free(tmp_buffer). It isn't ours.
}
}
//-------------------------------------------------------------------------
// ● 解码线程函数
//-------------------------------------------------------------------------
void decode_vorbis_thread(struct active_sound* sound) {
while (!sound->eof) {
decode_vorbis(sound);
}
}
}
<commit_msg>I'm multi-threaded now!<commit_after>//=============================================================================
// ■ audio.cpp
//-----------------------------------------------------------------------------
// 提供声音支持。
//=============================================================================
#include "global.hpp"
namespace Audio {
//-------------------------------------------------------------------------
// ● 全局变量
//-------------------------------------------------------------------------
const size_t vf_buffer_size = 4096;
PaStream* wave_stream;
struct callback_data data;
struct active_sound* active_sounds[16] = {NULL};
size_t active_sound_count = 0;
// 为了避免反复计算,将正弦值存储在这里。其分布为
// [0] = sin 0
// [64] = sin ⅛π
// [128] = sin ¼π
// [192] = sin ⅜π
float sine_table[256];
const size_t sine_table_size = ARRAY_SIZE(sine_table);
//-------------------------------------------------------------------------
// ● 初始化
//-------------------------------------------------------------------------
void init() {
ensure_no_error(Pa_Initialize());
populate_sine_table();
data.type = 0;
// 44100Hz
data.sample_rate = 44100.0d;
ensure_no_error(Pa_OpenDefaultStream(
&wave_stream,
// 无声输入 - 立体声输出、32位浮点数
0, 2, paFloat32,
data.sample_rate,
// 256格缓冲区
256,
play_callback, &data
));
ensure_no_error(Pa_StartStream(wave_stream));
}
//-------------------------------------------------------------------------
// ● 释放
//-------------------------------------------------------------------------
void wobuzhidaozhegefangfayinggaijiaoshenmemingzi() {
ensure_no_error(Pa_StopStream(wave_stream));
ensure_no_error(Pa_CloseStream(wave_stream));
Pa_Terminate();
}
//-------------------------------------------------------------------------
// ● 统一处理错误
//-------------------------------------------------------------------------
void ensure_no_error(PaError err) {
if (err >= 0) return;
Pa_Terminate();
rb_raise(
rb_eRuntimeError,
"PortAudio error %d: %s",
err, Pa_GetErrorText(err)
);
}
//-------------------------------------------------------------------------
// ● 内部使用的回调函数
//-------------------------------------------------------------------------
int play_callback(
const void* input_buffer UNUSED,
void* output_buffer,
unsigned long frame_count,
const PaStreamCallbackTimeInfo* time_info UNUSED,
PaStreamCallbackFlags status_flags UNUSED,
void* user_data
) {
float* output = (float*) output_buffer;
struct callback_data* data = (struct callback_data*) user_data;
// Magic. 吔屎啦PortAudio!
#define FEED_AUDIO_DATA(value) do { \
*output++ = (value); \
*output++ = (value); \
frame_count--; \
} while (false)
while (frame_count > 0) switch (data->type) {
case 0:
FEED_AUDIO_DATA(.0f);
break;
case 1:
get_next_triangle_value(&data->data.triangle);
FEED_AUDIO_DATA(data->data.triangle.value);
break;
case 2:
default:
get_next_sine_value(&data->data.sine);
FEED_AUDIO_DATA(data->data.sine.value);
break;
case 3:
*((float*) 0) = .0f; // 音频就是爆炸!
FEED_AUDIO_DATA(.0f);
break;
case 4:
FEED_AUDIO_DATA((float) (
(double) rand() / (double) RAND_MAX * 2.0d - 1.0d
));
break;
}
#undef FEED_AUDIO_DATA
return paContinue;
}
//-------------------------------------------------------------------------
// ● 停止播放
//-------------------------------------------------------------------------
void stop() {
data.type = 0;
}
//-------------------------------------------------------------------------
// ● 播放三角波
// freq : 频率(Hz)
//-------------------------------------------------------------------------
void play_triangle(float freq) {
data.data.triangle.value = -1.0f;
data.data.triangle.delta = 2.0f / ((float) data.sample_rate / freq / 2);
data.type = 1;
}
//-------------------------------------------------------------------------
// ● 计算下一个值使输出呈三角波形
//-------------------------------------------------------------------------
void get_next_triangle_value(struct triangle_data* data) {
data->value += data->delta;
if (data->value > 1.0f) {
data->value = 2.0f - data->value;
data->delta = -data->delta;
} else if (data->value < -1.0f) {
data->value = -2.0f - data->value;
data->delta = -data->delta;
}
}
//-------------------------------------------------------------------------
// ● 播放正弦波
// freq : 频率(Hz)
//-------------------------------------------------------------------------
void play_sine(float freq) {
data.data.sine.index = .0f;
data.data.sine.index_delta =
sine_table_size / ((float) data.sample_rate / 4 / freq);
data.data.sine.minus = false;
data.type = 2;
}
//-------------------------------------------------------------------------
// ● 向正弦表中填充数据
//-------------------------------------------------------------------------
void populate_sine_table() {
float k = 0.5f / (float) sine_table_size * Util::PIf;
for (size_t i = 0; i < sine_table_size; i++) sine_table[i] = sin(i * k);
}
//-------------------------------------------------------------------------
// ● 计算正弦函数的下一值
//-------------------------------------------------------------------------
void get_next_sine_value(struct sine_data* data) {
data->index += data->index_delta;
if (data->index > (float) sine_table_size) {
data->index = sine_table_size * 2.0f - data->index;
data->index_delta = -data->index_delta;
} else if (data->index < 0) {
data->index = -data->index;
data->index_delta = -data->index_delta;
data->minus = !data->minus;
}
data->value = sine_table[(size_t) (int) data->index];
if (data->minus) data->value = -data->value;
}
//-------------------------------------------------------------------------
// ● 播放声音
//-------------------------------------------------------------------------
void play_sound(const char* filename) {
compact_active_sounds_array();
log("play sound %s", filename);
struct active_sound* sound = new struct active_sound;
sound->stream = NULL;
// sound->file
sound->file = fopen(filename, "rb");
if (!sound->file) {
delete sound;
rb_raise(rb_eIOError, "can't open this file: %s", filename);
}
// sound->vf
if (ov_open_callbacks(
sound->file, &sound->vf,
NULL, 0, OV_CALLBACKS_NOCLOSE
) < 0) {
delete sound;
fclose(sound->file);
rb_raise(rb_eRuntimeError, "can't open ogg vorbis file: %s", filename);
}
// sound->stream
ensure_no_error(Pa_OpenDefaultStream(
&sound->stream, 0, 2, paFloat32, 44100,
256, play_sound_callback, sound
));
// sound->*_head
sound->play_head = 0;
sound->load_head = 0;
// etc
sound->eof = false;
active_sounds[active_sound_count] = sound;
active_sound_count++;
decode_vorbis(sound);
// sound->decode_thread
sound->decode_thread = new thread(decode_vorbis_thread, sound);
ensure_no_error(Pa_StartStream(sound->stream));
}
//-------------------------------------------------------------------------
// ● 扔掉active_sounds中已经播放完的条目
//-------------------------------------------------------------------------
void compact_active_sounds_array() {
size_t size = ARRAY_SIZE(active_sounds);
for (size_t i = 0; i < size; i++) {
if (!active_sounds[i]) continue;
PaError active = Pa_IsStreamActive(active_sounds[i]->stream);
ensure_no_error(active);
if (!active) {
Pa_CloseStream(active_sounds[i]->stream);
ov_clear(&active_sounds[i]->vf);
fclose(active_sounds[i]->file);
active_sounds[i]->decode_thread->join();
delete active_sounds[i]->decode_thread;
delete active_sounds[i];
active_sounds[i] = NULL;
}
}
}
//-------------------------------------------------------------------------
// ● 播放声音的回调函数
//-------------------------------------------------------------------------
int play_sound_callback(
const void* input_buffer UNUSED,
void* output_buffer,
unsigned long frame_count,
const PaStreamCallbackTimeInfo* time_info UNUSED,
PaStreamCallbackFlags status_flags UNUSED,
void* user_data
) {
float* output = (float*) output_buffer;
struct active_sound* sound = (struct active_sound*) user_data;
while (frame_count > 0) {
if (sound->play_head < sound->load_head) {
size_t index = sound->play_head % vf_buffer_size;
*output++ = sound->vf_buffer[0][index];
*output++ = sound->vf_buffer[1][index];
sound->play_head++;
} else {
TWICE *output++ = .0f;
}
frame_count--;
}
return sound->eof ? paComplete : paContinue;
}
//-------------------------------------------------------------------------
// ● 解码文件来填active_sound结构中的缓冲区
//-------------------------------------------------------------------------
void decode_vorbis(struct active_sound* sound) {
while (sound->load_head - sound->play_head < vf_buffer_size) {
// After ov_read_float(), tmp_buffer will be changed.
float** tmp_buffer;
long ret = ov_read_float(
&sound->vf,
&tmp_buffer,
vf_buffer_size,
&sound->bitstream
);
if (ret > 0) {
for (long i = 0; i < ret; i++) {
size_t j = (sound->load_head + i) % vf_buffer_size;
sound->vf_buffer[0][j] = tmp_buffer[0][i];
sound->vf_buffer[1][j] = tmp_buffer[1][i];
}
sound->load_head += ret;
} else if (ret == 0) {
while (sound->load_head - sound->play_head < vf_buffer_size) {
size_t j = sound->load_head % vf_buffer_size;
sound->vf_buffer[0][j] = .0f;
sound->vf_buffer[1][j] = .0f;
sound->load_head++;
}
sound->eof = true;
break;
} else if (ret == OV_EBADLINK) {
rb_raise(rb_eIOError, "bad vorbis data (OV_EBADLINK)");
} else if (ret == OV_EINVAL) {
rb_raise(rb_eIOError, "bad vorbis data (OV_EINVAL)");
}
// We must not free(tmp_buffer). It isn't ours.
}
}
//-------------------------------------------------------------------------
// ● 解码线程函数
//-------------------------------------------------------------------------
void decode_vorbis_thread(struct active_sound* sound) {
while (!sound->eof) {
decode_vorbis(sound);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Samplebuffer.cpp
*
* Created on: Dec 4, 2013
* Author: gwue
*/
#include "Soundbuffer.hpp"
Soundbuffer::Soundbuffer(unsigned int samplerate)
{
int err;
// Always offer chunks of the same size to ALSA
this->alsaSamples = ALSACHARS / this->getFrameSize();
this->sane = true;
this->running = true;
this->playing = false;
this->writeoffset = 0;
this->readoffset = ALSACHARS;
for (int i = 0; i < SOUNDBUFFERSIZE; i++)
{
this->buffer[i] = 0;
}
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_open(&(this->pcm_handle), "plughw:0,0", stream, 0);
if ((err = snd_pcm_open(&(this->pcm_handle), "plughw:0,0", stream, 0)) < 0)
{
fprintf(stderr, "cannot open audio device (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)
{
fprintf(stderr,
"cannot allocate record hardware parameter structure (%s)\n",
snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)
{
fprintf(stderr, "cannot initialize hardware parameter structure (%s)\n",
snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,
SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
{
fprintf(stderr, "cannot set access type (%s)\n", snd_strerror(err));
this->sane = false;
}
//TODO only one format supported right now. should be made selectable in the future
// Currently, it is set to Unsigned Integer 32 Bit, Little Endian.
// If you change this here, every function that operates on sound data would need to be adjusted accordingly!
if ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,
SND_PCM_FORMAT_S32_LE)) < 0)
{
fprintf(stderr, "cannot set sample format (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,
this->hw_params, 2048)) < 0)
{
fprintf(stderr, "cannot set buffer size (%s)\n", snd_strerror(err));
this->sane = false;
}
//TODO Handling for unsupported sampling rates
unsigned int exact_rate = samplerate;
if ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,
this->hw_params, &exact_rate, 0)) < 0)
{
fprintf(stderr, "cannot set sample rate (%s)\n", snd_strerror(err));
this->sane = false;
}
if (samplerate != exact_rate)
{
printf("Rate %i not supported, set to %i \n", samplerate, exact_rate);
}
// TODO For now, only one channel. Increase this to two channels in the future
if ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,
1)) < 0)
{
fprintf(stderr, "cannot set channel count (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)
{
fprintf(stderr, "cannot set parameters (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_prepare(this->pcm_handle)) < 0)
{
fprintf(stderr, "cannot prepare audio interface for use (%s)\n",
snd_strerror(err));
this->sane = false;
}
// If no errors occured we can create our playback thread
//TODO uncomment this
// if (this->sane)
{
this->bufferThread = boost::thread(&Soundbuffer::run, this);
}
}
void Soundbuffer::run()
{
int nframes;
int err = 0;
snd_pcm_prepare(this->pcm_handle);
while (this->running)
{
// Wait for the playback to start
if (!this->playing)
{
usleep(50000);
}
else
{
nframes = 0;
// Wait for the audio device to become ready (or timeout after a second)
if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
{
fprintf(stderr, "poll failed (%s)\n", snd_strerror(err));
this->running = 0;
}
// Ask the audio device how many frames it can accept
if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
{
fprintf(stderr, "unknown ALSA avail update return value (%s)\n",
snd_strerror(nframes));
this->running = 0;
}
// Only write to the soundcard if alsa requested enough frames
if (nframes >= this->alsaSamples)
{
this->mutex.lock();
char* frames = this->getNextFrames();
if ((err = snd_pcm_writei(this->pcm_handle, frames,
this->alsaSamples)) < 0)
{
fprintf(stderr, "write to audio interface failed (%s)\n",
snd_strerror(err));
this->running = 0;
}
this->mutex.unlock();
}
}
}
}
Soundbuffer::~Soundbuffer()
{
}
char* Soundbuffer::getNextFrames()
{
char* buffer_ptr = this->buffer + this->readoffset;
// Advance readbuffer by ALSACHUNKS
int nextReadOffset = this->readoffset + ALSACHARS;
if (nextReadOffset >= SOUNDBUFFERSIZE)
{
nextReadOffset = 0;
}
if (nextReadOffset == this->writeoffset)
{
std::cerr
<< "Buffer has run dry! This should not happen! Will now play previous samples again!"
<< std::endl;
}
else
{
this->readoffset = nextReadOffset;
}
return buffer_ptr;
}
void Soundbuffer::startPlayback()
{
this->playing = true;
}
void Soundbuffer::stopThread()
{
this->running = false;
this->bufferThread.join();
}
void Soundbuffer::testPlayback()
{
printf("Starting test playback!\n");
int err;
int nframes = 0;
char sine[SOUNDBUFFERSIZE];
double phase = 0;
for (double freq = 27.5; freq < 4187; freq *=
1.0594630943592952645618252949463)
{
printf("Freq: %f\n", freq);
for (int i = 0; i < 50; i++)
{
if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
{
fprintf(stderr, "poll failed (%s)\n", strerror(err));
return;
}
if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
{
fprintf(stderr, "unknown ALSA avail update return value (%d)\n",
nframes);
return;
}
if (nframes > SOUNDBUFFERSIZE / 4)
{
nframes = SOUNDBUFFERSIZE / 4;
}
for (int j = 0; j < nframes; j++)
{
((int*) sine)[j] = (int) (sin(phase) * INT_MAX);
phase += (2 * M_PI / 44100.0) * freq;
if (phase > M_PI * 2)
{
phase -= M_PI * 2;
}
}
if ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)
{
fprintf(stderr, "write to audio interface failed (%s)\n",
snd_strerror(err));
return;
}
}
}
printf("Stopping test playback!\n");
}
void Soundbuffer::fillbuffer(char* data, int size)
{
if ((size & (size - 1)) != 0)
{
std::cerr << "You need to fill the buffer with array sizes x^2"
<< std::endl;
return;
}
if (size >= SOUNDBUFFERSIZE)
{
std::cerr << "Too many samples. Might be at most "
<< SOUNDBUFFERSIZE / 2 << std::endl;
return;
}
while (!this->canAcceptData(size))
{
usleep(100);
}
this->mutex.lock();
for (int i = 0; i < size; i++)
{
this->buffer[this->writeoffset] = data[i];
this->writeoffset++;
if (this->writeoffset >= SOUNDBUFFERSIZE)
{
this->writeoffset = 0;
}
}
this->mutex.unlock();
}
bool Soundbuffer::canAcceptData(int size)
{
int free;
this->mutex.lock();
if (this->writeoffset > this->readoffset)
{
free = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);
}
else if (this->writeoffset < this->readoffset)
{
free = this->readoffset - this->writeoffset;
}
else
{
//write and readoffset equal ---> buffer is full
free = 0;
}
this->mutex.unlock();
if (free >= size)
{
return true;
}
else
{
return false;
}
}
int Soundbuffer::getFrameSize()
{
return 4;
}
<commit_msg>why exactly did i open the audio device twice?<commit_after>/*
* Samplebuffer.cpp
*
* Created on: Dec 4, 2013
* Author: gwue
*/
#include "Soundbuffer.hpp"
Soundbuffer::Soundbuffer(unsigned int samplerate)
{
int err;
// Always offer chunks of the same size to ALSA
this->alsaSamples = ALSACHARS / this->getFrameSize();
this->sane = true;
this->running = true;
this->playing = false;
this->writeoffset = 0;
this->readoffset = ALSACHARS;
for (int i = 0; i < SOUNDBUFFERSIZE; i++)
{
this->buffer[i] = 0;
}
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
if ((err = snd_pcm_open(&(this->pcm_handle), "plughw:0,0", stream, 0)) < 0)
{
fprintf(stderr, "cannot open audio device (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)
{
fprintf(stderr,
"cannot allocate record hardware parameter structure (%s)\n",
snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)
{
fprintf(stderr, "cannot initialize hardware parameter structure (%s)\n",
snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,
SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
{
fprintf(stderr, "cannot set access type (%s)\n", snd_strerror(err));
this->sane = false;
}
//TODO only one format supported right now. should be made selectable in the future
// Currently, it is set to Unsigned Integer 32 Bit, Little Endian.
// If you change this here, every function that operates on sound data would need to be adjusted accordingly!
if ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,
SND_PCM_FORMAT_S32_LE)) < 0)
{
fprintf(stderr, "cannot set sample format (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,
this->hw_params, 2048)) < 0)
{
fprintf(stderr, "cannot set buffer size (%s)\n", snd_strerror(err));
this->sane = false;
}
//TODO Handling for unsupported sampling rates
unsigned int exact_rate = samplerate;
if ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,
this->hw_params, &exact_rate, 0)) < 0)
{
fprintf(stderr, "cannot set sample rate (%s)\n", snd_strerror(err));
this->sane = false;
}
if (samplerate != exact_rate)
{
printf("Rate %i not supported, set to %i \n", samplerate, exact_rate);
}
// TODO For now, only one channel. Increase this to two channels in the future
if ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,
1)) < 0)
{
fprintf(stderr, "cannot set channel count (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)
{
fprintf(stderr, "cannot set parameters (%s)\n", snd_strerror(err));
this->sane = false;
}
if ((err = snd_pcm_prepare(this->pcm_handle)) < 0)
{
fprintf(stderr, "cannot prepare audio interface for use (%s)\n",
snd_strerror(err));
this->sane = false;
}
// If no errors occured we can create our playback thread
//TODO uncomment this
// if (this->sane)
{
this->bufferThread = boost::thread(&Soundbuffer::run, this);
}
}
void Soundbuffer::run()
{
int nframes;
int err = 0;
snd_pcm_prepare(this->pcm_handle);
while (this->running)
{
// Wait for the playback to start
if (!this->playing)
{
usleep(50000);
}
else
{
nframes = 0;
// Wait for the audio device to become ready (or timeout after a second)
if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
{
fprintf(stderr, "poll failed (%s)\n", snd_strerror(err));
this->running = 0;
}
// Ask the audio device how many frames it can accept
if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
{
fprintf(stderr, "unknown ALSA avail update return value (%s)\n",
snd_strerror(nframes));
this->running = 0;
}
// Only write to the soundcard if alsa requested enough frames
if (nframes >= this->alsaSamples)
{
this->mutex.lock();
char* frames = this->getNextFrames();
if ((err = snd_pcm_writei(this->pcm_handle, frames,
this->alsaSamples)) < 0)
{
fprintf(stderr, "write to audio interface failed (%s)\n",
snd_strerror(err));
this->running = 0;
}
this->mutex.unlock();
}
}
}
}
Soundbuffer::~Soundbuffer()
{
}
char* Soundbuffer::getNextFrames()
{
char* buffer_ptr = this->buffer + this->readoffset;
// Advance readbuffer by ALSACHUNKS
int nextReadOffset = this->readoffset + ALSACHARS;
if (nextReadOffset >= SOUNDBUFFERSIZE)
{
nextReadOffset = 0;
}
if (nextReadOffset == this->writeoffset)
{
std::cerr
<< "Buffer has run dry! This should not happen! Will now play previous samples again!"
<< std::endl;
}
else
{
this->readoffset = nextReadOffset;
}
return buffer_ptr;
}
void Soundbuffer::startPlayback()
{
this->playing = true;
}
void Soundbuffer::stopThread()
{
this->running = false;
this->bufferThread.join();
}
void Soundbuffer::testPlayback()
{
printf("Starting test playback!\n");
int err;
int nframes = 0;
char sine[SOUNDBUFFERSIZE];
double phase = 0;
for (double freq = 27.5; freq < 4187; freq *=
1.0594630943592952645618252949463)
{
printf("Freq: %f\n", freq);
for (int i = 0; i < 50; i++)
{
if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
{
fprintf(stderr, "poll failed (%s)\n", strerror(err));
return;
}
if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
{
fprintf(stderr, "unknown ALSA avail update return value (%d)\n",
nframes);
return;
}
if (nframes > SOUNDBUFFERSIZE / 4)
{
nframes = SOUNDBUFFERSIZE / 4;
}
for (int j = 0; j < nframes; j++)
{
((int*) sine)[j] = (int) (sin(phase) * INT_MAX);
phase += (2 * M_PI / 44100.0) * freq;
if (phase > M_PI * 2)
{
phase -= M_PI * 2;
}
}
if ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)
{
fprintf(stderr, "write to audio interface failed (%s)\n",
snd_strerror(err));
return;
}
}
}
printf("Stopping test playback!\n");
}
void Soundbuffer::fillbuffer(char* data, int size)
{
if ((size & (size - 1)) != 0)
{
std::cerr << "You need to fill the buffer with array sizes x^2"
<< std::endl;
return;
}
if (size >= SOUNDBUFFERSIZE)
{
std::cerr << "Too many samples. Might be at most "
<< SOUNDBUFFERSIZE / 2 << std::endl;
return;
}
while (!this->canAcceptData(size))
{
usleep(100);
}
this->mutex.lock();
for (int i = 0; i < size; i++)
{
this->buffer[this->writeoffset] = data[i];
this->writeoffset++;
if (this->writeoffset >= SOUNDBUFFERSIZE)
{
this->writeoffset = 0;
}
}
this->mutex.unlock();
}
bool Soundbuffer::canAcceptData(int size)
{
int free;
this->mutex.lock();
if (this->writeoffset > this->readoffset)
{
free = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);
}
else if (this->writeoffset < this->readoffset)
{
free = this->readoffset - this->writeoffset;
}
else
{
//write and readoffset equal ---> buffer is full
free = 0;
}
this->mutex.unlock();
if (free >= size)
{
return true;
}
else
{
return false;
}
}
int Soundbuffer::getFrameSize()
{
return 4;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreShaderSubRenderState.h"
#include "OgreException.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------
SubRenderState::SubRenderState()
{
}
//-----------------------------------------------------------------------
SubRenderState::~SubRenderState()
{
if (mOtherAccessor.isNull() == false)
{
mOtherAccessor->removeSubRenderStateInstance(this);
}
}
//-----------------------------------------------------------------------
SubRenderStateFactory::~SubRenderStateFactory()
{
assert(mSubRenderStateList.empty() &&
"SubRenderStateFactory::~SubRenderStateFactory -> Sub render states still exists !!!");
}
//-----------------------------------------------------------------------
SubRenderState* SubRenderStateFactory::createInstance()
{
SubRenderState* subRenderState = createInstanceImpl();
mSubRenderStateList.insert(subRenderState);
return subRenderState;
}
//-----------------------------------------------------------------------
SubRenderState* SubRenderStateFactory::createOrRetrieveInstance(SGScriptTranslator* translator)
{
//check if we already create a SRS
SubRenderState* subRenderState = translator->getGeneratedSubRenderState(getType());
if (subRenderState == NULL)
{
//create a new sub render state
subRenderState = SubRenderStateFactory::createInstance();
}
return subRenderState;
}
//-----------------------------------------------------------------------
void SubRenderStateFactory::destroyInstance(SubRenderState* subRenderState)
{
SubRenderStateSetIterator it = mSubRenderStateList.find(subRenderState);
if (it != mSubRenderStateList.end())
{
OGRE_DELETE *it;
mSubRenderStateList.erase(it);
}
}
//-----------------------------------------------------------------------
void SubRenderStateFactory::destroyAllInstances()
{
SubRenderStateSetIterator it;
for (it = mSubRenderStateList.begin(); it != mSubRenderStateList.end(); ++it)
{
OGRE_DELETE *it;
}
mSubRenderStateList.clear();
}
//-----------------------------------------------------------------------
SubRenderState& SubRenderState::operator=(const SubRenderState& rhs)
{
if (getType() != rhs.getType())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Can not copy sub render states of different types !!",
"SubRenderState::operator=");
}
copyFrom(rhs);
SubRenderStateAccessorPtr rhsAccessor = rhs.getAccessor();
rhsAccessor->addSubRenderStateInstance(this);
mOtherAccessor = rhsAccessor;
return *this;
}
//-----------------------------------------------------------------------
bool SubRenderState::createCpuSubPrograms(ProgramSet* programSet)
{
bool result;
// Resolve parameters.
result = resolveParameters(programSet);
if (false == result)
return false;
// Resolve dependencies.
result = resolveDependencies(programSet);
if (false == result)
return false;
// Add function invocations.
result = addFunctionInvocations(programSet);
if (false == result)
return false;
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::resolveParameters(ProgramSet* programSet)
{
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::resolveDependencies(ProgramSet* programSet)
{
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::addFunctionInvocations( ProgramSet* programSet )
{
return true;
}
//-----------------------------------------------------------------------
SubRenderStateAccessorPtr SubRenderState::getAccessor()
{
if (mThisAccessor.isNull())
{
SubRenderStateAccessor* accessor = OGRE_NEW_T(SubRenderStateAccessor, MEMCATEGORY_GENERAL)(this);
mThisAccessor.bind(accessor, SPFM_DELETE_T);
}
return mThisAccessor;
}
//-----------------------------------------------------------------------
SubRenderStateAccessorPtr SubRenderState::getAccessor() const
{
if (mThisAccessor.isNull())
{
SubRenderStateAccessor* accessor = OGRE_NEW_T(SubRenderStateAccessor, MEMCATEGORY_GENERAL)(this);
mThisAccessor.bind(accessor, SPFM_DELETE_T);
}
return mThisAccessor;
}
}
}
<commit_msg>replace plain assert with OgreAssert<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreShaderSubRenderState.h"
#include "OgreException.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------
SubRenderState::SubRenderState()
{
}
//-----------------------------------------------------------------------
SubRenderState::~SubRenderState()
{
if (mOtherAccessor.isNull() == false)
{
mOtherAccessor->removeSubRenderStateInstance(this);
}
}
//-----------------------------------------------------------------------
SubRenderStateFactory::~SubRenderStateFactory()
{
OgreAssert(mSubRenderStateList.empty(),
"SubRenderStateFactory::~SubRenderStateFactory -> Sub render states still exists !!!");
}
//-----------------------------------------------------------------------
SubRenderState* SubRenderStateFactory::createInstance()
{
SubRenderState* subRenderState = createInstanceImpl();
mSubRenderStateList.insert(subRenderState);
return subRenderState;
}
//-----------------------------------------------------------------------
SubRenderState* SubRenderStateFactory::createOrRetrieveInstance(SGScriptTranslator* translator)
{
//check if we already create a SRS
SubRenderState* subRenderState = translator->getGeneratedSubRenderState(getType());
if (subRenderState == NULL)
{
//create a new sub render state
subRenderState = SubRenderStateFactory::createInstance();
}
return subRenderState;
}
//-----------------------------------------------------------------------
void SubRenderStateFactory::destroyInstance(SubRenderState* subRenderState)
{
SubRenderStateSetIterator it = mSubRenderStateList.find(subRenderState);
if (it != mSubRenderStateList.end())
{
OGRE_DELETE *it;
mSubRenderStateList.erase(it);
}
}
//-----------------------------------------------------------------------
void SubRenderStateFactory::destroyAllInstances()
{
SubRenderStateSetIterator it;
for (it = mSubRenderStateList.begin(); it != mSubRenderStateList.end(); ++it)
{
OGRE_DELETE *it;
}
mSubRenderStateList.clear();
}
//-----------------------------------------------------------------------
SubRenderState& SubRenderState::operator=(const SubRenderState& rhs)
{
if (getType() != rhs.getType())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Can not copy sub render states of different types !!",
"SubRenderState::operator=");
}
copyFrom(rhs);
SubRenderStateAccessorPtr rhsAccessor = rhs.getAccessor();
rhsAccessor->addSubRenderStateInstance(this);
mOtherAccessor = rhsAccessor;
return *this;
}
//-----------------------------------------------------------------------
bool SubRenderState::createCpuSubPrograms(ProgramSet* programSet)
{
bool result;
// Resolve parameters.
result = resolveParameters(programSet);
if (false == result)
return false;
// Resolve dependencies.
result = resolveDependencies(programSet);
if (false == result)
return false;
// Add function invocations.
result = addFunctionInvocations(programSet);
if (false == result)
return false;
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::resolveParameters(ProgramSet* programSet)
{
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::resolveDependencies(ProgramSet* programSet)
{
return true;
}
//-----------------------------------------------------------------------
bool SubRenderState::addFunctionInvocations( ProgramSet* programSet )
{
return true;
}
//-----------------------------------------------------------------------
SubRenderStateAccessorPtr SubRenderState::getAccessor()
{
if (mThisAccessor.isNull())
{
SubRenderStateAccessor* accessor = OGRE_NEW_T(SubRenderStateAccessor, MEMCATEGORY_GENERAL)(this);
mThisAccessor.bind(accessor, SPFM_DELETE_T);
}
return mThisAccessor;
}
//-----------------------------------------------------------------------
SubRenderStateAccessorPtr SubRenderState::getAccessor() const
{
if (mThisAccessor.isNull())
{
SubRenderStateAccessor* accessor = OGRE_NEW_T(SubRenderStateAccessor, MEMCATEGORY_GENERAL)(this);
mThisAccessor.bind(accessor, SPFM_DELETE_T);
}
return mThisAccessor;
}
}
}
<|endoftext|>
|
<commit_before>
#include "ioFrogs.h"
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#include <MQTTSender.h>
#include <DHT.h>
#include <Adafruit_TSL2591.h>
#include <TemperatureSensor.h>
#include <HumiditySensor.h>
#include <LuminositySensor.h>
#include <TemperatureLogger.h>
#include <HumidityLogger.h>
#include <LuminosityLogger.h>
#include <MQTTTemperatureListener.h>
#include <MQTTLuminosityListener.h>
#include <MQTTHumidityListener.h>
EthernetClient c;
IPStack * ipstack;
MQTT::Client<IPStack, Countdown>* client;
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x76, 0xEC }; // replace with your device's MAC
DHT * dht;
DHTTemperatureSensorAdapter* temperatureSensor;
DHTHumiditySensorAdapter* humiditySensor;
Adafruit_TSL2591* tsl;
TSL2591LuminositySensorAdapter* luminositySensor;
MQTTTemperatureListener* mqttTempListener;
MQTTHumidityListener* mqttHumListener;
MQTTLuminosityListener* mqttLuminosityListener;
TemperatureLogger* tempListener;
HumidityLogger* humListener;
LuminosityLogger* luminosityListener;
void connect() {
char hostname[] = "192.168.1.4";
int port = 1883;
Serial.print("Connecting to ");
Serial.print(hostname);
Serial.print(":");
Serial.println(port);
int rc = ipstack->connect(hostname, port);
if (rc != 1) {
Serial.print("rc from TCP connect is ");
Serial.println(rc);
}
Serial.println("MQTT connecting");
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = (char*) "arduino-sample";
rc = client->connect(data);
if (rc != 0) {
Serial.print("rc from MQTT connect is ");
Serial.println(rc);
}
Serial.println("MQTT connected");
}
void setup() {
Serial.begin(9600);
dht = new DHT(2, DHT22);
dht->begin();
tsl = new Adafruit_TSL2591(2591);
tsl->begin();
temperatureSensor = new DHTTemperatureSensorAdapter(dht);
tempListener = new TemperatureLogger();
temperatureSensor->attach(tempListener);
humiditySensor = new DHTHumiditySensorAdapter(dht);
humListener = new HumidityLogger();
humiditySensor->attach(humListener);
luminositySensor = new TSL2591LuminositySensorAdapter(tsl);
luminosityListener = new LuminosityLogger();
luminositySensor->attach(luminosityListener);
/**/
Ethernet.begin(mac);
ipstack = new IPStack(c);
client = new MQTT::Client<IPStack, Countdown>(*ipstack);
connect();
/**/
mqttTempListener = new MQTTTemperatureListener(client);
temperatureSensor->attach(mqttTempListener);
/**/
mqttHumListener = new MQTTHumidityListener(client);
humiditySensor->attach(mqttHumListener);
/**/
mqttLuminosityListener = new MQTTLuminosityListener(client);
luminositySensor->attach(mqttLuminosityListener);
/**/
}
void loop() {
if (!client->isConnected())
connect();
temperatureSensor->update(millis());
humiditySensor->update(millis());
luminositySensor->update(millis());
delay(1000);
}
<commit_msg>refactoring du programme principal<commit_after>
#include "ioFrogs.h"
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#include <MQTTSender.h>
#include <DHT.h>
#include <Adafruit_TSL2591.h>
#include <TemperatureSensor.h>
#include <HumiditySensor.h>
#include <LuminositySensor.h>
#include <TemperatureLogger.h>
#include <HumidityLogger.h>
#include <LuminosityLogger.h>
#include <MQTTTemperatureListener.h>
#include <MQTTLuminosityListener.h>
#include <MQTTHumidityListener.h>
EthernetClient* ethernetClient;
IPStack* ipstack;
MQTT::Client<IPStack, Countdown>* mqttClient;
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x76, 0xEC }; // replace with your device's MAC
DHT * dht;
DHTTemperatureSensorAdapter* temperatureSensor;
DHTHumiditySensorAdapter* humiditySensor;
Adafruit_TSL2591* tsl;
TSL2591LuminositySensorAdapter* luminositySensor;
MQTTTemperatureListener* mqttTempListener;
MQTTHumidityListener* mqttHumListener;
MQTTLuminosityListener* mqttLuminosityListener;
TemperatureLogger* tempListener;
HumidityLogger* humListener;
LuminosityLogger* luminosityListener;
void connectToServer() {
char hostname[] = "192.168.1.4";
int port = 1883;
Serial.print("Connecting to ");
Serial.print(hostname);
Serial.print(":");
Serial.print(port);
Serial.print("...");
int rc = ipstack->connect(hostname, port);
if (rc != 1) {
Serial.print("rc from TCP connect is ");
Serial.println(rc);
}
Serial.println("OK");
}
void connectToMQTT(){
Serial.print("MQTT connecting...");
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = (char*) "terrarium";
int rc = mqttClient->connect(data);
if (rc != 0) {
Serial.print("rc from MQTT connect is ");
Serial.println(rc);
}
Serial.println("OK");
}
void connect(){
connectToServer();
connectToMQTT();
}
void MQTTListenersAttachment() {
Serial.println("MQTT Listener attachment...");
mqttTempListener = new MQTTTemperatureListener(mqttClient);
temperatureSensor->attach(mqttTempListener);
mqttHumListener = new MQTTHumidityListener(mqttClient);
humiditySensor->attach(mqttHumListener);
mqttLuminosityListener = new MQTTLuminosityListener(mqttClient);
luminositySensor->attach(mqttLuminosityListener);
Serial.println("OK");
}
void loggersAttachment() {
Serial.print("Loggers attachment...");
tempListener = new TemperatureLogger();
temperatureSensor->attach(tempListener);
humListener = new HumidityLogger();
humiditySensor->attach(humListener);
luminosityListener = new LuminosityLogger();
luminositySensor->attach(luminosityListener);
Serial.println("OK");
}
void initializeSensorAdapters() {
Serial.print("Sensor Adapter Initialisation...");
temperatureSensor = new DHTTemperatureSensorAdapter(dht);
humiditySensor = new DHTHumiditySensorAdapter(dht);
luminositySensor = new TSL2591LuminositySensorAdapter(tsl);
Serial.println("OK");
}
void initializeLuminositySensor() {
Serial.print("TSL2591 Initialisation...");
tsl = new Adafruit_TSL2591(2591);
tsl->begin();
Serial.println("OK");
}
void initializeTemperatureHumiditySensor() {
/**/
Serial.print("DHT Initialisation...");
dht = new DHT(2, DHT11);
dht->begin();
Serial.println("OK");
}
void initializeNetwork() {
/**/
Serial.print("Etherner Shield Initialisation...");
Ethernet.begin(mac);
ethernetClient = new EthernetClient();
ipstack = new IPStack(*ethernetClient);
mqttClient = new MQTT::Client<IPStack, Countdown>(*ipstack);
Serial.println("OK\n");
}
void setup() {
Serial.begin(9600);
Serial.println("=== Internet Of Frogs ===");
Serial.println("By Carole Lai Tong and geeks from LAB");
Serial.println("Sponsorised by W4");
Serial.println("");
initializeTemperatureHumiditySensor();
initializeLuminositySensor();
initializeSensorAdapters();
loggersAttachment();
initializeNetwork();
connect();
MQTTListenersAttachment();
Serial.println("=========================");
}
void loop() {
if (!mqttClient->isConnected())
connect();
temperatureSensor->update(millis());
humiditySensor->update(millis());
luminositySensor->update(millis());
delay(1000);
}
<|endoftext|>
|
<commit_before>// Day18.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
constexpr size_t Rows = 40;
typedef std::vector<bool> Row;
typedef std::array <Row, Rows> Board;
Board PopulateBoard(const std::string & Input, size_t & SafeTiles);
int main()
{
std::string Line = GetFileLines("Input.txt")[0];
size_t SafeTiles;
Board Floor = PopulateBoard(Line, SafeTiles);
std::cout << "Safe Tiles: " << SafeTiles << std::endl;
system("pause");
return 0;
}
Row FillRow(const std::string & Input, size_t & SafeTiles)
{
Row NewRow;
NewRow.reserve(Input.size());
for (char Field : Input)
{
bool IsSafeTile = (Field == '.');
NewRow.push_back(IsSafeTile);
SafeTiles += IsSafeTile ? 1 : 0;
}
return NewRow;
}
bool IsSafe(const Row & PreviousRow, size_t Index)
{
bool Left = (Index > 0) ? PreviousRow[Index - 1] : true;
bool Right = (Index < (PreviousRow.size() - 1)) ? PreviousRow[Index + 1] : true;
return (Left == Right);
}
Row ComputeRow(const Row & PreviousRow, size_t & SafeTiles)
{
Row NewRow;
NewRow.reserve(PreviousRow.size());
for (size_t i = 0; i < PreviousRow.size(); i++)
{
bool IsSafeTile = IsSafe(PreviousRow, i);
NewRow.push_back(IsSafeTile);
SafeTiles += IsSafeTile ? 1 : 0;
}
return NewRow;
}
Board PopulateBoard(const std::string & Input, size_t & SafeTiles)
{
SafeTiles = 0;
Board Floor;
Floor[0] = FillRow(Input, SafeTiles);
for (size_t i = 1; i < Rows; i++)
{
Floor[i] = ComputeRow(Floor[i - 1], SafeTiles);
}
return Floor;
}<commit_msg>Day18 part two<commit_after>// Day18.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
constexpr size_t PartOne = 40;
constexpr size_t PartTwo = 400000;
typedef std::vector<bool> Row;
size_t ComputeRow(const std::string & Input, size_t RowCount);
int main()
{
std::string Line = GetFileLines("Input.txt")[0];
std::cout << PartOne << ": " << ComputeRow(Line, PartOne) << std::endl;
std::cout << PartOne << ": " << ComputeRow(Line, PartTwo) << std::endl;
system("pause");
return 0;
}
Row FillRow(const std::string & Input, size_t & SafeTiles)
{
Row NewRow;
NewRow.reserve(Input.size());
for (char Field : Input)
{
bool IsSafeTile = (Field == '.');
NewRow.push_back(IsSafeTile);
SafeTiles += IsSafeTile ? 1 : 0;
}
return NewRow;
}
bool IsSafe(const Row & PreviousRow, size_t Index)
{
bool Left = (Index > 0) ? PreviousRow[Index - 1] : true;
bool Right = (Index < (PreviousRow.size() - 1)) ? PreviousRow[Index + 1] : true;
return (Left == Right);
}
Row ComputeRow(const Row & PreviousRow, size_t & SafeTiles)
{
Row NewRow;
NewRow.reserve(PreviousRow.size());
for (size_t i = 0; i < PreviousRow.size(); i++)
{
bool IsSafeTile = IsSafe(PreviousRow, i);
NewRow.push_back(IsSafeTile);
SafeTiles += IsSafeTile ? 1 : 0;
}
return NewRow;
}
size_t ComputeRow(const std::string & Input, size_t RowCount)
{
size_t SafeTiles = 0;
Row CurrentRow = FillRow(Input, SafeTiles);
for (size_t i = 1; i < RowCount; i++)
{
Row NextRow = ComputeRow(CurrentRow, SafeTiles);
std::swap(CurrentRow, NextRow);
}
return SafeTiles;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTextFrameContext.hxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:08:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX
#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; class XTextContent; }
} } }
class SvXMLAttributeList;
class XMLTextFrameContextHyperlink_Impl;
class XMLTextFrameContext : public SvXMLImportContext
{
::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > m_xAttrList;
SvXMLImportContextRef m_xImplContext;
SvXMLImportContextRef m_xReplImplContext;
SvXMLAttributeList *m_pAttrList;
XMLTextFrameContextHyperlink_Impl *m_pHyperlink;
::rtl::OUString m_sDesc;
::com::sun::star::text::TextContentAnchorType m_eDefaultAnchorType;
// --> OD 2006-03-10 #i51726#
// The <draw:name> can longer be used to distinguish Writer graphic/text box
// objects and Draw graphic/text box objects.
// The new distinguish attribute is the parent style of the automatic style
// of the object. All Draw objects have an automatic style without a parent style.
sal_Bool m_HasAutomaticStyleWithoutParentStyle;
// <--
sal_Bool m_bSupportsReplacement;
sal_Bool CreateIfNotThere();
sal_Bool CreateIfNotThere( ::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet >& rPropSet );
public:
TYPEINFO();
XMLTextFrameContext( SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
::com::sun::star::text::TextContentAnchorType eDfltAnchorType );
virtual ~XMLTextFrameContext();
virtual void EndElement();
SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
void SetHyperlink( const ::rtl::OUString& rHRef,
const ::rtl::OUString& rName,
const ::rtl::OUString& rTargetFrameName,
sal_Bool bMap );
::com::sun::star::text::TextContentAnchorType GetAnchorType() const;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextContent > GetTextContent() const;
// --> OD 2004-08-24 #i33242#
::com::sun::star::uno::Reference <
::com::sun::star::drawing::XShape > GetShape() const;
// <--
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.24.162); FILE MERGED 2008/04/01 13:05:30 thb 1.24.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:37 rt 1.24.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTextFrameContext.hxx,v $
* $Revision: 1.25 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX
#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif
#include <xmloff/xmlictxt.hxx>
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; class XTextContent; }
} } }
class SvXMLAttributeList;
class XMLTextFrameContextHyperlink_Impl;
class XMLTextFrameContext : public SvXMLImportContext
{
::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > m_xAttrList;
SvXMLImportContextRef m_xImplContext;
SvXMLImportContextRef m_xReplImplContext;
SvXMLAttributeList *m_pAttrList;
XMLTextFrameContextHyperlink_Impl *m_pHyperlink;
::rtl::OUString m_sDesc;
::com::sun::star::text::TextContentAnchorType m_eDefaultAnchorType;
// --> OD 2006-03-10 #i51726#
// The <draw:name> can longer be used to distinguish Writer graphic/text box
// objects and Draw graphic/text box objects.
// The new distinguish attribute is the parent style of the automatic style
// of the object. All Draw objects have an automatic style without a parent style.
sal_Bool m_HasAutomaticStyleWithoutParentStyle;
// <--
sal_Bool m_bSupportsReplacement;
sal_Bool CreateIfNotThere();
sal_Bool CreateIfNotThere( ::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet >& rPropSet );
public:
TYPEINFO();
XMLTextFrameContext( SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
::com::sun::star::text::TextContentAnchorType eDfltAnchorType );
virtual ~XMLTextFrameContext();
virtual void EndElement();
SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
void SetHyperlink( const ::rtl::OUString& rHRef,
const ::rtl::OUString& rName,
const ::rtl::OUString& rTargetFrameName,
sal_Bool bMap );
::com::sun::star::text::TextContentAnchorType GetAnchorType() const;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextContent > GetTextContent() const;
// --> OD 2004-08-24 #i33242#
::com::sun::star::uno::Reference <
::com::sun::star::drawing::XShape > GetShape() const;
// <--
};
#endif
<|endoftext|>
|
<commit_before>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#if !defined(CLI_BUILD)
#include "HackerRank.h"
#endif
typedef vector< vector<bool> > AdjacencyMatrix;
// for each leaf node return 1 as the weight of the edge that leads to it
// for non-leaf nodes, return sum of all the outcoming edges
// if an node returns an even number, that means that edge that leads to that node
// has even weight, that means there's even number of nodes on each side of that edge
// thus it splits the tree in two even components
// so if the weight is even, increas the count of edges to be removed by 1
int TraceGraph(const AdjacencyMatrix &graph, int vertex, vector<bool> &visited, int *count) {
// Mark as visited
visited[vertex] = true;
// Use 1 as default (will be the value for leaf nodes)
int weight = 1;
// Walk adjacent vertices
for (int i = 0; i < graph.size(); i++) {
if (visited[i]) { continue; }
if (graph[vertex][i]) {
// Trace each edge from this node
int w = TraceGraph(graph, i, visited, count);
// Check if that edge leads to another even tree
if (w % 2 == 0) {
*count += 1;
}
// Count total nodes, including current one
weight += w;
}
}
return weight;
}
int CountComponents(const AdjacencyMatrix &graph) {
// pick any vertex to start from and do a DFS search to put proper weights on the edges (aka count things)
// assume that input has no gaps in vertex indeces and pick 0 as starting vertex
vector<bool> visited(graph.size());
int count = 0;
TraceGraph(graph, 0, visited, &count);
return count;
}
void evenTreeCpp() {
int n, m;
cin >> n >> m;
// cout << n << m << endl;
// Adjacency matrix, aka graph representation
AdjacencyMatrix graph(n);
for (int i = 0; i < n; i++) {
graph[i] = vector<bool>(n);
}
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u - 1][v - 1] = true;
graph[v - 1][u - 1] = true;
}
cout << CountComponents(graph) << endl;
}
#ifdef CLI_BUILD
int main() {
evenTreeCpp();
return 0;
}
#endif
<commit_msg>Minor refactoring<commit_after>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#if !defined(CLI_BUILD)
#include "HackerRank.h"
#endif
typedef vector< vector<bool> > AdjacencyMatrix;
// for each leaf node return 1 as the weight of the edge that leads to it
// for non-leaf nodes, return sum of all the outcoming edges
// if an node returns an even number, that means that edge that leads to that node
// has even weight, that means there's even number of nodes on each side of that edge
// thus it splits the tree in two even components
// so if the weight is even, increas the count of edges to be removed by 1
int TraceGraph(const AdjacencyMatrix &graph, int vertex, vector<bool> &visited, int *count) {
// Mark as visited
visited[vertex] = true;
// Use 1 as default (will be the value for leaf nodes)
int weight = 1;
// Walk adjacent vertices
for (int i = 0; i < graph.size(); i++) {
if (visited[i]) { continue; }
if (graph[vertex][i]) {
// Trace each edge from this node
int w = TraceGraph(graph, i, visited, count);
// Check if that edge leads to another even tree
if (w % 2 == 0) {
*count += 1;
}
// Count total nodes, including current one
weight += w;
}
}
return weight;
}
int CountEdges(const AdjacencyMatrix &graph) {
// pick any vertex to start from and do a DFS search to put proper weights on the edges (aka count things)
// assume that input has no gaps in vertex indeces and pick 0 as starting vertex
vector<bool> visited(graph.size());
int count = 0;
TraceGraph(graph, 0, visited, &count);
return count;
}
void evenTreeCpp() {
int n, m;
cin >> n >> m;
// cout << n << m << endl;
// Adjacency matrix, aka graph representation
AdjacencyMatrix graph(n);
for (int i = 0; i < n; i++) {
graph[i] = vector<bool>(n);
}
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u - 1][v - 1] = true;
graph[v - 1][u - 1] = true;
}
cout << CountEdges(graph) << endl;
}
#ifdef CLI_BUILD
int main() {
evenTreeCpp();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/lite/c/common.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/benchmarks/micro_benchmark.h"
#include "tensorflow/lite/micro/examples/person_detection/model_settings.h"
#include "tensorflow/lite/micro/examples/person_detection/no_person_image_data.h"
#include "tensorflow/lite/micro/examples/person_detection/person_detect_model_data.h"
#include "tensorflow/lite/micro/examples/person_detection/person_image_data.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_utils.h"
#include "tensorflow/lite/schema/schema_generated.h"
/*
* Person Detection benchmark. Evaluates runtime performance of the visual
* wakewords person detection model. This is the same model found in
* exmaples/person_detection.
*/
namespace tflite {
using PersonDetectionOpResolver = tflite::AllOpsResolver;
using PersonDetectionBenchmarkRunner = MicroBenchmarkRunner<int8_t>;
// Create an area of memory to use for input, output, and intermediate arrays.
// Align arena to 16 bytes to avoid alignment warnings on certain platforms.
constexpr int kTensorArenaSize = 135 * 1024;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];
uint8_t op_resolver_buffer[sizeof(PersonDetectionOpResolver)];
uint8_t benchmark_runner_buffer[sizeof(PersonDetectionBenchmarkRunner)];
// Initialize benchmark runner instance explicitly to avoid global init order
// issues on Sparkfun. Use new since static variables within a method
// are automatically surrounded by locking, which breaks bluepill and stm32f4.
PersonDetectionBenchmarkRunner* CreateBenchmarkRunner(MicroProfiler* profiler) {
// We allocate PersonDetectionOpResolver from a global buffer
// because the object's lifetime must exceed that of the
// PersonDetectionBenchmarkRunner object.
return new (benchmark_runner_buffer) PersonDetectionBenchmarkRunner(
g_person_detect_model_data,
new (op_resolver_buffer) PersonDetectionOpResolver(), tensor_arena,
kTensorArenaSize, profiler);
}
void PersonDetectionNIerations(const int8_t* input, int iterations,
const char* tag,
PersonDetectionBenchmarkRunner& benchmark_runner,
MicroProfiler& profiler) {
benchmark_runner.SetInput(input);
int32_t ticks = 0;
for (int i = 0; i < iterations; ++i) {
profiler.ClearEvents();
benchmark_runner.RunSingleIteration();
ticks += profiler.GetTotalTicks();
}
MicroPrintf("%s took %d ticks (%d ms)", tag, ticks, TicksToMs(ticks));
}
} // namespace tflite
int main(int argc, char** argv) {
tflite::MicroProfiler profiler;
uint32_t event_handle = profiler.BeginEvent("InitializeBenchmarkRunner");
tflite::PersonDetectionBenchmarkRunner* benchmark_runner =
CreateBenchmarkRunner(&profiler);
profiler.EndEvent(event_handle);
profiler.Log();
MicroPrintf("");
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_person_data), 1,
"WithPersonDataIterations(1)", *benchmark_runner, profiler);
profiler.Log();
MicroPrintf("");
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_no_person_data), 1,
"NoPersonDataIterations(1)", *benchmark_runner, profiler);
profiler.Log();
MicroPrintf("");
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_person_data), 10,
"WithPersonDataIterations(10)", *benchmark_runner, profiler);
MicroPrintf("");
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_no_person_data), 10,
"NoPersonDataIterations(10)", *benchmark_runner, profiler);
MicroPrintf("");
}
<commit_msg>additional comments that I forgot to add in my last commit.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/lite/c/common.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/benchmarks/micro_benchmark.h"
#include "tensorflow/lite/micro/examples/person_detection/model_settings.h"
#include "tensorflow/lite/micro/examples/person_detection/no_person_image_data.h"
#include "tensorflow/lite/micro/examples/person_detection/person_detect_model_data.h"
#include "tensorflow/lite/micro/examples/person_detection/person_image_data.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_utils.h"
#include "tensorflow/lite/schema/schema_generated.h"
/*
* Person Detection benchmark. Evaluates runtime performance of the visual
* wakewords person detection model. This is the same model found in
* exmaples/person_detection.
*/
namespace tflite {
using PersonDetectionOpResolver = tflite::AllOpsResolver;
using PersonDetectionBenchmarkRunner = MicroBenchmarkRunner<int8_t>;
// Create an area of memory to use for input, output, and intermediate arrays.
// Align arena to 16 bytes to avoid alignment warnings on certain platforms.
constexpr int kTensorArenaSize = 135 * 1024;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];
uint8_t op_resolver_buffer[sizeof(PersonDetectionOpResolver)];
uint8_t benchmark_runner_buffer[sizeof(PersonDetectionBenchmarkRunner)];
// Initialize benchmark runner instance explicitly to avoid global init order
// issues on Sparkfun. Use new since static variables within a method
// are automatically surrounded by locking, which breaks bluepill and stm32f4.
PersonDetectionBenchmarkRunner* CreateBenchmarkRunner(MicroProfiler* profiler) {
// We allocate PersonDetectionOpResolver from a global buffer
// because the object's lifetime must exceed that of the
// PersonDetectionBenchmarkRunner object.
return new (benchmark_runner_buffer) PersonDetectionBenchmarkRunner(
g_person_detect_model_data,
new (op_resolver_buffer) PersonDetectionOpResolver(), tensor_arena,
kTensorArenaSize, profiler);
}
void PersonDetectionNIerations(const int8_t* input, int iterations,
const char* tag,
PersonDetectionBenchmarkRunner& benchmark_runner,
MicroProfiler& profiler) {
benchmark_runner.SetInput(input);
int32_t ticks = 0;
for (int i = 0; i < iterations; ++i) {
profiler.ClearEvents();
benchmark_runner.RunSingleIteration();
ticks += profiler.GetTotalTicks();
}
MicroPrintf("%s took %d ticks (%d ms)", tag, ticks, TicksToMs(ticks));
}
} // namespace tflite
int main(int argc, char** argv) {
tflite::MicroProfiler profiler;
uint32_t event_handle = profiler.BeginEvent("InitializeBenchmarkRunner");
tflite::PersonDetectionBenchmarkRunner* benchmark_runner =
CreateBenchmarkRunner(&profiler);
profiler.EndEvent(event_handle);
profiler.Log();
MicroPrintf(""); // null MicroPrintf serves as a newline.
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_person_data), 1,
"WithPersonDataIterations(1)", *benchmark_runner, profiler);
profiler.Log();
MicroPrintf(""); // null MicroPrintf serves as a newline.
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_no_person_data), 1,
"NoPersonDataIterations(1)", *benchmark_runner, profiler);
profiler.Log();
MicroPrintf(""); // null MicroPrintf serves as a newline.
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_person_data), 10,
"WithPersonDataIterations(10)", *benchmark_runner, profiler);
MicroPrintf(""); // null MicroPrintf serves as a newline.
tflite::PersonDetectionNIerations(
reinterpret_cast<const int8_t*>(g_no_person_data), 10,
"NoPersonDataIterations(10)", *benchmark_runner, profiler);
MicroPrintf(""); // null MicroPrintf serves as a newline.
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2016 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "governance.h"
#include "main.h"
#include "masternode.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "netfulfilledman.h"
#include "spork.h"
#include "util.h"
class CMasternodeSync;
CMasternodeSync masternodeSync;
bool CMasternodeSync::IsBlockchainSynced()
{
static bool fBlockchainSynced = false;
static int64_t lastProcess = GetTime();
// if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process
if(GetTime() - lastProcess > 60*60) {
Reset();
fBlockchainSynced = false;
}
lastProcess = GetTime();
if(fBlockchainSynced) return true;
if(!pCurrentBlockIndex || !pindexBestHeader || fImporting || fReindex) return false;
// same as !IsInitialBlockDownload() but no cs_main needed here
int nMaxBlockTime = std::max(pCurrentBlockIndex->GetBlockTime(), pindexBestHeader->GetBlockTime());
fBlockchainSynced = pindexBestHeader->nHeight - pCurrentBlockIndex->nHeight < 24 * 6 &&
GetTime() - nMaxBlockTime < Params().MaxTipAge();
return fBlockchainSynced;
}
void CMasternodeSync::Fail()
{
nTimeLastFailure = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;
}
void CMasternodeSync::Reset()
{
nRequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
nTimeLastMasternodeList = GetTime();
nTimeLastPaymentVote = GetTime();
nTimeLastBudgetItem = GetTime();
nTimeLastFailure = 0;
nCountFailures = 0;
}
std::string CMasternodeSync::GetAssetName()
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_INITIAL): return "MASTERNODE_SYNC_INITIAL";
case(MASTERNODE_SYNC_SPORKS): return "MASTERNODE_SYNC_SPORKS";
case(MASTERNODE_SYNC_LIST): return "MASTERNODE_SYNC_LIST";
case(MASTERNODE_SYNC_MNW): return "MASTERNODE_SYNC_MNW";
case(MASTERNODE_SYNC_GOVERNANCE): return "MASTERNODE_SYNC_GOVERNANCE";
case(MASTERNODE_SYNC_FAILED): return "MASTERNODE_SYNC_FAILED";
case MASTERNODE_SYNC_FINISHED: return "MASTERNODE_SYNC_FINISHED";
default: return "UNKNOWN";
}
}
void CMasternodeSync::SwitchToNextAsset()
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_FAILED):
throw std::runtime_error("Can't switch to next asset from failed, should use Reset() first!");
break;
case(MASTERNODE_SYNC_INITIAL):
ClearFulfilledRequests();
nRequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;
break;
case(MASTERNODE_SYNC_SPORKS):
nTimeLastMasternodeList = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_LIST;
break;
case(MASTERNODE_SYNC_LIST):
nTimeLastPaymentVote = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_MNW;
break;
case(MASTERNODE_SYNC_MNW):
nTimeLastBudgetItem = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_GOVERNANCE;
break;
case(MASTERNODE_SYNC_GOVERNANCE):
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Sync has finished\n");
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
uiInterface.NotifyAdditionalDataSyncProgressChanged(1);
//try to activate our masternode if possible
activeMasternode.ManageState();
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes) {
netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync");
}
break;
}
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
}
std::string CMasternodeSync::GetSyncStatus()
{
switch (masternodeSync.nRequestedMasternodeAssets) {
case MASTERNODE_SYNC_INITIAL: return _("Synchronization pending...");
case MASTERNODE_SYNC_SPORKS: return _("Synchronizing sporks...");
case MASTERNODE_SYNC_LIST: return _("Synchronizing masternodes...");
case MASTERNODE_SYNC_MNW: return _("Synchronizing masternode payments...");
case MASTERNODE_SYNC_GOVERNANCE: return _("Synchronizing governance objects...");
case MASTERNODE_SYNC_FAILED: return _("Synchronization failed");
case MASTERNODE_SYNC_FINISHED: return _("Synchronization finished");
default: return "";
}
}
void CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { //Sync status count
//do not care about stats if sync process finished or failed
if(IsSynced() || IsFailed()) return;
int nItemID;
int nCount;
vRecv >> nItemID >> nCount;
LogPrintf("CMasternodeSync::ProcessMessage -- SYNCSTATUSCOUNT -- got inventory count: nItemID=%d nCount=%d peer=%d\n", nItemID, nCount, pfrom->id);
}
}
void CMasternodeSync::ClearFulfilledRequests()
{
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "spork-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-list-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-payment-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "governance-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "full-sync");
}
}
void CMasternodeSync::ProcessTick()
{
static int nTick = 0;
if(nTick++ % 6 != 0) return;
if(!pCurrentBlockIndex) return;
//the actual count of masternodes we have currently
int nMnCount = mnodeman.CountEnabled();
// RESET SYNCING INCASE OF FAILURE
{
if(IsSynced()) {
/*
Resync if we lose all masternodes from sleep/wake or failure to sync originally
*/
if(nMnCount == 0) {
Reset();
} else {
//if syncing is complete and we have masternodes, return
return;
}
}
//try syncing again
if(IsFailed()) {
if(nTimeLastFailure + (1*60) < GetTime()) { // 1 minute cooldown after failed sync
Reset();
}
return;
}
}
// INITIAL SYNC SETUP / LOG REPORTING
double nSyncProgress = double(nRequestedMasternodeAttempt + (nRequestedMasternodeAssets - 1) * 8) / (8*4);
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d nRequestedMasternodeAttempt %d nSyncProgress %f\n", nTick, nRequestedMasternodeAssets, nRequestedMasternodeAttempt, nSyncProgress);
uiInterface.NotifyAdditionalDataSyncProgressChanged(nSyncProgress);
// sporks synced but blockchain is not, wait until we're almost at a recent block to continue
if(Params().NetworkIDString() != CBaseChainParams::REGTEST &&
!IsBlockchainSynced() && nRequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) {
SwitchToNextAsset();
}
BOOST_FOREACH(CNode* pnode, vNodes)
{
// QUICK MODE (REGTEST ONLY!)
if(Params().NetworkIDString() == CBaseChainParams::REGTEST)
{
if(nRequestedMasternodeAttempt <= 2) {
pnode->PushMessage(NetMsgType::GETSPORKS); //get current network sporks
} else if(nRequestedMasternodeAttempt < 4) {
mnodeman.DsegUpdate(pnode);
} else if(nRequestedMasternodeAttempt < 6) {
int nMnCount = mnodeman.CountEnabled();
pnode->PushMessage(NetMsgType::MASTERNODEPAYMENTSYNC, nMnCount); //sync payment votes
uint256 n = uint256();
pnode->PushMessage(NetMsgType::MNGOVERNANCESYNC, n); //sync masternode votes
} else {
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
}
nRequestedMasternodeAttempt++;
return;
}
// NORMAL NETWORK MODE - TESTNET/MAINNET
{
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "full-sync")) {
// we already fully synced from this node recently,
// disconnect to free this connection slot for a new node
pnode->fDisconnect = true;
LogPrintf("CMasternodeSync::ProcessTick -- disconnecting from recently synced node %d\n", pnode->id);
continue;
}
// SPORK : ALWAYS ASK FOR SPORKS AS WE SYNC (we skip this mode now)
if(!netfulfilledman.HasFulfilledRequest(pnode->addr, "spork-sync")) {
// only request once from each peer
netfulfilledman.AddFulfilledRequest(pnode->addr, "spork-sync");
// get current network sporks
pnode->PushMessage(NetMsgType::GETSPORKS);
// we always ask for sporks, so just skip this
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS) SwitchToNextAsset();
continue; // always get sporks first, switch to the next node without waiting for the next tick
}
// MNLIST : SYNC MASTERNODE LIST FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {
// check for timeout first
if(nTimeLastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// there is no way we can continue without masternode list, fail here and try later
Fail();
return;
}
SwitchToNextAsset();
return;
}
// check for data
// if we have enough masternodes in or list, switch to the next asset
/* Note: Is this activing up? It's probably related to int CMasternodeMan::GetEstimatedMasternodes(int nBlock)
Surely doesn't work right for testnet currently */
// try to fetch data from at least two peers though
if(nRequestedMasternodeAttempt > 1 && nMnCount > mnodeman.GetEstimatedMasternodes(pCurrentBlockIndex->nHeight)*0.9) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- found enough data\n", nTick, nRequestedMasternodeAssets);
SwitchToNextAsset();
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-list-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-list-sync");
if (pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
mnodeman.DsegUpdate(pnode);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// MNW : SYNC MASTERNODE PAYMENT VOTES FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {
// check for timeout first
// This might take a lot longer than MASTERNODE_SYNC_TIMEOUT_SECONDS minutes due to new blocks,
// but that should be OK and it should timeout eventually.
if(nTimeLastPaymentVote < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// probably not a good idea to proceed without winner list
Fail();
return;
}
SwitchToNextAsset();
return;
}
// check for data
// if mnpayments already has enough blocks and votes, switch to the next asset
// try to fetch data from at least two peers though
if(nRequestedMasternodeAttempt > 1 && mnpayments.IsEnoughData()) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- found enough data\n", nTick, nRequestedMasternodeAssets);
SwitchToNextAsset();
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-payment-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-payment-sync");
if(pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
// ask node for all payment votes it has (new nodes will only return votes for future payments)
pnode->PushMessage(NetMsgType::MASTERNODEPAYMENTSYNC, mnpayments.GetStorageLimit());
// ask node for missing pieces only (old nodes will not be asked)
mnpayments.RequestLowDataPaymentBlocks(pnode);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// GOVOBJ : SYNC GOVERNANCE ITEMS FROM OUR PEERS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_GOVERNANCE) {
// check for timeout first
if(nTimeLastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS){
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if(nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// it's kind of ok to skip this for now, hopefully we'll catch up later?
}
SwitchToNextAsset();
return;
}
// check for data
// if(nCountBudgetItemProp > 0 && nCountBudgetItemFin)
// {
// if(governance.CountProposalInventoryItems() >= (nSumBudgetItemProp / nCountBudgetItemProp)*0.9)
// {
// if(governance.CountFinalizedInventoryItems() >= (nSumBudgetItemFin / nCountBudgetItemFin)*0.9)
// {
// SwitchToNextAsset();
// return;
// }
// }
// }
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "governance-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "governance-sync");
if (pnode->nVersion < MSG_GOVERNANCE_PEER_PROTO_VERSION) continue;
nRequestedMasternodeAttempt++;
pnode->PushMessage(NetMsgType::MNGOVERNANCESYNC, uint256()); //sync masternode votes
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
}
}
}
void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindex)
{
pCurrentBlockIndex = pindex;
}
void CMasternodeSync::AddedBudgetItem(uint256 hash)
{
// skip this for now
return;
}
<commit_msg>Do not switch from MASTERNODE_SYNC_SPORKS to next asset until blockchain is synced<commit_after>// Copyright (c) 2014-2016 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "governance.h"
#include "main.h"
#include "masternode.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "netfulfilledman.h"
#include "spork.h"
#include "util.h"
class CMasternodeSync;
CMasternodeSync masternodeSync;
bool CMasternodeSync::IsBlockchainSynced()
{
static bool fBlockchainSynced = false;
static int64_t lastProcess = GetTime();
// if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process
if(GetTime() - lastProcess > 60*60) {
Reset();
fBlockchainSynced = false;
}
lastProcess = GetTime();
if(fBlockchainSynced) return true;
if(!pCurrentBlockIndex || !pindexBestHeader || fImporting || fReindex) return false;
// same as !IsInitialBlockDownload() but no cs_main needed here
int nMaxBlockTime = std::max(pCurrentBlockIndex->GetBlockTime(), pindexBestHeader->GetBlockTime());
fBlockchainSynced = pindexBestHeader->nHeight - pCurrentBlockIndex->nHeight < 24 * 6 &&
GetTime() - nMaxBlockTime < Params().MaxTipAge();
return fBlockchainSynced;
}
void CMasternodeSync::Fail()
{
nTimeLastFailure = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;
}
void CMasternodeSync::Reset()
{
nRequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
nTimeLastMasternodeList = GetTime();
nTimeLastPaymentVote = GetTime();
nTimeLastBudgetItem = GetTime();
nTimeLastFailure = 0;
nCountFailures = 0;
}
std::string CMasternodeSync::GetAssetName()
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_INITIAL): return "MASTERNODE_SYNC_INITIAL";
case(MASTERNODE_SYNC_SPORKS): return "MASTERNODE_SYNC_SPORKS";
case(MASTERNODE_SYNC_LIST): return "MASTERNODE_SYNC_LIST";
case(MASTERNODE_SYNC_MNW): return "MASTERNODE_SYNC_MNW";
case(MASTERNODE_SYNC_GOVERNANCE): return "MASTERNODE_SYNC_GOVERNANCE";
case(MASTERNODE_SYNC_FAILED): return "MASTERNODE_SYNC_FAILED";
case MASTERNODE_SYNC_FINISHED: return "MASTERNODE_SYNC_FINISHED";
default: return "UNKNOWN";
}
}
void CMasternodeSync::SwitchToNextAsset()
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_FAILED):
throw std::runtime_error("Can't switch to next asset from failed, should use Reset() first!");
break;
case(MASTERNODE_SYNC_INITIAL):
ClearFulfilledRequests();
nRequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;
break;
case(MASTERNODE_SYNC_SPORKS):
nTimeLastMasternodeList = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_LIST;
break;
case(MASTERNODE_SYNC_LIST):
nTimeLastPaymentVote = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_MNW;
break;
case(MASTERNODE_SYNC_MNW):
nTimeLastBudgetItem = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_GOVERNANCE;
break;
case(MASTERNODE_SYNC_GOVERNANCE):
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Sync has finished\n");
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
uiInterface.NotifyAdditionalDataSyncProgressChanged(1);
//try to activate our masternode if possible
activeMasternode.ManageState();
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes) {
netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync");
}
break;
}
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
}
std::string CMasternodeSync::GetSyncStatus()
{
switch (masternodeSync.nRequestedMasternodeAssets) {
case MASTERNODE_SYNC_INITIAL: return _("Synchronization pending...");
case MASTERNODE_SYNC_SPORKS: return _("Synchronizing sporks...");
case MASTERNODE_SYNC_LIST: return _("Synchronizing masternodes...");
case MASTERNODE_SYNC_MNW: return _("Synchronizing masternode payments...");
case MASTERNODE_SYNC_GOVERNANCE: return _("Synchronizing governance objects...");
case MASTERNODE_SYNC_FAILED: return _("Synchronization failed");
case MASTERNODE_SYNC_FINISHED: return _("Synchronization finished");
default: return "";
}
}
void CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { //Sync status count
//do not care about stats if sync process finished or failed
if(IsSynced() || IsFailed()) return;
int nItemID;
int nCount;
vRecv >> nItemID >> nCount;
LogPrintf("CMasternodeSync::ProcessMessage -- SYNCSTATUSCOUNT -- got inventory count: nItemID=%d nCount=%d peer=%d\n", nItemID, nCount, pfrom->id);
}
}
void CMasternodeSync::ClearFulfilledRequests()
{
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "spork-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-list-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-payment-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "governance-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "full-sync");
}
}
void CMasternodeSync::ProcessTick()
{
static int nTick = 0;
if(nTick++ % 6 != 0) return;
if(!pCurrentBlockIndex) return;
//the actual count of masternodes we have currently
int nMnCount = mnodeman.CountEnabled();
// RESET SYNCING INCASE OF FAILURE
{
if(IsSynced()) {
/*
Resync if we lose all masternodes from sleep/wake or failure to sync originally
*/
if(nMnCount == 0) {
Reset();
} else {
//if syncing is complete and we have masternodes, return
return;
}
}
//try syncing again
if(IsFailed()) {
if(nTimeLastFailure + (1*60) < GetTime()) { // 1 minute cooldown after failed sync
Reset();
}
return;
}
}
// INITIAL SYNC SETUP / LOG REPORTING
double nSyncProgress = double(nRequestedMasternodeAttempt + (nRequestedMasternodeAssets - 1) * 8) / (8*4);
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d nRequestedMasternodeAttempt %d nSyncProgress %f\n", nTick, nRequestedMasternodeAssets, nRequestedMasternodeAttempt, nSyncProgress);
uiInterface.NotifyAdditionalDataSyncProgressChanged(nSyncProgress);
// sporks synced but blockchain is not, wait until we're almost at a recent block to continue
if(Params().NetworkIDString() != CBaseChainParams::REGTEST &&
!IsBlockchainSynced() && nRequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL ||
(nRequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS && IsBlockchainSynced()))
{
SwitchToNextAsset();
}
BOOST_FOREACH(CNode* pnode, vNodes)
{
// QUICK MODE (REGTEST ONLY!)
if(Params().NetworkIDString() == CBaseChainParams::REGTEST)
{
if(nRequestedMasternodeAttempt <= 2) {
pnode->PushMessage(NetMsgType::GETSPORKS); //get current network sporks
} else if(nRequestedMasternodeAttempt < 4) {
mnodeman.DsegUpdate(pnode);
} else if(nRequestedMasternodeAttempt < 6) {
int nMnCount = mnodeman.CountEnabled();
pnode->PushMessage(NetMsgType::MASTERNODEPAYMENTSYNC, nMnCount); //sync payment votes
uint256 n = uint256();
pnode->PushMessage(NetMsgType::MNGOVERNANCESYNC, n); //sync masternode votes
} else {
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
}
nRequestedMasternodeAttempt++;
return;
}
// NORMAL NETWORK MODE - TESTNET/MAINNET
{
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "full-sync")) {
// we already fully synced from this node recently,
// disconnect to free this connection slot for a new node
pnode->fDisconnect = true;
LogPrintf("CMasternodeSync::ProcessTick -- disconnecting from recently synced node %d\n", pnode->id);
continue;
}
// SPORK : ALWAYS ASK FOR SPORKS AS WE SYNC (we skip this mode now)
if(!netfulfilledman.HasFulfilledRequest(pnode->addr, "spork-sync")) {
// only request once from each peer
netfulfilledman.AddFulfilledRequest(pnode->addr, "spork-sync");
// get current network sporks
pnode->PushMessage(NetMsgType::GETSPORKS);
continue; // always get sporks first, switch to the next node without waiting for the next tick
}
// MNLIST : SYNC MASTERNODE LIST FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {
// check for timeout first
if(nTimeLastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// there is no way we can continue without masternode list, fail here and try later
Fail();
return;
}
SwitchToNextAsset();
return;
}
// check for data
// if we have enough masternodes in or list, switch to the next asset
/* Note: Is this activing up? It's probably related to int CMasternodeMan::GetEstimatedMasternodes(int nBlock)
Surely doesn't work right for testnet currently */
// try to fetch data from at least two peers though
if(nRequestedMasternodeAttempt > 1 && nMnCount > mnodeman.GetEstimatedMasternodes(pCurrentBlockIndex->nHeight)*0.9) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- found enough data\n", nTick, nRequestedMasternodeAssets);
SwitchToNextAsset();
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-list-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-list-sync");
if (pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
mnodeman.DsegUpdate(pnode);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// MNW : SYNC MASTERNODE PAYMENT VOTES FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {
// check for timeout first
// This might take a lot longer than MASTERNODE_SYNC_TIMEOUT_SECONDS minutes due to new blocks,
// but that should be OK and it should timeout eventually.
if(nTimeLastPaymentVote < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// probably not a good idea to proceed without winner list
Fail();
return;
}
SwitchToNextAsset();
return;
}
// check for data
// if mnpayments already has enough blocks and votes, switch to the next asset
// try to fetch data from at least two peers though
if(nRequestedMasternodeAttempt > 1 && mnpayments.IsEnoughData()) {
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- found enough data\n", nTick, nRequestedMasternodeAssets);
SwitchToNextAsset();
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-payment-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-payment-sync");
if(pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
// ask node for all payment votes it has (new nodes will only return votes for future payments)
pnode->PushMessage(NetMsgType::MASTERNODEPAYMENTSYNC, mnpayments.GetStorageLimit());
// ask node for missing pieces only (old nodes will not be asked)
mnpayments.RequestLowDataPaymentBlocks(pnode);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// GOVOBJ : SYNC GOVERNANCE ITEMS FROM OUR PEERS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_GOVERNANCE) {
// check for timeout first
if(nTimeLastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT_SECONDS){
LogPrintf("CMasternodeSync::Process -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if(nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::Process -- WARNING: failed to sync %s\n", GetAssetName());
// it's kind of ok to skip this for now, hopefully we'll catch up later?
}
SwitchToNextAsset();
return;
}
// check for data
// if(nCountBudgetItemProp > 0 && nCountBudgetItemFin)
// {
// if(governance.CountProposalInventoryItems() >= (nSumBudgetItemProp / nCountBudgetItemProp)*0.9)
// {
// if(governance.CountFinalizedInventoryItems() >= (nSumBudgetItemFin / nCountBudgetItemFin)*0.9)
// {
// SwitchToNextAsset();
// return;
// }
// }
// }
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "governance-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "governance-sync");
if (pnode->nVersion < MSG_GOVERNANCE_PEER_PROTO_VERSION) continue;
nRequestedMasternodeAttempt++;
pnode->PushMessage(NetMsgType::MNGOVERNANCESYNC, uint256()); //sync masternode votes
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
}
}
}
void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindex)
{
pCurrentBlockIndex = pindex;
}
void CMasternodeSync::AddedBudgetItem(uint256 hash)
{
// skip this for now
return;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mdecoratorframe.h"
#include "mcompositewindow.h"
#include "mtexturepixmapitem.h"
#include "mcompositemanager.h"
#include <mrmiclient.h>
#include <QX11Info>
#include <X11/Xutil.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xmd.h>
MDecoratorFrame *MDecoratorFrame::d = 0;
MDecoratorFrame *MDecoratorFrame::instance()
{
if (!d)
d = new MDecoratorFrame();
return d;
}
MDecoratorFrame::MDecoratorFrame(QObject *p)
: QObject(p),
client(0),
decorator_window(0),
decorator_item(0),
no_resize(false)
{
MCompositeManager *mgr = (MCompositeManager *) qApp;
connect(mgr, SIGNAL(decoratorRectChanged(const QRect&)), this,
SLOT(setDecoratorAvailableRect(const QRect&)));
/*!
* Excute decorator process here.
*/
remote_decorator = new MRmiClient(".mabstractdecorator", this);
}
Qt::HANDLE MDecoratorFrame::managedWindow() const
{
return client ? client->window() : 0;
}
Qt::HANDLE MDecoratorFrame::winId() const
{
return decorator_window;
}
void MDecoratorFrame::lower()
{
if (decorator_item)
decorator_item->setVisible(false);
}
void MDecoratorFrame::raise()
{
if (decorator_item)
decorator_item->setVisible(true);
}
void MDecoratorFrame::updateManagedWindowGeometry()
{
if (client && client->needDecoration()) {
#if 0
Display *dpy = QX11Info::display();
XWindowAttributes a;
if (!XGetWindowAttributes(dpy, decorator_window, &a)) {
qWarning("%s: invalid window 0x%lx", __func__, decorator_window);
return;
}
#endif
setDecoratorAvailableRect(decorator_rect);
}
}
void MDecoratorFrame::setManagedWindow(MCompositeWindow *cw,
bool no_resize)
{
this->no_resize = no_resize;
if (client == cw)
return;
disconnect(this, SLOT(destroyClient()));
client = cw;
qulonglong winid = client ? client->window() : 0;
if (decorator_window) {
long val = winid;
Atom a = XInternAtom(QX11Info::display(),
"_MDECORATOR_MANAGED_WINDOW", False);
XChangeProperty(QX11Info::display(), decorator_window, a, XA_WINDOW,
32, PropModeReplace, (unsigned char *)&val, 1);
}
if (!decorator_item)
return;
if(cw)
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetClientGeometry",
cw->propertyCache()->requestedGeometry());
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetAutoRotation", false);
/* FIXME: replaced with a window property due to reliability problems
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetManagedWinId", winid);
*/
if (cw)
connect(cw, SIGNAL(destroyed()), SLOT(destroyClient()));
}
void MDecoratorFrame::setDecoratorWindow(Qt::HANDLE window)
{
decorator_window = window;
XMapWindow(QX11Info::display(), window);
}
void MDecoratorFrame::setDecoratorItem(MCompositeWindow *window)
{
decorator_item = window;
connect(decorator_item, SIGNAL(destroyed()), SLOT(destroyDecorator()));
MTexturePixmapItem *item = (MTexturePixmapItem *) window;
if (!decorator_window)
setDecoratorWindow(item->window());
}
MCompositeWindow *MDecoratorFrame::decoratorItem() const
{
return decorator_item;
}
void MDecoratorFrame::destroyDecorator()
{
decorator_item = 0;
decorator_window = 0;
}
void MDecoratorFrame::destroyClient()
{
if (client == sender())
client = 0;
}
void MDecoratorFrame::visualizeDecorator(bool visible)
{
if (sender() == decorator_item)
return;
if (decorator_item)
decorator_item->setVisible(visible);
}
void MDecoratorFrame::setDecoratorAvailableRect(const QRect& decorect)
{
if (!client || no_resize)
return;
Display* dpy = QX11Info::display();
// cache this. we need actual positon of decorator window
static int actual_decor_ypos = 0;
if (!actual_decor_ypos) {
XWindowAttributes a;
if (!XGetWindowAttributes(dpy, decorator_window, &a)) {
qWarning("%s: invalid window 0x%lx", __func__, decorator_window);
return;
}
actual_decor_ypos = a.y;
}
decorator_rect = decorect;
// if window is not same width as screen, stretch it.
QRect appgeometry = client->propertyCache()->requestedGeometry();
if(appgeometry.width() < decorect.width())
appgeometry = QApplication::desktop()->screenGeometry();
// region of decorator + statusbar window. remove this once we removed the statubar
QRect actual_decorect = decorect;
actual_decorect.setHeight(decorect.height() + actual_decor_ypos);
QRect r = (QRegion(appgeometry) - actual_decorect).boundingRect();
int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;
int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;
int excess = r.y() + r.height() - yres;
if (excess > 0)
r.setHeight(r.height() - excess);
excess = r.x() + r.width() - xres;
if (excess > 0)
r.setWidth(r.width() - excess);
XMoveResizeWindow(dpy, client->window(), r.x(), r.y(), r.width(), r.height());
}
void MDecoratorFrame::setAutoRotation(bool mode)
{
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetAutoRotation", mode);
}
void MDecoratorFrame::setOnlyStatusbar(bool mode)
{
if (decorator_window) {
long val = mode;
Atom a = XInternAtom(QX11Info::display(),
"_MDECORATOR_ONLY_STATUSBAR", False);
XChangeProperty(QX11Info::display(), decorator_window, a, XA_CARDINAL,
32, PropModeReplace, (unsigned char *)&val, 1);
}
/* FIXME: replaced with a window property due to reliability problems
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetOnlyStatusbar", mode);
*/
}
<commit_msg>Avoid XGetWindowAttributes call in MDecoratorFrame by using the cache.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mdecoratorframe.h"
#include "mcompositewindow.h"
#include "mtexturepixmapitem.h"
#include "mcompositemanager.h"
#include <mrmiclient.h>
#include <QX11Info>
#include <X11/Xutil.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xmd.h>
MDecoratorFrame *MDecoratorFrame::d = 0;
MDecoratorFrame *MDecoratorFrame::instance()
{
if (!d)
d = new MDecoratorFrame();
return d;
}
MDecoratorFrame::MDecoratorFrame(QObject *p)
: QObject(p),
client(0),
decorator_window(0),
decorator_item(0),
no_resize(false)
{
MCompositeManager *mgr = (MCompositeManager *) qApp;
connect(mgr, SIGNAL(decoratorRectChanged(const QRect&)), this,
SLOT(setDecoratorAvailableRect(const QRect&)));
/*!
* Excute decorator process here.
*/
remote_decorator = new MRmiClient(".mabstractdecorator", this);
}
Qt::HANDLE MDecoratorFrame::managedWindow() const
{
return client ? client->window() : 0;
}
Qt::HANDLE MDecoratorFrame::winId() const
{
return decorator_window;
}
void MDecoratorFrame::lower()
{
if (decorator_item)
decorator_item->setVisible(false);
}
void MDecoratorFrame::raise()
{
if (decorator_item)
decorator_item->setVisible(true);
}
void MDecoratorFrame::updateManagedWindowGeometry()
{
if (client && client->needDecoration()) {
#if 0
Display *dpy = QX11Info::display();
XWindowAttributes a;
if (!XGetWindowAttributes(dpy, decorator_window, &a)) {
qWarning("%s: invalid window 0x%lx", __func__, decorator_window);
return;
}
#endif
setDecoratorAvailableRect(decorator_rect);
}
}
void MDecoratorFrame::setManagedWindow(MCompositeWindow *cw,
bool no_resize)
{
this->no_resize = no_resize;
if (client == cw)
return;
disconnect(this, SLOT(destroyClient()));
client = cw;
qulonglong winid = client ? client->window() : 0;
if (decorator_window) {
long val = winid;
Atom a = XInternAtom(QX11Info::display(),
"_MDECORATOR_MANAGED_WINDOW", False);
XChangeProperty(QX11Info::display(), decorator_window, a, XA_WINDOW,
32, PropModeReplace, (unsigned char *)&val, 1);
}
if (!decorator_item)
return;
if(cw)
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetClientGeometry",
cw->propertyCache()->requestedGeometry());
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetAutoRotation", false);
/* FIXME: replaced with a window property due to reliability problems
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetManagedWinId", winid);
*/
if (cw)
connect(cw, SIGNAL(destroyed()), SLOT(destroyClient()));
}
void MDecoratorFrame::setDecoratorWindow(Qt::HANDLE window)
{
decorator_window = window;
XMapWindow(QX11Info::display(), window);
}
void MDecoratorFrame::setDecoratorItem(MCompositeWindow *window)
{
decorator_item = window;
connect(decorator_item, SIGNAL(destroyed()), SLOT(destroyDecorator()));
MTexturePixmapItem *item = (MTexturePixmapItem *) window;
if (!decorator_window)
setDecoratorWindow(item->window());
}
MCompositeWindow *MDecoratorFrame::decoratorItem() const
{
return decorator_item;
}
void MDecoratorFrame::destroyDecorator()
{
decorator_item = 0;
decorator_window = 0;
}
void MDecoratorFrame::destroyClient()
{
if (client == sender())
client = 0;
}
void MDecoratorFrame::visualizeDecorator(bool visible)
{
if (sender() == decorator_item)
return;
if (decorator_item)
decorator_item->setVisible(visible);
}
void MDecoratorFrame::setDecoratorAvailableRect(const QRect& decorect)
{
if (!client || no_resize || !decorator_item
|| !decorator_item->propertyCache())
return;
Display* dpy = QX11Info::display();
int actual_decor_ypos = decorator_item->propertyCache()->realGeometry().y();
decorator_rect = decorect;
// if window is not same width as screen, stretch it.
QRect appgeometry = client->propertyCache()->requestedGeometry();
if(appgeometry.width() < decorect.width())
appgeometry = QApplication::desktop()->screenGeometry();
// region of decorator + statusbar window. remove this once we removed the statubar
QRect actual_decorect = decorect;
actual_decorect.setHeight(decorect.height() + actual_decor_ypos);
QRect r = (QRegion(appgeometry) - actual_decorect).boundingRect();
int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;
int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;
int excess = r.y() + r.height() - yres;
if (excess > 0)
r.setHeight(r.height() - excess);
excess = r.x() + r.width() - xres;
if (excess > 0)
r.setWidth(r.width() - excess);
XMoveResizeWindow(dpy, client->window(), r.x(), r.y(), r.width(), r.height());
}
void MDecoratorFrame::setAutoRotation(bool mode)
{
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetAutoRotation", mode);
}
void MDecoratorFrame::setOnlyStatusbar(bool mode)
{
if (decorator_window) {
long val = mode;
Atom a = XInternAtom(QX11Info::display(),
"_MDECORATOR_ONLY_STATUSBAR", False);
XChangeProperty(QX11Info::display(), decorator_window, a, XA_CARDINAL,
32, PropModeReplace, (unsigned char *)&val, 1);
}
/* FIXME: replaced with a window property due to reliability problems
remote_decorator->invoke("MAbstractDecorator",
"RemoteSetOnlyStatusbar", mode);
*/
}
<|endoftext|>
|
<commit_before>#include "Template.h"
#include <string>
#include <iostream>
#include <TestFixture.h>
#include <TestAssert.h>
#include <TestSuite.h>
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
using namespace std;
/* ************************************************************************* */
/* ************************************************************************* */
/* ************************************************************************* */
class TemplateTest : public CppUnit::TestFixture
{
private:
Template *t, *tr, *t1;
string test_ok;
string test_ok_marshall;
string test_ok_xml;
string test_ok_str;
public:
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
TemplateTest()
{
test_ok =
"#This line is a comment\n"
" # Other comment\n"
"MEMORY=345 # more comments behind an attribute\n"
" CPU = 4\n"
"#------------------------------\n"
"#Comments in the middle\n"
"#------------------------------\n"
" empty_var = \n"
"REQUIREMENTS = \"HOSTNAME = \\\"host*.com\\\"\"\n"
" DISK= [file = path1, extra = \"disk attribute \"]\n"
"DISK =[ FILE = \"path2\", EXTRA = str, TYPE=disk]\n"
" graphics = [\n"
" VNC = \"127.0.0.1\",\n"
" PORT = 12\n"
" ]\n";
test_ok_marshall="CPU=4\nDISK=EXTRA=disk attribute @^_^@FILE=path1\n"
"DISK=EXTRA=str@^_^@FILE=path2@^_^@TYPE=disk\nEMPTY_VAR=\n"
"GRAPHICS=PORT=12@^_^@VNC=127.0.0.1\nMEMORY=345\n"
"REQUIREMENTS=HOSTNAME = \"host*.com\"\n";
test_ok_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><DISK><EXTRA>"
"<![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]></FILE>"
"</DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2]]>"
"</FILE><TYPE><![CDATA[disk]]></TYPE></DISK><EMPTY_VAR><![CDATA[]]>"
"</EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC>"
"<![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]>"
"</MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]>"
"</REQUIREMENTS></TEMPLATE>";
test_ok_str=
"\n\tCPU=4"
"\n\tDISK=EXTRA=disk attribute ,FILE=path1"
"\n\tDISK=EXTRA=str,FILE=path2,TYPE=disk"
"\n\tEMPTY_VAR="
"\n\tGRAPHICS=PORT=12,VNC=127.0.0.1"
"\n\tMEMORY=345"
"\n\tREQUIREMENTS=HOSTNAME = \"host*.com\"";
}
~TemplateTest(){};
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void setUp()
{
char *error = 0;
t = new Template();
tr= new Template(true);
tr->parse(test_ok,&error);
t1= new Template();
t1->parse(test_ok,&error);
}
void tearDown()
{
delete t;
delete tr;
delete t1;
}
/* ********************************************************************* */
/* ********************************************************************* */
void test_parser()
{
char * error = 0;
int rc;
string tmp;
rc = t->parse(test_ok,&error);
if ( error != 0 )
{
cerr << error << endl;
free(error);
}
CPPUNIT_ASSERT( rc == 0);
}
/* --------------------------------------------------------------------- */
void test_marshall()
{
string tmp;
t1->marshall(tmp);
CPPUNIT_ASSERT(test_ok_marshall == tmp);
}
/* --------------------------------------------------------------------- */
void test_xml()
{
string tmp;
t1->to_xml(tmp);
CPPUNIT_ASSERT(test_ok_xml == tmp);
}
/* --------------------------------------------------------------------- */
void test_str()
{
string tmp;
t1->to_str(tmp);
CPPUNIT_ASSERT(test_ok_str == tmp);
}
/* --------------------------------------------------------------------- */
void test_get()
{
vector<Attribute*> attrs;
string *tmp;
CPPUNIT_ASSERT(t1->get("DISK",attrs) == 2 );
CPPUNIT_ASSERT(attrs[0]->type() == Attribute::VECTOR);
tmp = attrs[0]->to_xml();
CPPUNIT_ASSERT( *tmp ==
"<DISK><EXTRA><![CDATA[disk attribute ]]></EXTRA><FILE>"
"<![CDATA[path1]]></FILE></DISK>");
delete tmp;
CPPUNIT_ASSERT(attrs[1]->type() == Attribute::VECTOR);
tmp = attrs[1]->to_xml();
CPPUNIT_ASSERT( *tmp ==
"<DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2]]>"
"</FILE><TYPE><![CDATA[disk]]></TYPE></DISK>");
delete tmp;
CPPUNIT_ASSERT(t1->get("CPU",attrs) == 1 );
CPPUNIT_ASSERT(attrs[2]->type() == Attribute::SIMPLE);
tmp = attrs[2]->to_xml();
CPPUNIT_ASSERT( *tmp == "<CPU><![CDATA[4]]></CPU>");
delete tmp;
string sval;
string sname = "REQUIREMENTS";
string iname = "MEMORY";
int ival;
t1->get(iname,ival);
t1->get(sname,sval);
CPPUNIT_ASSERT ( ival == 345 );
CPPUNIT_ASSERT ( sval == "HOSTNAME = \"host*.com\"");
}
/* --------------------------------------------------------------------- */
void test_remove()
{
vector<Attribute*> attrs;
string t1_xml;
string rm_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><EMPTY_VAR>"
"<![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC>"
"<![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]>"
"</MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]>"
"</REQUIREMENTS></TEMPLATE>";
t1->remove("DISK",attrs);
t1->to_xml(t1_xml);
CPPUNIT_ASSERT(t1_xml == rm_xml);
delete attrs[0];
delete attrs[1];
}
/* --------------------------------------------------------------------- */
void test_set()
{
string t1_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><DISK><EXTRA>"
"<![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]>"
"</FILE></DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE>"
"<![CDATA[path2]]></FILE><TYPE><![CDATA[disk]]></TYPE></DISK>"
"<EMPTY_VAR><![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]>"
"</PORT><VNC><![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY>"
"<![CDATA[345]]></MEMORY><REQUIREMENTS>"
"<![CDATA[HOSTNAME = \"host*.com\"]]></REQUIREMENTS><XTRA>"
"<![CDATA[44]]></XTRA></TEMPLATE>";
string xml;
string nattr = "XTRA";
string vattr = "44";
SingleAttribute *a = new SingleAttribute(nattr,vattr);
t1->set(a);
t1->to_xml(xml);
CPPUNIT_ASSERT(t1_xml == xml);
nattr = "CPU";
vattr = "5";
t1_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><CPU><![CDATA[5]]></CPU><DISK"
"><EXTRA><![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]>"
"</FILE></DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2"
"]]></FILE><TYPE><![CDATA[disk]]></TYPE></DISK><EMPTY_VAR><![CDATA[]]>"
"</EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC><![CDATA[127.0.0"
".1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]></MEMORY><REQUIREMENTS>"
"<![CDATA[HOSTNAME = \"host*.com\"]]></REQUIREMENTS><XTRA><![CDATA[44]]"
"></XTRA></TEMPLATE>";
SingleAttribute *b = new SingleAttribute(nattr,vattr);
t1->set(b);
t1->to_xml(xml);
CPPUNIT_ASSERT(t1_xml == xml);
string tr_xml="<TEMPLATE><CPU><![CDATA[5]]></CPU><DISK><EXTRA><![CDATA["
"str]]></EXTRA><FILE><![CDATA[path2]]></FILE><TYPE><![CDATA[disk]]></TY"
"PE></DISK><EMPTY_VAR><![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA["
"12]]></PORT><VNC><![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDAT"
"A[345]]></MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]></R"
"EQUIREMENTS></TEMPLATE>";
SingleAttribute *c = new SingleAttribute(nattr,vattr);
tr->set(c);
tr->to_xml(xml);
CPPUNIT_ASSERT(tr_xml == xml);
}
/* ********************************************************************* */
/* ********************************************************************* */
static CppUnit::TestSuite * suite()
{
CppUnit::TestSuite *ts=new CppUnit::TestSuite("Template Tests");
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"parse() Test",
&TemplateTest::test_parser));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"marshall() Test",
&TemplateTest::test_marshall));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"xml() Test",
&TemplateTest::test_xml));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"str() Test",
&TemplateTest::test_str));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"get() Test",
&TemplateTest::test_get));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"remove() Test",
&TemplateTest::test_remove));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"set() Test",
&TemplateTest::test_set));
return ts;
}
};
/* ************************************************************************* */
/* ************************************************************************* */
/* ************************************************************************* */
int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
tr.addTest(TemplateTest::suite());
tr.run();
return 0;
}
<commit_msg>feature #192: New test for Template::erase.<commit_after>#include "Template.h"
#include <string>
#include <iostream>
#include <TestFixture.h>
#include <TestAssert.h>
#include <TestSuite.h>
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
using namespace std;
/* ************************************************************************* */
/* ************************************************************************* */
/* ************************************************************************* */
class TemplateTest : public CppUnit::TestFixture
{
private:
Template *t, *tr, *t1;
string test_ok;
string test_ok_marshall;
string test_ok_xml;
string test_ok_str;
public:
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
TemplateTest()
{
test_ok =
"#This line is a comment\n"
" # Other comment\n"
"MEMORY=345 # more comments behind an attribute\n"
" CPU = 4\n"
"#------------------------------\n"
"#Comments in the middle\n"
"#------------------------------\n"
" empty_var = \n"
"REQUIREMENTS = \"HOSTNAME = \\\"host*.com\\\"\"\n"
" DISK= [file = path1, extra = \"disk attribute \"]\n"
"DISK =[ FILE = \"path2\", EXTRA = str, TYPE=disk]\n"
" graphics = [\n"
" VNC = \"127.0.0.1\",\n"
" PORT = 12\n"
" ]\n";
test_ok_marshall="CPU=4\nDISK=EXTRA=disk attribute @^_^@FILE=path1\n"
"DISK=EXTRA=str@^_^@FILE=path2@^_^@TYPE=disk\nEMPTY_VAR=\n"
"GRAPHICS=PORT=12@^_^@VNC=127.0.0.1\nMEMORY=345\n"
"REQUIREMENTS=HOSTNAME = \"host*.com\"\n";
test_ok_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><DISK><EXTRA>"
"<![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]></FILE>"
"</DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2]]>"
"</FILE><TYPE><![CDATA[disk]]></TYPE></DISK><EMPTY_VAR><![CDATA[]]>"
"</EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC>"
"<![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]>"
"</MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]>"
"</REQUIREMENTS></TEMPLATE>";
test_ok_str=
"\n\tCPU=4"
"\n\tDISK=EXTRA=disk attribute ,FILE=path1"
"\n\tDISK=EXTRA=str,FILE=path2,TYPE=disk"
"\n\tEMPTY_VAR="
"\n\tGRAPHICS=PORT=12,VNC=127.0.0.1"
"\n\tMEMORY=345"
"\n\tREQUIREMENTS=HOSTNAME = \"host*.com\"";
}
~TemplateTest(){};
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void setUp()
{
char *error = 0;
t = new Template();
tr= new Template(true);
tr->parse(test_ok,&error);
t1= new Template();
t1->parse(test_ok,&error);
}
void tearDown()
{
delete t;
delete tr;
delete t1;
}
/* ********************************************************************* */
/* ********************************************************************* */
void test_parser()
{
char * error = 0;
int rc;
string tmp;
rc = t->parse(test_ok,&error);
if ( error != 0 )
{
cerr << error << endl;
free(error);
}
CPPUNIT_ASSERT( rc == 0);
}
/* --------------------------------------------------------------------- */
void test_marshall()
{
string tmp;
t1->marshall(tmp);
CPPUNIT_ASSERT(test_ok_marshall == tmp);
}
/* --------------------------------------------------------------------- */
void test_xml()
{
string tmp;
t1->to_xml(tmp);
CPPUNIT_ASSERT(test_ok_xml == tmp);
}
/* --------------------------------------------------------------------- */
void test_str()
{
string tmp;
t1->to_str(tmp);
CPPUNIT_ASSERT(test_ok_str == tmp);
}
/* --------------------------------------------------------------------- */
void test_get()
{
vector<Attribute*> attrs;
string *tmp;
CPPUNIT_ASSERT(t1->get("DISK",attrs) == 2 );
CPPUNIT_ASSERT(attrs[0]->type() == Attribute::VECTOR);
tmp = attrs[0]->to_xml();
CPPUNIT_ASSERT( *tmp ==
"<DISK><EXTRA><![CDATA[disk attribute ]]></EXTRA><FILE>"
"<![CDATA[path1]]></FILE></DISK>");
delete tmp;
CPPUNIT_ASSERT(attrs[1]->type() == Attribute::VECTOR);
tmp = attrs[1]->to_xml();
CPPUNIT_ASSERT( *tmp ==
"<DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2]]>"
"</FILE><TYPE><![CDATA[disk]]></TYPE></DISK>");
delete tmp;
CPPUNIT_ASSERT(t1->get("CPU",attrs) == 1 );
CPPUNIT_ASSERT(attrs[2]->type() == Attribute::SIMPLE);
tmp = attrs[2]->to_xml();
CPPUNIT_ASSERT( *tmp == "<CPU><![CDATA[4]]></CPU>");
delete tmp;
string sval;
string sname = "REQUIREMENTS";
string iname = "MEMORY";
int ival;
t1->get(iname,ival);
t1->get(sname,sval);
CPPUNIT_ASSERT ( ival == 345 );
CPPUNIT_ASSERT ( sval == "HOSTNAME = \"host*.com\"");
}
/* --------------------------------------------------------------------- */
void test_remove()
{
vector<Attribute*> attrs;
string t1_xml;
string rm_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><EMPTY_VAR>"
"<![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC>"
"<![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]>"
"</MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]>"
"</REQUIREMENTS></TEMPLATE>";
t1->remove("DISK",attrs);
t1->to_xml(t1_xml);
CPPUNIT_ASSERT(t1_xml == rm_xml);
delete attrs[0];
delete attrs[1];
}
/* --------------------------------------------------------------------- */
void test_set()
{
string t1_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><DISK><EXTRA>"
"<![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]>"
"</FILE></DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE>"
"<![CDATA[path2]]></FILE><TYPE><![CDATA[disk]]></TYPE></DISK>"
"<EMPTY_VAR><![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]>"
"</PORT><VNC><![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY>"
"<![CDATA[345]]></MEMORY><REQUIREMENTS>"
"<![CDATA[HOSTNAME = \"host*.com\"]]></REQUIREMENTS><XTRA>"
"<![CDATA[44]]></XTRA></TEMPLATE>";
string xml;
string nattr = "XTRA";
string vattr = "44";
SingleAttribute *a = new SingleAttribute(nattr,vattr);
t1->set(a);
t1->to_xml(xml);
CPPUNIT_ASSERT(t1_xml == xml);
nattr = "CPU";
vattr = "5";
t1_xml="<TEMPLATE><CPU><![CDATA[4]]></CPU><CPU><![CDATA[5]]></CPU><DISK"
"><EXTRA><![CDATA[disk attribute ]]></EXTRA><FILE><![CDATA[path1]]>"
"</FILE></DISK><DISK><EXTRA><![CDATA[str]]></EXTRA><FILE><![CDATA[path2"
"]]></FILE><TYPE><![CDATA[disk]]></TYPE></DISK><EMPTY_VAR><![CDATA[]]>"
"</EMPTY_VAR><GRAPHICS><PORT><![CDATA[12]]></PORT><VNC><![CDATA[127.0.0"
".1]]></VNC></GRAPHICS><MEMORY><![CDATA[345]]></MEMORY><REQUIREMENTS>"
"<![CDATA[HOSTNAME = \"host*.com\"]]></REQUIREMENTS><XTRA><![CDATA[44]]"
"></XTRA></TEMPLATE>";
SingleAttribute *b = new SingleAttribute(nattr,vattr);
t1->set(b);
t1->to_xml(xml);
CPPUNIT_ASSERT(t1_xml == xml);
string tr_xml="<TEMPLATE><CPU><![CDATA[5]]></CPU><DISK><EXTRA><![CDATA["
"str]]></EXTRA><FILE><![CDATA[path2]]></FILE><TYPE><![CDATA[disk]]></TY"
"PE></DISK><EMPTY_VAR><![CDATA[]]></EMPTY_VAR><GRAPHICS><PORT><![CDATA["
"12]]></PORT><VNC><![CDATA[127.0.0.1]]></VNC></GRAPHICS><MEMORY><![CDAT"
"A[345]]></MEMORY><REQUIREMENTS><![CDATA[HOSTNAME = \"host*.com\"]]></R"
"EQUIREMENTS></TEMPLATE>";
SingleAttribute *c = new SingleAttribute(nattr,vattr);
tr->set(c);
tr->to_xml(xml);
CPPUNIT_ASSERT(tr_xml == xml);
}
/* --------------------------------------------------------------------- */
void test_erase()
{
// There are Single and Vector type attributes, and any att. can be
// unique within the template, or not.
int n;
// Non-existing attribute
n = t1->erase("NON_EXISTING_ATT");
CPPUNIT_ASSERT( n == 0 );
// CPU is a Unique & Single Att.
n = t1->erase("CPU");
CPPUNIT_ASSERT( n == 1 );
// GRAPHICS is a Unique & Vector Att.
n = t1->erase("GRAPHICS");
CPPUNIT_ASSERT( n == 1 );
// MEMORY is now a Multiple & Single Att.
SingleAttribute* satt = new SingleAttribute("MEMORY", "123");
t1->set(satt);
n = t1->erase("MEMORY");
CPPUNIT_ASSERT( n == 2 );
// DISK is a Multiple & Vector Att.
n = t1->erase("DISK");
CPPUNIT_ASSERT( n == 2 );
}
/* ********************************************************************* */
/* ********************************************************************* */
static CppUnit::TestSuite * suite()
{
CppUnit::TestSuite *ts=new CppUnit::TestSuite("Template Tests");
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"parse() Test",
&TemplateTest::test_parser));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"marshall() Test",
&TemplateTest::test_marshall));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"xml() Test",
&TemplateTest::test_xml));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"str() Test",
&TemplateTest::test_str));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"get() Test",
&TemplateTest::test_get));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"remove() Test",
&TemplateTest::test_remove));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"set() Test",
&TemplateTest::test_set));
ts->addTest(new CppUnit::TestCaller<TemplateTest>(
"erase() Test",
&TemplateTest::test_erase));
return ts;
}
};
/* ************************************************************************* */
/* ************************************************************************* */
/* ************************************************************************* */
int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
tr.addTest(TemplateTest::suite());
tr.run();
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program 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 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
* 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
*/
#ifdef UGS_LINUX_X11
#include <X11/keysym.h>
#include "cursor.h"
#include "main.h"
#include "input_x11.h"
#include "video_x11.h"
#include <X11/Xutil.h>
RCSID("$Id$")
static KeyCode xlate[256];
Input_X11::Input_X11() {
int i;
Video_X11* videox11;
videox11 = dynamic_cast<Video_X11*>(video);
mouse.dx = mouse.dy = mouse.dz = 0;
mouse.quel = -1;
for(i = 0; i < 4; i++)
mouse.button[i] = RELEASED;
pause = false;
clear_key();
/* Here, I'm just about to go mad. */
for(i = 0; i < 256; i++)
xlate[i] = 0;
for(i = 9; i < 92; i++)
xlate[i] = i - 8;
//xlate[] = SCANCODE_LESS; // 86
//xlate[] = SCANCODE_BREAK; // 101
for(i = 94; i < 97; i++)
xlate[i] = i - 8;
for(i = 97; i < 101; i++)
xlate[i] = i + 5;
for(i = 102; i < 108; i++)
xlate[i] = i + 4;
xlate[108] = 96; /* SCANCODE_KEYPADENTER */
xlate[109] = 97; /* SCANCODE_RIGHTCONTROL */
xlate[110] = 119; /* SCANCODE_BREAK_ALTERNATIVE */
xlate[111] = 99; /* SCANCODE_PRINTSCREEN */
xlate[112] = 98; /* SCANCODE_KEYPADDIVIDE */
xlate[113] = 100; /* SCANCODE_RIGHTALT */
xlate[115] = 219; /* Win left */
xlate[116] = 220; /* Win right */
xlate[117] = 221; /* Win popup */
im = XOpenIM(videox11->display, NULL, NULL, NULL);
if(im) {
ic = XCreateIC(im,
XNInputStyle, XIMPreeditNothing|XIMStatusNothing,
XNClientWindow, videox11->window,
XNFocusWindow, videox11->window,
NULL);
if(!ic) {
msgbox("Warning: unsupported input method\n");
XCloseIM(im);
im = NULL;
}
} else {
msgbox("Warning: error opening X input method\n");
ic = NULL;
}
reraw();
}
Input_X11::~Input_X11() {
if(ic)
XDestroyIC(ic);
if(im)
XCloseIM(im);
}
void Input_X11::clear_key() {
int i;
shift_key = 0;
quel_key = -1;
key_pending = 0;
for(i = 0; i < 256; i++)
keys[i] = 0;
}
void Input_X11::check() {
Video_X11* videox11;
int pending;
if(!video)
return;
videox11 = dynamic_cast<Video_X11*>(video);
for(pending = XPending(videox11->display);
pending > 0;
pending--) {
XEvent event;
XNextEvent(videox11->display, &event);
if(!XFilterEvent(&event, None))
switch(event.type) {
case KeyPress:
case KeyRelease:
process_key(event);
break;
case ButtonPress:
case ButtonRelease:
case LeaveNotify:
case MotionNotify:
process_mouse(event);
break;
case FocusIn:
alt_tab = false;
break;
case FocusOut:
alt_tab = true;
break;
case ClientMessage:
if((Atom)event.xclient.data.l[0] == videox11->delete_win)
quit_game();
break;
case Expose:
if(videox11)
videox11->dirty2(event.xexpose.x,
event.xexpose.y,
event.xexpose.x+event.xexpose.width,
event.xexpose.y+event.xexpose.height);
break;
default:
skelton_msgbox("Unknown XEvent (%i)\n", event.type);
break;
}
}
}
void Input_X11::process_key(XEvent event) {
KeyCode key = xlate[event.xkey.keycode];
char buf[20];
KeySym keysym;
Status status;
int num;
switch(event.type) {
case KeyPress:
keys[key] |= PRESSED;
if(!key)
skelton_msgbox("Unknown KeyCode: %i\n", event.xkey.keycode);
if(israw) {
switch(key) {
case KEY_RSHIFT:
case KEY_LSHIFT:
shift_key |= SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
shift_key |= ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
shift_key |= CONTROL;
break;
case 101:
case 119:
pause = true;
break;
default:
quel_key = key;
}
} else {
if(ic) {
num = XmbLookupString(ic, &event.xkey, buf, 20, &keysym, &status);
} else {
num = XLookupString(&event.xkey, buf, 20, &keysym, NULL);
}
if(num) {
switch(buf[0]) {
case 27:
quel_key = KEY_ESCAPE;
break;
case 10:
case 13:
quel_key = KEY_ENTER;
break;
default:
if(key_pending < MAXKEY) {
key_buf[key_pending].c = buf[0];
key_buf[key_pending].special = false;
key_pending++;
}
}
}
}
break;
case KeyRelease:
keys[key] = RELEASED;
switch(key) {
case KEY_RSHIFT:
case KEY_LSHIFT:
shift_key &= ~SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
shift_key &= ~ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
shift_key &= ~CONTROL;
break;
}
break;
default:
skelton_msgbox("process_key got non-key event\n");
break;
}
}
void Input_X11::process_mouse(XEvent event) {
switch(event.type) {
case ButtonPress:
switch(event.xbutton.button) {
case 1:
if(mouse.button[0] == RELEASED)
mouse.quel = 0;
mouse.button[0] = PRESSED;
break;
case 2:
if(mouse.button[1] == RELEASED)
mouse.quel = 1;
mouse.button[1] = PRESSED;
break;
case 3:
if(mouse.button[2] == RELEASED)
mouse.quel = 2;
mouse.button[2] = PRESSED;
break;
}
break;
case ButtonRelease:
switch(event.xbutton.button) {
case 1:
mouse.button[0] = RELEASED;
break;
case 2:
mouse.button[1] = RELEASED;
break;
case 3:
mouse.button[2] = RELEASED;
break;
}
break;
case LeaveNotify:
cursor->set_pos(-1, -1);
break;
case MotionNotify:
if(cursor)
cursor->set_pos(event.xmotion.x, event.xmotion.y);
break;
default:
skelton_msgbox("process_mouse got non-mouse event\n");
break;
}
}
void Input_X11::deraw() {
israw = false;
}
void Input_X11::reraw() {
israw = true;
}
#endif /* UGS_LINUX_X11 */
<commit_msg>Fixed some spacing.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program 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 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
* 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
*/
#ifdef UGS_LINUX_X11
#include <X11/keysym.h>
#include "cursor.h"
#include "main.h"
#include "input_x11.h"
#include "video_x11.h"
#include <X11/Xutil.h>
RCSID("$Id$")
static KeyCode xlate[256];
Input_X11::Input_X11() {
int i;
Video_X11* videox11;
videox11 = dynamic_cast<Video_X11*>(video);
mouse.dx = mouse.dy = mouse.dz = 0;
mouse.quel = -1;
for(i = 0; i < 4; i++)
mouse.button[i] = RELEASED;
pause = false;
clear_key();
/* Here, I'm just about to go mad. */
for(i = 0; i < 256; i++)
xlate[i] = 0;
for(i = 9; i < 92; i++)
xlate[i] = i - 8;
//xlate[] = SCANCODE_LESS; // 86
//xlate[] = SCANCODE_BREAK; // 101
for(i = 94; i < 97; i++)
xlate[i] = i - 8;
for(i = 97; i < 101; i++)
xlate[i] = i + 5;
for(i = 102; i < 108; i++)
xlate[i] = i + 4;
xlate[108] = 96; /* SCANCODE_KEYPADENTER */
xlate[109] = 97; /* SCANCODE_RIGHTCONTROL */
xlate[110] = 119; /* SCANCODE_BREAK_ALTERNATIVE */
xlate[111] = 99; /* SCANCODE_PRINTSCREEN */
xlate[112] = 98; /* SCANCODE_KEYPADDIVIDE */
xlate[113] = 100; /* SCANCODE_RIGHTALT */
xlate[115] = 219; /* Win left */
xlate[116] = 220; /* Win right */
xlate[117] = 221; /* Win popup */
im = XOpenIM(videox11->display, NULL, NULL, NULL);
if(im) {
ic = XCreateIC(im,
XNInputStyle, XIMPreeditNothing|XIMStatusNothing,
XNClientWindow, videox11->window,
XNFocusWindow, videox11->window,
NULL);
if(!ic) {
msgbox("Warning: unsupported input method\n");
XCloseIM(im);
im = NULL;
}
} else {
msgbox("Warning: error opening X input method\n");
ic = NULL;
}
reraw();
}
Input_X11::~Input_X11() {
if(ic)
XDestroyIC(ic);
if(im)
XCloseIM(im);
}
void Input_X11::clear_key() {
int i;
shift_key = 0;
quel_key = -1;
key_pending = 0;
for(i = 0; i < 256; i++)
keys[i] = 0;
}
void Input_X11::check() {
Video_X11* videox11;
int pending;
if(!video)
return;
videox11 = dynamic_cast<Video_X11*>(video);
for(pending = XPending(videox11->display);
pending > 0;
pending--) {
XEvent event;
XNextEvent(videox11->display, &event);
if(!XFilterEvent(&event, None))
switch(event.type) {
case KeyPress:
case KeyRelease:
process_key(event);
break;
case ButtonPress:
case ButtonRelease:
case LeaveNotify:
case MotionNotify:
process_mouse(event);
break;
case FocusIn:
alt_tab = false;
break;
case FocusOut:
alt_tab = true;
break;
case ClientMessage:
if((Atom)event.xclient.data.l[0] == videox11->delete_win)
quit_game();
break;
case Expose:
if(videox11)
videox11->dirty2(event.xexpose.x,
event.xexpose.y,
event.xexpose.x+event.xexpose.width,
event.xexpose.y+event.xexpose.height);
break;
default:
skelton_msgbox("Unknown XEvent (%i)\n", event.type);
break;
}
}
}
void Input_X11::process_key(XEvent event) {
KeyCode key = xlate[event.xkey.keycode];
char buf[20];
KeySym keysym;
Status status;
int num;
switch(event.type) {
case KeyPress:
keys[key] |= PRESSED;
if(!key)
skelton_msgbox("Unknown KeyCode: %i\n", event.xkey.keycode);
if(israw) {
switch(key) {
case KEY_RSHIFT:
case KEY_LSHIFT:
shift_key |= SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
shift_key |= ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
shift_key |= CONTROL;
break;
case 101:
case 119:
pause = true;
break;
default:
quel_key = key;
}
} else {
if(ic) {
num = XmbLookupString(ic, &event.xkey, buf, 20, &keysym, &status);
} else {
num = XLookupString(&event.xkey, buf, 20, &keysym, NULL);
}
if(num) {
switch(buf[0]) {
case 27:
quel_key = KEY_ESCAPE;
break;
case 10:
case 13:
quel_key = KEY_ENTER;
break;
default:
if(key_pending < MAXKEY) {
key_buf[key_pending].c = buf[0];
key_buf[key_pending].special = false;
key_pending++;
}
}
}
}
break;
case KeyRelease:
keys[key] = RELEASED;
switch(key) {
case KEY_RSHIFT:
case KEY_LSHIFT:
shift_key &= ~SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
shift_key &= ~ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
shift_key &= ~CONTROL;
break;
}
break;
default:
skelton_msgbox("process_key got non-key event\n");
break;
}
}
void Input_X11::process_mouse(XEvent event) {
switch(event.type) {
case ButtonPress:
switch(event.xbutton.button) {
case 1:
if(mouse.button[0] == RELEASED)
mouse.quel = 0;
mouse.button[0] = PRESSED;
break;
case 2:
if(mouse.button[1] == RELEASED)
mouse.quel = 1;
mouse.button[1] = PRESSED;
break;
case 3:
if(mouse.button[2] == RELEASED)
mouse.quel = 2;
mouse.button[2] = PRESSED;
break;
}
break;
case ButtonRelease:
switch(event.xbutton.button) {
case 1:
mouse.button[0] = RELEASED;
break;
case 2:
mouse.button[1] = RELEASED;
break;
case 3:
mouse.button[2] = RELEASED;
break;
}
break;
case LeaveNotify:
cursor->set_pos(-1, -1);
break;
case MotionNotify:
if(cursor)
cursor->set_pos(event.xmotion.x, event.xmotion.y);
break;
default:
skelton_msgbox("process_mouse got non-mouse event\n");
break;
}
}
void Input_X11::deraw() {
israw = false;
}
void Input_X11::reraw() {
israw = true;
}
#endif /* UGS_LINUX_X11 */
<|endoftext|>
|
<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <string>
#include <iomanip>
#include <cstring>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <tr1/memory>
#include <stdlib.h>
#include <signal.h>
#include <fstream>
#include <algorithm>
void Log(int, const char *, ...);
#include "include/RPiHQ_raspistill.h"
#include "include/mode_RPiHQ_mean.h"
#define US_IN_SEC (1000000.0) // microseconds in a second
double mean_history [5] = {0.0,1.0,0.0,1.0,0.0};
int exp_history [5] = {0,0,0,0,0};
int MeanCnt = 0;
double dMean = 1.0; // Mean(n-1)-Mean(n)
int dExp = 1.0; //Exp(n-1)-Exp(n)
int lastExposureChange = 0;
int dExposureChange = 0;
bool createMaskHorizon = true;
bool fastforward = false;
// Test focus
// https://stackoverflow.com/questions/7765810/is-there-a-way-to-detect-if-an-image-is-blurry
// https://drive.google.com/file/d/0B6UHr3GQEkQwYnlDY2dKNTdudjg/view?resourcekey=0-a73PvBnc3a2B5wztAV0QaA
double get_focus_measure(cv::Mat img, modeMeanSetting ¤tModeMeanSetting)
{
cv::Mat lap;
cv::Laplacian(img, lap, CV_64F);
cv::Scalar mu, sigma;
cv::meanStdDev(lap, mu, sigma);
double focusMeasure = sigma.val[0]*sigma.val[0];
Log(3, " > Focus: %'f\n", focusMeasure);
return(focusMeasure);
}
// Calculate new raspistillSettings (exposure, gain)
// Algorithm not perfect, but better than no exposure control at all
float RPiHQcalcMean(const char* fileName, int exposure_us, double gain, raspistillSetting ¤tRaspistillSetting, modeMeanSetting ¤tModeMeanSetting)
{
//Hauptvariablen
double mean;
double mean_diff;
double this_mean;
// Init some values first
if (currentModeMeanSetting.init) {
currentModeMeanSetting.init = false;
currentModeMeanSetting.ExposureLevelMax = log(gain * exposure_us/US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) + 1;
currentModeMeanSetting.ExposureLevelMin = log(1.0 * 1.0 /US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) - 1;
Log(1, " > Valid ExposureLevels: %1.8f to %1.8f\n", currentModeMeanSetting.ExposureLevelMin, currentModeMeanSetting.ExposureLevelMax);
}
// get old ExposureTime
double ExposureTime_s = (double) currentRaspistillSetting.shutter_us/US_IN_SEC;
cv::Mat image = cv::imread(fileName, cv::IMREAD_UNCHANGED);
if (!image.data) {
fprintf(stderr, "*** ERROR Error reading file '%s'\n", basename(fileName));
return(-1);
}
//Then define your mask image
//cv::Mat mask = cv::Mat::zeros(image.size(), image.type());
cv::Mat mask = cv::Mat::zeros(image.size(), CV_8U);
//Define your destination image
cv::Mat dstImage = cv::Mat::zeros(image.size(), CV_8U);
//I assume you want to draw the circle at the center of your image, with a radius of mask.rows/3
cv::circle(mask, cv::Point(mask.cols/2, mask.rows/2), mask.rows/3, cv::Scalar(255, 255, 255), -1, 8, 0);
//Now you can copy your source image to destination image with masking
image.copyTo(dstImage, mask);
if (0)
{
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
// Don't need to save file
bool result = cv::imwrite("mask.jpg", dstImage, compression_params);
if (! result) fprintf(stderr, "*** ERROR: Unable to write to 'mask.jpg'\n");
}
cv::Scalar mean_scalar = cv::mean(image, mask);
switch (image.channels())
{
default: // mono case
Log(3, " > mean_scalar.val[0] %d\n", mean_scalar.val[0]);
mean = mean_scalar.val[0];
break;
case 3: // for color use average of the channels
case 4:
mean = (mean_scalar[0] + mean_scalar[1] + mean_scalar[2]) / 3.0;
break;
}
// Scale to 0-1 range
switch (image.depth())
{
case CV_8U:
mean /= 255.0;
break;
case CV_16U:
mean /= 65535.0;
break;
}
Log(1, " > %s: %.1f sec, mean: %f %f\n", basename(fileName), ExposureTime_s, mean, (currentModeMeanSetting.mean_value - mean));
this_mean = mean; // return current image's mean
// avg of mean history
Log(3, " > MeanCnt: %d, mean_historySize: %d\n", MeanCnt, currentModeMeanSetting.historySize);
mean_history[MeanCnt % currentModeMeanSetting.historySize] = mean;
int values = 0;
mean=0.0;
for (int i=1; i <= currentModeMeanSetting.historySize; i++) {
int idx = (MeanCnt + i) % currentModeMeanSetting.historySize;
Log(1, " > i=%d: idx=%d mean=%1.4f exp=%d\n", i, idx, mean_history[idx], exp_history[idx]);
mean += mean_history[idx] * (double) i;
values += i;
}
int idx = (MeanCnt + currentModeMeanSetting.historySize) % currentModeMeanSetting.historySize;
int idxN1 = (MeanCnt + currentModeMeanSetting.historySize-1) % currentModeMeanSetting.historySize;
dMean = mean_history[idx] - mean_history[idxN1];
dExp = exp_history[idx] - exp_history[idxN1];
// forcast (m_forcast = m_neu + diff = m_neu + m_neu - m_alt = 2*m_neu - m_alt)
double mean_forecast = 2.0 * mean_history[idx] - mean_history[idxN1];
mean_forecast = std::min((double) std::max((double) mean_forecast, 0.0), 1.0);
Log(2, " > mean_forecast: %1.4f\n", mean_forecast);
// gleiche Wertigkeit wie aktueller Wert
mean += mean_forecast * currentModeMeanSetting.historySize;
values += currentModeMeanSetting.historySize;
Log(2, " > values: %d\n", values);
mean = mean / (double) values;
mean_diff = abs(mean - currentModeMeanSetting.mean_value);
Log(2, " > mean_diff: %1.4f\n", mean_diff);
int ExposureChange = currentModeMeanSetting.shuttersteps / 2;
// fast forward
if ((fastforward) || (mean_diff > (currentModeMeanSetting.mean_threshold * 2.0))) {
ExposureChange = std::max(1.0, currentModeMeanSetting.mean_p0 + currentModeMeanSetting.mean_p1 * mean_diff + pow (currentModeMeanSetting.mean_p2 * mean_diff,2.0));
}
// slow forward
else if (mean_diff > (currentModeMeanSetting.mean_threshold)) {
ExposureChange = std::max(1.0, currentModeMeanSetting.mean_p0 + currentModeMeanSetting.mean_p1 * mean_diff);
}
dExposureChange = ExposureChange-lastExposureChange;
lastExposureChange = ExposureChange;
Log(2, " > ExposureChange: %d (%d)\n", ExposureChange, dExposureChange);
if (mean < (currentModeMeanSetting.mean_value - (currentModeMeanSetting.mean_threshold))) {
if ((currentRaspistillSetting.analoggain < gain) || (currentRaspistillSetting.shutter_us < exposure_us)) { // obere Grenze durch Gaim und shutter
currentModeMeanSetting.ExposureLevel += ExposureChange;
}
}
if (mean > (currentModeMeanSetting.mean_value + currentModeMeanSetting.mean_threshold)) {
if (ExposureTime_s <= 1 / US_IN_SEC) { // untere Grenze durch shuttertime
Log(2, " > ExposureTime_s too low - stop !\n");
}
else {
currentModeMeanSetting.ExposureLevel -= ExposureChange;
}
}
// check limits of exposurelevel
currentModeMeanSetting.ExposureLevel = std::max(std::min((int)currentModeMeanSetting.ExposureLevel, (int)currentModeMeanSetting.ExposureLevelMax), (int)currentModeMeanSetting.ExposureLevelMin);
// fastforward ?
if ((currentModeMeanSetting.ExposureLevel == (int)currentModeMeanSetting.ExposureLevelMax) || (currentModeMeanSetting.ExposureLevel == (int)currentModeMeanSetting.ExposureLevelMin)) {
fastforward = true;
Log(2, " > FF aktiviert\n");
}
if ((abs(mean_history[idx] - currentModeMeanSetting.mean_value) < currentModeMeanSetting.mean_threshold) &&
(abs(mean_history[idxN1] - currentModeMeanSetting.mean_value) < currentModeMeanSetting.mean_threshold)) {
fastforward = false;
Log(2, " > FF deaktiviert\n");
}
//#############################################################################################################
// calculate gain und exposuretime
double newGain = std::min(gain, std::max(1.0, pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)) / (exposure_us/US_IN_SEC)));
double deltaGain = newGain - currentRaspistillSetting.analoggain;
if (deltaGain > 2.0) {
currentRaspistillSetting.analoggain += 2.0;
}
else if (deltaGain < -2.0) {
currentRaspistillSetting.analoggain -= 2.0;
}
else {
currentRaspistillSetting.analoggain = newGain;
}
// min=1 us, max=exposure_us
Log(5, "XXXX exposure_US/US_IN_SEC: %.2f, ExposureLevel:%d, shuttersteps: %.2f, analoggain: %.1f, pow=%.2f\n",
exposure_us/US_IN_SEC,
currentModeMeanSetting.ExposureLevel,
currentModeMeanSetting.shuttersteps,
currentRaspistillSetting.analoggain,
pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)));
ExposureTime_s = std::min(exposure_us/US_IN_SEC, std::max(1 / US_IN_SEC, pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)) / currentRaspistillSetting.analoggain));
//#############################################################################################################
// prepare for the next measurement
if (currentModeMeanSetting.quickstart > 0) {
// xxxx TODO: If already at the max exposure and we want to increase, then set quickstart to 0.
// xxxx OR, if at a good exposure, set quickstart to 0.
currentModeMeanSetting.quickstart--;
}
// Exposure gilt fuer die naechste Messung
MeanCnt++;
exp_history[MeanCnt % currentModeMeanSetting.historySize] = currentModeMeanSetting.ExposureLevel;
currentRaspistillSetting.shutter_us = ExposureTime_s * US_IN_SEC;
Log(2, " > Mean: %f, diff: %f, Exposure level:%d (%d), Exposure time:%1.8f ms, analoggain:%1.2f\n", mean, mean_diff, currentModeMeanSetting.ExposureLevel, currentModeMeanSetting.ExposureLevel-exp_history[idx], ExposureTime_s, currentRaspistillSetting.analoggain);
return(this_mean);
}
<commit_msg>cleanup: first exposure with currentRaspistillSetting.shutter_us, so we have to calculate the startpoint for ExposureLevel<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <string>
#include <iomanip>
#include <cstring>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <tr1/memory>
#include <stdlib.h>
#include <signal.h>
#include <fstream>
#include <algorithm>
void Log(int, const char *, ...);
#include "include/RPiHQ_raspistill.h"
#include "include/mode_RPiHQ_mean.h"
#define US_IN_SEC (1000000.0) // microseconds in a second
double mean_history [5] = {0.0,0.0,0.0,0.0,0.0};
int exp_history [5] = {0,0,0,0,0};
int MeanCnt = 0;
double dMean = 1.0; // Mean(n-1)-Mean(n)
int dExp = 1.0; //Exp(n-1)-Exp(n)
int lastExposureChange = 0;
int dExposureChange = 0;
bool createMaskHorizon = true;
bool fastforward = false;
// Test focus
// https://stackoverflow.com/questions/7765810/is-there-a-way-to-detect-if-an-image-is-blurry
// https://drive.google.com/file/d/0B6UHr3GQEkQwYnlDY2dKNTdudjg/view?resourcekey=0-a73PvBnc3a2B5wztAV0QaA
double get_focus_measure(cv::Mat img, modeMeanSetting ¤tModeMeanSetting)
{
cv::Mat lap;
cv::Laplacian(img, lap, CV_64F);
cv::Scalar mu, sigma;
cv::meanStdDev(lap, mu, sigma);
double focusMeasure = sigma.val[0]*sigma.val[0];
Log(3, " > Focus: %'f\n", focusMeasure);
return(focusMeasure);
}
// Calculate new raspistillSettings (exposure, gain)
// Algorithm not perfect, but better than no exposure control at all
float RPiHQcalcMean(const char* fileName, int exposure_us, double gain, raspistillSetting ¤tRaspistillSetting, modeMeanSetting ¤tModeMeanSetting)
{
//Hauptvariablen
double mean;
double mean_diff;
double this_mean;
// Init some values first
if (currentModeMeanSetting.init) {
currentModeMeanSetting.init = false;
currentModeMeanSetting.ExposureLevelMax = log(gain * exposure_us/US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) + 1;
currentModeMeanSetting.ExposureLevelMin = log(1.0 * 1.0 /US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) - 1;
// only for the output
for (int i=0; i < currentModeMeanSetting.historySize; i++) {
mean_history[i] = currentModeMeanSetting.mean_value;
exp_history[i] = log(1.0 * currentRaspistillSetting.shutter_us/US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) - 1;
}
// first exposure with currentRaspistillSetting.shutter_us, so we have to calculate the startpoint for ExposureLevel
currentModeMeanSetting.ExposureLevel = log(1.0 * currentRaspistillSetting.shutter_us/US_IN_SEC) / log (2.0) * pow(currentModeMeanSetting.shuttersteps,2.0) - 1;
Log(1, " > Valid ExposureLevels: %1.8f to %1.8f\n", currentModeMeanSetting.ExposureLevelMin, currentModeMeanSetting.ExposureLevelMax);
}
// get old ExposureTime
double ExposureTime_s = (double) currentRaspistillSetting.shutter_us/US_IN_SEC;
cv::Mat image = cv::imread(fileName, cv::IMREAD_UNCHANGED);
if (!image.data) {
fprintf(stderr, "*** ERROR Error reading file '%s'\n", basename(fileName));
return(-1);
}
//Then define your mask image
//cv::Mat mask = cv::Mat::zeros(image.size(), image.type());
cv::Mat mask = cv::Mat::zeros(image.size(), CV_8U);
//Define your destination image
cv::Mat dstImage = cv::Mat::zeros(image.size(), CV_8U);
//I assume you want to draw the circle at the center of your image, with a radius of mask.rows/3
cv::circle(mask, cv::Point(mask.cols/2, mask.rows/2), mask.rows/3, cv::Scalar(255, 255, 255), -1, 8, 0);
//Now you can copy your source image to destination image with masking
image.copyTo(dstImage, mask);
if (0)
{
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
// Don't need to save file
bool result = cv::imwrite("mask.jpg", dstImage, compression_params);
if (! result) fprintf(stderr, "*** ERROR: Unable to write to 'mask.jpg'\n");
}
cv::Scalar mean_scalar = cv::mean(image, mask);
switch (image.channels())
{
default: // mono case
Log(3, " > mean_scalar.val[0] %d\n", mean_scalar.val[0]);
mean = mean_scalar.val[0];
break;
case 3: // for color use average of the channels
case 4:
mean = (mean_scalar[0] + mean_scalar[1] + mean_scalar[2]) / 3.0;
break;
}
// Scale to 0-1 range
switch (image.depth())
{
case CV_8U:
mean /= 255.0;
break;
case CV_16U:
mean /= 65535.0;
break;
}
Log(1, " > %s: %.1f sec, mean: %f %f\n", basename(fileName), ExposureTime_s, mean, (currentModeMeanSetting.mean_value - mean));
this_mean = mean; // return current image's mean
// avg of mean history
Log(3, " > MeanCnt: %d, mean_historySize: %d\n", MeanCnt, currentModeMeanSetting.historySize);
mean_history[MeanCnt % currentModeMeanSetting.historySize] = mean;
int values = 0;
mean=0.0;
for (int i=1; i <= currentModeMeanSetting.historySize; i++) {
int idx = (MeanCnt + i) % currentModeMeanSetting.historySize;
Log(1, " > i=%d: idx=%d mean=%1.4f exp=%d\n", i, idx, mean_history[idx], exp_history[idx]);
mean += mean_history[idx] * (double) i;
values += i;
}
int idx = (MeanCnt + currentModeMeanSetting.historySize) % currentModeMeanSetting.historySize;
int idxN1 = (MeanCnt + currentModeMeanSetting.historySize-1) % currentModeMeanSetting.historySize;
dMean = mean_history[idx] - mean_history[idxN1];
dExp = exp_history[idx] - exp_history[idxN1];
// forcast (m_forcast = m_neu + diff = m_neu + m_neu - m_alt = 2*m_neu - m_alt)
double mean_forecast = 2.0 * mean_history[idx] - mean_history[idxN1];
mean_forecast = std::min((double) std::max((double) mean_forecast, 0.0), 1.0);
Log(2, " > mean_forecast: %1.4f\n", mean_forecast);
// gleiche Wertigkeit wie aktueller Wert
mean += mean_forecast * currentModeMeanSetting.historySize;
values += currentModeMeanSetting.historySize;
Log(2, " > values: %d\n", values);
mean = mean / (double) values;
mean_diff = abs(mean - currentModeMeanSetting.mean_value);
Log(2, " > mean_diff: %1.4f\n", mean_diff);
int ExposureChange = currentModeMeanSetting.shuttersteps / 2;
// fast forward
if ((fastforward) || (mean_diff > (currentModeMeanSetting.mean_threshold * 2.0))) {
ExposureChange = std::max(1.0, currentModeMeanSetting.mean_p0 + currentModeMeanSetting.mean_p1 * mean_diff + pow (currentModeMeanSetting.mean_p2 * mean_diff,2.0));
}
// slow forward
else if (mean_diff > (currentModeMeanSetting.mean_threshold)) {
ExposureChange = std::max(1.0, currentModeMeanSetting.mean_p0 + currentModeMeanSetting.mean_p1 * mean_diff);
}
dExposureChange = ExposureChange-lastExposureChange;
lastExposureChange = ExposureChange;
Log(2, " > ExposureChange: %d (%d)\n", ExposureChange, dExposureChange);
if (mean < (currentModeMeanSetting.mean_value - (currentModeMeanSetting.mean_threshold))) {
if ((currentRaspistillSetting.analoggain < gain) || (currentRaspistillSetting.shutter_us < exposure_us)) { // obere Grenze durch Gaim und shutter
currentModeMeanSetting.ExposureLevel += ExposureChange;
}
}
if (mean > (currentModeMeanSetting.mean_value + currentModeMeanSetting.mean_threshold)) {
if (ExposureTime_s <= 1 / US_IN_SEC) { // untere Grenze durch shuttertime
Log(2, " > ExposureTime_s too low - stop !\n");
}
else {
currentModeMeanSetting.ExposureLevel -= ExposureChange;
}
}
// check limits of exposurelevel
currentModeMeanSetting.ExposureLevel = std::max(std::min((int)currentModeMeanSetting.ExposureLevel, (int)currentModeMeanSetting.ExposureLevelMax), (int)currentModeMeanSetting.ExposureLevelMin);
// fastforward ?
if ((currentModeMeanSetting.ExposureLevel == (int)currentModeMeanSetting.ExposureLevelMax) || (currentModeMeanSetting.ExposureLevel == (int)currentModeMeanSetting.ExposureLevelMin)) {
fastforward = true;
Log(2, " > FF aktiviert\n");
}
if ((abs(mean_history[idx] - currentModeMeanSetting.mean_value) < currentModeMeanSetting.mean_threshold) &&
(abs(mean_history[idxN1] - currentModeMeanSetting.mean_value) < currentModeMeanSetting.mean_threshold)) {
fastforward = false;
Log(2, " > FF deaktiviert\n");
}
//#############################################################################################################
// calculate gain und exposuretime
double newGain = std::min(gain, std::max(1.0, pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)) / (exposure_us/US_IN_SEC)));
double deltaGain = newGain - currentRaspistillSetting.analoggain;
if (deltaGain > 2.0) {
currentRaspistillSetting.analoggain += 2.0;
}
else if (deltaGain < -2.0) {
currentRaspistillSetting.analoggain -= 2.0;
}
else {
currentRaspistillSetting.analoggain = newGain;
}
// min=1 us, max=exposure_us
Log(5, "XXXX exposure_US/US_IN_SEC: %.2f, ExposureLevel:%d, shuttersteps: %.2f, analoggain: %.1f, pow=%.2f\n",
exposure_us/US_IN_SEC,
currentModeMeanSetting.ExposureLevel,
currentModeMeanSetting.shuttersteps,
currentRaspistillSetting.analoggain,
pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)));
ExposureTime_s = std::min(exposure_us/US_IN_SEC, std::max(1 / US_IN_SEC, pow(2.0, double(currentModeMeanSetting.ExposureLevel)/pow(currentModeMeanSetting.shuttersteps,2.0)) / currentRaspistillSetting.analoggain));
//#############################################################################################################
// prepare for the next measurement
if (currentModeMeanSetting.quickstart > 0) {
// xxxx TODO: If already at the max exposure and we want to increase, then set quickstart to 0.
// xxxx OR, if at a good exposure, set quickstart to 0.
currentModeMeanSetting.quickstart--;
}
// Exposure gilt fuer die naechste Messung
MeanCnt++;
exp_history[MeanCnt % currentModeMeanSetting.historySize] = currentModeMeanSetting.ExposureLevel;
currentRaspistillSetting.shutter_us = ExposureTime_s * US_IN_SEC;
Log(2, " > Mean: %f, diff: %f, Exposure level:%d (%d), Exposure time:%1.8f s, analoggain:%1.2f\n", mean, mean_diff, currentModeMeanSetting.ExposureLevel, currentModeMeanSetting.ExposureLevel-exp_history[idx], ExposureTime_s, currentRaspistillSetting.analoggain);
return(this_mean);
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include "logvisor/logvisor.hpp"
#include "nod/nod.hpp"
static void printHelp()
{
fprintf(stderr, "Usage:\n"
" nodtool extract [-f] <image-in> [<dir-out>]\n"
" nodtool makegcn <fsroot-in> [<image-out>]\n"
" nodtool makewii <fsroot-in> [<image-out>]\n"
" nodtool mergegcn <fsroot-in> <image-in> [<image-out>]\n"
" nodtool mergewii <fsroot-in> <image-in> [<image-out>]\n");
}
#if NOD_UCS2
#ifdef strcasecmp
#undef strcasecmp
#endif
#define strcasecmp _wcsicmp
#define PRISize "Iu"
int wmain(int argc, wchar_t* argv[])
#else
#define PRISize "zu"
int main(int argc, char* argv[])
#endif
{
if (argc < 3 ||
(!strcasecmp(argv[1], _S("makegcn")) && argc < 3) ||
(!strcasecmp(argv[1], _S("makewii")) && argc < 3) ||
(!strcasecmp(argv[1], _S("mergegcn")) && argc < 4) ||
(!strcasecmp(argv[1], _S("mergewii")) && argc < 4))
{
printHelp();
return 1;
}
/* Enable logging to console */
logvisor::RegisterStandardExceptions();
logvisor::RegisterConsoleLogger();
bool verbose = false;
nod::ExtractionContext ctx = {true,
[&](std::string_view str, float c) {
if (verbose)
fprintf(stderr, "Current node: %s, Extraction %g%% Complete\n", str.data(), c * 100.f);
}};
const nod::SystemChar* inDir = nullptr;
const nod::SystemChar* outDir = _S(".");
for (int a=2 ; a<argc ; ++a)
{
if (argv[a][0] == '-' && argv[a][1] == 'f')
ctx.force = true;
else if (argv[a][0] == '-' && argv[a][1] == 'v')
verbose = true;
else if (!inDir)
inDir = argv[a];
else
outDir = argv[a];
}
auto progFunc = [&](float prog, nod::SystemStringView name, size_t bytes)
{
nod::Printf(_S("\r "));
if (bytes != -1)
nod::Printf(_S("\r%g%% %s %" PRISize " B"), prog * 100.f, name.data(), bytes);
else
nod::Printf(_S("\r%g%% %s"), prog * 100.f, name.data());
fflush(stdout);
};
if (!strcasecmp(argv[1], _S("extract")))
{
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(inDir, isWii);
if (!disc)
return 1;
nod::Mkdir(outDir, 0755);
nod::Partition* dataPart = disc->getDataPartition();
if (!dataPart)
return 1;
if (!dataPart->extractToDirectory(outDir, ctx))
return 1;
}
else if (!strcasecmp(argv[1], _S("makegcn")))
{
/* Pre-validate path */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::DiscBuilderGCN::CalculateTotalSizeRequired(argv[2]) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 4)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscBuilderGCN b(outPath, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
else
{
nod::DiscBuilderGCN b(argv[3], progFunc);
ret = b.buildFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("makewii")))
{
/* Pre-validate path */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[4]);
return 1;
}
bool dual = false;
if (nod::DiscBuilderWii::CalculateTotalSizeRequired(argv[2], dual) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 4)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscBuilderWii b(outPath.c_str(), dual, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
else
{
nod::DiscBuilderWii b(argv[3], dual, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("mergegcn")))
{
/* Pre-validate paths */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::Stat(argv[3], &theStat) || !S_ISREG(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as file"), argv[3]);
return 1;
}
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(argv[3], isWii);
if (!disc)
{
nod::LogModule.report(logvisor::Error, _S("unable to open image %s"), argv[3]);
return 1;
}
if (isWii)
{
nod::LogModule.report(logvisor::Error, _S("Wii images should be merged with 'mergewii'"));
return 1;
}
if (nod::DiscMergerGCN::CalculateTotalSizeRequired(static_cast<nod::DiscGCN&>(*disc), argv[2]) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 5)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscMergerGCN b(outPath.c_str(), static_cast<nod::DiscGCN&>(*disc), progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
else
{
nod::DiscMergerGCN b(argv[4], static_cast<nod::DiscGCN&>(*disc), progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("mergewii")))
{
/* Pre-validate paths */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::Stat(argv[3], &theStat) || !S_ISREG(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as file"), argv[3]);
return 1;
}
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(argv[3], isWii);
if (!disc)
{
nod::LogModule.report(logvisor::Error, _S("unable to open image %s"), argv[3]);
return 1;
}
if (!isWii)
{
nod::LogModule.report(logvisor::Error, _S("GameCube images should be merged with 'mergegcn'"));
return 1;
}
bool dual = false;
if (nod::DiscMergerWii::CalculateTotalSizeRequired(static_cast<nod::DiscWii&>(*disc), argv[2], dual) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 5)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscMergerWii b(outPath.c_str(), static_cast<nod::DiscWii&>(*disc), dual, progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
else
{
nod::DiscMergerWii b(argv[4], static_cast<nod::DiscWii&>(*disc), dual, progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else
{
printHelp();
return 1;
}
nod::LogModule.report(logvisor::Info, _S("Success!"));
return 0;
}
<commit_msg>Driver fix<commit_after>#include <cstdio>
#include <cstring>
#include "logvisor/logvisor.hpp"
#include "nod/nod.hpp"
static void printHelp()
{
fprintf(stderr, "Usage:\n"
" nodtool extract [-f] <image-in> [<dir-out>]\n"
" nodtool makegcn <fsroot-in> [<image-out>]\n"
" nodtool makewii <fsroot-in> [<image-out>]\n"
" nodtool mergegcn <fsroot-in> <image-in> [<image-out>]\n"
" nodtool mergewii <fsroot-in> <image-in> [<image-out>]\n");
}
#if NOD_UCS2
#ifdef strcasecmp
#undef strcasecmp
#endif
#define strcasecmp _wcsicmp
#define PRISize "Iu"
int wmain(int argc, wchar_t* argv[])
#else
#define PRISize "zu"
int main(int argc, char* argv[])
#endif
{
if (argc < 3 ||
(!strcasecmp(argv[1], _S("makegcn")) && argc < 3) ||
(!strcasecmp(argv[1], _S("makewii")) && argc < 3) ||
(!strcasecmp(argv[1], _S("mergegcn")) && argc < 4) ||
(!strcasecmp(argv[1], _S("mergewii")) && argc < 4))
{
printHelp();
return 1;
}
/* Enable logging to console */
logvisor::RegisterStandardExceptions();
logvisor::RegisterConsoleLogger();
bool verbose = false;
nod::ExtractionContext ctx = {true,
[&](std::string_view str, float c) {
if (verbose)
fprintf(stderr, "Current node: %s, Extraction %g%% Complete\n", str.data(), c * 100.f);
}};
const nod::SystemChar* inDir = nullptr;
const nod::SystemChar* outDir = _S(".");
for (int a=2 ; a<argc ; ++a)
{
if (argv[a][0] == '-' && argv[a][1] == 'f')
ctx.force = true;
else if (argv[a][0] == '-' && argv[a][1] == 'v')
verbose = true;
else if (!inDir)
inDir = argv[a];
else
outDir = argv[a];
}
auto progFunc = [&](float prog, nod::SystemStringView name, size_t bytes)
{
nod::Printf(_S("\r "));
if (bytes != -1)
nod::Printf(_S("\r%g%% %s %" PRISize " B"), prog * 100.f, name.data(), bytes);
else
nod::Printf(_S("\r%g%% %s"), prog * 100.f, name.data());
fflush(stdout);
};
if (!strcasecmp(argv[1], _S("extract")))
{
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(inDir, isWii);
if (!disc)
return 1;
nod::Mkdir(outDir, 0755);
nod::IPartition* dataPart = disc->getDataPartition();
if (!dataPart)
return 1;
if (!dataPart->extractToDirectory(outDir, ctx))
return 1;
}
else if (!strcasecmp(argv[1], _S("makegcn")))
{
/* Pre-validate path */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::DiscBuilderGCN::CalculateTotalSizeRequired(argv[2]) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 4)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscBuilderGCN b(outPath, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
else
{
nod::DiscBuilderGCN b(argv[3], progFunc);
ret = b.buildFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("makewii")))
{
/* Pre-validate path */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[4]);
return 1;
}
bool dual = false;
if (nod::DiscBuilderWii::CalculateTotalSizeRequired(argv[2], dual) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 4)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscBuilderWii b(outPath.c_str(), dual, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
else
{
nod::DiscBuilderWii b(argv[3], dual, progFunc);
ret = b.buildFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("mergegcn")))
{
/* Pre-validate paths */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::Stat(argv[3], &theStat) || !S_ISREG(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as file"), argv[3]);
return 1;
}
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(argv[3], isWii);
if (!disc)
{
nod::LogModule.report(logvisor::Error, _S("unable to open image %s"), argv[3]);
return 1;
}
if (isWii)
{
nod::LogModule.report(logvisor::Error, _S("Wii images should be merged with 'mergewii'"));
return 1;
}
if (nod::DiscMergerGCN::CalculateTotalSizeRequired(static_cast<nod::DiscGCN&>(*disc), argv[2]) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 5)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscMergerGCN b(outPath.c_str(), static_cast<nod::DiscGCN&>(*disc), progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
else
{
nod::DiscMergerGCN b(argv[4], static_cast<nod::DiscGCN&>(*disc), progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else if (!strcasecmp(argv[1], _S("mergewii")))
{
/* Pre-validate paths */
nod::Sstat theStat;
if (nod::Stat(argv[2], &theStat) || !S_ISDIR(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as directory"), argv[2]);
return 1;
}
if (nod::Stat(argv[3], &theStat) || !S_ISREG(theStat.st_mode))
{
nod::LogModule.report(logvisor::Error, _S("unable to stat %s as file"), argv[3]);
return 1;
}
bool isWii;
std::unique_ptr<nod::DiscBase> disc = nod::OpenDiscFromImage(argv[3], isWii);
if (!disc)
{
nod::LogModule.report(logvisor::Error, _S("unable to open image %s"), argv[3]);
return 1;
}
if (!isWii)
{
nod::LogModule.report(logvisor::Error, _S("GameCube images should be merged with 'mergegcn'"));
return 1;
}
bool dual = false;
if (nod::DiscMergerWii::CalculateTotalSizeRequired(static_cast<nod::DiscWii&>(*disc), argv[2], dual) == -1)
return 1;
nod::EBuildResult ret;
if (argc < 5)
{
nod::SystemString outPath(argv[2]);
outPath.append(_S(".iso"));
nod::DiscMergerWii b(outPath.c_str(), static_cast<nod::DiscWii&>(*disc), dual, progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
else
{
nod::DiscMergerWii b(argv[4], static_cast<nod::DiscWii&>(*disc), dual, progFunc);
ret = b.mergeFromDirectory(argv[2]);
}
printf("\n");
if (ret != nod::EBuildResult::Success)
return 1;
}
else
{
printHelp();
return 1;
}
nod::LogModule.report(logvisor::Info, _S("Success!"));
return 0;
}
<|endoftext|>
|
<commit_before>#include <Flight_controller.h>
#include <Logger.h>
#include <unistd.h>
//Initialization of the static variable
mutex Flight_controller::flight_controller_lock;
Flight_controller::Flight_controller(Logger &logger):logger(logger), orientation_manager(logger){
desired_pitch = 0.0;
desired_yaw = 0.0;
desired_roll = 0.0;
roll_precision = 0;
pitch_precision = 0;
yaw_precision = 0;
}
/**
* To init the flight controller
*/
int Flight_controller::init(int update_frequency_ms){
this->update_frequency_ms = update_frequency_ms;
// Launching the task necessary for flight_controller
logger.log(LOG_INFO, "Launching orientation manager");
orientation_manager.init(ORIENTATION_MANAGER_UPDATE_FREQUENCY_MS);
// Launching the flight controllerN
run = true;
flight_controller_task = thread(&Flight_controller::_main_task, this);
return 0;
}
/**
* Allow to teardown the flight controller
*/
int Flight_controller::teardown(){
orientation_manager.teardown();
run = false;
flight_controller_task.join();
logger.log(LOG_INFO, "Flight Controller task terminated");
return 0;
}
/**
* Allow to command the pitch
* desired_pitch : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_pitch(float desired_pitch, int precision){
flight_controller_lock.lock();
this->desired_pitch = desired_pitch;
this->pitch_precision = precision;
flight_controller_lock.unlock();
}
/**
* Allow to command the roll
* desired_roll : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_roll(float desired_roll, int precision){
flight_controller_lock.lock();
this->desired_roll = desired_roll;
this->roll_precision = precision;
flight_controller_lock.unlock();
}
/**
* Allow to command the yaw
* desired_yaw : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_yaw(float desired_yaw, int precision){
flight_controller_lock.lock();
this->desired_yaw = desired_yaw;
this->yaw_precision = precision;
flight_controller_lock.unlock();
}
void Flight_controller::_main_task(){
while(run){
logger.log(LOG_ERROR, "Do nothing");
flight_controller_lock.lock();
flight_controller_lock.unlock();
usleep(update_frequency_ms*1000);
}
}
<commit_msg>Add comment<commit_after>#include <Flight_controller.h>
#include <Logger.h>
#include <unistd.h>
//Initialization of the static variable
mutex Flight_controller::flight_controller_lock;
Flight_controller::Flight_controller(Logger &logger):logger(logger), orientation_manager(logger){
desired_pitch = 0.0;
desired_yaw = 0.0;
desired_roll = 0.0;
roll_precision = 0;
pitch_precision = 0;
yaw_precision = 0;
}
/**
* To init the flight controller
*/
int Flight_controller::init(int update_frequency_ms){
this->update_frequency_ms = update_frequency_ms;
// Launching the task necessary for flight_controller
logger.log(LOG_INFO, "Launching orientation manager");
orientation_manager.init(ORIENTATION_MANAGER_UPDATE_FREQUENCY_MS);
// Launching the flight controllerN
run = true;
flight_controller_task = thread(&Flight_controller::_main_task, this);
return 0;
}
/**
* Allow to teardown the flight controller
*/
int Flight_controller::teardown(){
orientation_manager.teardown();
run = false;
flight_controller_task.join();
logger.log(LOG_INFO, "Flight Controller task terminated");
return 0;
}
/**
* Allow to command the pitch
* desired_pitch : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_pitch(float desired_pitch, int precision){
flight_controller_lock.lock();
this->desired_pitch = desired_pitch;
this->pitch_precision = precision;
flight_controller_lock.unlock();
}
/**
* Allow to command the roll
* desired_roll : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_roll(float desired_roll, int precision){
flight_controller_lock.lock();
this->desired_roll = desired_roll;
this->roll_precision = precision;
flight_controller_lock.unlock();
}
/**
* Allow to command the yaw
* desired_yaw : the desired angle
* precision : the input - output tolerance
*/
int Flight_controller::command_yaw(float desired_yaw, int precision){
flight_controller_lock.lock();
this->desired_yaw = desired_yaw;
this->yaw_precision = precision;
flight_controller_lock.unlock();
}
/**
* This is the main task of the Flight Controller
* It will receives the informations on the orientation and the desired orientation
* It will command the motors in order to fit the command
*/
void Flight_controller::_main_task(){
while(run){
flight_controller_lock.lock();
logger.log(LOG_ERROR, "Not implemented yet");
flight_controller_lock.unlock();
usleep(update_frequency_ms*1000);
}
}
<|endoftext|>
|
<commit_before>// $Id: vertex1.C,v 1.5 2000/03/15 08:44:38 oliver Exp $
#include <BALL/VIEW/KERNEL/vertex1.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
Vertex::Vertex()
: vertex1_(),
vertex1_ptr_(&vertex1_)
{
}
Vertex::Vertex(const Vertex& v, bool deep)
: vertex1_(v.vertex1_),
vertex1_ptr_(v.vertex1_ptr_)
{
}
Vertex::~Vertex()
{
#ifdef BALL_VIEW_DEBUG
cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Vertex>() << endl;
#endif
destroy();
}
void Vertex::clear()
{
vertex1_.set(0.0);
vertex1_ptr_ = &vertex1_;
}
void Vertex::destroy()
{
clear();
}
void Vertex::set(const Vertex& v, bool deep)
{
vertex1_.set(v.vertex1_, deep);
vertex1_ptr_ = v.vertex1_ptr_;
}
Vertex& Vertex::operator = (const Vertex& v)
{
set(v);
return *this;
}
void Vertex::get(Vertex& v, bool deep) const
{
v.set(*this, deep);
}
void Vertex::swap(Vertex& v)
{
Vector3 *tmp_vector = vertex1_ptr_;
if (v.vertex1_ptr_ != &v.vertex1_)
{
vertex1_ptr_ = v.vertex1_ptr_;
if (tmp_vector != &vertex1_)
{
v.vertex1_ptr_ = tmp_vector;
}
else
{
v.vertex1_ptr_ = &v.vertex1_;
}
}
else if (vertex1_ptr_ != &vertex1_)
{
v.vertex1_ptr_ = tmp_vector;
vertex1_ptr_ = &v.vertex1_;
}
vertex1_.swap(v.vertex1_);
}
bool Vertex::isValid() const
{
return (bool)(vertex1_.isValid() == true);
}
void Vertex::dump
(ostream& s, Size depth) const
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "vertex1 : " << vertex1_ << endl;
BALL_DUMP_DEPTH(s, depth);
s << "*vertex1 : " << (*vertex1_ptr_) << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void Vertex::read(istream & /* s */)
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void Vertex::write(ostream & /* s */) const
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/VIEW/KERNEL/vertex1.iC>
# endif
} // namespace VIEW
} // namespace BALL
<commit_msg>fixed: superfluous bool argument<commit_after>// $Id: vertex1.C,v 1.6 2000/03/27 12:06:24 oliver Exp $
#include <BALL/VIEW/KERNEL/vertex1.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
Vertex::Vertex()
: vertex1_(),
vertex1_ptr_(&vertex1_)
{
}
Vertex::Vertex(const Vertex& v, bool deep)
: vertex1_(v.vertex1_),
vertex1_ptr_(v.vertex1_ptr_)
{
}
Vertex::~Vertex()
{
#ifdef BALL_VIEW_DEBUG
cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Vertex>() << endl;
#endif
destroy();
}
void Vertex::clear()
{
vertex1_.set(0.0);
vertex1_ptr_ = &vertex1_;
}
void Vertex::destroy()
{
clear();
}
void Vertex::set(const Vertex& v, bool deep)
{
vertex1_.set(v.vertex1_);
vertex1_ptr_ = v.vertex1_ptr_;
}
Vertex& Vertex::operator = (const Vertex& v)
{
set(v);
return *this;
}
void Vertex::get(Vertex& v, bool deep) const
{
v.set(*this, deep);
}
void Vertex::swap(Vertex& v)
{
Vector3 *tmp_vector = vertex1_ptr_;
if (v.vertex1_ptr_ != &v.vertex1_)
{
vertex1_ptr_ = v.vertex1_ptr_;
if (tmp_vector != &vertex1_)
{
v.vertex1_ptr_ = tmp_vector;
}
else
{
v.vertex1_ptr_ = &v.vertex1_;
}
}
else if (vertex1_ptr_ != &vertex1_)
{
v.vertex1_ptr_ = tmp_vector;
vertex1_ptr_ = &v.vertex1_;
}
vertex1_.swap(v.vertex1_);
}
bool Vertex::isValid() const
{
return (bool)(vertex1_.isValid() == true);
}
void Vertex::dump
(ostream& s, Size depth) const
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BALL_DUMP_DEPTH(s, depth);
s << "vertex1 : " << vertex1_ << endl;
BALL_DUMP_DEPTH(s, depth);
s << "*vertex1 : " << (*vertex1_ptr_) << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void Vertex::read(istream & /* s */)
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void Vertex::write(ostream & /* s */) const
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/VIEW/KERNEL/vertex1.iC>
# endif
} // namespace VIEW
} // namespace BALL
<|endoftext|>
|
<commit_before>// @(#) $Id$
// Author: Fons Rademakers 26/11/99
/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// AliTagDB //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <TSystem.h>
#include <TTimeStamp.h>
#include "AliESD.h"
#include "AliRawDB.h"
#include "AliRawEventTag.h"
#include "AliTagDB.h"
#include "AliRawEventHeaderBase.h"
ClassImp(AliTagDB)
//______________________________________________________________________________
AliTagDB::AliTagDB(AliRawEventTag *eventTag, const char* fileName) :
fTagDB(NULL),
fTree(NULL),
fEventTag(eventTag),
fMaxSize(-1),
fFS(""),
fDeleteFiles(kFALSE)
{
// Create tag DB.
if (fileName) {
if (!Create(fileName))
MakeZombie();
}
}
//______________________________________________________________________________
Bool_t AliTagDB::Create(const char* fileName)
{
// Create a new tag DB.
const char *name = fileName;
if (!name) name = GetFileName();
fTagDB = new TFile(name, "RECREATE",
Form("ALICE tag DB (%s)", AliRawDB::GetAliRootTag()), 1);
if (fTagDB->IsZombie()) {
Error("Create", "error opening tag DB");
fTagDB = 0;
return kFALSE;
}
// Put wide read-write permissions
if(gSystem->Chmod(name,438)) {
Error("Create", "can't set permissions for tag DB file");
fTagDB = 0;
return kFALSE;
}
// Create ROOT Tree object container
fTree = new TTree("T", Form("ALICE raw-data tag tree (%s)", AliRawDB::GetAliRootTag()));
fTree->SetAutoSave(100000000); // autosave when 100 Mbyte written
Int_t bufsize = 32000;
Int_t split = 1;
const char *tagname = fEventTag->GetName();
fTree->Branch("TAG", tagname, &fEventTag, bufsize, split);
return kTRUE;
}
//______________________________________________________________________________
void AliTagDB::Close()
{
// Close tag DB.
if (!fTagDB) return;
fTagDB->cd();
// Write the tree.
fTree->Write();
// Close DB, this also deletes the fTree
fTagDB->Close();
if (fDeleteFiles)
gSystem->Unlink(fTagDB->GetName());
delete fTagDB;
fTagDB = 0;
}
//______________________________________________________________________________
Bool_t AliTagDB::NextFile(const char* fileName)
{
// Close te current file and open a new one.
// Returns kFALSE in case opening failed.
Close();
if (!Create(fileName)) return kFALSE;
return kTRUE;
}
//______________________________________________________________________________
void AliTagDB::SetFS(const char* fs)
{
// set the file system location
fFS = fs;
if (fs) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs);
}
}
}
//______________________________________________________________________________
Float_t AliTagDB::GetCompressionFactor() const
{
// Return compression factor.
if (fTree->GetZipBytes() == 0.)
return 1.0;
else
return fTree->GetTotBytes()/fTree->GetZipBytes();
}
//______________________________________________________________________________
const char *AliTagDB::GetFileName() const
{
// Return filename based on hostname and date and time. This will make
// each file unique. The tags will be stored in the /data1/tags directory.
static char fname[1024];
const char *fs = fFS;
// check that fs exists (crude check fails if fs is a file)
gSystem->MakeDirectory(fs);
// Get the run number
Int_t runNumber = -1;
if (fEventTag) {
AliRawEventHeaderBase *header = fEventTag->GetHeader();
if (header) runNumber = header->Get("RunNb");
}
char hostname[1024];
strcpy(hostname, gSystem->HostName());
char *s;
if ((s = strchr(hostname, '.')))
*s = 0;
TTimeStamp ts;
sprintf(fname, "%s/Run%d.%s_%d_%d_%d.RAW.tag.root", fs, runNumber, hostname,
ts.GetDate(), ts.GetTime(), ts.GetNanoSec());
return fname;
}
<commit_msg>Removal of the last sprintf. Using TString instead<commit_after>// @(#) $Id$
// Author: Fons Rademakers 26/11/99
/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// AliTagDB //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <TSystem.h>
#include <TTimeStamp.h>
#include "AliESD.h"
#include "AliRawDB.h"
#include "AliRawEventTag.h"
#include "AliTagDB.h"
#include "AliRawEventHeaderBase.h"
ClassImp(AliTagDB)
//______________________________________________________________________________
AliTagDB::AliTagDB(AliRawEventTag *eventTag, const char* fileName) :
fTagDB(NULL),
fTree(NULL),
fEventTag(eventTag),
fMaxSize(-1),
fFS(""),
fDeleteFiles(kFALSE)
{
// Create tag DB.
if (fileName) {
if (!Create(fileName))
MakeZombie();
}
}
//______________________________________________________________________________
Bool_t AliTagDB::Create(const char* fileName)
{
// Create a new tag DB.
const char *name = fileName;
if (!name) name = GetFileName();
fTagDB = new TFile(name, "RECREATE",
Form("ALICE tag DB (%s)", AliRawDB::GetAliRootTag()), 1);
if (fTagDB->IsZombie()) {
Error("Create", "error opening tag DB");
fTagDB = 0;
return kFALSE;
}
// Put wide read-write permissions
if(gSystem->Chmod(name,438)) {
Error("Create", "can't set permissions for tag DB file");
fTagDB = 0;
return kFALSE;
}
// Create ROOT Tree object container
fTree = new TTree("T", Form("ALICE raw-data tag tree (%s)", AliRawDB::GetAliRootTag()));
fTree->SetAutoSave(100000000); // autosave when 100 Mbyte written
Int_t bufsize = 32000;
Int_t split = 1;
const char *tagname = fEventTag->GetName();
fTree->Branch("TAG", tagname, &fEventTag, bufsize, split);
return kTRUE;
}
//______________________________________________________________________________
void AliTagDB::Close()
{
// Close tag DB.
if (!fTagDB) return;
fTagDB->cd();
// Write the tree.
fTree->Write();
// Close DB, this also deletes the fTree
fTagDB->Close();
if (fDeleteFiles)
gSystem->Unlink(fTagDB->GetName());
delete fTagDB;
fTagDB = 0;
}
//______________________________________________________________________________
Bool_t AliTagDB::NextFile(const char* fileName)
{
// Close te current file and open a new one.
// Returns kFALSE in case opening failed.
Close();
if (!Create(fileName)) return kFALSE;
return kTRUE;
}
//______________________________________________________________________________
void AliTagDB::SetFS(const char* fs)
{
// set the file system location
fFS = fs;
if (fs) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs);
}
}
}
//______________________________________________________________________________
Float_t AliTagDB::GetCompressionFactor() const
{
// Return compression factor.
if (fTree->GetZipBytes() == 0.)
return 1.0;
else
return fTree->GetTotBytes()/fTree->GetZipBytes();
}
//______________________________________________________________________________
const char *AliTagDB::GetFileName() const
{
// Return filename based on hostname and date and time. This will make
// each file unique. The tags will be stored in the /data1/tags directory.
static TString fname;
const char *fs = fFS;
// check that fs exists (crude check fails if fs is a file)
gSystem->MakeDirectory(fs);
// Get the run number
Int_t runNumber = -1;
if (fEventTag) {
AliRawEventHeaderBase *header = fEventTag->GetHeader();
if (header) runNumber = header->Get("RunNb");
}
TString hostname;
hostname.Form("%s",gSystem->HostName());
hostname.Resize(hostname.First('.'));
TTimeStamp ts;
fname.Form("%s/Run%d.%s_%d_%d_%d.RAW.tag.root", fs, runNumber, hostname.Data(),
ts.GetDate(), ts.GetTime(), ts.GetNanoSec());
return fname.Data();
}
<|endoftext|>
|
<commit_before>#include <windows.h>
#include <OvRender.h>
#include <sloverlay.h>
#include <overlay.h>
SlOverlayMenu* Menu;
MenuVars MenuOsd[20];
MenuVars MenuGpu[10];
WCHAR* GroupOpt[] = {L"", L""};
WCHAR* ItemOpt[] = {L"Off", L"On"};
BOOLEAN MnuInitialized;
HANDLE MenuProcessHeap;
//Add menu items to menu
VOID AddItems()
{
Menu->AddGroup(L"OSD", GroupOpt, &MenuOsd[0].Var);
if (MenuOsd[0].Var)
{
Menu->AddItem(L"GPU Core utilization", ItemOpt, &MenuOsd[1].Var);
Menu->AddItem(L"GPU Core temperature", ItemOpt, &MenuOsd[2].Var);
Menu->AddItem(L"GPU Engine Clock", ItemOpt, &MenuOsd[3].Var);
Menu->AddItem(L"GPU Memory Clock", ItemOpt, &MenuOsd[4].Var);
Menu->AddItem(L"GPU VRAM usage", ItemOpt, &MenuOsd[5].Var);
Menu->AddItem(L"CPU utilization", ItemOpt, &MenuOsd[6].Var);
Menu->AddItem(L"CPU temperature", ItemOpt, &MenuOsd[7].Var);
Menu->AddItem(L"RAM usage", ItemOpt, &MenuOsd[8].Var);
Menu->AddItem(L"Max core usage", ItemOpt, &MenuOsd[9].Var);
Menu->AddItem(L"Max thread usage", ItemOpt, &MenuOsd[10].Var);
Menu->AddItem(L"Disk read-write rate", ItemOpt, &MenuOsd[11].Var);
Menu->AddItem(L"Disk response time", ItemOpt, &MenuOsd[12].Var);
Menu->AddItem(L"Frame Buffer count", ItemOpt, &MenuOsd[13].Var);
Menu->AddItem(L"Show Time", ItemOpt, &MenuOsd[14].Var);
Menu->AddItem(L"Reset Overloads", ItemOpt, &MenuOsd[15].Var);
}
Menu->AddGroup(L"GPU", GroupOpt, &MenuGpu[0].Var);
if (MenuGpu[0].Var)
{
Menu->AddItem(L"Force Max Clocks", ItemOpt, &MenuGpu[1].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[2].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[3].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[4].Var);
}
}
VOID ProcessOptions()
{
if (MenuOsd[1].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;
/*else
PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/
//this needs to be fixed, if it was enable by main gui
//checkbox then it'll get disabled. too lazy...
if (MenuOsd[2].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;
if (MenuOsd[3].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
if (MenuOsd[4].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
if (MenuOsd[7].Var > 0)
PushSharedMemory->OSDFlags |= OSD_CPU_TEMP;
if (MenuOsd[8].Var > 0)
PushSharedMemory->OSDFlags |= OSD_RAM;
if (MenuOsd[9].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MCU;
if (MenuOsd[10].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MTU;
if (MenuOsd[11].Var > 0)
PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE;
if (MenuOsd[12].Var > 0)
PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE;
if (MenuOsd[14].Var > 0)
PushSharedMemory->OSDFlags |= OSD_TIME;
if (MenuOsd[15].Var > 0)
{
PushSharedMemory->Overloads = 0;
MenuOsd[15].Var = 0;
}
if (MenuGpu[1].Var > 0)
{
HANDLE hPipe;
DWORD dwWritten;
WCHAR command[] = L"ForceMaxClocks";
hPipe = CreateFile(TEXT("\\\\.\\pipe\\Push"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe != INVALID_HANDLE_VALUE)
{
WriteFile(hPipe, command, sizeof(command), &dwWritten, NULL);
CloseHandle(hPipe);
}
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
PushSharedMemory->Overloads &= ~OSD_GPU_E_CLK;
PushSharedMemory->Overloads &= ~OSD_GPU_M_CLK;
}
}
VOID MnuRender( OvOverlay* Overlay )
{
if (!MnuInitialized)
{
Menu = new SlOverlayMenu(300);
MnuInitialized = TRUE;
}
if( Menu->mSet.MaxItems == 0 )
AddItems();
//Call drawing and navigation functions
Menu->Render(100, 200, Overlay);
}
#define GROUP 1
#define ITEM 2
#define HEIGHT 16
DWORD LightBlue = 0xFF4DD0EB;
DWORD Green = 0xFF33FF00;
DWORD White = 0xFFE6E6E6;
DWORD Blue = 0xFF00A4C5;
WNDPROC OldWNDPROC;
SlOverlayMenu* OvmMenu;
VOID MenuKeyboardHook( WPARAM Key )
{
if (!OvmMenu)
return;
if (Key == VK_INSERT || Key == VK_UP || Key == VK_DOWN || Key == VK_LEFT || Key == VK_RIGHT)
{
switch (Key)
{
case VK_INSERT:
OvmMenu->mSet.Show = !OvmMenu->mSet.Show;
break;
case VK_UP:
{
if (!OvmMenu->mSet.Show)
break;
OvmMenu->mSet.SeletedIndex--;
if (OvmMenu->mSet.SeletedIndex < 0)
OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1;
} break;
case VK_DOWN:
{
if (!OvmMenu->mSet.Show)
break;
OvmMenu->mSet.SeletedIndex++;
if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems)
OvmMenu->mSet.SeletedIndex = 0;
} break;
case VK_LEFT:
{
if (!OvmMenu->mSet.Show)
break;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0)
{
*OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)
OvmMenu->mSet.MaxItems = 0;
}
} break;
case VK_RIGHT:
{
if (!OvmMenu->mSet.Show)
break;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var
&& *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1))
{
*OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)
OvmMenu->mSet.MaxItems = 0;
}
} break;
}
// Update osd items.
ProcessOptions();
}
}
SlOverlayMenu::SlOverlayMenu( int OptionsX )
{
OpX = OptionsX;
mSet.Show = FALSE;
mSet.MaxItems = 0;
mSet.SeletedIndex = 0;
OvmMenu = this;
MenuProcessHeap = GetProcessHeap();
}
void SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type)
{
Items[mSet.MaxItems].Title = Title;
Items[mSet.MaxItems].Options= Options;
Items[mSet.MaxItems].Var = Var;
Items[mSet.MaxItems].MaxValue = MaxValue;
Items[mSet.MaxItems].Type = Type;
mSet.MaxItems++;
}
VOID
SlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay )
{
DWORD ColorOne, ColorTwo;
int ValueOne, ValueTwo;
if (!mSet.Show)
return;
for (int i = 0; i < mSet.MaxItems; i++)
{
ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0;
ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0;
if (i == mSet.SeletedIndex)
{
ColorOne = LightBlue;
ColorTwo = (ValueTwo) ? Green : White;
}
else if (Items[i].Type == GROUP)
{
ColorOne = Blue;
ColorTwo = Blue;
}
else
{
ColorOne = (ValueOne) ? White : White;
ColorTwo = (ValueTwo) ? Green : White;
}
if (Items[i].Type == GROUP)
Overlay->DrawText(Items[i].Title, X, Y, ColorOne);
if (Items[i].Type == ITEM)
Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne);
if (Items[i].Options)
Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo);
Y += HEIGHT;
}
}
<commit_msg>makes more sense than on/off<commit_after>#include <windows.h>
#include <OvRender.h>
#include <sloverlay.h>
#include <overlay.h>
SlOverlayMenu* Menu;
MenuVars MenuOsd[20];
MenuVars MenuGpu[10];
WCHAR* GroupOpt[] = {L"", L""};
WCHAR* ItemOpt[] = {L"Off", L"On"};
WCHAR* PressOpt[] = { L">>", L">>" };
BOOLEAN MnuInitialized;
HANDLE MenuProcessHeap;
//Add menu items to menu
VOID AddItems()
{
Menu->AddGroup(L"OSD", GroupOpt, &MenuOsd[0].Var);
if (MenuOsd[0].Var)
{
Menu->AddItem(L"GPU Core utilization", ItemOpt, &MenuOsd[1].Var);
Menu->AddItem(L"GPU Core temperature", ItemOpt, &MenuOsd[2].Var);
Menu->AddItem(L"GPU Engine Clock", ItemOpt, &MenuOsd[3].Var);
Menu->AddItem(L"GPU Memory Clock", ItemOpt, &MenuOsd[4].Var);
Menu->AddItem(L"GPU VRAM usage", ItemOpt, &MenuOsd[5].Var);
Menu->AddItem(L"CPU utilization", ItemOpt, &MenuOsd[6].Var);
Menu->AddItem(L"CPU temperature", ItemOpt, &MenuOsd[7].Var);
Menu->AddItem(L"RAM usage", ItemOpt, &MenuOsd[8].Var);
Menu->AddItem(L"Max core usage", ItemOpt, &MenuOsd[9].Var);
Menu->AddItem(L"Max thread usage", ItemOpt, &MenuOsd[10].Var);
Menu->AddItem(L"Disk read-write rate", ItemOpt, &MenuOsd[11].Var);
Menu->AddItem(L"Disk response time", ItemOpt, &MenuOsd[12].Var);
Menu->AddItem(L"Frame Buffer count", ItemOpt, &MenuOsd[13].Var);
Menu->AddItem(L"Show Time", ItemOpt, &MenuOsd[14].Var);
Menu->AddItem(L"Reset Overloads", PressOpt, &MenuOsd[15].Var);
}
Menu->AddGroup(L"GPU", GroupOpt, &MenuGpu[0].Var);
if (MenuGpu[0].Var)
{
Menu->AddItem(L"Force Max Clocks", ItemOpt, &MenuGpu[1].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[2].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[3].Var);
Menu->AddItem(L"NULL", ItemOpt, &MenuGpu[4].Var);
}
}
VOID ProcessOptions()
{
if (MenuOsd[1].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;
/*else
PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/
//this needs to be fixed, if it was enable by main gui
//checkbox then it'll get disabled. too lazy...
if (MenuOsd[2].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;
if (MenuOsd[3].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
if (MenuOsd[4].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
if (MenuOsd[7].Var > 0)
PushSharedMemory->OSDFlags |= OSD_CPU_TEMP;
if (MenuOsd[8].Var > 0)
PushSharedMemory->OSDFlags |= OSD_RAM;
if (MenuOsd[9].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MCU;
if (MenuOsd[10].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MTU;
if (MenuOsd[11].Var > 0)
PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE;
if (MenuOsd[12].Var > 0)
PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE;
if (MenuOsd[14].Var > 0)
PushSharedMemory->OSDFlags |= OSD_TIME;
if (MenuOsd[15].Var > 0)
{
PushSharedMemory->Overloads = 0;
MenuOsd[15].Var = 0;
}
if (MenuGpu[1].Var > 0)
{
HANDLE hPipe;
DWORD dwWritten;
WCHAR command[] = L"ForceMaxClocks";
hPipe = CreateFile(TEXT("\\\\.\\pipe\\Push"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe != INVALID_HANDLE_VALUE)
{
WriteFile(hPipe, command, sizeof(command), &dwWritten, NULL);
CloseHandle(hPipe);
}
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
PushSharedMemory->Overloads &= ~OSD_GPU_E_CLK;
PushSharedMemory->Overloads &= ~OSD_GPU_M_CLK;
}
}
VOID MnuRender( OvOverlay* Overlay )
{
if (!MnuInitialized)
{
Menu = new SlOverlayMenu(300);
MnuInitialized = TRUE;
}
if( Menu->mSet.MaxItems == 0 )
AddItems();
//Call drawing and navigation functions
Menu->Render(100, 200, Overlay);
}
#define GROUP 1
#define ITEM 2
#define HEIGHT 16
DWORD LightBlue = 0xFF4DD0EB;
DWORD Green = 0xFF33FF00;
DWORD White = 0xFFE6E6E6;
DWORD Blue = 0xFF00A4C5;
WNDPROC OldWNDPROC;
SlOverlayMenu* OvmMenu;
VOID MenuKeyboardHook( WPARAM Key )
{
if (!OvmMenu)
return;
if (Key == VK_INSERT || Key == VK_UP || Key == VK_DOWN || Key == VK_LEFT || Key == VK_RIGHT)
{
switch (Key)
{
case VK_INSERT:
OvmMenu->mSet.Show = !OvmMenu->mSet.Show;
break;
case VK_UP:
{
if (!OvmMenu->mSet.Show)
break;
OvmMenu->mSet.SeletedIndex--;
if (OvmMenu->mSet.SeletedIndex < 0)
OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1;
} break;
case VK_DOWN:
{
if (!OvmMenu->mSet.Show)
break;
OvmMenu->mSet.SeletedIndex++;
if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems)
OvmMenu->mSet.SeletedIndex = 0;
} break;
case VK_LEFT:
{
if (!OvmMenu->mSet.Show)
break;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0)
{
*OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)
OvmMenu->mSet.MaxItems = 0;
}
} break;
case VK_RIGHT:
{
if (!OvmMenu->mSet.Show)
break;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var
&& *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1))
{
*OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1;
if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)
OvmMenu->mSet.MaxItems = 0;
}
} break;
}
// Update osd items.
ProcessOptions();
}
}
SlOverlayMenu::SlOverlayMenu( int OptionsX )
{
OpX = OptionsX;
mSet.Show = FALSE;
mSet.MaxItems = 0;
mSet.SeletedIndex = 0;
OvmMenu = this;
MenuProcessHeap = GetProcessHeap();
}
void SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type)
{
Items[mSet.MaxItems].Title = Title;
Items[mSet.MaxItems].Options= Options;
Items[mSet.MaxItems].Var = Var;
Items[mSet.MaxItems].MaxValue = MaxValue;
Items[mSet.MaxItems].Type = Type;
mSet.MaxItems++;
}
VOID
SlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay )
{
DWORD ColorOne, ColorTwo;
int ValueOne, ValueTwo;
if (!mSet.Show)
return;
for (int i = 0; i < mSet.MaxItems; i++)
{
ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0;
ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0;
if (i == mSet.SeletedIndex)
{
ColorOne = LightBlue;
ColorTwo = (ValueTwo) ? Green : White;
}
else if (Items[i].Type == GROUP)
{
ColorOne = Blue;
ColorTwo = Blue;
}
else
{
ColorOne = (ValueOne) ? White : White;
ColorTwo = (ValueTwo) ? Green : White;
}
if (Items[i].Type == GROUP)
Overlay->DrawText(Items[i].Title, X, Y, ColorOne);
if (Items[i].Type == ITEM)
Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne);
if (Items[i].Options)
Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo);
Y += HEIGHT;
}
}
<|endoftext|>
|
<commit_before>#include <net/VRNetServer.h>
#include <main/VRLog.h>
#include <main/VRError.h>
using namespace std;
namespace MinVR {
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 100 // how many pending connections queue will hold
#ifndef WIN32
void sigchld_handler(int s) {
while (waitpid(-1, NULL, WNOHANG) > 0);
}
#endif
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
VRNetServer::VRNetServer(const std::string &listenPort, int numExpectedClients)
{
VRLOG_STATUS("VRNetServer starting networking.");
#ifdef WIN32 // Winsock implementation
WSADATA wsaData;
// listen on sock_fd, new connection on new_fd
SOCKET sockfd = INVALID_SOCKET;
SOCKET new_fd = INVALID_SOCKET;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
const char yes = 1;
char saddr[INET6_ADDRSTRLEN];
int rv;
rv = WSAStartup(MAKEWORD(2,2), &wsaData);
if (rv != 0) {
stringstream s;
s << "WSAStartup failed with error: " << rv;
VRERROR(s, "Check for a problem with Windows networking."); exit(1);
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, listenPort.c_str(), &hints, &servinfo)) != 0) {
stringstream s;
s << "getaddrinfo() failed with error: " << rv;
VRERROR(s.str(), "Check for a problem with Windows networking.");
WSACleanup();
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == INVALID_SOCKET) {
stringstream s;
s << "socket() failed with error " << WSAGetLastError() << "; will retry.";
VRLOG_STATUS(s.str());
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == SOCKET_ERROR) {
stringstream s;
s << "setsockopt() failed with error " << WSAGetLastError() << ".";
VRERROR(s.str(), "Check for a problem with Windows networking.");
closesocket(sockfd);
WSACleanup();
exit(1);
}
if (bind(sockfd, p->ai_addr, (int)p->ai_addrlen) == SOCKET_ERROR) {
closesocket(sockfd);
sockfd = INVALID_SOCKET;
stringstream s;
s << "bind() failed with error " << WSAGetLastError() << "; will retry.";
VRLOG_STATUS(s.str());
continue;
}
break;
}
if (p == NULL) {
VRERROR("VRNetServer failed to bind -- exiting.", "Check for a problem with Windows networking.");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == SOCKET_ERROR) {
stringstream s;
s << "listen() failed with error " << WSAGetLastError() << ".";
VRERROR(s.str(), "Check for a problem with Windows networking.");
closesocket(sockfd);
WSACleanup();
exit(1);
}
// Should we do the "reap all dead processes" as in the linux implementation below?
VRLOG_STATUS("VRNetServer waiting for client connection(s)...");
int numConnected = 0;
while (numConnected < numExpectedClients) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == INVALID_SOCKET) {
stringstream s;
s << "accept() got an INVALID_SOCKET; will retry.";
VRLOG_STATUS(s.str());
continue;
}
// Disable Nagle's algorithm on the client's socket
char value = 1;
setsockopt(new_fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
numConnected++;
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), saddr, sizeof saddr);
stringstream s;
s << "Received connection " << numConnected << " of " << numExpectedClients << " from " << saddr;
VRLOG_STATUS(s.str());
_clientSocketFDs.push_back(new_fd);
}
VRLOG_STATUS("Established all expected connections.");
#else // BSD sockets implementation
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char saddr[INET6_ADDRSTRLEN];
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, listenPort.c_str(), &hints, &servinfo)) != 0) {
stringstream s;
s << "getaddrinfo() failed with error: " << gai_strerror(rv);
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
stringstream s;
s << "socket() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
stringstream s;
s << "setsockopt() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
stringstream s;
s << "bind() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
break;
}
if (p == NULL) {
VRERROR("VRNetServer failed to bind -- exiting.", "Check for a problem with networking.");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
stringstream s;
s << "listen() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
stringstream s;
s << "sigaction() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
VRLOG_STATUS("VRNetServer waiting for client connection(s)...");
int numConnected = 0;
while (numConnected < numExpectedClients) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
stringstream s;
s << "accept() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
// Disable Nagle's algorithm on the client's socket
char value = 1;
setsockopt(new_fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
numConnected++;
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), saddr, sizeof saddr);
stringstream s;
s << "Received connection " << numConnected << " of " << numExpectedClients << " from " << saddr;
VRLOG_STATUS(s.str());
_clientSocketFDs.push_back(new_fd);
}
#endif
}
VRNetServer::~VRNetServer()
{
VRLOG_STATUS("VRNetServer closing all sockets.");
for (std::vector<SOCKET>::iterator i=_clientSocketFDs.begin(); i < _clientSocketFDs.end(); i++) {
#ifdef WIN32
closesocket(*i);
#else
close(*i);
#endif
}
#ifdef WIN32
WSACleanup();
#endif
}
// Wait for and receive an eventData message from every client, add
// them together and send them out again.
VRDataQueue VRNetServer::syncEventDataAcrossAllNodes(VRDataQueue eventQueue) {
// TODO: rather than a for loop, could use a select() system call
// here (I think) to figure out which socket is ready for a read in
// the situation where one client is ready but other(s) are not
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
VRDataQueue::serialData eventData = waitForAndReceiveEventData(*itr);
eventQueue.addQueue(eventData);
}
VRDataQueue::serialData serializedEventQueue = eventQueue.serialize();
// 2. send new combined inputEvents array out to all clients
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
sendEventData(*itr, serializedEventQueue);
}
return eventQueue;
}
void VRNetServer::syncSwapBuffersAcrossAllNodes() {
// 1. wait for, receive, and parse a swap_buffers_request message
// from every client
// TODO: rather than a for loop could use a select() system call
// here (I think) to figure out which socket is ready for a read in
// the situation where 1 is ready but other(s) are not
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
waitForAndReceiveSwapBuffersRequest(*itr);
}
// 2. send a swap_buffers_now message to every client
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
sendSwapBuffersNow(*itr);
}
}
} // end namespace MinVR
<commit_msg>Update VRNetServer.cpp<commit_after>#include <net/VRNetServer.h>
#include <main/VRLog.h>
#include <main/VRError.h>
using namespace std;
namespace MinVR {
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 100 // how many pending connections queue will hold
#ifndef WIN32
void sigchld_handler(int s) {
while (waitpid(-1, NULL, WNOHANG) > 0);
}
#endif
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
VRNetServer::VRNetServer(const std::string &listenPort, int numExpectedClients)
{
VRLOG_STATUS("VRNetServer starting networking.");
#ifdef WIN32 // Winsock implementation
WSADATA wsaData;
// listen on sock_fd, new connection on new_fd
SOCKET sockfd = INVALID_SOCKET;
SOCKET new_fd = INVALID_SOCKET;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
const char yes = 1;
char saddr[INET6_ADDRSTRLEN];
int rv;
rv = WSAStartup(MAKEWORD(2,2), &wsaData);
if (rv != 0) {
stringstream s;
s << "WSAStartup failed with error: " << rv;
VRERROR(s.str(), "Check for a problem with Windows networking."); exit(1);
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, listenPort.c_str(), &hints, &servinfo)) != 0) {
stringstream s;
s << "getaddrinfo() failed with error: " << rv;
VRERROR(s.str(), "Check for a problem with Windows networking.");
WSACleanup();
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == INVALID_SOCKET) {
stringstream s;
s << "socket() failed with error " << WSAGetLastError() << "; will retry.";
VRLOG_STATUS(s.str());
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == SOCKET_ERROR) {
stringstream s;
s << "setsockopt() failed with error " << WSAGetLastError() << ".";
VRERROR(s.str(), "Check for a problem with Windows networking.");
closesocket(sockfd);
WSACleanup();
exit(1);
}
if (bind(sockfd, p->ai_addr, (int)p->ai_addrlen) == SOCKET_ERROR) {
closesocket(sockfd);
sockfd = INVALID_SOCKET;
stringstream s;
s << "bind() failed with error " << WSAGetLastError() << "; will retry.";
VRLOG_STATUS(s.str());
continue;
}
break;
}
if (p == NULL) {
VRERROR("VRNetServer failed to bind -- exiting.", "Check for a problem with Windows networking.");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == SOCKET_ERROR) {
stringstream s;
s << "listen() failed with error " << WSAGetLastError() << ".";
VRERROR(s.str(), "Check for a problem with Windows networking.");
closesocket(sockfd);
WSACleanup();
exit(1);
}
// Should we do the "reap all dead processes" as in the linux implementation below?
VRLOG_STATUS("VRNetServer waiting for client connection(s)...");
int numConnected = 0;
while (numConnected < numExpectedClients) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == INVALID_SOCKET) {
stringstream s;
s << "accept() got an INVALID_SOCKET; will retry.";
VRLOG_STATUS(s.str());
continue;
}
// Disable Nagle's algorithm on the client's socket
char value = 1;
setsockopt(new_fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
numConnected++;
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), saddr, sizeof saddr);
stringstream s;
s << "Received connection " << numConnected << " of " << numExpectedClients << " from " << saddr;
VRLOG_STATUS(s.str());
_clientSocketFDs.push_back(new_fd);
}
VRLOG_STATUS("Established all expected connections.");
#else // BSD sockets implementation
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char saddr[INET6_ADDRSTRLEN];
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, listenPort.c_str(), &hints, &servinfo)) != 0) {
stringstream s;
s << "getaddrinfo() failed with error: " << gai_strerror(rv);
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
stringstream s;
s << "socket() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
stringstream s;
s << "setsockopt() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
stringstream s;
s << "bind() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
break;
}
if (p == NULL) {
VRERROR("VRNetServer failed to bind -- exiting.", "Check for a problem with networking.");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
stringstream s;
s << "listen() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
stringstream s;
s << "sigaction() failed.";
VRERROR(s.str(), "Check for a problem with networking.");
exit(1);
}
VRLOG_STATUS("VRNetServer waiting for client connection(s)...");
int numConnected = 0;
while (numConnected < numExpectedClients) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
stringstream s;
s << "accept() failed; will retry.";
VRLOG_STATUS(s.str());
continue;
}
// Disable Nagle's algorithm on the client's socket
char value = 1;
setsockopt(new_fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
numConnected++;
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), saddr, sizeof saddr);
stringstream s;
s << "Received connection " << numConnected << " of " << numExpectedClients << " from " << saddr;
VRLOG_STATUS(s.str());
_clientSocketFDs.push_back(new_fd);
}
#endif
}
VRNetServer::~VRNetServer()
{
VRLOG_STATUS("VRNetServer closing all sockets.");
for (std::vector<SOCKET>::iterator i=_clientSocketFDs.begin(); i < _clientSocketFDs.end(); i++) {
#ifdef WIN32
closesocket(*i);
#else
close(*i);
#endif
}
#ifdef WIN32
WSACleanup();
#endif
}
// Wait for and receive an eventData message from every client, add
// them together and send them out again.
VRDataQueue VRNetServer::syncEventDataAcrossAllNodes(VRDataQueue eventQueue) {
// TODO: rather than a for loop, could use a select() system call
// here (I think) to figure out which socket is ready for a read in
// the situation where one client is ready but other(s) are not
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
VRDataQueue::serialData eventData = waitForAndReceiveEventData(*itr);
eventQueue.addQueue(eventData);
}
VRDataQueue::serialData serializedEventQueue = eventQueue.serialize();
// 2. send new combined inputEvents array out to all clients
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
sendEventData(*itr, serializedEventQueue);
}
return eventQueue;
}
void VRNetServer::syncSwapBuffersAcrossAllNodes() {
// 1. wait for, receive, and parse a swap_buffers_request message
// from every client
// TODO: rather than a for loop could use a select() system call
// here (I think) to figure out which socket is ready for a read in
// the situation where 1 is ready but other(s) are not
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
waitForAndReceiveSwapBuffersRequest(*itr);
}
// 2. send a swap_buffers_now message to every client
for (std::vector<SOCKET>::iterator itr=_clientSocketFDs.begin();
itr < _clientSocketFDs.end(); itr++) {
sendSwapBuffersNow(*itr);
}
}
} // end namespace MinVR
<|endoftext|>
|
<commit_before>/** This is a TcpServer's performance test.
* It could be run in N different modes:
* 1) Local throughput test:
* Clients and server created on the same machine and communicates through the loopback.
* This mode is designated to test server performance locally, on a single machine. And
* this mode is very limited because clients affects the server performance.
* 2) Server mode:
* Application starts in server mode and accepts incomming connections. It can be termia
* ted using ^C signal. This mode can be used to test server performance in isolation.
* Also, this test mode takes network into account. Application should dump number of me
* ssages per second to stdout.
* 3) Client mode:
* Application started in client mode can connect to server (the same application should
* be started on another node in server mode) and dump specified number of messages to
* the server.
*
* Parameters:
* a) `mode` can accept three parameters - 'client', 'server' or 'local'.
* b) `host` url or ip of the server if app was started in client mode.
* c) `count` number of messages to send inf started in client mode.
* d) `njobs` number of threads to use
*/
#include <iostream>
#include <thread>
#include <boost/thread/barrier.hpp>
#include <boost/program_options.hpp>
#include "tcp_server.h"
#include "perftest_tools.h"
#include <sys/time.h>
using namespace Akumuli;
namespace po = boost::program_options;
struct DbMock : DbConnection {
typedef std::tuple<aku_ParamId, aku_TimeStamp, double> ValueT;
aku_ParamId idsum;
aku_TimeStamp tssum;
double valsum;
DbMock() {
idsum = 0;
tssum = 0;
valsum = 0;
}
void write_double(aku_ParamId param, aku_TimeStamp ts, double data) {
idsum += param;
tssum += ts;
valsum += data;
}
};
enum Mode {
CLIENT,
SERVER,
LOCAL,
};
Mode str_to_mode(std::string str) {
if (str == "client" || str == "CLIENT") {
return CLIENT;
} else if (str == "server" || str == "SERVER") {
return SERVER;
} else if (str == "local" || str == "LOCAL") {
return LOCAL;
}
throw std::runtime_error("Bad mode value");
}
struct Server {
Mode mode;
std::shared_ptr<IngestionPipeline> pline;
std::shared_ptr<DbMock> dbcon;
std::shared_ptr<TcpServer> serv;
boost::asio::io_service ioA;
std::vector<IOService*> iovec = { &ioA };
boost::barrier barrier;
Server(Mode mode)
: mode(mode)
, barrier(iovec.size() + 1)
{
dbcon = std::make_shared<DbMock>();
pline = std::make_shared<IngestionPipeline>(dbcon, AKU_LINEAR_BACKOFF);
int port = 4096;
serv = std::make_shared<TcpServer>(iovec, port, pline);
pline->start();
serv->start();
}
//! Run IO service
void start() {
auto iorun = [](IOService& io, boost::barrier& bar) {
auto fn = [&]() {
io.run();
bar.wait();
};
return fn;
};
for (auto io: iovec) {
std::thread iothread(iorun(*io, barrier));
iothread.detach();
}
}
void stop() {
serv->stop();
std::cout << "TcpServer stopped" << std::endl;
// No need to joint I/O threads, just wait until they completes.
barrier.wait();
std::cout << "I/O threads stopped" << std::endl;
pline->stop();
std::cout << "Pipeline stopped" << std::endl;
for (auto io: iovec) {
io->stop();
}
std::cout << "I/O service stopped" << std::endl;
std::cout << dbcon->idsum << " messages received" << std::endl;
}
};
struct Client {
int nthreads;
int count;
boost::barrier start_barrier, stop_barrier;
EndpointT endpoint;
Client(EndpointT ep, int nthreads = 4, int count = 2500000)
: nthreads(nthreads)
, count(count)
, start_barrier(nthreads)
, stop_barrier(nthreads + 1)
, endpoint(ep)
{
}
void start() {
auto self = this;
auto push = [self]() {
IOService io;
TcpSocket socket(io);
std::cout << "Connecting to server at " << self->endpoint << std::endl;
socket.connect(self->endpoint);
self->start_barrier.wait();
boost::asio::streambuf stream;
std::ostream os(&stream);
os << ":1\r\n" ":2\r\n" "+3.14\r\n";
for (int i = self->count; i --> 0; ) {
boost::asio::write(socket, stream);
}
socket.shutdown(TcpSocket::shutdown_both);
self->stop_barrier.wait();
std::cout << "Push process completed" << std::endl;
};
for (int i = 0; i < nthreads; i++) {
std::thread th(push);
th.detach();
}
}
void wait() {
stop_barrier.wait();
}
};
int main(int argc, char *argv[]) {
std::cout << "Tcp server performance test" << std::endl;
po::options_description desc("Allowed options");
/*
* Parameters:
* a) `mode` can accept three parameters - 'client', 'server' or 'local'.
* b) `host` url or ip of the server if app was started in client mode.
* c) `count` number of messages to send inf started in client mode.
* d) `njobs` number of threads to use
*/
std::string strmode;
std::string host;
int num_messages;
desc.add_options()
("help", "produce help message")
("mode", po::value<std::string>(&strmode)->default_value("local"), "test mode")
("host", po::value<std::string>(&host)->default_value("localhost"), "server host in client mode")
("count", po::value<int>(&num_messages)->default_value(1000000), "number of messages to send")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
Mode mode = str_to_mode(strmode);
switch(mode) {
case LOCAL: {
Server server(mode);
EndpointT ep(boost::asio::ip::address_v4::loopback(), 4096);
Client client(ep);
server.start();
client.start();
client.wait();
server.stop();
break;
}
case SERVER:
break;
case CLIENT:
break;
}
return 0;
}
<commit_msg>WIP: tcp server test suite, tcp server now can send data to graphite, individual clients now can measure throughput<commit_after>/** This is a TcpServer's performance test.
* It could be run in N different modes:
* 1) Local throughput test:
* Clients and server created on the same machine and communicates through the loopback.
* This mode is designated to test server performance locally, on a single machine. And
* this mode is very limited because clients affects the server performance.
* 2) Server mode:
* Application starts in server mode and accepts incomming connections. It can be termia
* ted using ^C signal. This mode can be used to test server performance in isolation.
* Also, this test mode takes network into account. Application should dump number of me
* ssages per second to stdout.
* 3) Client mode:
* Application started in client mode can connect to server (the same application should
* be started on another node in server mode) and dump specified number of messages to
* the server.
*
* Parameters:
* a) `mode` can accept three parameters - 'client', 'server' or 'local'.
* b) `host` url or ip of the server if app was started in client mode.
* c) `count` number of messages to send inf started in client mode.
* d) `njobs` number of threads to use
*/
#include <iostream>
#include <thread>
#include <boost/thread/barrier.hpp>
#include <boost/program_options.hpp>
#include "tcp_server.h"
#include "perftest_tools.h"
#include <sys/time.h>
using namespace Akumuli;
namespace po = boost::program_options;
struct DbMock : DbConnection {
typedef std::tuple<aku_ParamId, aku_TimeStamp, double> ValueT;
aku_ParamId idsum;
aku_TimeStamp tssum;
double valsum;
DbMock() {
idsum = 0;
tssum = 0;
valsum = 0;
}
void write_double(aku_ParamId param, aku_TimeStamp ts, double data) {
idsum += param;
tssum += ts;
valsum += data;
}
};
enum Mode {
CLIENT,
SERVER,
LOCAL,
};
Mode str_to_mode(std::string str) {
if (str == "client" || str == "CLIENT") {
return CLIENT;
} else if (str == "server" || str == "SERVER") {
return SERVER;
} else if (str == "local" || str == "LOCAL") {
return LOCAL;
}
throw std::runtime_error("Bad mode value");
}
struct Server {
Mode mode;
std::shared_ptr<IngestionPipeline> pline;
std::shared_ptr<DbMock> dbcon;
std::shared_ptr<TcpServer> serv;
boost::asio::io_service ioA;
std::vector<IOService*> iovec = { &ioA };
boost::barrier barrier;
Server(Mode mode)
: mode(mode)
, barrier(iovec.size() + 1)
{
dbcon = std::make_shared<DbMock>();
pline = std::make_shared<IngestionPipeline>(dbcon, AKU_LINEAR_BACKOFF);
int port = 4096;
serv = std::make_shared<TcpServer>(iovec, port, pline);
pline->start();
serv->start();
}
//! Run IO service
void start() {
auto iorun = [](IOService& io, boost::barrier& bar) {
auto fn = [&]() {
io.run();
bar.wait();
};
return fn;
};
for (auto io: iovec) {
std::thread iothread(iorun(*io, barrier));
iothread.detach();
}
}
void stop() {
serv->stop();
std::cout << "TcpServer stopped" << std::endl;
// No need to joint I/O threads, just wait until they completes.
barrier.wait();
std::cout << "I/O threads stopped" << std::endl;
pline->stop();
std::cout << "Pipeline stopped" << std::endl;
for (auto io: iovec) {
io->stop();
}
std::cout << "I/O service stopped" << std::endl;
std::cout << dbcon->idsum << " messages received" << std::endl;
}
};
struct Client {
int nthreads;
int count;
boost::barrier start_barrier, stop_barrier;
EndpointT endpoint;
PerfTimer *timer;
Client(EndpointT ep, PerfTimer *timer, int nthreads = 4, int count = 2500000)
: nthreads(nthreads)
, count(count)
, start_barrier(nthreads + 1)
, stop_barrier(nthreads + 1)
, endpoint(ep)
, timer(timer)
{
}
void start() {
auto self = this;
auto push = [self]() {
std::vector<double> threshold_values;
IOService io;
TcpSocket socket(io);
std::cout << "Connecting to server at " << self->endpoint << std::endl;
socket.connect(self->endpoint);
self->start_barrier.wait();
boost::asio::streambuf stream;
std::ostream os(&stream);
size_t nsent = 0u;
double tm = self->timer->elapsed();
for (int i = self->count; i --> 0; ) {
os << ":1\r\n" ":2\r\n" "+3.14\r\n";
nsent += boost::asio::write(socket, stream);
if (nsent >= 1024*1024) { // +1Mb was sent
double newtm = self->timer->elapsed();
threshold_values.push_back(newtm - tm);
nsent = 0u;
tm = newtm;
}
}
socket.shutdown(TcpSocket::shutdown_both);
self->stop_barrier.wait();
std::cout << "Push process completed" << std::endl;
if (threshold_values.size()) {
std::sort(threshold_values.begin(), threshold_values.end());
double min = threshold_values.front(), max = threshold_values.back();
double sum = 0, avg = 0, med = threshold_values[threshold_values.size() / 2];
for (auto x: threshold_values) { sum += x; }
avg = sum / threshold_values.size();
auto convert = [&](double val) {
// Convert seconds per Mb to Mb per second
return 1.0/val;
};
std::cout << "Push process performance" << std::endl;
std::cout << "max: " << convert(min) << " Mb/sec" << std::endl; // min and max should be
std::cout << "min: " << convert(max) << " Mb/sec" << std::endl; // swapped because of conv
std::cout << "avg: " << convert(avg) << " Mb/sec" << std::endl;
std::cout << "med: " << convert(med) << " Mb/sec" << std::endl;
}
};
for (int i = 0; i < nthreads; i++) {
std::thread th(push);
th.detach();
}
start_barrier.wait();
timer->restart();
}
void wait() {
stop_barrier.wait();
}
};
int main(int argc, char *argv[]) {
std::cout << "Tcp server performance test" << std::endl;
po::options_description desc("Allowed options");
/*
* Parameters:
* a) `mode` can accept three parameters - 'client', 'server' or 'local'.
* b) `host` url or ip of the server if app was started in client mode.
* c) `count` number of messages to send inf started in client mode.
* d) `njobs` number of threads to use
*/
std::string strmode;
std::string host;
int num_messages;
bool graphite_enabled = false;
desc.add_options()
("help", "produce help message")
("mode", po::value<std::string>(&strmode)->default_value("local"), "test mode")
("host", po::value<std::string>(&host)->default_value("localhost"), "server host in client mode")
("count", po::value<int>(&num_messages)->default_value(1000000), "number of messages to send")
("graphite", po::value<bool>(&graphite_enabled)->default_value(false), "push result to graphite")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
Mode mode = str_to_mode(strmode);
switch(mode) {
case LOCAL: {
PerfTimer tm;
Server server(mode);
EndpointT ep(boost::asio::ip::address_v4::loopback(), 4096);
Client client(ep, &tm, 4, 2500000);
server.start();
client.start();
client.wait();
server.stop();
double elapsed = tm.elapsed();
std::cout << "Local test completed in " << elapsed << " seconds" << std::endl;
if (graphite_enabled) {
push_metric_to_graphite("tcp_server_local", elapsed);
}
break;
}
case SERVER:
break;
case CLIENT:
break;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(const Contigs& contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Size is store in
an uint64_t (ulong) to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
uint64_t nbContigs = contigs.get_nbContigs();
uint64_t ultraSequenceSize = 0;
vector<uint64_t> contigs_size (nbContigs, 0);
for(uint64_t i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
uint64_t i = 0;
//Get each contigs sequence and add it in ultraSequence
for(uint64_t c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU for the run
cl::Event ev;
//infos buffer (64bits): nbcontigs
//buffer only accepts non-dynamics arrays (even of size 1)
uint64_t infos[1] = {ultraSequenceSize};
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);
//sequences sizes (array of 64bits) buffer
cl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs);
m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);
//Update the kernel (gpu function)
m_kernel.setArg(0, buf_infos);
//Run the kernel and wait the end
m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);
ev.wait();
//Clean the memory
delete ultraSequence;
ultraSequence = nullptr;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = 0;
}
)CLCODE";
<commit_msg>Add global ids<commit_after>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(const Contigs& contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Size is store in
an uint64_t (ulong) to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
uint64_t nbContigs = contigs.get_nbContigs();
uint64_t ultraSequenceSize = 0;
vector<uint64_t> contigs_size (nbContigs, 0);
for(uint64_t i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
uint64_t i = 0;
//Get each contigs sequence and add it in ultraSequence
for(uint64_t c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU for the run
cl::Event ev;
//infos buffer (64bits): nbcontigs
//buffer only accepts non-dynamics arrays (even of size 1)
uint64_t infos[1] = {ultraSequenceSize};
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);
//sequences sizes (array of 64bits) buffer
cl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs);
m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);
//Update the kernel (gpu function)
m_kernel.setArg(0, buf_infos);
//Run the kernel and wait the end
m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);
ev.wait();
//Clean the memory
delete ultraSequence;
ultraSequence = nullptr;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = get_global_id(0);
int j = get_global_id(1);
}
)CLCODE";
<|endoftext|>
|
<commit_before>//
// SubFunctions.hpp
//
//
// Created by Myoung-Jong Noh on 3/30/20.
//
#ifndef SubFunctions_hpp
#define SubFunctions_hpp
#include <string.h>
#include <stdio.h>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <iostream>
#include "Typedefine.hpp"
#include "CoordConversion.hpp"
#include "Template.hpp"
#include "setsmgeo.hpp"
#include "grid_triangulation.hpp"
#include <sys/resource.h>
#include <sys/time.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define SUB_RATIO 4.6
char* remove_ext(const char* mystr);
char* GetFileName(char file_path[]);
char* GetFileDir(char file_path[],int *size);
char* SetOutpathName(char *_path);
int Maketmpfolders(ProInfo *info);
double getSystemMemory();
bool GetRAinfo(ProInfo *proinfo, const char* RAfile, double **Imageparams);
bool GetRAinfoFromEcho(ProInfo *proinfo, const char* echofile, double **Imageparams);
bool GetsubareaImage(const int sensor_type, const FrameInfo m_frameinfo, const int ti, const TransParam transparam, const double *ImageParam, const double * const *RPCs, char *ImageFilename, CSize Imagesize, const double *subBoundary, const double *minmaxHeight, long *cols, long *rows);
bool GetImageSize(char *filename, CSize *Imagesize);
bool GetsubareaImage_GeoTiff(ProInfo proinfo, char *ImageFilename, CSize Imagesize, double *subBoundary, long *cols,long *rows);
float* GetDEMValue(char *GIMP_path,CSize seeddem_size);
bool OpenProject(char* _filename, ProInfo *info, ARGINFO args);
bool OpenDMCproject(char* project_path,ProInfo *proinfo, ARGINFO args);
void SetPySizes(CSize *data_size_lr, const CSize Lsubsetsize, const int level);
void RemoveFiles(const ProInfo *proinfo,const char *save_path, char **filename, const int py_level,const bool flag);
double Correlate(const double *L, const double *R, const int N);
double Correlate(const vector<double> &L, const vector<double> &R, const int N);
void SetTranParam_fromGeoTiff(TransParam *param, char* inputfile);
void SetTransParam_param(TransParam *param, bool Hemisphere);
void SetTransParam(double minLat, double minLon, TransParam *param);
void RPCsFree(double **rpcs);
double** OpenXMLFile(ProInfo *proinfo, int ImageID, double* gsd_r, double* gsd_c, double* gsd, BandInfo* band);
double** OpenXMLFile_Pleiades(char* _filename);
double** OpenXMLFile_Planet(char* _filename);
void OpenXMLFile_orientation(char* _filename, ImageInfo *Iinfo);
float median(int n, float* x,float min, float max);
float binmedian(int n, float *x);
double quickselect(double *arr, int n, int k);
double quickselect(vector<double> &arr, int n, int k);
bool CheckOverlap(const D2DPOINT br1_lt, const D2DPOINT br1_rb, const D2DPOINT br2_lt, const D2DPOINT br2_rb);
void Preprocessing(const ProInfo *proinfo, const char *save_path,char **Subsetfile, const uint8 py_level, const CSize * const *data_size_lr, FILE *fid);
void MakeSobelMagnitudeImage(const CSize _img_size,const uint16* _src_image, uint16* _dist_mag_image, int16* _dir);
void Orientation(const CSize imagesize,const uint16* Gmag,const int16* Gdir,const uint8 Template_size, uint8* plhs);
double InterpolatePatch(const uint16 *Image, const long int position, const CSize Imagesize, const double dx, const double dy);
struct KernelPatchArg {
SetKernel &rkernel;
CSize LImagesize;
CSize RImagesize;
const uint16 *left_image;
const uint16 *left_mag_image;
const uint16 *right_image;
const uint16 *right_mag_image;
};
void SetVecKernelValue(const KernelPatchArg &kernel_patch, const int row, const int col, const D2DPOINT &pos_left, const D2DPOINT &pos_right, const int radius2, int *Count_N);
void ComputeMultiNCC(SetKernel &rsetkernel, const int Th_rho, const int *Count_N, double &count_NCC, double &sum_NCC_multi);
D2DPOINT *SetDEMGrid(const double *Boundary, const double Grid_x, const double Grid_y, CSize *Size_2D);
void SetPyramidImages(const ProInfo *proinfo, const int py_level_set, const CSize * const *data_size_lr, uint16 ***SubImages, uint16 ***SubMagImages, uint8 ***SubOriImages);
uint16 *SubsetImageFrombitsToUint16(const int image_bits, char *imagefile, long *cols, long *rows, CSize *subsize);
uint8 *SubsetImageFrombitsToUint8(const int image_bits, char *imagefile, long *cols, long *rows, CSize *subsize);
uint16* LoadPyramidImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
uint16* LoadPyramidMagImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
uint8* LoadPyramidOriImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
GMA_double* GMA_double_create(uint32 size_row, uint32 size_col);
void GMA_double_destroy(GMA_double* in);
void GMA_double_inv(GMA_double *a, GMA_double *I);
void GMA_double_mul(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_Tran(GMA_double *a, GMA_double *out);
void GMA_double_sub(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_sum(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_printf(GMA_double *a);
FullTriangulation *TINCreate_list(D3DPOINT *ptslists, int numofpts, vector<UI3DPOINT> *trilists, double min_max[], int *count_tri, double resolution);
//void TINUpdate(D3DPOINT *ptslists, int numofpts, UI3DPOINT* trilists, double min_max[], int *count_tri, double resolution, FullTriangulation* oldTri, D3DPOINT* blunderlist, int numblunders);
void TINUpdate_list(D3DPOINT *ptslists, int numofpts, vector<UI3DPOINT> *trilists, double min_max[], int *count_tri, double resolution, FullTriangulation* oldTri, D3DPOINT* blunderlist, int numblunders);
void SetTinBoundary(LevelInfo &rlevelinfo, const D3DPOINT &TriP1, const D3DPOINT &TriP2, const D3DPOINT &TriP3, int *PixelMinXY, int *PixelMaxXY, double &Total_Min_Z, double &Total_Max_Z, double &temp_MinZ, double &temp_MaxZ);
bool IsTinInside(const D3DPOINT &CurGPXY, const D3DPOINT &TriP1, const D3DPOINT &TriP2, const D3DPOINT &TriP3, float &Z);
double SetNormalAngle(const D3DPOINT &pts0, const D3DPOINT &pts1, const D3DPOINT &pts2);
void SetAngle(double &angle);
//FullTriangulation *TINCreate_float(F3DPOINT *ptslists, long numofpts, UI3DPOINT* trilists, double min_max[], long *count_tri, double resolution);
//FullTriangulation *TINCreate(D3DPOINT *ptslists, int numofpts, UI3DPOINT* trilists, double min_max[], int *count_tri, double resolution);
CSize Envihdr_reader(char *filename);
CSize Envihdr_reader_seedDEM(TransParam _param, char *filename, double *minX, double *maxY, double *grid_size);
bool TFW_reader_LSFDEM(char *filename, double *minX, double *maxY, double *grid_size, int *zone, char *dir);
//bool TFW_reader_seedDEM(char *filename, double *minX, double *maxY, double *grid_size);
#endif /* SubFunctions_hpp */
<commit_msg>Use constexpr for min/max instead of macro<commit_after>//
// SubFunctions.hpp
//
//
// Created by Myoung-Jong Noh on 3/30/20.
//
#ifndef SubFunctions_hpp
#define SubFunctions_hpp
#include <string.h>
#include <stdio.h>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <iostream>
#include "Typedefine.hpp"
#include "CoordConversion.hpp"
#include "Template.hpp"
#include "setsmgeo.hpp"
#include "grid_triangulation.hpp"
#include <sys/resource.h>
#include <sys/time.h>
// Don't use macros here, they break things in the c++ stdlibrary
// see here for rationale:
// https://en.cppreference.com/w/cpp/language/template_argument_deduction
template<typename T> struct identity { typedef T type; };
template <typename T>
constexpr const T& min(const T& a, const typename identity<T>::type& b) { return a < b ? a : b; }
template <typename T>
constexpr const T& max(const T& a, const typename identity<T>::type& b) { return a > b ? a : b; }
#define SUB_RATIO 4.6
char* remove_ext(const char* mystr);
char* GetFileName(char file_path[]);
char* GetFileDir(char file_path[],int *size);
char* SetOutpathName(char *_path);
int Maketmpfolders(ProInfo *info);
double getSystemMemory();
bool GetRAinfo(ProInfo *proinfo, const char* RAfile, double **Imageparams);
bool GetRAinfoFromEcho(ProInfo *proinfo, const char* echofile, double **Imageparams);
bool GetsubareaImage(const int sensor_type, const FrameInfo m_frameinfo, const int ti, const TransParam transparam, const double *ImageParam, const double * const *RPCs, char *ImageFilename, CSize Imagesize, const double *subBoundary, const double *minmaxHeight, long *cols, long *rows);
bool GetImageSize(char *filename, CSize *Imagesize);
bool GetsubareaImage_GeoTiff(ProInfo proinfo, char *ImageFilename, CSize Imagesize, double *subBoundary, long *cols,long *rows);
float* GetDEMValue(char *GIMP_path,CSize seeddem_size);
bool OpenProject(char* _filename, ProInfo *info, ARGINFO args);
bool OpenDMCproject(char* project_path,ProInfo *proinfo, ARGINFO args);
void SetPySizes(CSize *data_size_lr, const CSize Lsubsetsize, const int level);
void RemoveFiles(const ProInfo *proinfo,const char *save_path, char **filename, const int py_level,const bool flag);
double Correlate(const double *L, const double *R, const int N);
double Correlate(const vector<double> &L, const vector<double> &R, const int N);
void SetTranParam_fromGeoTiff(TransParam *param, char* inputfile);
void SetTransParam_param(TransParam *param, bool Hemisphere);
void SetTransParam(double minLat, double minLon, TransParam *param);
void RPCsFree(double **rpcs);
double** OpenXMLFile(ProInfo *proinfo, int ImageID, double* gsd_r, double* gsd_c, double* gsd, BandInfo* band);
double** OpenXMLFile_Pleiades(char* _filename);
double** OpenXMLFile_Planet(char* _filename);
void OpenXMLFile_orientation(char* _filename, ImageInfo *Iinfo);
float median(int n, float* x,float min, float max);
float binmedian(int n, float *x);
double quickselect(double *arr, int n, int k);
double quickselect(vector<double> &arr, int n, int k);
bool CheckOverlap(const D2DPOINT br1_lt, const D2DPOINT br1_rb, const D2DPOINT br2_lt, const D2DPOINT br2_rb);
void Preprocessing(const ProInfo *proinfo, const char *save_path,char **Subsetfile, const uint8 py_level, const CSize * const *data_size_lr, FILE *fid);
void MakeSobelMagnitudeImage(const CSize _img_size,const uint16* _src_image, uint16* _dist_mag_image, int16* _dir);
void Orientation(const CSize imagesize,const uint16* Gmag,const int16* Gdir,const uint8 Template_size, uint8* plhs);
double InterpolatePatch(const uint16 *Image, const long int position, const CSize Imagesize, const double dx, const double dy);
struct KernelPatchArg {
SetKernel &rkernel;
CSize LImagesize;
CSize RImagesize;
const uint16 *left_image;
const uint16 *left_mag_image;
const uint16 *right_image;
const uint16 *right_mag_image;
};
void SetVecKernelValue(const KernelPatchArg &kernel_patch, const int row, const int col, const D2DPOINT &pos_left, const D2DPOINT &pos_right, const int radius2, int *Count_N);
void ComputeMultiNCC(SetKernel &rsetkernel, const int Th_rho, const int *Count_N, double &count_NCC, double &sum_NCC_multi);
D2DPOINT *SetDEMGrid(const double *Boundary, const double Grid_x, const double Grid_y, CSize *Size_2D);
void SetPyramidImages(const ProInfo *proinfo, const int py_level_set, const CSize * const *data_size_lr, uint16 ***SubImages, uint16 ***SubMagImages, uint8 ***SubOriImages);
uint16 *SubsetImageFrombitsToUint16(const int image_bits, char *imagefile, long *cols, long *rows, CSize *subsize);
uint8 *SubsetImageFrombitsToUint8(const int image_bits, char *imagefile, long *cols, long *rows, CSize *subsize);
uint16* LoadPyramidImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
uint16* LoadPyramidMagImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
uint8* LoadPyramidOriImages(const char *save_path,char *subsetfile,const CSize data_size,const uint8 py_level);
GMA_double* GMA_double_create(uint32 size_row, uint32 size_col);
void GMA_double_destroy(GMA_double* in);
void GMA_double_inv(GMA_double *a, GMA_double *I);
void GMA_double_mul(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_Tran(GMA_double *a, GMA_double *out);
void GMA_double_sub(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_sum(GMA_double *a, GMA_double *b, GMA_double *out);
void GMA_double_printf(GMA_double *a);
FullTriangulation *TINCreate_list(D3DPOINT *ptslists, int numofpts, vector<UI3DPOINT> *trilists, double min_max[], int *count_tri, double resolution);
//void TINUpdate(D3DPOINT *ptslists, int numofpts, UI3DPOINT* trilists, double min_max[], int *count_tri, double resolution, FullTriangulation* oldTri, D3DPOINT* blunderlist, int numblunders);
void TINUpdate_list(D3DPOINT *ptslists, int numofpts, vector<UI3DPOINT> *trilists, double min_max[], int *count_tri, double resolution, FullTriangulation* oldTri, D3DPOINT* blunderlist, int numblunders);
void SetTinBoundary(LevelInfo &rlevelinfo, const D3DPOINT &TriP1, const D3DPOINT &TriP2, const D3DPOINT &TriP3, int *PixelMinXY, int *PixelMaxXY, double &Total_Min_Z, double &Total_Max_Z, double &temp_MinZ, double &temp_MaxZ);
bool IsTinInside(const D3DPOINT &CurGPXY, const D3DPOINT &TriP1, const D3DPOINT &TriP2, const D3DPOINT &TriP3, float &Z);
double SetNormalAngle(const D3DPOINT &pts0, const D3DPOINT &pts1, const D3DPOINT &pts2);
void SetAngle(double &angle);
//FullTriangulation *TINCreate_float(F3DPOINT *ptslists, long numofpts, UI3DPOINT* trilists, double min_max[], long *count_tri, double resolution);
//FullTriangulation *TINCreate(D3DPOINT *ptslists, int numofpts, UI3DPOINT* trilists, double min_max[], int *count_tri, double resolution);
CSize Envihdr_reader(char *filename);
CSize Envihdr_reader_seedDEM(TransParam _param, char *filename, double *minX, double *maxY, double *grid_size);
bool TFW_reader_LSFDEM(char *filename, double *minX, double *maxY, double *grid_size, int *zone, char *dir);
//bool TFW_reader_seedDEM(char *filename, double *minX, double *maxY, double *grid_size);
#endif /* SubFunctions_hpp */
<|endoftext|>
|
<commit_before>#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(DGR);
unitlist.append(DGPaise);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case NXC:
case Nexxie:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case NXC: return QString("NXC");
case Nexxie: return QString("Nexxie");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case NXC: return QString("NexxusCoins");
case Nexxie: return QString("Nexxie (1 / 100)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case NXC: return 100;
case Nexxie: return 100;
default: return 100;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case NXC: return 16; // 21,000,000 (# digits, without commas)
case Nexxie: return 16; // 21,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case NXC: return 2;
case Nexxie: return 2;
default: return 0;
}
}
int BitcoinUnits::step(int unit)
{
switch(unit)
{
case NXC: return 100;
case Nexxie: return 1;
default: return 100;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<commit_msg>Update bitcoinunits.cpp<commit_after>#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(DGR);
unitlist.append(DGPaise);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case NXC:
case Nexxi:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case NXC: return QString("NXC");
case Nexxie: return QString("Nexxie");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case NXC: return QString("NexxusCoins");
case Nexxie: return QString("Nexxie (1 / 100)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case NXC: return 100;
case Nexxie: return 100;
default: return 100;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case NXC: return 16; // 21,000,000 (# digits, without commas)
case Nexxie: return 16; // 21,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case NXC: return 2;
case Nexxie: return 2;
default: return 0;
}
}
int BitcoinUnits::step(int unit)
{
switch(unit)
{
case NXC: return 100;
case Nexxie: return 1;
default: return 100;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Strength in Numbers Foundation
#include "giftcardpage.h"
#include "ui_giftcardpage.h"
#include "giftcardtablemodel.h"
#include "optionsmodel.h"
#include "bitcoingui.h"
#include "creategiftdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"
#include "paperwallet.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QDesktopServices> // dvd add for launching URL
#include <QUrl> // dvd add for launching URL
#ifdef USE_QRCODE
#include "qrcodedialog.h"
#endif
extern int VanityGen(int addrtype, char *prefix, char *pubKey, char *privKey);
GiftCardPage::GiftCardPage(Mode mode, Tabs tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::GiftCardPage),
model(0),
optionsModel(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddressButton->setIcon(QIcon());
ui->templateButton->setIcon(QIcon());
ui->copyToClipboard->setIcon(QIcon());
ui->deleteButton->setIcon(QIcon());
#endif
#ifndef USE_QRCODE
ui->showQRCode->setVisible(false);
#endif
switch(mode)
{
case ForSending:
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
break;
case ForEditing:
ui->buttonBox->setVisible(false);
break;
}
ui->labelExplanation->setVisible(true);
ui->deleteButton->setVisible(true);
ui->signMessage->setVisible(false);
//dvd considering adding a "Give" option from the right click
// Context menu actions
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *copyAddressAction = new QAction(ui->copyToClipboard->text(), this);
QAction *editAction = new QAction(tr("&Edit"), this);
QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this);
// QAction *signMessageAction = new QAction(ui->signMessage->text(), this);
QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this);
deleteAction = new QAction(ui->deleteButton->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
contextMenu->addAction(showQRCodeAction);
contextMenu->addAction(verifyMessageAction);
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboard_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked()));
connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked()));
// connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
// Pass through accept action from button box
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
// Set default filepath to save to
filePath = QDir::homePath();
printf("homePath = %s\n", filePath.toStdString().c_str());
}
GiftCardPage::~GiftCardPage()
{
delete ui;
}
void GiftCardPage::setModel(GiftCardTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(GiftCardTableModel::TypeRole);
proxyModel->setFilterFixedString(GiftCardTableModel::Gift);
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->resizeSection(
GiftCardTableModel::Address, 333);
ui->tableView->horizontalHeader()->setResizeMode(
GiftCardTableModel::Label, QHeaderView::Stretch);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void GiftCardPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void GiftCardPage::on_copyToClipboard_clicked()
{
GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Address);
}
void GiftCardPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Label);
}
void GiftCardPage::onEditAction()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
CreateGiftDialog dlg(CreateGiftDialog::EditGiftAddress);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void GiftCardPage::on_signMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
QString addr;
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
addr = address.toString();
}
emit signMessage(addr);
}
void GiftCardPage::on_verifyMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
QString addr;
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
addr = address.toString();
}
emit verifyMessage(addr);
}
void GiftCardPage::on_newAddressButton_clicked()
{
char strPubKey[256],
strPrivKey[256];
if(!model)
return;
printf("GiftCardPage::on_newAddressButton(): CreateGiftDialog\n");
CreateGiftDialog dlg(CreateGiftDialog::NewGiftAddress);
dlg.setModel(model);
if(dlg.exec())
{
printf("GiftCardPage::on_newAddressButton(): dlg.exec()\n");
newAddressToSelect = dlg.getAddress();
QStringList giftKeys = newAddressToSelect.split(":");
strcpy(strPubKey, giftKeys.at(0).toStdString().c_str());
strcpy(strPrivKey, giftKeys.at(1).toStdString().c_str());
printf("strPubKey = %s\tstrPrivKey = %s\n", strPubKey, strPrivKey);
// QString appDirPath = QCoreApplication::applicationDirPath();
// printf("appDirPath = %s\n", appDirPath.toStdString().c_str());
QString defaultFileName = filePath + QDir::separator() + giftKeys.at(0) + ".html";
QString fileName = GUIUtil::getSaveFileName(
this, tr("Save Gift* Card"), defaultFileName, tr(".html"));
if (!fileName.isNull()) {
PaperWallet pWallet = PaperWallet::PaperWallet(fileName, giftKeys.at(0), giftKeys.at(1), "");
if (pWallet.genWallet()) {
QFile file(fileName);
if (file.exists()) {
// save the user selected folder for easy next use
QFileInfo fileInfo(file.fileName());
filePath = fileInfo.absolutePath();
// launch browser to display/print
QString url = "file://" + fileName;
QDesktopServices::openUrl(QUrl(url));
}
}
}
}
}
void GiftCardPage::on_templateButton_clicked()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Update Templates");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
PaperWallet pWallet = PaperWallet::PaperWallet("", "", "", "");
if (pWallet.updateTemplates())
msgBox.setText("Template Update Successful");
else {
msgBox.setText("Template Update Failed");
msgBox.setInformativeText("Check your network connectivity and retry");
}
msgBox.exec();
}
void GiftCardPage::on_deleteButton_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void GiftCardPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
// In gift tab, allow deletion of selection
ui->deleteButton->setEnabled(true);
ui->deleteButton->setVisible(true);
deleteAction->setEnabled(true);
ui->signMessage->setEnabled(false);
ui->signMessage->setVisible(false);
ui->verifyMessage->setEnabled(true);
ui->verifyMessage->setVisible(true);
ui->copyToClipboard->setEnabled(true);
ui->showQRCode->setEnabled(true);
}
else
{
ui->deleteButton->setEnabled(false);
ui->showQRCode->setEnabled(false);
ui->copyToClipboard->setEnabled(false);
ui->signMessage->setEnabled(false);
ui->verifyMessage->setEnabled(false);
}
}
void GiftCardPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// When this is a tab/widget and not a model dialog, ignore "done"
if(mode == ForEditing)
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void GiftCardPage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Address Book Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", GiftCardTableModel::Label, Qt::EditRole);
writer.addColumn("Address", GiftCardTableModel::Address, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void GiftCardPage::on_showQRCode_clicked()
{
#ifdef USE_QRCODE
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString();
QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this);
if(optionsModel)
dialog->setModel(optionsModel);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
#endif
}
void GiftCardPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void GiftCardPage::selectNewAddress(const QModelIndex &parent, int begin, int end)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, GiftCardTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
<commit_msg>XBUILD is bitching about a "redundant" ::PaperWallet [-permissive] thing !?<commit_after>// Copyright 2016 Strength in Numbers Foundation
#include "giftcardpage.h"
#include "ui_giftcardpage.h"
#include "giftcardtablemodel.h"
#include "optionsmodel.h"
#include "bitcoingui.h"
#include "creategiftdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"
#include "paperwallet.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QDesktopServices> // dvd add for launching URL
#include <QUrl> // dvd add for launching URL
#ifdef USE_QRCODE
#include "qrcodedialog.h"
#endif
extern int VanityGen(int addrtype, char *prefix, char *pubKey, char *privKey);
GiftCardPage::GiftCardPage(Mode mode, Tabs tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::GiftCardPage),
model(0),
optionsModel(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddressButton->setIcon(QIcon());
ui->templateButton->setIcon(QIcon());
ui->copyToClipboard->setIcon(QIcon());
ui->deleteButton->setIcon(QIcon());
#endif
#ifndef USE_QRCODE
ui->showQRCode->setVisible(false);
#endif
switch(mode)
{
case ForSending:
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
break;
case ForEditing:
ui->buttonBox->setVisible(false);
break;
}
ui->labelExplanation->setVisible(true);
ui->deleteButton->setVisible(true);
ui->signMessage->setVisible(false);
//dvd considering adding a "Give" option from the right click
// Context menu actions
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *copyAddressAction = new QAction(ui->copyToClipboard->text(), this);
QAction *editAction = new QAction(tr("&Edit"), this);
QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this);
// QAction *signMessageAction = new QAction(ui->signMessage->text(), this);
QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this);
deleteAction = new QAction(ui->deleteButton->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
contextMenu->addAction(showQRCodeAction);
contextMenu->addAction(verifyMessageAction);
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboard_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked()));
connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked()));
// connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
// Pass through accept action from button box
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
// Set default filepath to save to
filePath = QDir::homePath();
printf("homePath = %s\n", filePath.toStdString().c_str());
}
GiftCardPage::~GiftCardPage()
{
delete ui;
}
void GiftCardPage::setModel(GiftCardTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(GiftCardTableModel::TypeRole);
proxyModel->setFilterFixedString(GiftCardTableModel::Gift);
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->resizeSection(
GiftCardTableModel::Address, 333);
ui->tableView->horizontalHeader()->setResizeMode(
GiftCardTableModel::Label, QHeaderView::Stretch);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void GiftCardPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void GiftCardPage::on_copyToClipboard_clicked()
{
GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Address);
}
void GiftCardPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Label);
}
void GiftCardPage::onEditAction()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
CreateGiftDialog dlg(CreateGiftDialog::EditGiftAddress);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void GiftCardPage::on_signMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
QString addr;
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
addr = address.toString();
}
emit signMessage(addr);
}
void GiftCardPage::on_verifyMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
QString addr;
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
addr = address.toString();
}
emit verifyMessage(addr);
}
void GiftCardPage::on_newAddressButton_clicked()
{
char strPubKey[256],
strPrivKey[256];
if(!model)
return;
printf("GiftCardPage::on_newAddressButton(): CreateGiftDialog\n");
CreateGiftDialog dlg(CreateGiftDialog::NewGiftAddress);
dlg.setModel(model);
if(dlg.exec())
{
printf("GiftCardPage::on_newAddressButton(): dlg.exec()\n");
newAddressToSelect = dlg.getAddress();
QStringList giftKeys = newAddressToSelect.split(":");
strcpy(strPubKey, giftKeys.at(0).toStdString().c_str());
strcpy(strPrivKey, giftKeys.at(1).toStdString().c_str());
printf("strPubKey = %s\tstrPrivKey = %s\n", strPubKey, strPrivKey);
// QString appDirPath = QCoreApplication::applicationDirPath();
// printf("appDirPath = %s\n", appDirPath.toStdString().c_str());
QString defaultFileName = filePath + QDir::separator() + giftKeys.at(0) + ".html";
QString fileName = GUIUtil::getSaveFileName(
this, tr("Save Gift* Card"), defaultFileName, tr(".html"));
if (!fileName.isNull()) {
PaperWallet pWallet = PaperWallet::PaperWallet(fileName, giftKeys.at(0), giftKeys.at(1), "");
if (pWallet.genWallet()) {
QFile file(fileName);
if (file.exists()) {
// save the user selected folder for easy next use
QFileInfo fileInfo(file.fileName());
filePath = fileInfo.absolutePath();
// launch browser to display/print
QString url = "file://" + fileName;
QDesktopServices::openUrl(QUrl(url));
}
}
}
}
}
void GiftCardPage::on_templateButton_clicked()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Update Templates");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
PaperWallet pWallet = PaperWallet("", "", "", "");
if (pWallet.updateTemplates())
msgBox.setText("Template Update Successful");
else {
msgBox.setText("Template Update Failed");
msgBox.setInformativeText("Check your network connectivity and retry");
}
msgBox.exec();
}
void GiftCardPage::on_deleteButton_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void GiftCardPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
// In gift tab, allow deletion of selection
ui->deleteButton->setEnabled(true);
ui->deleteButton->setVisible(true);
deleteAction->setEnabled(true);
ui->signMessage->setEnabled(false);
ui->signMessage->setVisible(false);
ui->verifyMessage->setEnabled(true);
ui->verifyMessage->setVisible(true);
ui->copyToClipboard->setEnabled(true);
ui->showQRCode->setEnabled(true);
}
else
{
ui->deleteButton->setEnabled(false);
ui->showQRCode->setEnabled(false);
ui->copyToClipboard->setEnabled(false);
ui->signMessage->setEnabled(false);
ui->verifyMessage->setEnabled(false);
}
}
void GiftCardPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// When this is a tab/widget and not a model dialog, ignore "done"
if(mode == ForEditing)
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void GiftCardPage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Address Book Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", GiftCardTableModel::Label, Qt::EditRole);
writer.addColumn("Address", GiftCardTableModel::Address, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void GiftCardPage::on_showQRCode_clicked()
{
#ifdef USE_QRCODE
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString();
QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this);
if(optionsModel)
dialog->setModel(optionsModel);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
#endif
}
void GiftCardPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void GiftCardPage::selectNewAddress(const QModelIndex &parent, int begin, int end)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, GiftCardTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
<|endoftext|>
|
<commit_before>#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(qVariantCanConvert<QColor>(value))
{
foreground = qvariant_cast<QColor>(value);
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
currentBalance(-1),
currentStake(0),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
isUpdateRunning = false;
updateConcluderTimer = new QTimer(this);
updateConcluderTimeout = 3000;
updateCheckTimer = new QTimer(this);
updateCheckTimerTimeout = 15*60*1000; //check for updates every 15 minutes
ui->setupUi(this);
setupUpdateControls();
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
updateCheckTimer->start(updateCheckTimerTimeout);
checkForNeblioUpdates();
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
emit transactionClicked(filter->mapToSource(index));
}
void OverviewPage::updateCheckAnimation_frameChanged(int frameNumber) {
if(frameNumber == (bottom_bar_updater_check_movie->frameCount()-1)) {
bottom_bar_updater_check_movie->stop();
}
}
void OverviewPage::checkForNeblioUpdates()
{
if(!isUpdateRunning) {
printf("Checking for updates...\n");
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_spinner_movie);
bottom_bar_updater_spinner_movie->start();
latestVersion.clear();
updateAvailablePromise = boost::promise<bool>();
updateAvailableFuture = updateAvailablePromise.get_future();
boost::thread updaterThread(boost::bind(&NeblioUpdater::checkIfUpdateIsAvailable,
&neblioUpdater,
boost::ref(updateAvailablePromise),
boost::ref(latestVersion)
));
updaterThread.detach();
updateConcluderTimer->start(updateConcluderTimeout);
isUpdateRunning = true;
}
}
void OverviewPage::finishCheckForNeblioUpdates()
{
if(isUpdateRunning) {
printf("Concluding update check...\n");
try {
bool updateAvailable = updateAvailableFuture.get();
if(updateAvailable) {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_no_update_movie);
bottom_bar_updater_no_update_movie->start();
ui->bottom_bar_updater_label->setToolTip("An update exists. Please visit nebl.io and download it.");
} else {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_check_movie);
bottom_bar_updater_check_movie->start();
ui->bottom_bar_updater_label->setToolTip("Your Neblio client is up-to-date.");
}
} catch (std::exception& ex) {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_error_movie);
bottom_bar_updater_error_movie->start();
ui->bottom_bar_updater_label->setToolTip(QString("Unable to retrieve update information: ") + QString(ex.what()));
}
updateConcluderTimer->stop();
printf("Done with updates check.\n");
isUpdateRunning = false;
}
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
int unit = model->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentStake = stake;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
ui->spendable_value_label->setText(BitcoinUnits::formatWithUnit(unit, balance));
ui->stake_value_label->setText(BitcoinUnits::formatWithUnit(unit, stake));
ui->unconfirmed_value_label->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
ui->immature_value_label->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
ui->total_value_label->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
ui->immature_value_label->setVisible(showImmature);
ui->immature_title_label->setVisible(showImmature);
}
void OverviewPage::setupUpdateControls()
{
// Updater animations
QSize updaterIconSize(this->height()/ui->bottom_bar_downscale_factor,
this->height()/ui->bottom_bar_downscale_factor);
bottom_bar_updater_check_movie = new QMovie(":images/update-animated-check", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_check_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_check_movie->start();
bottom_bar_updater_no_update_movie = new QMovie(":images/update-no-update", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_no_update_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_no_update_movie->start();
bottom_bar_updater_error_movie = new QMovie(":images/update-error", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_error_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_error_movie->start();
bottom_bar_updater_spinner_movie = new QMovie(":images/update-spinner", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_spinner_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_spinner_movie->start();
connect(bottom_bar_updater_check_movie, &QMovie::frameChanged,
this, &OverviewPage::updateCheckAnimation_frameChanged);
connect(ui->bottom_bar_updater_label, &ClickableLabel::clicked,
this, &OverviewPage::checkForNeblioUpdates);
connect(updateConcluderTimer, &QTimer::timeout,
this, &OverviewPage::finishCheckForNeblioUpdates);
connect(updateCheckTimer, &QTimer::timeout,
this, &OverviewPage::checkForNeblioUpdates);
}
void OverviewPage::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = model->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
<commit_msg>Renamed some resource files in the source and a tooltip change while updates are running.<commit_after>#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(qVariantCanConvert<QColor>(value))
{
foreground = qvariant_cast<QColor>(value);
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
currentBalance(-1),
currentStake(0),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
isUpdateRunning = false;
updateConcluderTimer = new QTimer(this);
updateConcluderTimeout = 3000;
updateCheckTimer = new QTimer(this);
updateCheckTimerTimeout = 15*60*1000; //check for updates every 15 minutes
ui->setupUi(this);
setupUpdateControls();
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
updateCheckTimer->start(updateCheckTimerTimeout);
checkForNeblioUpdates();
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
emit transactionClicked(filter->mapToSource(index));
}
void OverviewPage::updateCheckAnimation_frameChanged(int frameNumber) {
if(frameNumber == (bottom_bar_updater_check_movie->frameCount()-1)) {
bottom_bar_updater_check_movie->stop();
}
}
void OverviewPage::checkForNeblioUpdates()
{
if(!isUpdateRunning) {
printf("Checking for updates...\n");
ui->bottom_bar_updater_label->setToolTip("Checking for updates...");
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_spinner_movie);
bottom_bar_updater_spinner_movie->start();
latestVersion.clear();
updateAvailablePromise = boost::promise<bool>();
updateAvailableFuture = updateAvailablePromise.get_future();
boost::thread updaterThread(boost::bind(&NeblioUpdater::checkIfUpdateIsAvailable,
&neblioUpdater,
boost::ref(updateAvailablePromise),
boost::ref(latestVersion)
));
updaterThread.detach();
updateConcluderTimer->start(updateConcluderTimeout);
isUpdateRunning = true;
}
}
void OverviewPage::finishCheckForNeblioUpdates()
{
if(isUpdateRunning) {
printf("Concluding update check...\n");
try {
bool updateAvailable = updateAvailableFuture.get();
if(updateAvailable) {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_no_update_movie);
bottom_bar_updater_no_update_movie->start();
ui->bottom_bar_updater_label->setToolTip("An update exists. Please visit nebl.io and download it.");
} else {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_check_movie);
bottom_bar_updater_check_movie->start();
ui->bottom_bar_updater_label->setToolTip("Your Neblio client is up-to-date.");
}
} catch (std::exception& ex) {
ui->bottom_bar_updater_label->setMovie(bottom_bar_updater_error_movie);
bottom_bar_updater_error_movie->start();
ui->bottom_bar_updater_label->setToolTip(QString("Unable to retrieve update information: ") + QString(ex.what()));
}
updateConcluderTimer->stop();
printf("Done with updates check.\n");
isUpdateRunning = false;
}
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
int unit = model->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentStake = stake;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
ui->spendable_value_label->setText(BitcoinUnits::formatWithUnit(unit, balance));
ui->stake_value_label->setText(BitcoinUnits::formatWithUnit(unit, stake));
ui->unconfirmed_value_label->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
ui->immature_value_label->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
ui->total_value_label->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
ui->immature_value_label->setVisible(showImmature);
ui->immature_title_label->setVisible(showImmature);
}
void OverviewPage::setupUpdateControls()
{
// Updater animations
QSize updaterIconSize(this->height()/ui->bottom_bar_downscale_factor,
this->height()/ui->bottom_bar_downscale_factor);
bottom_bar_updater_check_movie = new QMovie(":images/update-animated-check", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_check_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_check_movie->start();
bottom_bar_updater_no_update_movie = new QMovie(":images/update-update-available", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_no_update_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_no_update_movie->start();
bottom_bar_updater_error_movie = new QMovie(":images/update-error", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_error_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_error_movie->start();
bottom_bar_updater_spinner_movie = new QMovie(":images/update-spinner", QByteArray(), ui->bottom_bar_widget);
bottom_bar_updater_spinner_movie->setScaledSize(updaterIconSize);
bottom_bar_updater_spinner_movie->start();
connect(bottom_bar_updater_check_movie, &QMovie::frameChanged,
this, &OverviewPage::updateCheckAnimation_frameChanged);
connect(ui->bottom_bar_updater_label, &ClickableLabel::clicked,
this, &OverviewPage::checkForNeblioUpdates);
connect(updateConcluderTimer, &QTimer::timeout,
this, &OverviewPage::finishCheckForNeblioUpdates);
connect(updateCheckTimer, &QTimer::timeout,
this, &OverviewPage::checkForNeblioUpdates);
}
void OverviewPage::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = model->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/splashscreen.h>
#include <clientversion.h>
#include <interfaces/handler.h>
#include <interfaces/node.h>
#include <interfaces/wallet.h>
#include <qt/guiutil.h>
#include <qt/networkstyle.h>
#include <ui_interface.h>
#include <util/system.h>
#include <util/translation.h>
#include <version.h>
#include <QApplication>
#include <QCloseEvent>
#include <QPainter>
#include <QRadialGradient>
#include <QScreen>
SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) :
QWidget(nullptr, f), curAlignment(0), m_node(node)
{
// set reference point, paddings
int paddingRight = 50;
int paddingTop = 50;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 40;
float fontFactor = 1.0;
float devicePixelRatio = 1.0;
devicePixelRatio = static_cast<QGuiApplication*>(QCoreApplication::instance())->devicePixelRatio();
// define text to place
QString titleText = PACKAGE_NAME;
QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText = QString::fromUtf8(CopyrightHolders(strprintf("\xc2\xA9 %u-%u ", 2009, COPYRIGHT_YEAR)).c_str());
QString titleAddText = networkStyle->getTitleAddText();
QString font = QApplication::font().toString();
// create a bitmap according to device pixelratio
QSize splashSize(480*devicePixelRatio,320*devicePixelRatio);
pixmap = QPixmap(splashSize);
// change to HiDPI if it makes sense
pixmap.setDevicePixelRatio(devicePixelRatio);
QPainter pixPaint(&pixmap);
pixPaint.setPen(QColor(100,100,100));
// draw a slightly radial gradient
QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio);
gradient.setColorAt(0, Qt::white);
gradient.setColorAt(1, QColor(247,247,247));
QRect rGradient(QPoint(0,0), splashSize);
pixPaint.fillRect(rGradient, gradient);
// draw the bitcoin icon, expected size of PNG: 1024x1024
QRect rectIcon(QPoint(-150,-122), QSize(430,430));
const QSize requiredSize(1024,1024);
QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize));
pixPaint.drawPixmap(rectIcon, icon);
// check font size and drawing with
pixPaint.setFont(QFont(font, 33*fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = GUIUtil::TextWidth(fm, titleText);
if (titleTextWidth > 176) {
fontFactor = fontFactor * 176 / titleTextWidth;
}
pixPaint.setFont(QFont(font, 33*fontFactor));
fm = pixPaint.fontMetrics();
titleTextWidth = GUIUtil::TextWidth(fm, titleText);
pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText);
pixPaint.setFont(QFont(font, 15*fontFactor));
// if the version string is too long, reduce size
fm = pixPaint.fontMetrics();
int versionTextWidth = GUIUtil::TextWidth(fm, versionText);
if(versionTextWidth > titleTextWidth+paddingRight-10) {
pixPaint.setFont(QFont(font, 10*fontFactor));
titleVersionVSpace -= 5;
}
pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);
// draw copyright stuff
{
pixPaint.setFont(QFont(font, 10*fontFactor));
const int x = pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight;
const int y = paddingTop+titleCopyrightVSpace;
QRect copyrightRect(x, y, pixmap.width() - x - paddingRight, pixmap.height() - y);
pixPaint.drawText(copyrightRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, copyrightText);
}
// draw additional text if special network
if(!titleAddText.isEmpty()) {
QFont boldFont = QFont(font, 10*fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int titleAddTextWidth = GUIUtil::TextWidth(fm, titleAddText);
pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText);
}
pixPaint.end();
// Set window title
setWindowTitle(titleText + " " + titleAddText);
// Resize window and move to center of desktop, disallow resizing
QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio));
resize(r.size());
setFixedSize(r.size());
move(QGuiApplication::primaryScreen()->geometry().center() - r.center());
subscribeToCoreSignals();
installEventFilter(this);
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) {
if (ev->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
if(keyEvent->text()[0] == 'q') {
m_node.startShutdown();
}
}
return QObject::eventFilter(obj, ev);
}
void SplashScreen::finish()
{
/* If the window is minimized, hide() will be ignored. */
/* Make sure we de-minimize the splashscreen window before hiding */
if (isMinimized())
showNormal();
hide();
deleteLater(); // No more need for this
}
static void InitMessage(SplashScreen *splash, const std::string &message)
{
bool invoked = QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
Q_ARG(QColor, QColor(55,55,55)));
assert(invoked);
}
static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress, bool resume_possible)
{
InitMessage(splash, title + std::string("\n") +
(resume_possible ? _("(press q to shutdown and continue later)").translated
: _("press q to shutdown").translated) +
strprintf("\n%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet)
{
m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2, false)));
m_connected_wallets.emplace_back(std::move(wallet));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
m_handler_init_message = m_node.handleInitMessage(std::bind(InitMessage, this, std::placeholders::_1));
m_handler_show_progress = m_node.handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
#ifdef ENABLE_WALLET
m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); });
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
m_handler_init_message->disconnect();
m_handler_show_progress->disconnect();
for (const auto& handler : m_connected_wallet_handlers) {
handler->disconnect();
}
m_connected_wallet_handlers.clear();
m_connected_wallets.clear();
}
void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color)
{
curMessage = message;
curAlignment = alignment;
curColor = color;
update();
}
void SplashScreen::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap);
QRect r = rect().adjusted(5, 5, -5, -5);
painter.setPen(curColor);
painter.drawText(r, curAlignment, curMessage);
}
void SplashScreen::closeEvent(QCloseEvent *event)
{
m_node.startShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
<commit_msg>Port splash screen<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/splashscreen.h>
#include <clientversion.h>
#include <interfaces/handler.h>
#include <interfaces/node.h>
#include <interfaces/wallet.h>
#include <qt/guiutil.h>
#include <qt/networkstyle.h>
#include <ui_interface.h>
#include <util/system.h>
#include <util/translation.h>
#include <version.h>
#include <QApplication>
#include <QCloseEvent>
#include <QPainter>
#include <QRadialGradient>
#include <QScreen>
SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) :
QWidget(nullptr, f), curAlignment(0), m_node(node)
{
// set sizes
int versionTextHeight = 30;
int statusHeight = 30;
int titleAddTextHeight = 20;
float fontFactor = 1.0;
float devicePixelRatio = 1.0;
devicePixelRatio = static_cast<QGuiApplication*>(QCoreApplication::instance())->devicePixelRatio();
// define text to place
QString titleText = PACKAGE_NAME;
QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText = QString::fromUtf8(CopyrightHolders(strprintf("\xc2\xA9 %u ", COPYRIGHT_YEAR)).c_str());
QString titleAddText = networkStyle->getTitleAddText();
QString font = QApplication::font().toString();
// create a bitmap according to device pixelratio
QSize splashSize(480,320);
pixmap = QPixmap(480*devicePixelRatio,320*devicePixelRatio);
// change to HiDPI if it makes sense
pixmap.setDevicePixelRatio(devicePixelRatio);
QPainter pixPaint(&pixmap);
pixPaint.setPen(QColor("#ffffff"));
QRect mainRect(QPoint(0,0), splashSize);
pixPaint.fillRect(mainRect, QColor("#030509"));
// draw background
QRect rectBg(QPoint(-50, -50), QSize(splashSize.width() + 50, splashSize.height() + 50));
QPixmap bg(":/styles/app-icons/splash_bg");
pixPaint.drawPixmap(rectBg, bg);
pixPaint.setFont(QFont(font, 32*fontFactor, QFont::Bold));
QRect rectTitle(QPoint(0,0), QSize(splashSize.width(), (splashSize.height() / 2)));
pixPaint.drawText(rectTitle, Qt::AlignHCenter | Qt::AlignBottom, titleText);
QPoint versionPoint(rectTitle.bottomLeft());
// draw additional text if special network
if(!titleAddText.isEmpty())
{
QRect titleAddRect(rectTitle.bottomLeft(), QSize(rectTitle.width(), titleAddTextHeight));
versionPoint = titleAddRect.bottomLeft();
pixPaint.setFont(QFont(font, 8*fontFactor, QFont::Bold));
pixPaint.drawText(titleAddRect, Qt::AlignHCenter | Qt::AlignVCenter, titleAddText);
}
pixPaint.setFont(QFont(font, 11*fontFactor));
QRect versionRect(versionPoint, QSize(rectTitle.width(), versionTextHeight));
pixPaint.drawText(versionRect, Qt::AlignHCenter | Qt::AlignTop, versionText);
// draw copyright stuff
QFont statusFont = QApplication::font();
statusFont.setPointSizeF(statusFont.pointSizeF() * 0.9);
pixPaint.setFont(statusFont);
QRect statusRect(mainRect.left(), mainRect.height() - statusHeight, mainRect.width(), statusHeight);
QColor statusColor(255, 255, 255);
statusColor.setAlphaF(0.1);
pixPaint.fillRect(statusRect, statusColor);
pixPaint.drawText(statusRect.adjusted(10, 0, -10, 0), Qt::AlignLeft | Qt::AlignVCenter, copyrightText);
pixPaint.end();
// Set window title
setWindowTitle(titleText + " " + titleAddText);
// Resize window and move to center of desktop, disallow resizing
QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio));
resize(r.size());
setFixedSize(r.size());
move(QGuiApplication::primaryScreen()->geometry().center() - r.center());
subscribeToCoreSignals();
installEventFilter(this);
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) {
if (ev->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
if(keyEvent->text()[0] == 'q') {
m_node.startShutdown();
}
}
return QObject::eventFilter(obj, ev);
}
void SplashScreen::finish()
{
/* If the window is minimized, hide() will be ignored. */
/* Make sure we de-minimize the splashscreen window before hiding */
if (isMinimized())
showNormal();
hide();
deleteLater(); // No more need for this
}
static void InitMessage(SplashScreen *splash, const std::string &message)
{
bool invoked = QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom|Qt::AlignRight),
Q_ARG(QColor, QColor("#ffffff")));
assert(invoked);
}
static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress, bool resume_possible)
{
InitMessage(splash, title + std::string("\n") +
(resume_possible ? _("(press q to shutdown and continue later)").translated
: _("press q to shutdown").translated) +
strprintf("\n%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet)
{
m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2, false)));
m_connected_wallets.emplace_back(std::move(wallet));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
m_handler_init_message = m_node.handleInitMessage(std::bind(InitMessage, this, std::placeholders::_1));
m_handler_show_progress = m_node.handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
#ifdef ENABLE_WALLET
m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); });
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
m_handler_init_message->disconnect();
m_handler_show_progress->disconnect();
for (const auto& handler : m_connected_wallet_handlers) {
handler->disconnect();
}
m_connected_wallet_handlers.clear();
m_connected_wallets.clear();
}
void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color)
{
curMessage = message;
curAlignment = alignment;
curColor = color;
update();
}
void SplashScreen::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap);
QRect r = rect().adjusted(10, 10, -10, -10);
painter.setPen(curColor);
QFont font = QApplication::font();
font.setPointSizeF(font.pointSizeF() * 0.9);
painter.setFont(font);
painter.drawText(r, curAlignment, curMessage);
}
void SplashScreen::closeEvent(QCloseEvent *event)
{
m_node.startShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "clientversion.h"
#include "ui_interface.h"
#include "util.h"
#include <QApplication>
#include <QPainter>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
QSplashScreen(pixmap, f)
{
setAutoFillBackground(true);
// set reference point, paddings
int paddingRight = 50;
int paddingTop = 50;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 40;
float fontFactor = 1.0;
// define text to place
QString titleText = tr("Dogecoin Core");
QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object
QString font = "Comic Sans MS";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(isTestNet) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(100,100,100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 33*fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if(titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 33*fontFactor));
fm = pixPaint.fontMetrics();
titleTextWidth = fm.width(titleText);
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);
pixPaint.setFont(QFont(font, 15*fontFactor));
// if the version string is to long, reduce size
fm = pixPaint.fontMetrics();
int versionTextWidth = fm.width(versionText);
if(versionTextWidth > titleTextWidth+paddingRight-10) {
pixPaint.setFont(QFont(font, 10*fontFactor));
titleVersionVSpace -= 5;
}
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10*fontFactor));
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);
// draw testnet string if testnet is on
if(isTestNet) {
QFont boldFont = QFont(font, 10*fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int testnetAddTextWidth = fm.width(testnetAddText);
pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
}
pixPaint.end();
this->setPixmap(newPixmap);
subscribeToCoreSignals();
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
void SplashScreen::slotFinish(QWidget *mainWin)
{
finish(mainWin);
}
static void InitMessage(SplashScreen *splash, const std::string &message)
{
QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
Q_ARG(QColor, QColor(55,55,55)));
}
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
}
<commit_msg>Add Dogecoin devs to splashscreen copyright.<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "clientversion.h"
#include "ui_interface.h"
#include "util.h"
#include <QApplication>
#include <QPainter>
#include <QRectF>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
QSplashScreen(pixmap, f)
{
setAutoFillBackground(true);
// set reference point, paddings
int paddingRight = 50;
int paddingTop = 50;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 40;
float fontFactor = 1.0;
// define text to place
QString titleText = tr("Dogecoin Core");
QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers\n")) + QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dogecoin Core developers"));
QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object
QString font = "Comic Sans MS";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(isTestNet) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(100,100,100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 33*fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if(titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 33*fontFactor));
fm = pixPaint.fontMetrics();
titleTextWidth = fm.width(titleText);
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);
pixPaint.setFont(QFont(font, 15*fontFactor));
// if the version string is to long, reduce size
fm = pixPaint.fontMetrics();
int versionTextWidth = fm.width(versionText);
if(versionTextWidth > titleTextWidth+paddingRight-10) {
pixPaint.setFont(QFont(font, 10*fontFactor));
titleVersionVSpace -= 5;
}
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10*fontFactor));
QRect copyrightRect = QRect(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,fm.width(copyrightText),fm.height()*2);
pixPaint.drawText(copyrightRect,Qt::TextWordWrap,copyrightText);
// draw testnet string if testnet is on
if(isTestNet) {
QFont boldFont = QFont(font, 10*fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int testnetAddTextWidth = fm.width(testnetAddText);
pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
}
pixPaint.end();
this->setPixmap(newPixmap);
subscribeToCoreSignals();
}
SplashScreen::~SplashScreen()
{
unsubscribeFromCoreSignals();
}
void SplashScreen::slotFinish(QWidget *mainWin)
{
finish(mainWin);
}
static void InitMessage(SplashScreen *splash, const std::string &message)
{
QMetaObject::invokeMethod(splash, "showMessage",
Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
Q_ARG(QColor, QColor(55,55,55)));
}
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
}
<|endoftext|>
|
<commit_before>#include "centsa/request_process.h"
#include "centsa/ui.h"
#include "centsa/ping.h"
#include "rapidjson/document.h"
#include <iostream>
#include <vector>
std::string mainPage(int &code, const char *data)
{
code = 200;
return ui_html();
}
std::string pingServer(int &code, const char *data)
{
code = 204;
ping::alive();
return std::string("");
}
std::string addAccount(int &code, const char *data)
{
try
{
long id = dao::addAccount(data);
std::cout << "Created new account: " << id << "\n";
code = 200;
return std::to_string(id);
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string setSetting(int &code, const char *data)
{
try
{
rapidjson::Document setting;
rapidjson::ParseResult result = setting.Parse(data);
if (result)
{
const char *key = setting["setting"].GetString();
const char *value = setting["value"].GetString();
dao::setSetting(key, value);
std::cout << "Set " << key << " to " << value << "\n";
code = 204;
return std::string("");
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string saveTrans(int &code, const char *data)
{
try
{
rapidjson::Document trans;
rapidjson::ParseResult result = trans.Parse(data);
if (result)
{
dao::transaction t;
t.amount = trans["amount"].GetDouble();
t.comment = trans["comment"].GetString();
t.accountId = trans["account"].GetInt64();
t.typeId = trans["type"].GetInt64();
t.expenseId = trans["expense"].GetInt64();
t.date = trans["date"].GetInt64();
long id = dao::saveTransaction(t);
code = 200;
return std::to_string(id);
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string addType(int &code, const char *data)
{
try
{
long id = dao::addType(data);
std::cout << "Created new type: " << id << "\n";
code = 200;
return std::to_string(id);
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getTrans(int &code, const char *data)
{
try
{
rapidjson::Document req;
rapidjson::ParseResult result = req.Parse(data);
if (result)
{
std::vector<dao::transaction> trans = dao::getTransactions(req["limit"].GetInt64(), req["offset"].GetInt64());
std::string resp("[");
for (dao::transaction t : trans)
{
resp += "{";
resp += "\"id\":";
resp += std::to_string(t.id);
resp += ",\"amount\":";
resp += std::to_string(t.amount);
resp += ",\"comment\":\"";
resp += t.comment;
resp += "\",\"account\":";
resp += std::to_string(t.accountId);
resp += ",\"type\":";
resp += std::to_string(t.typeId);
resp += ",\"date\":";
resp += std::to_string(t.date);
resp += ",\"expense\":";
resp += std::to_string(t.expenseId);
resp += "},";
}
if (trans.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getAccounts(int &code, const char *data)
{
try
{
std::vector<dao::account> accounts = dao::getAccounts();
std::string resp("[");
for (dao::account account : accounts)
{
resp += "{\"id\":";
resp += std::to_string(account.id);
resp += ",\"name\":\"";
resp += account.name;
resp += "\"},";
}
if (accounts.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getTypes(int &code, const char *data)
{
try
{
std::vector<dao::type> types = dao::getTypes();
std::string resp("[");
for (dao::type type : types)
{
resp += "{\"id\":";
resp += std::to_string(type.id);
resp += ",\"name\":\"";
resp += type.name;
resp += "\"},";
}
if (types.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getExpenses(int &code, const char *data)
{
try
{
std::vector<dao::expense> expenses = dao::getExpensesLite();
std::string resp("[");
for (dao::expense expense : expenses)
{
resp += "{\"id\":";
resp += std::to_string(expense.id);
resp += ",\"name\":\"";
resp += expense.name;
resp += "\"},";
}
if (expenses.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
void bindUris()
{
uriBindings["/"] = mainPage;
uriBindings["/ping"] = pingServer;
uriBindings["/addAccount"] = addAccount;
uriBindings["/setSetting"] = setSetting;
uriBindings["/saveTrans"] = saveTrans;
uriBindings["/addType"] = addType;
uriBindings["/getTrans.json"] = getTrans;
uriBindings["/getAccounts.json"] = getAccounts;
uriBindings["/getTypes.json"] = getTypes;
uriBindings["/getExpenses.json"] = getExpenses;
}
<commit_msg>Added getSetting REST service<commit_after>#include "centsa/request_process.h"
#include "centsa/ui.h"
#include "centsa/ping.h"
#include "rapidjson/document.h"
#include <iostream>
#include <vector>
std::string mainPage(int &code, const char *data)
{
code = 200;
return ui_html();
}
std::string pingServer(int &code, const char *data)
{
code = 204;
ping::alive();
return std::string("");
}
std::string addAccount(int &code, const char *data)
{
try
{
long id = dao::addAccount(data);
std::cout << "Created new account: " << id << "\n";
code = 200;
return std::to_string(id);
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string setSetting(int &code, const char *data)
{
try
{
rapidjson::Document setting;
rapidjson::ParseResult result = setting.Parse(data);
if (result)
{
const char *key = setting["setting"].GetString();
const char *value = setting["value"].GetString();
dao::setSetting(key, value);
std::cout << "Set " << key << " to " << value << "\n";
code = 204;
return std::string("");
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string saveTrans(int &code, const char *data)
{
try
{
rapidjson::Document trans;
rapidjson::ParseResult result = trans.Parse(data);
if (result)
{
dao::transaction t;
t.amount = trans["amount"].GetDouble();
t.comment = trans["comment"].GetString();
t.accountId = trans["account"].GetInt64();
t.typeId = trans["type"].GetInt64();
t.expenseId = trans["expense"].GetInt64();
t.date = trans["date"].GetInt64();
long id = dao::saveTransaction(t);
code = 200;
return std::to_string(id);
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string addType(int &code, const char *data)
{
try
{
long id = dao::addType(data);
std::cout << "Created new type: " << id << "\n";
code = 200;
return std::to_string(id);
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getTrans(int &code, const char *data)
{
try
{
rapidjson::Document req;
rapidjson::ParseResult result = req.Parse(data);
if (result)
{
std::vector<dao::transaction> trans = dao::getTransactions(req["limit"].GetInt64(), req["offset"].GetInt64());
std::string resp("[");
for (dao::transaction t : trans)
{
resp += "{";
resp += "\"id\":";
resp += std::to_string(t.id);
resp += ",\"amount\":";
resp += std::to_string(t.amount);
resp += ",\"comment\":\"";
resp += t.comment;
resp += "\",\"account\":";
resp += std::to_string(t.accountId);
resp += ",\"type\":";
resp += std::to_string(t.typeId);
resp += ",\"date\":";
resp += std::to_string(t.date);
resp += ",\"expense\":";
resp += std::to_string(t.expenseId);
resp += "},";
}
if (trans.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
code = 400;
return std::string("JSON error ") + data;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getAccounts(int &code, const char *data)
{
try
{
std::vector<dao::account> accounts = dao::getAccounts();
std::string resp("[");
for (dao::account account : accounts)
{
resp += "{\"id\":";
resp += std::to_string(account.id);
resp += ",\"name\":\"";
resp += account.name;
resp += "\"},";
}
if (accounts.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getTypes(int &code, const char *data)
{
try
{
std::vector<dao::type> types = dao::getTypes();
std::string resp("[");
for (dao::type type : types)
{
resp += "{\"id\":";
resp += std::to_string(type.id);
resp += ",\"name\":\"";
resp += type.name;
resp += "\"},";
}
if (types.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getExpenses(int &code, const char *data)
{
try
{
std::vector<dao::expense> expenses = dao::getExpensesLite();
std::string resp("[");
for (dao::expense expense : expenses)
{
resp += "{\"id\":";
resp += std::to_string(expense.id);
resp += ",\"name\":\"";
resp += expense.name;
resp += "\"},";
}
if (expenses.size() > 0)
resp.pop_back();
resp += "]";
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
std::string getSetting(int &code, const char *data)
{
try
{
std::string resp = dao::getSetting(data);
code = 200;
return resp;
}
catch (const char *err)
{
std::cerr << err << "\n";
return std::string(err);
}
}
void bindUris()
{
uriBindings["/"] = mainPage;
uriBindings["/ping"] = pingServer;
uriBindings["/addAccount"] = addAccount;
uriBindings["/setSetting"] = setSetting;
uriBindings["/saveTrans"] = saveTrans;
uriBindings["/addType"] = addType;
uriBindings["/getTrans.json"] = getTrans;
uriBindings["/getAccounts.json"] = getAccounts;
uriBindings["/getTypes.json"] = getTypes;
uriBindings["/getExpenses.json"] = getExpenses;
uriBindings["/getSetting"] = getSetting;
}
<|endoftext|>
|
<commit_before>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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 Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/
//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <stdio.h>
#include <math.h>
#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>
#include <LinearMath/btQuaternion.h>
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t);
class TargetState {
public:
geometry_msgs::TransformStamped target;
};
TargetState *target_state;
std::string frame_id;
std::string corrdinate_system_string;
enum CoordinateSystem {
vicon,
optitrack
} corrdinate_system;
// set to true in the VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;
class Rigid_Body {
private:
ros::Publisher target_pub;
tf::TransformBroadcaster br;
vrpn_Connection *connection;
vrpn_Tracker_Remote *tracker;
public:
Rigid_Body(ros::NodeHandle& nh, std::string server_ip, int port) {
target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
std::string connec_nm = server_ip + ":" + boost::lexical_cast<std::string>(port);
connection = vrpn_get_connection_by_name(connec_nm.c_str());
std::string target_name = nh.getNamespace().substr(1);
tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);
this->tracker->register_change_handler(NULL, track_target);
}
void publish_target_state(TargetState *target_state) {
br.sendTransform(target_state->target);
target_pub.publish(target_state->target);
}
void step_vrpn() {
this->tracker->mainloop();
this->connection->mainloop();
}
};
//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t) {
btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);
btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);
btQuaternion q_rot;
btVector3 pos;
switch (corrdinate_system) {
case optitrack: {
// optitrak <-- funky <-- object
// the q_fix.inverse() esures that when optitrak_funky says 0 0 0
// for roll pitch yaw, there is still a rotation that aligns the
// object frame with the /optitrak frame (and not /optitrak_funky)
q_rot = q_fix * q_orig * q_fix.inverse();
pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);
break;
}
case vicon: {
q_rot = q_orig;
pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);
break;
}
default: {
ROS_FATAL("Coordinate system not defined!");
break;
}
}
// verifying that each callback indeed gives fresh data.
if (prev_vrpn_data.quat[0] == t.quat[0] and prev_vrpn_data.quat[1] == t.quat[1]
and prev_vrpn_data.quat[2] == t.quat[2] and prev_vrpn_data.quat[3] == t.quat[3]
and prev_vrpn_data.pos[0] == t.pos[0] and prev_vrpn_data.pos[1] == t.pos[1]
and prev_vrpn_data.pos[2] == t.pos[2])
ROS_WARN("Repeated Values");
prev_vrpn_data = t;
const int kMicroSecToNanoSec = 1000;
ros::Time timestamp = ros::Time(t.msg_time.tv_sec, t.msg_time.tv_usec * kMicroSecToNanoSec);
target_state->target.transform.translation.x = pos.x();
target_state->target.transform.translation.y = pos.y();
target_state->target.transform.translation.z = pos.z();
target_state->target.transform.rotation.x = q_rot.x();
target_state->target.transform.rotation.y = q_rot.y();
target_state->target.transform.rotation.z = q_rot.z();
target_state->target.transform.rotation.w = q_rot.w();
target_state->target.header.frame_id = corrdinate_system_string;
target_state->target.child_frame_id = frame_id;
target_state->target.header.stamp = timestamp;
fresh_data = true;
}
int main(int argc, char* argv[]) {
ros::init(argc, argv, "ros_vrpn_client");
ros::NodeHandle nh("~");
target_state = new TargetState;
//frame_id = nh.getNamespace().substr(1);
frame_id = nh.getNamespace();
std::string vrpn_server_ip;
int vrpn_port;
std::string tracked_object_name;
nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
nh.param<int>("vrpn_port", vrpn_port, 3883);
nh.param<std::string>("vrpn_coordinate_system", corrdinate_system_string, "vicon");
std::cout << "vrpn_server_ip:" << vrpn_server_ip << std::endl;
std::cout << "vrpn_port:" << vrpn_port << std::endl;
std::cout << "vrpn_coordinate_system:" << corrdinate_system_string << std::endl;
if (corrdinate_system_string == std::string("vicon")) {
} else if (corrdinate_system_string == std::string("optitrack")) {
} else {
ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
}
Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);
ros::Rate loop_rate(1000); //TODO(gohlp): fix this
while (ros::ok()) {
tool.step_vrpn();
//vrpn_SleepMsecs(10);
if (fresh_data == true) { // only publish when receive data over VRPN.
tool.publish_target_state(target_state);
fresh_data = false;
}
//ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<commit_msg>added timezone adjustments and warning if delays are too big<commit_after>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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 Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/
//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <stdio.h>
#include <math.h>
#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>
#include <LinearMath/btQuaternion.h>
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t);
class TargetState {
public:
geometry_msgs::TransformStamped target;
};
TargetState *target_state;
std::string frame_id;
std::string corrdinate_system_string;
enum CoordinateSystem {
vicon,
optitrack
} corrdinate_system;
// set to true in the VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;
class Rigid_Body {
private:
ros::Publisher target_pub;
tf::TransformBroadcaster br;
vrpn_Connection *connection;
vrpn_Tracker_Remote *tracker;
public:
Rigid_Body(ros::NodeHandle& nh, std::string server_ip, int port) {
target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
std::string connec_nm = server_ip + ":" + boost::lexical_cast<std::string>(port);
connection = vrpn_get_connection_by_name(connec_nm.c_str());
std::string target_name = nh.getNamespace().substr(1);
tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);
this->tracker->register_change_handler(NULL, track_target);
}
void publish_target_state(TargetState *target_state) {
br.sendTransform(target_state->target);
target_pub.publish(target_state->target);
}
void step_vrpn() {
this->tracker->mainloop();
this->connection->mainloop();
}
};
//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t) {
btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);
btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);
btQuaternion q_rot;
btVector3 pos;
switch (corrdinate_system) {
case optitrack: {
// optitrak <-- funky <-- object
// the q_fix.inverse() esures that when optitrak_funky says 0 0 0
// for roll pitch yaw, there is still a rotation that aligns the
// object frame with the /optitrak frame (and not /optitrak_funky)
q_rot = q_fix * q_orig * q_fix.inverse();
pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);
break;
}
case vicon: {
q_rot = q_orig;
pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);
break;
}
default: {
ROS_FATAL("Coordinate system not defined!");
break;
}
}
// verifying that each callback indeed gives fresh data.
if (prev_vrpn_data.quat[0] == t.quat[0] and prev_vrpn_data.quat[1] == t.quat[1]
and prev_vrpn_data.quat[2] == t.quat[2] and prev_vrpn_data.quat[3] == t.quat[3]
and prev_vrpn_data.pos[0] == t.pos[0] and prev_vrpn_data.pos[1] == t.pos[1]
and prev_vrpn_data.pos[2] == t.pos[2])
ROS_WARN("Repeated Values");
prev_vrpn_data = t;
const uint32_t kMicroSecToNanoSec = 1000;
// Somehow the vrpn msgs are in a different time zone.
ros::Time timestamp_local = ros::Time::now();
int32_t timediff_sec = std::round(double(timestamp_local.sec - t.msg_time.tv_sec) / 3600) * 3600;
uint32_t timestamp_nsec = t.msg_time.tv_usec * kMicroSecToNanoSec;
ros::Time timestamp = ros::Time(t.msg_time.tv_sec + timediff_sec, timestamp_nsec);
ros::Duration time_diff = ros::Time::now() - timestamp;
if(std::abs(time_diff.toSec()) > 0.1) {
ROS_WARN_STREAM_THROTTLE(1, "Time delay: " << time_diff);
}
target_state->target.transform.translation.x = pos.x();
target_state->target.transform.translation.y = pos.y();
target_state->target.transform.translation.z = pos.z();
target_state->target.transform.rotation.x = q_rot.x();
target_state->target.transform.rotation.y = q_rot.y();
target_state->target.transform.rotation.z = q_rot.z();
target_state->target.transform.rotation.w = q_rot.w();
target_state->target.header.frame_id = corrdinate_system_string;
target_state->target.child_frame_id = frame_id;
target_state->target.header.stamp = timestamp;
fresh_data = true;
}
int main(int argc, char* argv[]) {
ros::init(argc, argv, "ros_vrpn_client");
ros::NodeHandle nh("~");
target_state = new TargetState;
//frame_id = nh.getNamespace().substr(1);
frame_id = nh.getNamespace();
std::string vrpn_server_ip;
int vrpn_port;
std::string tracked_object_name;
nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
nh.param<int>("vrpn_port", vrpn_port, 3883);
nh.param<std::string>("vrpn_coordinate_system", corrdinate_system_string, "vicon");
std::cout << "vrpn_server_ip:" << vrpn_server_ip << std::endl;
std::cout << "vrpn_port:" << vrpn_port << std::endl;
std::cout << "vrpn_coordinate_system:" << corrdinate_system_string << std::endl;
if (corrdinate_system_string == std::string("vicon")) {
} else if (corrdinate_system_string == std::string("optitrack")) {
} else {
ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
}
Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);
ros::Rate loop_rate(1000); //TODO(gohlp): fix this
while (ros::ok()) {
tool.step_vrpn();
//vrpn_SleepMsecs(10);
if (fresh_data == true) { // only publish when receive data over VRPN.
tool.publish_target_state(target_state);
fresh_data = false;
}
//ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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 Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/
//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <iostream>
#include <nav_msgs/Odometry.h>
#include <stdio.h>
#include <math.h>
#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>
#include <Eigen/Geometry>
#include "vicon_odometry_estimator.h"
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t);
// TODO(millanea@ethz.ch): The following callbacks should be implemented in the case that
// the tracking system supports them. In this case a flag should be
// added to the code indicating the whether or not the vicon estimator
// should be run.
//void VRPN_CALLBACK track_target_velocity(void *, const vrpn_TRACKERVELCB tv);
//void VRPN_CALLBACK track_target_acceleration(void *, const vrpn_TRACKERACCCB ta);
class TargetState
{
public:
geometry_msgs::TransformStamped target;
nav_msgs::Odometry odometry;
};
TargetState *target_state;
std::string object_name;
std::string coordinate_system_string;
enum CoordinateSystem
{
vicon,
optitrack
} coordinate_system;
// Global indicating the availability of new VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;
// Pointer to the vicon estimator. Global such that it can be accessed from the callback
vicon_estimator::ViconOdometryEstimator* vicon_odometry_estimator = NULL;
class Rigid_Body
{
private:
ros::Publisher target_pub;
ros::Publisher odometry_pub;
tf::TransformBroadcaster br;
vrpn_Connection *connection;
vrpn_Tracker_Remote *tracker;
public:
Rigid_Body(ros::NodeHandle& nh, std::string server_ip, int port, const std::string& object_name)
{
target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
odometry_pub = nh.advertise<nav_msgs::Odometry>("odometry", 100);
std::string connection_name = server_ip + ":" + boost::lexical_cast<std::string>(port);
connection = vrpn_get_connection_by_name(connection_name.c_str());
tracker = new vrpn_Tracker_Remote(object_name.c_str(), connection);
tracker->print_latest_report();
this->tracker->register_change_handler(NULL, track_target);
// TODO(millanea@ethz.ch): The following callbacks should be added if they're available.
// See detailed note above.
//this->tracker->register_change_handler(NULL, track_target_velocity);
//this->tracker->register_change_handler(NULL, track_target_acceleration);
tracker->print_latest_report();
}
void publish_target_state(TargetState *target_state)
{
br.sendTransform(target_state->target);
target_pub.publish(target_state->target);
}
void publish_odometry(TargetState *target_state)
{
odometry_pub.publish(target_state->odometry);
}
void step_vrpn()
{
this->tracker->mainloop();
this->connection->mainloop();
}
};
// TODO(millanea@ethz.ch): The following callbacks should be implemented if they're required.
// See detailed note above.
//void VRPN_CALLBACK track_target_acceleration(void *, const vrpn_TRACKERACCCB ta) {
// std::cout<<"acceleration_callback"<<std::endl;
// std::cout<<"ta.vel[0]"<<ta.acc[0]<<std::endl;
//}
//
//void VRPN_CALLBACK track_target_velocity(void *, const vrpn_TRACKERVELCB tv) {
// std::cout<<"velocity_callback"<<std::endl;
// std::cout<<"tv.vel[0]"<<tv.vel[0]<<std::endl;
//}
//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t)
{
Eigen::Quaterniond qOrig(t.quat[3], t.quat[0], t.quat[1], t.quat[2]);
Eigen::Quaterniond qFix(0.70710678, 0.70710678, 0., 0.);
Eigen::Quaterniond orientation_measured_B_W;
Eigen::Vector3d position_measured_W;
switch (coordinate_system)
{
case optitrack:
{
// Here we rotate the Optitrack measured quaternion by qFix, a
// Pi/2 rotation around the x-axis. By doing so we convert from
// NED to ENU (I think).
orientation_measured_B_W = qFix * qOrig * qFix.inverse();
position_measured_W = Eigen::Vector3d(t.pos[0], -t.pos[2], t.pos[1]);
break;
}
case vicon:
{
orientation_measured_B_W = qOrig;
position_measured_W = Eigen::Vector3d(t.pos[0], t.pos[1], t.pos[2]);
break;
}
default:
{
ROS_FATAL("Coordinate system not defined!");
break;
}
}
// verifying that each callback indeed gives fresh data.
if (prev_vrpn_data.quat[0] == t.quat[0] and prev_vrpn_data.quat[1] == t.quat[1]
and prev_vrpn_data.quat[2] == t.quat[2] and prev_vrpn_data.quat[3] == t.quat[3]
and prev_vrpn_data.pos[0] == t.pos[0] and prev_vrpn_data.pos[1] == t.pos[1]
and prev_vrpn_data.pos[2] == t.pos[2])
ROS_WARN("Repeated Values");
prev_vrpn_data = t;
// Somehow the vrpn msgs are in a different time zone.
const int kMicroSecToNanoSec = 1000;
ros::Time timestamp_local = ros::Time::now();
int timediff_sec = std::round(double(timestamp_local.sec - t.msg_time.tv_sec) / 3600) * 3600;
int timestamp_nsec = t.msg_time.tv_usec * kMicroSecToNanoSec;
ros::Time timestamp = ros::Time(t.msg_time.tv_sec + timediff_sec, timestamp_nsec);
ros::Duration time_diff = ros::Time::now() - timestamp;
if (std::abs(time_diff.toSec()) > 0.1) {
ROS_WARN_STREAM_THROTTLE(1, "Time delay: " << time_diff.toSec());
}
// Updating the estimates with the new measurements
vicon_odometry_estimator->updateEstimate(position_measured_W, orientation_measured_B_W);
vicon_odometry_estimator->publishResults(timestamp);
Eigen::Vector3d position_estimate_W = vicon_odometry_estimator->getEstimatedPosition();
Eigen::Vector3d velocity_estimate_W = vicon_odometry_estimator->getEstimatedVelocity();
Eigen::Quaterniond orientation_estimate_B_W = vicon_odometry_estimator->getEstimatedOrientation();
Eigen::Vector3d rate_estimate_B = vicon_odometry_estimator->getEstimatedAngularVelocity();
// Rotating the estimated global frame velocity into the body frame
Eigen::Vector3d velocity_estimate_B = orientation_estimate_B_W.toRotationMatrix() * velocity_estimate_W;
// Populating topic contents. Published in main loop
target_state->target.header.stamp = timestamp;
target_state->target.header.frame_id = coordinate_system_string;
target_state->target.child_frame_id = object_name;
target_state->target.transform.translation.x = position_estimate_W.x();
target_state->target.transform.translation.y = position_estimate_W.y();
target_state->target.transform.translation.z = position_estimate_W.z();
target_state->target.transform.rotation.x = orientation_estimate_B_W.x();
target_state->target.transform.rotation.y = orientation_estimate_B_W.y();
target_state->target.transform.rotation.z = orientation_estimate_B_W.z();
target_state->target.transform.rotation.w = orientation_estimate_B_W.w();
// Assemble odometry message.
target_state->odometry.header.stamp = timestamp;
target_state->odometry.header.frame_id = coordinate_system_string;
target_state->odometry.child_frame_id = object_name;
target_state->odometry.pose.pose.position.x = position_estimate_W.x();
target_state->odometry.pose.pose.position.y = position_estimate_W.y();
target_state->odometry.pose.pose.position.z = position_estimate_W.z();
target_state->odometry.pose.pose.orientation.w = orientation_estimate_B_W.w();
target_state->odometry.pose.pose.orientation.x = orientation_estimate_B_W.x();
target_state->odometry.pose.pose.orientation.y = orientation_estimate_B_W.y();
target_state->odometry.pose.pose.orientation.z = orientation_estimate_B_W.z();
target_state->odometry.twist.twist.linear.x = velocity_estimate_B.x();
target_state->odometry.twist.twist.linear.y = velocity_estimate_B.y();
target_state->odometry.twist.twist.linear.z = velocity_estimate_B.z();
target_state->odometry.twist.twist.angular.x = rate_estimate_B.x();
target_state->odometry.twist.twist.angular.y = rate_estimate_B.y();
target_state->odometry.twist.twist.angular.z = rate_estimate_B.z();
// Indicating to the main loop the data is ready for publishing
fresh_data = true;
}
int main(int argc, char* argv[])
{
ros::init(argc, argv, "ros_vrpn_client");
ros::NodeHandle nh("~");
target_state = new TargetState;
std::string vrpn_server_ip;
int vrpn_port;
std::string trackedObjectName;
std::string object_name;
nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
nh.param<int>("vrpn_port", vrpn_port, 3883);
nh.param<std::string>("vrpn_coordinate_system", coordinate_system_string, "vicon");
nh.param<std::string>("object_name", object_name, "bluebird");
std::cout << "vrpn_server_ip:" << vrpn_server_ip << std::endl;
std::cout << "vrpn_port:" << vrpn_port << std::endl;
std::cout << "vrpn_coordinate_system:" << coordinate_system_string << std::endl;
std::cout << "object_name:" << object_name << std::endl;
if (coordinate_system_string == std::string("vicon"))
{
}
else if (coordinate_system_string == std::string("optitrack"))
{
}
else
{
ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
}
// Creating the estimator
vicon_odometry_estimator = new vicon_estimator::ViconOdometryEstimator(nh);
vicon_odometry_estimator->initializeParameters(nh);
vicon_odometry_estimator->reset();
// Creating object which handles data publishing
Rigid_Body tool(nh, vrpn_server_ip, vrpn_port, object_name);
ros::Rate loop_rate(1000); //TODO(gohlp): fix this
while (ros::ok())
{
tool.step_vrpn();
// only publish when receive data over VRPN.
if (fresh_data == true)
{
tool.publish_target_state(target_state);
tool.publish_odometry(target_state);
fresh_data = false;
}
//ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<commit_msg>removed boost cast and added anonymous node name to ros init<commit_after>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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 Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/
//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <iostream>
#include <nav_msgs/Odometry.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>
#include <Eigen/Geometry>
#include "vicon_odometry_estimator.h"
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t);
// TODO(millanea@ethz.ch): The following callbacks should be implemented in the case that
// the tracking system supports them. In this case a flag should be
// added to the code indicating the whether or not the vicon estimator
// should be run.
//void VRPN_CALLBACK track_target_velocity(void *, const vrpn_TRACKERVELCB tv);
//void VRPN_CALLBACK track_target_acceleration(void *, const vrpn_TRACKERACCCB ta);
class TargetState
{
public:
geometry_msgs::TransformStamped target;
nav_msgs::Odometry odometry;
};
TargetState *target_state;
std::string object_name;
std::string coordinate_system_string;
enum CoordinateSystem
{
vicon,
optitrack
} coordinate_system;
// Global indicating the availability of new VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;
// Pointer to the vicon estimator. Global such that it can be accessed from the callback
vicon_estimator::ViconOdometryEstimator* vicon_odometry_estimator = NULL;
class Rigid_Body
{
private:
ros::Publisher target_pub;
ros::Publisher odometry_pub;
tf::TransformBroadcaster br;
vrpn_Connection *connection;
vrpn_Tracker_Remote *tracker;
public:
Rigid_Body(ros::NodeHandle& nh, std::string server_ip, int port, const std::string& object_name)
{
target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
odometry_pub = nh.advertise<nav_msgs::Odometry>("odometry", 100);
std::stringstream connection_name;
connection_name << server_ip << ":" << port;
connection = vrpn_get_connection_by_name(connection_name.str().c_str());
tracker = new vrpn_Tracker_Remote(object_name.c_str(), connection);
tracker->print_latest_report();
this->tracker->register_change_handler(NULL, track_target);
// TODO(millanea@ethz.ch): The following callbacks should be added if they're available.
// See detailed note above.
//this->tracker->register_change_handler(NULL, track_target_velocity);
//this->tracker->register_change_handler(NULL, track_target_acceleration);
tracker->print_latest_report();
}
void publish_target_state(TargetState *target_state)
{
br.sendTransform(target_state->target);
target_pub.publish(target_state->target);
}
void publish_odometry(TargetState *target_state)
{
odometry_pub.publish(target_state->odometry);
}
void step_vrpn()
{
this->tracker->mainloop();
this->connection->mainloop();
}
};
// TODO(millanea@ethz.ch): The following callbacks should be implemented if they're required.
// See detailed note above.
//void VRPN_CALLBACK track_target_acceleration(void *, const vrpn_TRACKERACCCB ta) {
// std::cout<<"acceleration_callback"<<std::endl;
// std::cout<<"ta.vel[0]"<<ta.acc[0]<<std::endl;
//}
//
//void VRPN_CALLBACK track_target_velocity(void *, const vrpn_TRACKERVELCB tv) {
// std::cout<<"velocity_callback"<<std::endl;
// std::cout<<"tv.vel[0]"<<tv.vel[0]<<std::endl;
//}
//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target(void *, const vrpn_TRACKERCB t)
{
Eigen::Quaterniond qOrig(t.quat[3], t.quat[0], t.quat[1], t.quat[2]);
Eigen::Quaterniond qFix(0.70710678, 0.70710678, 0., 0.);
Eigen::Quaterniond orientation_measured_B_W;
Eigen::Vector3d position_measured_W;
switch (coordinate_system)
{
case optitrack:
{
// Here we rotate the Optitrack measured quaternion by qFix, a
// Pi/2 rotation around the x-axis. By doing so we convert from
// NED to ENU (I think).
orientation_measured_B_W = qFix * qOrig * qFix.inverse();
position_measured_W = Eigen::Vector3d(t.pos[0], -t.pos[2], t.pos[1]);
break;
}
case vicon:
{
orientation_measured_B_W = qOrig;
position_measured_W = Eigen::Vector3d(t.pos[0], t.pos[1], t.pos[2]);
break;
}
default:
{
ROS_FATAL("Coordinate system not defined!");
break;
}
}
// verifying that each callback indeed gives fresh data.
if (prev_vrpn_data.quat[0] == t.quat[0] and prev_vrpn_data.quat[1] == t.quat[1]
and prev_vrpn_data.quat[2] == t.quat[2] and prev_vrpn_data.quat[3] == t.quat[3]
and prev_vrpn_data.pos[0] == t.pos[0] and prev_vrpn_data.pos[1] == t.pos[1]
and prev_vrpn_data.pos[2] == t.pos[2])
ROS_WARN("Repeated Values");
prev_vrpn_data = t;
// Somehow the vrpn msgs are in a different time zone.
const int kMicroSecToNanoSec = 1000;
ros::Time timestamp_local = ros::Time::now();
int timediff_sec = std::round(double(timestamp_local.sec - t.msg_time.tv_sec) / 3600) * 3600;
int timestamp_nsec = t.msg_time.tv_usec * kMicroSecToNanoSec;
ros::Time timestamp = ros::Time(t.msg_time.tv_sec + timediff_sec, timestamp_nsec);
ros::Duration time_diff = ros::Time::now() - timestamp;
if (std::abs(time_diff.toSec()) > 0.1) {
ROS_WARN_STREAM_THROTTLE(1, "Time delay: " << time_diff.toSec());
}
// Updating the estimates with the new measurements
vicon_odometry_estimator->updateEstimate(position_measured_W, orientation_measured_B_W);
vicon_odometry_estimator->publishResults(timestamp);
Eigen::Vector3d position_estimate_W = vicon_odometry_estimator->getEstimatedPosition();
Eigen::Vector3d velocity_estimate_W = vicon_odometry_estimator->getEstimatedVelocity();
Eigen::Quaterniond orientation_estimate_B_W = vicon_odometry_estimator->getEstimatedOrientation();
Eigen::Vector3d rate_estimate_B = vicon_odometry_estimator->getEstimatedAngularVelocity();
// Rotating the estimated global frame velocity into the body frame
Eigen::Vector3d velocity_estimate_B = orientation_estimate_B_W.toRotationMatrix() * velocity_estimate_W;
// Populating topic contents. Published in main loop
target_state->target.header.stamp = timestamp;
target_state->target.header.frame_id = coordinate_system_string;
target_state->target.child_frame_id = object_name;
target_state->target.transform.translation.x = position_estimate_W.x();
target_state->target.transform.translation.y = position_estimate_W.y();
target_state->target.transform.translation.z = position_estimate_W.z();
target_state->target.transform.rotation.x = orientation_estimate_B_W.x();
target_state->target.transform.rotation.y = orientation_estimate_B_W.y();
target_state->target.transform.rotation.z = orientation_estimate_B_W.z();
target_state->target.transform.rotation.w = orientation_estimate_B_W.w();
// Assemble odometry message.
target_state->odometry.header.stamp = timestamp;
target_state->odometry.header.frame_id = coordinate_system_string;
target_state->odometry.child_frame_id = object_name;
target_state->odometry.pose.pose.position.x = position_estimate_W.x();
target_state->odometry.pose.pose.position.y = position_estimate_W.y();
target_state->odometry.pose.pose.position.z = position_estimate_W.z();
target_state->odometry.pose.pose.orientation.w = orientation_estimate_B_W.w();
target_state->odometry.pose.pose.orientation.x = orientation_estimate_B_W.x();
target_state->odometry.pose.pose.orientation.y = orientation_estimate_B_W.y();
target_state->odometry.pose.pose.orientation.z = orientation_estimate_B_W.z();
target_state->odometry.twist.twist.linear.x = velocity_estimate_B.x();
target_state->odometry.twist.twist.linear.y = velocity_estimate_B.y();
target_state->odometry.twist.twist.linear.z = velocity_estimate_B.z();
target_state->odometry.twist.twist.angular.x = rate_estimate_B.x();
target_state->odometry.twist.twist.angular.y = rate_estimate_B.y();
target_state->odometry.twist.twist.angular.z = rate_estimate_B.z();
// Indicating to the main loop the data is ready for publishing
fresh_data = true;
}
int main(int argc, char* argv[])
{
ros::init(argc, argv, "ros_vrpn_client", ros::init_options::AnonymousName);
ros::NodeHandle nh("~");
target_state = new TargetState;
std::string vrpn_server_ip;
int vrpn_port;
std::string trackedObjectName;
nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
nh.param<int>("vrpn_port", vrpn_port, 3883);
nh.param<std::string>("vrpn_coordinate_system", coordinate_system_string, "vicon");
nh.param<std::string>("object_name", object_name, "bluebird");
std::cout << "vrpn_server_ip:" << vrpn_server_ip << std::endl;
std::cout << "vrpn_port:" << vrpn_port << std::endl;
std::cout << "vrpn_coordinate_system:" << coordinate_system_string << std::endl;
std::cout << "object_name:" << object_name << std::endl;
if (coordinate_system_string == std::string("vicon"))
{
}
else if (coordinate_system_string == std::string("optitrack"))
{
}
else
{
ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
}
// Creating the estimator
vicon_odometry_estimator = new vicon_estimator::ViconOdometryEstimator(nh);
vicon_odometry_estimator->initializeParameters(nh);
vicon_odometry_estimator->reset();
// Creating object which handles data publishing
Rigid_Body tool(nh, vrpn_server_ip, vrpn_port, object_name);
ros::Rate loop_rate(1000); //TODO(gohlp): fix this
while (ros::ok())
{
tool.step_vrpn();
// only publish when receive data over VRPN.
if (fresh_data == true)
{
tool.publish_target_state(target_state);
tool.publish_odometry(target_state);
fresh_data = false;
}
//ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacnsocket.h"
#include <QNetworkAddressEntry>
#include <QDebug>
#include <QThread>
#include "ipaddr.h"
#include "streamcommon.h"
#include "streamingacn.h"
#include "sacnlistener.h"
#include "preferences.h"
sACNRxSocket::sACNRxSocket(QNetworkInterface iface, QObject *parent) :
QUdpSocket(parent),
m_interface(iface)
{}
sACNRxSocket::sBindStatus sACNRxSocket::bind(quint16 universe)
{
sACNRxSocket::sBindStatus status;
m_universe = universe;
bool ok = false;
CIPAddr multicastAddr;
GetUniverseAddress(universe, multicastAddr);
QHostAddress listenAddr = QHostAddress::AnyIPv4;
#ifdef TARGET_WINXP
#pragma message("Unicast listener unavailable for this platform")
listenAddr = multicastAddr.ToQHostAddress();
#endif
ok = QUdpSocket::bind(listenAddr,
STREAM_IP_PORT,
QAbstractSocket::ShareAddress | QAbstractSocket::ReuseAddressHint);
status.unicast = ok ? BIND_OK : BIND_FAILED;
// Join multicast on selected NIC
if (ok) {
#if (QT_VERSION <= QT_VERSION_CHECK(5, 8, 0))
#ifdef Q_OS_WIN
#pragma message("setMulticastInterface() fails to bind to correct interface on systems running IPV4 and IPv6 with QT <= 5.8.0")
#else
#error setMulticastInterface() fails to bind to correct interface on systems running IPV4 and IPv6 with QT <= 5.8.0
#endif
#endif
setMulticastInterface(m_interface);
ok |= joinMulticastGroup(QHostAddress(multicastAddr.GetV4Address()), m_interface);
status.multicast = ok ? BIND_OK : BIND_FAILED;
}
if(ok) {
#ifdef TARGET_WINXP
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Bound to IP:" << listenAddr.toString();
#else
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Bound to interface:" << multicastInterface().name();
#endif
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Joining Multicast Group:" << QHostAddress(multicastAddr.GetV4Address()).toString();
} else {
close();
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Failed to bind RX socket";
}
return status;
}
sACNTxSocket::sACNTxSocket(QNetworkInterface iface, QObject *parent) :
QUdpSocket(parent),
m_interface(iface)
{}
bool sACNTxSocket::bind()
{
bool ok = false;
// Bind to first IPv4 address on selected NIC
foreach (QNetworkAddressEntry ifaceAddr, m_interface.addressEntries()) {
if (ifaceAddr.ip().protocol() == QAbstractSocket::IPv4Protocol) {
ok = QUdpSocket::bind(ifaceAddr.ip());
if (ok) {
qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Bound to IP:" << ifaceAddr.ip().toString();
#ifndef Q_OS_WIN
// Don't send to self, this will cause issues on multihomed systems
setSocketOption(QAbstractSocket::MulticastLoopbackOption, QVariant(0));
#endif
setSocketOption(QAbstractSocket::MulticastTtlOption, QVariant(Preferences::getInstance()->GetMulticastTtl()));
setMulticastInterface(m_interface);
qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Bound to interface:" << multicastInterface().name();
}
break;
}
}
if (!ok) qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Failed to bind TX socket";
return ok;
}
qint64 sACNTxSocket::writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port)
{
#ifndef Q_OS_WIN
// If destination multicast (and we're not in offline mode)
// Copy to correct internal listener(s) for local display
if (host.isMulticast() && !localAddress().isLoopback()) {
CIPAddr addr;
for (auto &weakListener : sACNManager::getInstance()->getListenerList()) {
sACNManager::tListener listener(weakListener);
if (listener) {
GetUniverseAddress(listener->universe(), addr);
if (QHostAddress(addr.GetV4Address()) == host) {
listener->processDatagram(
QByteArray(data, len),
QHostAddress(host),
localAddress());
}
}
}
}
#endif
// Send to world
return QUdpSocket::writeDatagram(data, len, host, port);
}
<commit_msg>Fix MacOS loopback<commit_after>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacnsocket.h"
#include <QNetworkAddressEntry>
#include <QDebug>
#include <QThread>
#include "ipaddr.h"
#include "streamcommon.h"
#include "streamingacn.h"
#include "sacnlistener.h"
#include "preferences.h"
sACNRxSocket::sACNRxSocket(QNetworkInterface iface, QObject *parent) :
QUdpSocket(parent),
m_interface(iface)
{}
sACNRxSocket::sBindStatus sACNRxSocket::bind(quint16 universe)
{
sACNRxSocket::sBindStatus status;
m_universe = universe;
bool ok = false;
CIPAddr multicastAddr;
GetUniverseAddress(universe, multicastAddr);
QHostAddress listenAddr = QHostAddress::AnyIPv4;
#ifdef TARGET_WINXP
#pragma message("Unicast listener unavailable for this platform")
listenAddr = multicastAddr.ToQHostAddress();
#endif
ok = QUdpSocket::bind(listenAddr,
STREAM_IP_PORT,
QAbstractSocket::ShareAddress | QAbstractSocket::ReuseAddressHint);
status.unicast = ok ? BIND_OK : BIND_FAILED;
// Join multicast on selected NIC
if (ok) {
#if (QT_VERSION <= QT_VERSION_CHECK(5, 8, 0))
#ifdef Q_OS_WIN
#pragma message("setMulticastInterface() fails to bind to correct interface on systems running IPV4 and IPv6 with QT <= 5.8.0")
#else
#error setMulticastInterface() fails to bind to correct interface on systems running IPV4 and IPv6 with QT <= 5.8.0
#endif
#endif
setMulticastInterface(m_interface);
ok |= joinMulticastGroup(QHostAddress(multicastAddr.GetV4Address()), m_interface);
status.multicast = ok ? BIND_OK : BIND_FAILED;
}
if(ok) {
#ifdef TARGET_WINXP
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Bound to IP:" << listenAddr.toString();
#else
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Bound to interface:" << multicastInterface().name();
#endif
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Joining Multicast Group:" << QHostAddress(multicastAddr.GetV4Address()).toString();
} else {
close();
qDebug() << "sACNRxSocket " << QThread::currentThreadId() << ": Failed to bind RX socket";
}
return status;
}
sACNTxSocket::sACNTxSocket(QNetworkInterface iface, QObject *parent) :
QUdpSocket(parent),
m_interface(iface)
{}
bool sACNTxSocket::bind()
{
bool ok = false;
// Bind to first IPv4 address on selected NIC
foreach (QNetworkAddressEntry ifaceAddr, m_interface.addressEntries()) {
if (ifaceAddr.ip().protocol() == QAbstractSocket::IPv4Protocol) {
ok = QUdpSocket::bind(ifaceAddr.ip());
if (ok) {
qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Bound to IP:" << ifaceAddr.ip().toString();
#ifndef Q_OS_WIN
// Don't send to self, this will cause issues on multihomed systems
setSocketOption(QAbstractSocket::MulticastLoopbackOption, QVariant(0));
#endif
setSocketOption(QAbstractSocket::MulticastTtlOption, QVariant(Preferences::getInstance()->GetMulticastTtl()));
setMulticastInterface(m_interface);
qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Bound to interface:" << multicastInterface().name();
}
break;
}
}
if (!ok) qDebug() << "sACNTxSocket " << QThread::currentThreadId() << ": Failed to bind TX socket";
return ok;
}
bool writeDatagramLoopbackTest(const QHostAddress &dest, QHostAddress localAddress) {
#ifdef Q_OS_WIN
return false;
#endif
#ifdef Q_OS_LINUX
return (dest.isMulticast() && !localAddress.isLoopback());
#endif
#ifdef Q_OS_MACOS
return (dest.isMulticast());
#endif
}
qint64 sACNTxSocket::writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port)
{
// Copy to correct internal listener(s) for local display, if required by platform
if (writeDatagramLoopbackTest(host, localAddress())) {
CIPAddr addr;
for (auto &weakListener : sACNManager::getInstance()->getListenerList()) {
sACNManager::tListener listener(weakListener);
if (listener) {
GetUniverseAddress(listener->universe(), addr);
if (QHostAddress(addr.GetV4Address()) == host) {
listener->processDatagram(
QByteArray(data, len),
QHostAddress(host),
localAddress());
}
}
}
}
// Send to world
return QUdpSocket::writeDatagram(data, len, host, port);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <CoreFoundation/CoreFoundation.h>
#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <pqrs/osx/launchctl.hpp>
#include <spdlog/fmt/fmt.h>
#include <string>
#include <string_view>
#include <thread>
namespace krbn {
class constants final {
public:
static const char* get_version_file_path(void) {
return "/Library/Application Support/org.pqrs/Karabiner-Elements/version";
}
static const char* get_tmp_directory(void) {
return "/Library/Application Support/org.pqrs/tmp";
}
static std::string get_pid_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/pid";
}
static std::string get_rootonly_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/rootonly";
}
static std::filesystem::path get_system_user_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/user";
}
static std::filesystem::path get_system_user_directory(uid_t uid) {
return fmt::format("{0}/{1}", get_system_user_directory().string(), uid);
}
static const char* get_observer_state_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_observer_state.json";
}
static const char* get_grabber_state_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_state.json";
}
static const char* get_grabber_socket_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_receiver";
}
static std::string get_grabber_session_monitor_receiver_socket_file_path(void) {
return get_rootonly_directory() + "/karabiner_grabber_session_monitor_receiver";
}
static const char* get_devices_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_devices.json";
}
static const char* get_device_details_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_device_details.json";
}
static const char* get_manipulator_environment_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_manipulator_environment.json";
}
static const char* get_notification_message_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_notification_message.json";
}
static std::string get_session_monitor_receiver_socket_file_path(uid_t uid) {
return fmt::format("{0}/karabiner_session_monitor_receiver.{1}", get_rootonly_directory(), uid);
}
static const char* get_system_configuration_directory(void) {
return "/Library/Application Support/org.pqrs/config";
}
static const char* get_system_core_configuration_file_path(void) {
return "/Library/Application Support/org.pqrs/config/karabiner.json";
}
static const std::string& get_user_configuration_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
if (auto xdg_config_home = std::getenv("XDG_CONFIG_HOME")) {
directory = xdg_config_home;
} else {
if (auto home = std::getenv("HOME")) {
directory = home;
directory += "/.config";
}
}
if (!directory.empty()) {
directory += "/karabiner";
}
}
return directory;
}
static const std::string& get_user_data_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
if (auto xdg_config_home = std::getenv("XDG_DATA_HOME")) {
directory = xdg_config_home;
} else {
if (auto home = std::getenv("HOME")) {
directory = home;
directory += "/.local/share";
}
}
if (!directory.empty()) {
directory += "/karabiner";
}
}
return directory;
}
static const std::string& get_user_core_configuration_file_path(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string file_path;
if (!once) {
once = true;
auto directory = get_user_configuration_directory();
if (!directory.empty()) {
file_path = directory + "/karabiner.json";
}
}
return file_path;
}
static const std::string& get_user_core_configuration_automatic_backups_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_configuration_directory();
if (!d.empty()) {
directory = d + "/automatic_backups";
}
}
return directory;
}
static const std::string& get_user_complex_modifications_assets_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_configuration_directory();
if (!d.empty()) {
directory = d + "/assets/complex_modifications";
}
}
return directory;
}
static const std::string& get_user_log_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_data_directory();
if (!d.empty()) {
directory = d + "/log";
}
}
return directory;
}
static const std::string& get_user_pid_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_data_directory();
if (!d.empty()) {
directory = d + "/pid";
}
}
return directory;
}
static const char* get_distributed_notification_observed_object(void) {
return "org.pqrs.karabiner";
}
static const char* get_distributed_notification_console_user_server_is_disabled(void) {
return "console_user_server_is_disabled";
}
static const size_t get_local_datagram_buffer_size(void) {
return 32 * 1024;
}
static pqrs::osx::launchctl::service_name get_observer_agent_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.agent.karabiner_observer");
}
static pqrs::osx::launchctl::service_path get_observer_agent_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.agent.karabiner_observer.plist");
}
static pqrs::osx::launchctl::service_name get_grabber_agent_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.agent.karabiner_grabber");
}
static pqrs::osx::launchctl::service_path get_grabber_agent_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.agent.karabiner_grabber.plist");
}
static pqrs::osx::launchctl::service_name get_session_monitor_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.karabiner_session_monitor");
}
static pqrs::osx::launchctl::service_path get_session_monitor_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.karabiner_session_monitor.plist");
}
static pqrs::osx::launchctl::service_name get_console_user_server_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.karabiner_console_user_server");
}
static pqrs::osx::launchctl::service_path get_console_user_server_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.karabiner_console_user_server.plist");
}
static pqrs::osx::launchctl::service_name get_notification_window_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.NotificationWindow");
}
static pqrs::osx::launchctl::service_path get_notification_window_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.NotificationWindow.plist");
}
};
} // namespace krbn
<commit_msg>Add constants::get_grabber_daemon_launchctl_service_name, get_grabber_daemon_launchctl_service_path<commit_after>#pragma once
#include <CoreFoundation/CoreFoundation.h>
#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <pqrs/osx/launchctl.hpp>
#include <spdlog/fmt/fmt.h>
#include <string>
#include <string_view>
#include <thread>
namespace krbn {
class constants final {
public:
static const char* get_version_file_path(void) {
return "/Library/Application Support/org.pqrs/Karabiner-Elements/version";
}
static const char* get_tmp_directory(void) {
return "/Library/Application Support/org.pqrs/tmp";
}
static std::string get_pid_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/pid";
}
static std::string get_rootonly_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/rootonly";
}
static std::filesystem::path get_system_user_directory(void) {
return "/Library/Application Support/org.pqrs/tmp/user";
}
static std::filesystem::path get_system_user_directory(uid_t uid) {
return fmt::format("{0}/{1}", get_system_user_directory().string(), uid);
}
static const char* get_observer_state_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_observer_state.json";
}
static const char* get_grabber_state_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_state.json";
}
static const char* get_grabber_socket_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_receiver";
}
static std::string get_grabber_session_monitor_receiver_socket_file_path(void) {
return get_rootonly_directory() + "/karabiner_grabber_session_monitor_receiver";
}
static const char* get_devices_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_devices.json";
}
static const char* get_device_details_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_device_details.json";
}
static const char* get_manipulator_environment_json_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_grabber_manipulator_environment.json";
}
static const char* get_notification_message_file_path(void) {
return "/Library/Application Support/org.pqrs/tmp/karabiner_notification_message.json";
}
static std::string get_session_monitor_receiver_socket_file_path(uid_t uid) {
return fmt::format("{0}/karabiner_session_monitor_receiver.{1}", get_rootonly_directory(), uid);
}
static const char* get_system_configuration_directory(void) {
return "/Library/Application Support/org.pqrs/config";
}
static const char* get_system_core_configuration_file_path(void) {
return "/Library/Application Support/org.pqrs/config/karabiner.json";
}
static const std::string& get_user_configuration_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
if (auto xdg_config_home = std::getenv("XDG_CONFIG_HOME")) {
directory = xdg_config_home;
} else {
if (auto home = std::getenv("HOME")) {
directory = home;
directory += "/.config";
}
}
if (!directory.empty()) {
directory += "/karabiner";
}
}
return directory;
}
static const std::string& get_user_data_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
if (auto xdg_config_home = std::getenv("XDG_DATA_HOME")) {
directory = xdg_config_home;
} else {
if (auto home = std::getenv("HOME")) {
directory = home;
directory += "/.local/share";
}
}
if (!directory.empty()) {
directory += "/karabiner";
}
}
return directory;
}
static const std::string& get_user_core_configuration_file_path(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string file_path;
if (!once) {
once = true;
auto directory = get_user_configuration_directory();
if (!directory.empty()) {
file_path = directory + "/karabiner.json";
}
}
return file_path;
}
static const std::string& get_user_core_configuration_automatic_backups_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_configuration_directory();
if (!d.empty()) {
directory = d + "/automatic_backups";
}
}
return directory;
}
static const std::string& get_user_complex_modifications_assets_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_configuration_directory();
if (!d.empty()) {
directory = d + "/assets/complex_modifications";
}
}
return directory;
}
static const std::string& get_user_log_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_data_directory();
if (!d.empty()) {
directory = d + "/log";
}
}
return directory;
}
static const std::string& get_user_pid_directory(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static std::string directory;
if (!once) {
once = true;
auto d = get_user_data_directory();
if (!d.empty()) {
directory = d + "/pid";
}
}
return directory;
}
static const char* get_distributed_notification_observed_object(void) {
return "org.pqrs.karabiner";
}
static const char* get_distributed_notification_console_user_server_is_disabled(void) {
return "console_user_server_is_disabled";
}
static const size_t get_local_datagram_buffer_size(void) {
return 32 * 1024;
}
static pqrs::osx::launchctl::service_name get_grabber_daemon_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.karabiner_grabber");
}
static pqrs::osx::launchctl::service_path get_grabber_daemon_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchDaemons/org.pqrs.karabiner.karabiner_grabber.plist");
}
static pqrs::osx::launchctl::service_name get_observer_agent_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.agent.karabiner_observer");
}
static pqrs::osx::launchctl::service_path get_observer_agent_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.agent.karabiner_observer.plist");
}
static pqrs::osx::launchctl::service_name get_grabber_agent_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.agent.karabiner_grabber");
}
static pqrs::osx::launchctl::service_path get_grabber_agent_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.agent.karabiner_grabber.plist");
}
static pqrs::osx::launchctl::service_name get_session_monitor_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.karabiner_session_monitor");
}
static pqrs::osx::launchctl::service_path get_session_monitor_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.karabiner_session_monitor.plist");
}
static pqrs::osx::launchctl::service_name get_console_user_server_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.karabiner_console_user_server");
}
static pqrs::osx::launchctl::service_path get_console_user_server_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.karabiner_console_user_server.plist");
}
static pqrs::osx::launchctl::service_name get_notification_window_launchctl_service_name(void) {
return pqrs::osx::launchctl::service_name("org.pqrs.karabiner.NotificationWindow");
}
static pqrs::osx::launchctl::service_path get_notification_window_launchctl_service_path(void) {
return pqrs::osx::launchctl::service_path("/Library/LaunchAgents/org.pqrs.karabiner.NotificationWindow.plist");
}
};
} // namespace krbn
<|endoftext|>
|
<commit_before><commit_msg>modified shession_client to use request_type strings instead of hardcoded strings<commit_after><|endoftext|>
|
<commit_before>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/component/body.h>
#include <shipsbattle/objects/ship.h>
#include <shipsbattle/components/spacedust.h>
#include <shipsbattle/components/playercontroller.h>
#include <shipsbattle/components/hull.h>
#include <shipsbattle/components/subsystems/subhull.h>
#include <btBulletDynamicsCommon.h>
#include <OgreSceneManager.h>
#include <OgreOverlaySystem.h>
#include <memory>
#include <iostream>
#include <sstream>
#define AREA_RANGE 200.0
using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::stringstream;
using std::cout;
using std::endl;
using shipsbattle::objects::Ship;
using shipsbattle::components::SpaceDust;
using shipsbattle::components::PlayerController;
ugdk::action::mode3d::Scene3D *ourscene;
void CreateHUD(Ship& pla, Ship& enemy) {
Ogre::OverlayManager* overlay_mgr = Ogre::OverlayManager::getSingletonPtr();
std::string over_name = "SBHUD";
Ogre::Overlay* hud = overlay_mgr->create(over_name);
hud->setZOrder(600);
Ogre::TextAreaOverlayElement* plaHullStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/PlaHullStats"));
plaHullStats->setMetricsMode(Ogre::GMM_PIXELS);
plaHullStats->setPosition(10, 0);
plaHullStats->setDimensions(350, 30);
plaHullStats->setFontName("testeFont");
plaHullStats->setCharHeight(16);
plaHullStats->setColour(Ogre::ColourValue::Black);
plaHullStats->setCaption("PLAYER HULL STATS");
Ogre::TextAreaOverlayElement* plaArmorStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/PlaArmorStats"));
plaArmorStats->setMetricsMode(Ogre::GMM_PIXELS);
plaArmorStats->setPosition(10, 30);
plaArmorStats->setDimensions(350, 30);
plaArmorStats->setFontName("testeFont");
plaArmorStats->setCharHeight(16);
plaArmorStats->setColour(Ogre::ColourValue::Blue);
plaArmorStats->setCaption("PLAYER ARMOR STATS");
Ogre::TextAreaOverlayElement* enemyHullStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/EnemyHullStats"));
enemyHullStats->setMetricsMode(Ogre::GMM_PIXELS);
enemyHullStats->setPosition(10, 60);
enemyHullStats->setDimensions(350, 30);
enemyHullStats->setFontName("testeFont");
enemyHullStats->setCharHeight(16);
enemyHullStats->setColour(Ogre::ColourValue::Black);
enemyHullStats->setCaption("ENEMY HULL STATS");
Ogre::TextAreaOverlayElement* enemyArmorStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/EnemyArmorStats"));
enemyArmorStats->setMetricsMode(Ogre::GMM_PIXELS);
enemyArmorStats->setPosition(10, 90);
enemyArmorStats->setDimensions(350, 30);
enemyArmorStats->setFontName("testeFont");
enemyArmorStats->setCharHeight(16);
enemyArmorStats->setColour(Ogre::ColourValue::Blue);
enemyArmorStats->setCaption("ENEMY ARMOR STATS");
Ogre::OverlayContainer* panel = static_cast<Ogre::OverlayContainer*>(overlay_mgr->createOverlayElement("Panel", over_name + "/Panel"));
panel->setMetricsMode(Ogre::GMM_PIXELS);
panel->setPosition(450, 0.0);
panel->setDimensions(350, 120);
panel->setMaterialName("BaseWhite");
panel->addChild(plaHullStats);
panel->addChild(plaArmorStats);
panel->addChild(enemyHullStats);
panel->addChild(enemyArmorStats);
hud->add2D(panel);
hud->show();
ourscene->AddTask(ugdk::system::Task(
[&pla, &enemy, plaHullStats, plaArmorStats, enemyHullStats, enemyArmorStats](double dt) {
auto func = [](Ship& ship, Ogre::TextAreaOverlayElement* hullStats, Ogre::TextAreaOverlayElement* armorStats) {
auto hull = ship.hull()->GetSubHull("MainHull");
double hullPerc = 100.0 * hull->hitpoints() / hull->max_hitpoints();
double armorPerc = 100.0 * hull->armor_rating() / hull->max_armor_rating();
stringstream ssh;
ssh.precision(2);
ssh.setf(std::ios::fixed, std::ios::floatfield);
ssh << ship->name() << " HULL: " << hullPerc << "% (" << hull->hitpoints() << "/" << hull->max_hitpoints() << ")";
hullStats->setCaption(ssh.str());
stringstream ssa;
ssa.precision(2);
ssa.setf(std::ios::fixed, std::ios::floatfield);
ssa << ship->name() << " ARMOR: " << armorPerc << "% (" << hull->armor_rating() << "/" << hull->max_armor_rating() << ")";
armorStats->setCaption(ssa.str());
};
func(pla, plaHullStats, plaArmorStats);
func(enemy, enemyHullStats, enemyArmorStats);
}));
}
Ship createShip(const std::string& name) {
return Ship(*ourscene, name, "AerOmar.mesh");
}
void AddSubHull(Ship& ship, const std::string& name, double radius, double x, double y, double z) {
shipsbattle::components::Hull* hull = ship.hull();
shipsbattle::components::subsystems::SubHull* sh = new shipsbattle::components::subsystems::SubHull(name);
sh->SetVolume(radius, btVector3(x, y, z));
hull->AddSubHull(std::shared_ptr<shipsbattle::components::subsystems::SubHull>(sh));
}
int main(int argc, char* argv[]) {
ugdk::system::Configuration config;
config.base_path = "assets/";
config.windows_list.front().title = "Ships Battle";
config.ogre_plugins.push_back("Plugin_ParticleFX");
ugdk::system::Initialize(config);
// create 3D scene
ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, 0.0, 0.0));
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));
// set some basic stuff our "space" scenes will need.
ourscene->ShowFrameStats();
ourscene->manager()->setSkyBox(true, "Backgrounds/Nebula1");
{
// create Player ship
Ship player = createShip("Player");
player->AddComponent(make_shared<SpaceDust>());
player->AddComponent(make_shared<PlayerController>());
ourscene->camera()->AttachTo(*player);
ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 100);
ourscene->camera()->SetDistance(10);
//AerOmar bounding box size: (3.07287, 1.06726, 6.79639) - bounding sphere radius: 3.88078
AddSubHull(player, "BallOrigin", 0.5, 0, 0, 0);
//AddSubHull(player, "BallUno", 1.0, 0, 0, 1.0);
//AddSubHull(player, "BallBottom", 0.1, 0, 0, 0.25);
AddSubHull(player, "BallFront", 0.2, 0, 0, 3.7);
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[&player](const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::I) {
player.hull()->TakeDamage(-100, 0.2, 5.0, btVector3(0, 0, 3.9));
}
else if (ev.scancode == ugdk::input::Scancode::O) {
player.hull()->TakeDamage(100, 0.2, 1.0, btVector3(0, 0, 3.9));
}
else if (ev.scancode == ugdk::input::Scancode::P) {
player.hull()->TakeDamage(100, 0.2, 0.0, btVector3(0, 0, 3.9));
}
});
// create Enemy ship
Ship enemy = createShip("Enemy");
enemy.body()->Translate(0, 0, 80);
CreateHUD(player, enemy);
// push scene
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
}
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<commit_msg>Updated main so that: -HUD checks if ship no longer exists -Fixed problem with scope of Ship variables; -Implemented method to create a sphere mesh with attached material -Added a useless subhull to enemy for damage testing purposes<commit_after>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/component/body.h>
#include <shipsbattle/objects/ship.h>
#include <shipsbattle/components/spacedust.h>
#include <shipsbattle/components/playercontroller.h>
#include <shipsbattle/components/subsystems/typedefs.h>
#include <shipsbattle/components/hull.h>
#include <shipsbattle/components/subsystems/subhull.h>
#include <shipsbattle/components/timedlife.h>
#include <btBulletDynamicsCommon.h>
#include <OgreSceneManager.h>
#include <OgreOverlaySystem.h>
#include <OgreMeshManager.h>
#include <OgreHardwareBufferManager.h>
#include <OgreSubMesh.h>
#include <memory>
#include <iostream>
#include <sstream>
#define AREA_RANGE 200.0
using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::stringstream;
using std::cout;
using std::endl;
using shipsbattle::objects::Ship;
using shipsbattle::components::SpaceDust;
using shipsbattle::components::PlayerController;
using namespace shipsbattle::components::subsystems::DecaymentFunctions;
ugdk::action::mode3d::Scene3D *ourscene;
void CreateHUD(Ship& pla, Ship& enemy) {
Ogre::OverlayManager* overlay_mgr = Ogre::OverlayManager::getSingletonPtr();
std::string over_name = "SBHUD";
Ogre::Overlay* hud = overlay_mgr->create(over_name);
hud->setZOrder(600);
Ogre::TextAreaOverlayElement* plaHullStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/PlaHullStats"));
plaHullStats->setMetricsMode(Ogre::GMM_PIXELS);
plaHullStats->setPosition(10, 0);
plaHullStats->setDimensions(350, 30);
plaHullStats->setFontName("testeFont");
plaHullStats->setCharHeight(16);
plaHullStats->setColour(Ogre::ColourValue::Black);
plaHullStats->setCaption("PLAYER HULL STATS");
Ogre::TextAreaOverlayElement* plaArmorStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/PlaArmorStats"));
plaArmorStats->setMetricsMode(Ogre::GMM_PIXELS);
plaArmorStats->setPosition(10, 30);
plaArmorStats->setDimensions(350, 30);
plaArmorStats->setFontName("testeFont");
plaArmorStats->setCharHeight(16);
plaArmorStats->setColour(Ogre::ColourValue::Blue);
plaArmorStats->setCaption("PLAYER ARMOR STATS");
Ogre::TextAreaOverlayElement* enemyHullStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/EnemyHullStats"));
enemyHullStats->setMetricsMode(Ogre::GMM_PIXELS);
enemyHullStats->setPosition(10, 60);
enemyHullStats->setDimensions(350, 30);
enemyHullStats->setFontName("testeFont");
enemyHullStats->setCharHeight(16);
enemyHullStats->setColour(Ogre::ColourValue::Black);
enemyHullStats->setCaption("ENEMY HULL STATS");
Ogre::TextAreaOverlayElement* enemyArmorStats = static_cast<Ogre::TextAreaOverlayElement*>(overlay_mgr->createOverlayElement("TextArea", over_name + "/EnemyArmorStats"));
enemyArmorStats->setMetricsMode(Ogre::GMM_PIXELS);
enemyArmorStats->setPosition(10, 90);
enemyArmorStats->setDimensions(350, 30);
enemyArmorStats->setFontName("testeFont");
enemyArmorStats->setCharHeight(16);
enemyArmorStats->setColour(Ogre::ColourValue::Blue);
enemyArmorStats->setCaption("ENEMY ARMOR STATS");
Ogre::OverlayContainer* panel = static_cast<Ogre::OverlayContainer*>(overlay_mgr->createOverlayElement("Panel", over_name + "/Panel"));
panel->setMetricsMode(Ogre::GMM_PIXELS);
panel->setPosition(450, 0.0);
panel->setDimensions(350, 120);
panel->setMaterialName("BaseWhite");
panel->addChild(plaHullStats);
panel->addChild(plaArmorStats);
panel->addChild(enemyHullStats);
panel->addChild(enemyArmorStats);
hud->add2D(panel);
hud->show();
ourscene->AddTask(ugdk::system::Task(
[&pla, &enemy, plaHullStats, plaArmorStats, enemyHullStats, enemyArmorStats](double dt) {
auto func = [](Ship& ship, Ogre::TextAreaOverlayElement* hullStats, Ogre::TextAreaOverlayElement* armorStats) {
if (ship.valid()) {
auto hull = ship.hull()->GetSubHull("MainHull");
double hullPerc = 100.0 * hull->hitpoints() / hull->max_hitpoints();
double armorPerc = 100.0 * hull->armor_rating() / hull->max_armor_rating();
stringstream ssh;
ssh.precision(2);
ssh.setf(std::ios::fixed, std::ios::floatfield);
ssh << ship->name() << " HULL: " << hullPerc << "% (" << hull->hitpoints() << "/" << hull->max_hitpoints() << ")";
hullStats->setCaption(ssh.str());
stringstream ssa;
ssa.precision(2);
ssa.setf(std::ios::fixed, std::ios::floatfield);
ssa << ship->name() << " ARMOR: " << armorPerc << "% (" << hull->armor_rating() << "/" << hull->max_armor_rating() << ")";
armorStats->setCaption(ssa.str());
}
else {
hullStats->setCaption("HULL: DESTROYED");
armorStats->setCaption("ARMOR: DESTROYED");
}
};
func(pla, plaHullStats, plaArmorStats);
func(enemy, enemyHullStats, enemyArmorStats);
}));
}
void createSphere(const std::string& name, const float r, const int nRings=16, const int nSegments=16) {
Ogre::MeshPtr pSphere = Ogre::MeshManager::getSingleton().createManual(Ogre::String(name), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::SubMesh *pSphereVertex = pSphere->createSubMesh();
pSphere->sharedVertexData = new Ogre::VertexData();
Ogre::VertexData* vertexData = pSphere->sharedVertexData;
// define the vertex format
Ogre::VertexDeclaration* vertexDecl = vertexData->vertexDeclaration;
size_t currOffset = 0;
// positions
vertexDecl->addElement(0, currOffset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
// normals
vertexDecl->addElement(0, currOffset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL);
currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
// two dimensional texture coordinates
vertexDecl->addElement(0, currOffset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0);
currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT2);
// allocate the vertex buffer
vertexData->vertexCount = (nRings + 1) * (nSegments + 1);
Ogre::HardwareVertexBufferSharedPtr vBuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(vertexDecl->getVertexSize(0), vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false);
Ogre::VertexBufferBinding* binding = vertexData->vertexBufferBinding;
binding->setBinding(0, vBuf);
float* pVertex = static_cast<float*>(vBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD));
// allocate index buffer
pSphereVertex->indexData->indexCount = 6 * nRings * (nSegments + 1);
pSphereVertex->indexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT, pSphereVertex->indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false);
Ogre::HardwareIndexBufferSharedPtr iBuf = pSphereVertex->indexData->indexBuffer;
unsigned short* pIndices = static_cast<unsigned short*>(iBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD));
float fDeltaRingAngle = (Ogre::Math::PI / nRings);
float fDeltaSegAngle = (2 * Ogre::Math::PI / nSegments);
unsigned short wVerticeIndex = 0;
// Generate the group of rings for the sphere
for (int ring = 0; ring <= nRings; ring++) {
float r0 = r * sinf(ring * fDeltaRingAngle);
float y0 = r * cosf(ring * fDeltaRingAngle);
// Generate the group of segments for the current ring
for (int seg = 0; seg <= nSegments; seg++) {
float x0 = r0 * sinf(seg * fDeltaSegAngle);
float z0 = r0 * cosf(seg * fDeltaSegAngle);
// Add one vertex to the strip which makes up the sphere
*pVertex++ = x0;
*pVertex++ = y0;
*pVertex++ = z0;
Ogre::Vector3 vNormal = Ogre::Vector3(x0, y0, z0).normalisedCopy();
*pVertex++ = vNormal.x;
*pVertex++ = vNormal.y;
*pVertex++ = vNormal.z;
*pVertex++ = (float)seg / (float)nSegments;
*pVertex++ = (float)ring / (float)nRings;
if (ring != nRings) {
// each vertex (except the last) has six indices pointing to it
*pIndices++ = wVerticeIndex + nSegments + 1;
*pIndices++ = wVerticeIndex;
*pIndices++ = wVerticeIndex + nSegments;
*pIndices++ = wVerticeIndex + nSegments + 1;
*pIndices++ = wVerticeIndex + 1;
*pIndices++ = wVerticeIndex;
wVerticeIndex++;
}
}; // end for seg
} // end for ring
// Unlock
vBuf->unlock();
iBuf->unlock();
// Generate face list
pSphereVertex->useSharedVertices = true;
// the original code was missing this line:
pSphere->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-r, -r, -r), Ogre::Vector3(r, r, r)), false);
pSphere->_setBoundingSphereRadius(r);
// this line makes clear the mesh is loaded (avoids memory leaks)
pSphere->load();
//material
Ogre::MaterialPtr mMat = Ogre::MaterialManager::getSingleton().create("AmmoSphere", "General", true);
mMat->getTechnique(0)->getPass(0)->setDiffuse(Ogre::ColourValue(1.0, 0.1, 0));
mMat->getTechnique(0)->getPass(0)->setEmissive(Ogre::ColourValue(1.0, 0.1, 0));
pSphereVertex->setMaterialName("AmmoSphere");
}
Ship createShip(const std::string& name) {
return Ship(*ourscene, name, "AerOmar.mesh");
}
void AddSubHull(Ship& ship, const std::string& name, double radius, double x, double y, double z) {
shipsbattle::components::Hull* hull = ship.hull();
shipsbattle::components::subsystems::SubHull* sh = new shipsbattle::components::subsystems::SubHull(name);
sh->SetVolume(radius, btVector3(x, y, z));
hull->AddSubHull(std::shared_ptr<shipsbattle::components::subsystems::SubHull>(sh));
}
int main(int argc, char* argv[]) {
ugdk::system::Configuration config;
config.base_path = "assets/";
config.windows_list.front().title = "Ships Battle";
config.ogre_plugins.push_back("Plugin_ParticleFX");
ugdk::system::Initialize(config);
// create 3D scene
ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, 0.0, 0.0));
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));
// set some basic stuff our "space" scenes will need.
ourscene->ShowFrameStats();
ourscene->manager()->setSkyBox(true, "Backgrounds/Nebula1");
// prepare our simple test mesh for projectiles
createSphere("Ammo", 0.1);
// create Player ship
Ship player = createShip("Player");
player->AddComponent(make_shared<SpaceDust>());
player->AddComponent(make_shared<PlayerController>());
ourscene->camera()->AttachTo(*player);
ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 100);
ourscene->camera()->SetDistance(10);
//AerOmar bounding box size: (3.07287, 1.06726, 6.79639) - bounding sphere radius: 3.88078
AddSubHull(player, "BallOrigin", 0.5, 0, 0, 0);
//AddSubHull(player, "BallUno", 1.0, 0, 0, 1.0);
//AddSubHull(player, "BallBottom", 0.1, 0, 0, 0.25);
AddSubHull(player, "BallFront", 0.2, 0, 0, 3.7);
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[&player](const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::I) {
player.hull()->TakeDamage(-100, 0.2, 5.0, btVector3(0, 0, 3.9), CONSTANT);
}
else if (ev.scancode == ugdk::input::Scancode::O) {
player.hull()->TakeDamage(100, 0.2, 1.0, btVector3(0, 0, 3.9), CONSTANT);
}
else if (ev.scancode == ugdk::input::Scancode::P) {
player.hull()->TakeDamage(100, 0.2, 0.0, btVector3(0, 0, 3.9), CONSTANT);
}
});
// create Enemy ship
Ship enemy = createShip("Enemy");
enemy.body()->Translate(0, 0, 80);
AddSubHull(enemy, "Butt", 0.2, 0.0, 0.0, -3.6);
player->component<PlayerController>()->set_target( enemy.hull()->GetSubHull("Butt").get() );
//enemy->AddComponent(std::make_shared<shipsbattle::components::TimedLife>(15.0));
CreateHUD(player, enemy);
// push scene
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sipattrextractor.hh"
#include <string>
#include <sstream>
#include <sofia-sip/sip.h>
#include <sofia-sip/sip_protos.h>
#include <stdexcept>
using namespace std;
static string subKey(const string &key, size_t *pos) {
size_t dot=key.find('.', *pos)-*pos;
if (dot != string::npos) {
string id=key.substr(*pos, dot);
// LOGD("SUBKEY '%s' from '%s'", id.c_str(), key.c_str());
*pos+=dot+1;
return id;
}
if (key.size() != *pos) {
// LOGD("SUBKEY '%s'", key.c_str());
*pos=key.size();
return key;
}
return "";
}
inline static string cstring_get(const string &key, size_t pos, const char *str) {
if (!str) throw new invalid_argument("Null string found in sip msg for " + key);
return std::string(str);
}
inline static string int_get(const string &key, size_t pos, int value) {
ostringstream oss;
oss << value;
return oss.str();
}
static string url_get(const string &key, size_t pos, const url_t *url) {
string id=subKey(key, &pos);
if (!url) throw new invalid_argument("No url found in sip msg for " + key);
if (id == "domain") return cstring_get(key, pos, url->url_host);
if (id == "user") return cstring_get(key, pos, url->url_user);
if (id == "params") return cstring_get(key, pos, url->url_params);
throw new runtime_error("url_get: unhandled arg '" + id + "' in " + key);
}
static string addr_get(const string &key, size_t pos, const sip_addr_s *addr) {
string id=subKey(key, &pos);
if (!addr) throw new invalid_argument("No address found in sip msg for " + key);
if (id == "uri") return url_get(key, pos, addr->a_url);
throw new runtime_error("addr_get: unhandled arg '" + id + "' in " + key);
}
static string request_get(const string &key, size_t pos, const sip_request_t *req) {
string id=subKey(key, &pos);
if (!req) throw new invalid_argument("No request found in sip msg for " + key);
if (id == "uri") return url_get(key, pos, req->rq_url);
if (id == "mn" || id == "method-name") return cstring_get(key, pos, req->rq_method_name);
throw new runtime_error("request_get: unhandled arg '" + id + "' in " + key);
}
static string ua_get(const string &key, size_t pos, const sip_user_agent_t *ua) {
if (!ua) throw new invalid_argument("No user-agent found in sip msg for " + key);
return cstring_get(key, pos, ua->g_string);
}
static string status_get(const string &key, size_t pos, const sip_status_s *status) {
string id=subKey(key, &pos);
if (!status) throw new invalid_argument("No status found in sip msg for " + key);
if (id == "phrase") return cstring_get(key, pos, status->st_phrase);
if (id == "code") return int_get(key, pos, status->st_status);
throw new runtime_error("status_get: unhandled arg '" + id + "' in " + key);
}
static string callid_get(const string &key, size_t pos, const sip_call_id_s *callid) {
string id=subKey(key, &pos);
if (id.empty()) return cstring_get(key, pos, callid->i_id);
if (id == "hash") return int_get(key, pos, callid->i_hash);
throw new runtime_error("callid_get: unhandled arg '" + id + "' in " + key);
}
static bool is_request(sip_t *sip) {
return sip_is_request((sip_header_t *)sip->sip_request);
}
std::string SipAttributes::get(const std::string &key) const {
size_t pos=0;
string id=subKey(key, &pos);
if (id == "from") return addr_get(key, pos, (sip_addr_s *)sip->sip_from);
if (id == "to") return addr_get(key, pos, (sip_addr_s *)sip->sip_to);
if (id == "request") return request_get(key, pos, sip->sip_request);
if (id == "direction") return is_request(sip) ? "request" : "response";
if (id == "status") return status_get(key, pos, (sip_status_s *) sip->sip_status);
if (id == "ua" || id == "user-agent") return ua_get(key, pos, sip->sip_user_agent);
if (id == "callid" ) return callid_get(key, pos, sip->sip_call_id);
throw new runtime_error("unhandled arg '" + id + "' in '" + key+ "'");
}
bool SipAttributes::isTrue(const string &key) const {
if (key == "is_request") {
return is_request(sip);
} else if (key == "is_response") {
return !is_request(sip);
}
throw new runtime_error("unhandled true/false " + key);
};
<commit_msg>Allow empty url params in filters.<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sipattrextractor.hh"
#include <string>
#include <sstream>
#include <sofia-sip/sip.h>
#include <sofia-sip/sip_protos.h>
#include <stdexcept>
using namespace std;
static string subKey(const string &key, size_t *pos) {
size_t dot=key.find('.', *pos)-*pos;
if (dot != string::npos) {
string id=key.substr(*pos, dot);
// LOGD("SUBKEY '%s' from '%s'", id.c_str(), key.c_str());
*pos+=dot+1;
return id;
}
if (key.size() != *pos) {
// LOGD("SUBKEY '%s'", key.c_str());
*pos=key.size();
return key;
}
return "";
}
inline static string cstring_get(const string &key, size_t pos, const char *str) {
if (!str) throw new invalid_argument("Null string found in sip msg for " + key);
return str;
}
inline static string cstring_or_empty_get(const string &key, size_t pos, const char *str) {
return str? str : "";
}
inline static string int_get(const string &key, size_t pos, int value) {
ostringstream oss;
oss << value;
return oss.str();
}
static string url_get(const string &key, size_t pos, const url_t *url) {
string id=subKey(key, &pos);
if (!url) throw new invalid_argument("No url found in sip msg for " + key);
if (id == "domain") return cstring_get(key, pos, url->url_host);
if (id == "user") return cstring_get(key, pos, url->url_user);
if (id == "params") return cstring_or_empty_get(key, pos, url->url_params);
throw new runtime_error("url_get: unhandled arg '" + id + "' in " + key);
}
static string addr_get(const string &key, size_t pos, const sip_addr_s *addr) {
string id=subKey(key, &pos);
if (!addr) throw new invalid_argument("No address found in sip msg for " + key);
if (id == "uri") return url_get(key, pos, addr->a_url);
throw new runtime_error("addr_get: unhandled arg '" + id + "' in " + key);
}
static string request_get(const string &key, size_t pos, const sip_request_t *req) {
string id=subKey(key, &pos);
if (!req) throw new invalid_argument("No request found in sip msg for " + key);
if (id == "uri") return url_get(key, pos, req->rq_url);
if (id == "mn" || id == "method-name") return cstring_get(key, pos, req->rq_method_name);
throw new runtime_error("request_get: unhandled arg '" + id + "' in " + key);
}
static string ua_get(const string &key, size_t pos, const sip_user_agent_t *ua) {
if (!ua) throw new invalid_argument("No user-agent found in sip msg for " + key);
return cstring_get(key, pos, ua->g_string);
}
static string status_get(const string &key, size_t pos, const sip_status_s *status) {
string id=subKey(key, &pos);
if (!status) throw new invalid_argument("No status found in sip msg for " + key);
if (id == "phrase") return cstring_get(key, pos, status->st_phrase);
if (id == "code") return int_get(key, pos, status->st_status);
throw new runtime_error("status_get: unhandled arg '" + id + "' in " + key);
}
static string callid_get(const string &key, size_t pos, const sip_call_id_s *callid) {
string id=subKey(key, &pos);
if (id.empty()) return cstring_get(key, pos, callid->i_id);
if (id == "hash") return int_get(key, pos, callid->i_hash);
throw new runtime_error("callid_get: unhandled arg '" + id + "' in " + key);
}
static bool is_request(sip_t *sip) {
return sip_is_request((sip_header_t *)sip->sip_request);
}
std::string SipAttributes::get(const std::string &key) const {
size_t pos=0;
string id=subKey(key, &pos);
if (id == "from") return addr_get(key, pos, (sip_addr_s *)sip->sip_from);
if (id == "to") return addr_get(key, pos, (sip_addr_s *)sip->sip_to);
if (id == "request") return request_get(key, pos, sip->sip_request);
if (id == "direction") return is_request(sip) ? "request" : "response";
if (id == "status") return status_get(key, pos, (sip_status_s *) sip->sip_status);
if (id == "ua" || id == "user-agent") return ua_get(key, pos, sip->sip_user_agent);
if (id == "callid" ) return callid_get(key, pos, sip->sip_call_id);
throw new runtime_error("unhandled arg '" + id + "' in '" + key+ "'");
}
bool SipAttributes::isTrue(const string &key) const {
if (key == "is_request") {
return is_request(sip);
} else if (key == "is_response") {
return !is_request(sip);
}
throw new runtime_error("unhandled true/false " + key);
};
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* 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 "StackingContext.h"
#include <new>
#include <iostream>
namespace org { namespace w3c { namespace dom { namespace bootstrap {
StackingContext* StackingContext::removeChild(StackingContext* item)
{
StackingContext* next = item->nextSibling;
StackingContext* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parent = 0;
--childCount;
return item;
}
StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
if (!after)
return appendChild(item);
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parent = this;
++childCount;
return item;
}
StackingContext* StackingContext::appendChild(StackingContext* item)
{
StackingContext* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parent = this;
++childCount;
return item;
}
StackingContext::StackingContext(int zIndex) :
zIndex(zIndex),
z1(0.0f),
z3(0.0f),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
zero(0)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::getAuto()
{
if (zIndex == 0)
return this;
if (!zero)
zero = addContext(0);
return zero;
}
StackingContext* StackingContext::addContext(int zIndex)
{
if (isAuto())
return parent->addContext(zIndex);
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (zIndex < i->zIndex) {
after = i;
break;
}
}
StackingContext* item = new(std::nothrow) StackingContext(zIndex);
if (item)
insertBefore(item, after);
return item;
}
float StackingContext::eval(float z)
{
z += 1.0f;
z1 = z3 = z;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
z = i->eval(z);
if (i->zIndex < 0) {
z += 1.0f;
z3 = z;
}
}
return z;
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: " << zIndex << " " << z1 << " " << z3 << "\n";
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap<commit_msg>(StackingContext::getAuto) : Fix a bug.<commit_after>/*
* Copyright 2011 Esrille Inc.
*
* 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 "StackingContext.h"
#include <new>
#include <iostream>
namespace org { namespace w3c { namespace dom { namespace bootstrap {
StackingContext* StackingContext::removeChild(StackingContext* item)
{
StackingContext* next = item->nextSibling;
StackingContext* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parent = 0;
--childCount;
return item;
}
StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
if (!after)
return appendChild(item);
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parent = this;
++childCount;
return item;
}
StackingContext* StackingContext::appendChild(StackingContext* item)
{
StackingContext* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parent = this;
++childCount;
return item;
}
StackingContext::StackingContext(int zIndex) :
zIndex(zIndex),
z1(0.0f),
z3(0.0f),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
zero(0)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::getAuto()
{
if (isAuto())
return this;
if (!zero)
zero = addContext(0);
return zero;
}
StackingContext* StackingContext::addContext(int zIndex)
{
if (isAuto())
return parent->addContext(zIndex);
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (zIndex < i->zIndex) {
after = i;
break;
}
}
StackingContext* item = new(std::nothrow) StackingContext(zIndex);
if (item)
insertBefore(item, after);
return item;
}
float StackingContext::eval(float z)
{
z += 1.0f;
z1 = z3 = z;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
z = i->eval(z);
if (i->zIndex < 0) {
z += 1.0f;
z3 = z;
}
}
return z;
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: " << zIndex << " " << z1 << " " << z3 << "\n";
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap<|endoftext|>
|
<commit_before>#ifndef AMGCL_COARSENING_AS_SCALAR_HPP
#define AMGCL_COARSENING_AS_SCALAR_HPP
/*
The MIT License
Copyright (c) 2012-2022 Denis Demidov <dennis.demidov@gmail.com>
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.
*/
/**
* \file amgcl/coarsening/as_scalar.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Scalar coarsening for block matrices.
*/
#include <amgcl/adapter/block_matrix.hpp>
#include <amgcl/backend/interface.hpp>
namespace amgcl {
namespace coarsening {
// Takes a block matrix as input,
// converts it to the scalar format,
// applies the base coarsening,
// converts the results back to block format.
template <class ScalarTemplate, template <class> class Coarsening>
struct as_scalar {
typedef Coarsening<ScalarTemplate> Base;
template <class Backend>
struct type {
typedef typename Base::params params;
Base base;
type(const params &prm = params()) : base(prm) {};
template <class Matrix>
std::tuple<
std::shared_ptr<Matrix>,
std::shared_ptr<Matrix>
>
transfer_operators(const Matrix &B) {
typedef typename backend::value_type<Matrix>::type Block;
auto T = base.transfer_operators(*adapter::unblock_matrix(B));
auto &P = *std::get<0>(T);
auto &R = *std::get<1>(T);
backend::sort_rows(P);
backend::sort_rows(R);
return std::make_tuple(
std::make_shared<Matrix>(adapter::block_matrix<Block>(P)),
std::make_shared<Matrix>(adapter::block_matrix<Block>(R))
);
}
template <class Matrix>
std::shared_ptr<Matrix>
coarse_operator(const Matrix &A, const Matrix &P, const Matrix &R) const {
return base.coarse_operator(A, P, R);
}
};
};
} // namespace coarsening
} // namespace amgcl
#endif
<commit_msg>No need to specify scalar backend for coarsening::as_scalar<commit_after>#ifndef AMGCL_COARSENING_AS_SCALAR_HPP
#define AMGCL_COARSENING_AS_SCALAR_HPP
/*
The MIT License
Copyright (c) 2012-2022 Denis Demidov <dennis.demidov@gmail.com>
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.
*/
/**
* \file amgcl/coarsening/as_scalar.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Scalar coarsening for block matrices.
*/
#include <amgcl/adapter/block_matrix.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/interface.hpp>
namespace amgcl {
namespace coarsening {
// Takes a block matrix as input,
// converts it to the scalar format,
// applies the base coarsening,
// converts the results back to block format.
template <template <class> class Coarsening>
struct as_scalar {
template <class Backend>
struct type {
typedef typename math::scalar_of<typename Backend::value_type>::type Scalar;
typedef Coarsening< backend::builtin<Scalar> > Base;
typedef typename Base::params params;
Base base;
type(const params &prm = params()) : base(prm) {};
template <class Matrix>
std::tuple<
std::shared_ptr<Matrix>,
std::shared_ptr<Matrix>
>
transfer_operators(const Matrix &B) {
typedef typename backend::value_type<Matrix>::type Block;
auto T = base.transfer_operators(*adapter::unblock_matrix(B));
auto &P = *std::get<0>(T);
auto &R = *std::get<1>(T);
backend::sort_rows(P);
backend::sort_rows(R);
return std::make_tuple(
std::make_shared<Matrix>(adapter::block_matrix<Block>(P)),
std::make_shared<Matrix>(adapter::block_matrix<Block>(R))
);
}
template <class Matrix>
std::shared_ptr<Matrix>
coarse_operator(const Matrix &A, const Matrix &P, const Matrix &R) const {
return base.coarse_operator(A, P, R);
}
};
};
} // namespace coarsening
} // namespace amgcl
#endif
<|endoftext|>
|
<commit_before>#ifndef AMGCL_PRECONDITIONER_DUMMY_HPP
#define AMGCL_PRECONDITIONER_DUMMY_HPP
/*
The MIT License
Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>
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.
*/
/**
* \file amgcl/preconditioner/dummy.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Dummy preconditioner (identity matrix).
*/
#include <boost/shared_ptr.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
namespace preconditioner {
template <class Backend>
class dummy {
public:
typedef Backend backend_type;
typedef typename Backend::matrix matrix;
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename backend::builtin<value_type>::matrix build_matrix;
typedef detail::empty_params params;
typedef typename Backend::params backend_params;
template <class Matrix>
dummy(
const Matrix &M,
const params& = params(),
const backend_params &bprm = backend_params()
)
: A(Backend::copy_matrix(boost::make_shared<build_matrix>(M), bprm))
{
}
dummy(
boost::shared_ptr<build_matrix> M,
const params& = params(),
const backend_params &bprm = backend_params()
)
: A(Backend::copy_matrix(M, bprm))
{
}
template <class Vec1, class Vec2>
void apply(
const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
backend::copy(rhs, x);
}
const matrix& system_matrix() const {
return *A;
}
private:
boost::shared_ptr<matrix> A;
friend std::ostream& operator<<(std::ostream &os, const dummy &p) {
os << "identity matrix as preconditioner" << std::endl;
os << " unknowns: " << backend::rows(p.system_matrix()) << std::endl;
os << " nonzeros: " << backend::nonzeros(p.system_matrix()) << std::endl;
return os;
}
};
} // namespace preconditioner
} // namespace amgcl
#endif
<commit_msg>Resolve namespace ambiguity<commit_after>#ifndef AMGCL_PRECONDITIONER_DUMMY_HPP
#define AMGCL_PRECONDITIONER_DUMMY_HPP
/*
The MIT License
Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>
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.
*/
/**
* \file amgcl/preconditioner/dummy.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Dummy preconditioner (identity matrix).
*/
#include <boost/shared_ptr.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
namespace preconditioner {
template <class Backend>
class dummy {
public:
typedef Backend backend_type;
typedef typename Backend::matrix matrix;
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename backend::builtin<value_type>::matrix build_matrix;
typedef amgcl::detail::empty_params params;
typedef typename Backend::params backend_params;
template <class Matrix>
dummy(
const Matrix &M,
const params& = params(),
const backend_params &bprm = backend_params()
)
: A(Backend::copy_matrix(boost::make_shared<build_matrix>(M), bprm))
{
}
dummy(
boost::shared_ptr<build_matrix> M,
const params& = params(),
const backend_params &bprm = backend_params()
)
: A(Backend::copy_matrix(M, bprm))
{
}
template <class Vec1, class Vec2>
void apply(
const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
backend::copy(rhs, x);
}
const matrix& system_matrix() const {
return *A;
}
private:
boost::shared_ptr<matrix> A;
friend std::ostream& operator<<(std::ostream &os, const dummy &p) {
os << "identity matrix as preconditioner" << std::endl;
os << " unknowns: " << backend::rows(p.system_matrix()) << std::endl;
os << " nonzeros: " << backend::nonzeros(p.system_matrix()) << std::endl;
return os;
}
};
} // namespace preconditioner
} // namespace amgcl
#endif
<|endoftext|>
|
<commit_before>#include "installercontroller.h"
#include <QProcess>
#include <QtTest>
static const QString configFile = SRCDIR + QStringLiteral("../../../installer/config/config.xml");
static const QString configScript = SRCDIR + QStringLiteral("../../../installer/config/controller.qs");
static const QString pkgFile = SRCDIR + QStringLiteral("../../../installer/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
static const QString binarycreator = BINDIR + QStringLiteral("binarycreator");
static const QString repogen = BINDIR + QStringLiteral("repogen");
InstallerController::InstallerController(QObject *parent) :
QObject(parent),
_version(1, 0, 0),
_buildDir()
{
setVersion(_version);
}
void InstallerController::createRepository()
{
auto res = QProcess::execute(repogen, {"--update-new-components", "-p", _buildDir.path() + "/packages", _buildDir.path() + "/repository"});
QCOMPARE(res, 0);
}
void InstallerController::createInstaller()
{
QFile configSrc(configFile);
QFile configOut(_buildDir.path() + "/config.xml");
QVERIFY(configSrc.open(QIODevice::ReadOnly | QIODevice::Text));
QVERIFY(configOut.open(QIODevice::WriteOnly | QIODevice::Text));
auto src = QString::fromUtf8(configSrc.readAll());
configOut.write(src
.arg(_buildDir.path() + "/install")
.arg(_buildDir.path())
.toUtf8());
configSrc.close();
configOut.close();
auto res = QProcess::execute(binarycreator, {"-n", "-c", configOut.fileName(), "-p", _buildDir.path() + "/packages", _buildDir.path() + "/QtAutoUpdaterTestInstaller"});
QCOMPARE(res, 0);
}
void InstallerController::installLocal()
{
auto res = QProcess::execute(_buildDir.path() + "/QtAutoUpdaterTestInstaller", {"--script", configScript});
QCOMPARE(res, 0);
}
void InstallerController::runUpdater()
{
}
QVersionNumber InstallerController::version() const
{
return _version;
}
QString InstallerController::maintenanceToolPath() const
{
return _buildDir.path() + "/install";
}
void InstallerController::setVersion(QVersionNumber version)
{
_version = version;
QDir tDir(_buildDir.path());
QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta"));
QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/data"));
QFile pkgSrc(pkgFile);
QFile pkgOut(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
QVERIFY(pkgSrc.open(QIODevice::ReadOnly | QIODevice::Text));
QVERIFY(pkgOut.open(QIODevice::WriteOnly | QIODevice::Text));
auto src = QString::fromUtf8(pkgSrc.readAll());
pkgOut.write(src.arg(_version.toString()).toUtf8());
pkgSrc.close();
pkgOut.close();
QFile dataFile(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/data/version.txt");
QVERIFY(dataFile.open(QIODevice::WriteOnly | QIODevice::Text));
dataFile.write(_version.toString().toUtf8());
dataFile.close();
}
<commit_msg>more debug logs<commit_after>#include "installercontroller.h"
#include <QProcess>
#include <QtTest>
static const QString configFile = SRCDIR + QStringLiteral("../../../installer/config/config.xml");
static const QString configScript = SRCDIR + QStringLiteral("../../../installer/config/controller.qs");
static const QString pkgFile = SRCDIR + QStringLiteral("../../../installer/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
static const QString binarycreator = BINDIR + QStringLiteral("binarycreator");
static const QString repogen = BINDIR + QStringLiteral("repogen");
InstallerController::InstallerController(QObject *parent) :
QObject(parent),
_version(1, 0, 0),
_buildDir()
{
setVersion(_version);
}
void InstallerController::createRepository()
{
qDebug() << "Creating repository";
auto res = QProcess::execute(repogen, {"--update-new-components", "-p", _buildDir.path() + "/packages", _buildDir.path() + "/repository"});
QCOMPARE(res, 0);
}
void InstallerController::createInstaller()
{
qDebug() << "Creating installer";
QFile configSrc(configFile);
QFile configOut(_buildDir.path() + "/config.xml");
QVERIFY(configSrc.open(QIODevice::ReadOnly | QIODevice::Text));
QVERIFY(configOut.open(QIODevice::WriteOnly | QIODevice::Text));
auto src = QString::fromUtf8(configSrc.readAll());
configOut.write(src
.arg(_buildDir.path() + "/install")
.arg(_buildDir.path())
.toUtf8());
configSrc.close();
configOut.close();
auto res = QProcess::execute(binarycreator, {"-n", "-c", configOut.fileName(), "-p", _buildDir.path() + "/packages", _buildDir.path() + "/QtAutoUpdaterTestInstaller"});
QCOMPARE(res, 0);
}
void InstallerController::installLocal()
{
qDebug() << "Installing example";
auto res = QProcess::execute(_buildDir.path() + "/QtAutoUpdaterTestInstaller", {"--script", configScript});
QCOMPARE(res, 0);
}
void InstallerController::runUpdater()
{
qDebug() << "Running updater";
}
QVersionNumber InstallerController::version() const
{
return _version;
}
QString InstallerController::maintenanceToolPath() const
{
return _buildDir.path() + "/install";
}
void InstallerController::setVersion(QVersionNumber version)
{
qDebug() << "Updating repository version";
_version = version;
QDir tDir(_buildDir.path());
QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta"));
QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/data"));
QFile pkgSrc(pkgFile);
QFile pkgOut(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
QVERIFY(pkgSrc.open(QIODevice::ReadOnly | QIODevice::Text));
QVERIFY(pkgOut.open(QIODevice::WriteOnly | QIODevice::Text));
auto src = QString::fromUtf8(pkgSrc.readAll());
pkgOut.write(src.arg(_version.toString()).toUtf8());
pkgSrc.close();
pkgOut.close();
QFile dataFile(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/data/version.txt");
QVERIFY(dataFile.open(QIODevice::WriteOnly | QIODevice::Text));
dataFile.write(_version.toString().toUtf8());
dataFile.close();
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv/cxcore.h>
#include <std_msgs/Float64.h>
#include <std_msgs/String.h>
#include <scan2image/ScanImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sensor_msgs/LaserScan.h>
#include <algorithm>
#include "scan2image.h"
#include "calibration_camera_lidar/projection_matrix.h"
#include <sensor_msgs/CameraInfo.h>
#if 1 // AXE
#define XSTR(x) #x
#define STR(x) XSTR(x)
#endif
static cv::Mat cameraExtrinsicMat;
static cv::Mat cameraMat;
static cv::Mat distCoeff;
static cv::Size imageSize;
ros::Publisher transformed_point_data;
static bool isProjection;
static bool isIntrinsic;
Scan_image scan_image;
void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset)
{
float camera_x;
float camera_y;
float camera_z;
int i;
for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) {
/*
* Coordinate transformation. Change from laser range finder coordinate to camera coordinate
*/
camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(0,3));
camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(1,3));
camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(2,3));
if (camera_z >= 0.0) {
/*
* Projection transformation. Change from camera coordinate to image coordinate
*/
image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2));
image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2));
/*
* Calculate euclidean distance from the camera to objects
*/
image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter
/*
* Copy to intensity
*/
if(!(scan_points_dataset->intensity.empty())){
image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i));
}
}
}
}
static void projection_callback(const calibration_camera_lidar::projection_matrix& msg)
{
printf("projection\n");
cameraExtrinsicMat = cv::Mat(4,4,CV_64F);
for (int row=0; row<4; row++) {
for (int col=0; col<4; col++) {
cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col];
printf("%f\t", cameraExtrinsicMat.at<double>(row, col));
}
printf("\n");
}
isProjection = true;
}
static void intrinsic_callback(const sensor_msgs::CameraInfo& msg)
{
printf("intrinsic\n");
if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) {
if (isIntrinsic) {
free(scan_image.distance);
free(scan_image.intensity);
}
scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float));
scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float));
scan_image.max_y = NO_DATA;
scan_image.min_y = NO_DATA;
}
imageSize.height = msg.height;
imageSize.width = msg.width;
cameraMat = cv::Mat(3,3, CV_64F);
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
cameraMat.at<double>(row, col) = msg.K[row * 3 + col];
printf("%f\t", cameraMat.at<double>(row, col));
}
printf("\n");
}
distCoeff = cv::Mat(1,5,CV_64F);
for (int col=0; col<5; col++) {
distCoeff.at<double>(col) = msg.D[col];
}
isIntrinsic = true;
}
void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
if (!(isIntrinsic && isProjection)){
return;
}
static Scan_points_dataset scan_points_dataset;
static Image_points_dataset image_points_dataset;
int i;
// ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max);
/*
* Initialize
*/
scan_points_dataset.scan_points.x.resize(msg->ranges.size());
scan_points_dataset.scan_points.y.resize(msg->ranges.size());
scan_points_dataset.scan_points.z.resize(msg->ranges.size());
scan_points_dataset.intensity.resize(msg->intensities.size());
image_points_dataset.image_points.x.clear();
image_points_dataset.image_points.y.clear();
image_points_dataset.distance.clear();
image_points_dataset.intensity.clear();
/*
* Change to three dimentional coordinate. And copy intensity
*/
for(i = 0; i < (int)msg->ranges.size(); i++) {
scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter
scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter
scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter
if(!(msg->intensities.empty())){
scan_points_dataset.intensity.at(i) = msg->intensities.at(i);
}
}
/*
* Change from laser range finder coordinate to image coordinate
*/
trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset);
/*
* Judge out of image frame. And Determine max_y and min_y
*/
for (i = 0; i < (int)image_points_dataset.image_points.x.size(); i++) {
/* Judge NaN */
if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) {
std::cout <<"Not a Number is i:" << i << std::endl;
continue;
}
/* Judge out of X-axis image */
if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) {
continue;
}
/* Judge out of Y-axis image */
if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) {
continue;
}
scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i);
if(!msg->intensities.empty()){
scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i);
}
if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) {
scan_image.max_y = (int)image_points_dataset.image_points.y.at(i);
} else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) {
scan_image.min_y = (int)image_points_dataset.image_points.y.at(i);
}
}
/*
* Create message(Topic)
*/
scan2image::ScanImage scan_image_msg;
scan_image_msg.header = msg->header;
scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height);
scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height);
scan_image_msg.max_y = scan_image.max_y;
scan_image_msg.min_y = scan_image.min_y;
/*
* Publish message(Topic)
*/
transformed_point_data.publish(scan_image_msg);
/*
* Init zero
*/
memset(scan_image.distance, 0, imageSize.width * imageSize.height);
memset(scan_image.intensity, 0, imageSize.width * imageSize.height);
scan_image.max_y = NO_DATA;
scan_image.min_y = NO_DATA;
}
int main(int argc, char **argv)
{
isProjection = false;
isIntrinsic = false;
ros::init(argc, argv, "scan2image");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("scan", 1, scanCallback);
ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback);
ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback);
transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1);
ros::spin();
free(scan_image.distance);
free(scan_image.intensity);
return 0;
}
<commit_msg>fixed bug of scan2image the third argument in memset() is wrong<commit_after>#include <ros/ros.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv/cxcore.h>
#include <std_msgs/Float64.h>
#include <std_msgs/String.h>
#include <scan2image/ScanImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sensor_msgs/LaserScan.h>
#include <algorithm>
#include "scan2image.h"
#include "calibration_camera_lidar/projection_matrix.h"
#include <sensor_msgs/CameraInfo.h>
#if 1 // AXE
#define XSTR(x) #x
#define STR(x) XSTR(x)
#endif
static cv::Mat cameraExtrinsicMat;
static cv::Mat cameraMat;
static cv::Mat distCoeff;
static cv::Size imageSize;
ros::Publisher transformed_point_data;
static bool isProjection;
static bool isIntrinsic;
Scan_image scan_image;
void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset)
{
float camera_x;
float camera_y;
float camera_z;
int i;
for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) {
/*
* Coordinate transformation. Change from laser range finder coordinate to camera coordinate
*/
camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(0,3));
camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(1,3));
camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000
+ cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000
+ cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000)
+ (cameraExtrinsicMat.at<double>(2,3));
if (camera_z >= 0.0) {
/*
* Projection transformation. Change from camera coordinate to image coordinate
*/
image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2));
image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2));
/*
* Calculate euclidean distance from the camera to objects
*/
image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter
/*
* Copy to intensity
*/
if(!(scan_points_dataset->intensity.empty())){
image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i));
}
}
}
}
static void projection_callback(const calibration_camera_lidar::projection_matrix& msg)
{
printf("projection\n");
cameraExtrinsicMat = cv::Mat(4,4,CV_64F);
for (int row=0; row<4; row++) {
for (int col=0; col<4; col++) {
cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col];
printf("%f\t", cameraExtrinsicMat.at<double>(row, col));
}
printf("\n");
}
isProjection = true;
}
static void intrinsic_callback(const sensor_msgs::CameraInfo& msg)
{
printf("intrinsic\n");
if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) {
if (isIntrinsic) {
free(scan_image.distance);
free(scan_image.intensity);
}
scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float));
scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float));
scan_image.max_y = NO_DATA;
scan_image.min_y = NO_DATA;
}
imageSize.height = msg.height;
imageSize.width = msg.width;
cameraMat = cv::Mat(3,3, CV_64F);
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
cameraMat.at<double>(row, col) = msg.K[row * 3 + col];
printf("%f\t", cameraMat.at<double>(row, col));
}
printf("\n");
}
distCoeff = cv::Mat(1,5,CV_64F);
for (int col=0; col<5; col++) {
distCoeff.at<double>(col) = msg.D[col];
}
isIntrinsic = true;
}
void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
if (!(isIntrinsic && isProjection)){
return;
}
static Scan_points_dataset scan_points_dataset;
static Image_points_dataset image_points_dataset;
int i;
// ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max);
/*
* Initialize
*/
scan_points_dataset.scan_points.x.resize(msg->ranges.size());
scan_points_dataset.scan_points.y.resize(msg->ranges.size());
scan_points_dataset.scan_points.z.resize(msg->ranges.size());
scan_points_dataset.intensity.resize(msg->intensities.size());
image_points_dataset.image_points.x.clear();
image_points_dataset.image_points.y.clear();
image_points_dataset.distance.clear();
image_points_dataset.intensity.clear();
/*
* Change to three dimentional coordinate. And copy intensity
*/
for(i = 0; i < (int)msg->ranges.size(); i++) {
scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter
scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter
scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter
if(!(msg->intensities.empty())){
scan_points_dataset.intensity.at(i) = msg->intensities.at(i);
}
}
/*
* Change from laser range finder coordinate to image coordinate
*/
trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset);
/*
* Judge out of image frame. And Determine max_y and min_y
*/
for (i = 0; i < (int)image_points_dataset.image_points.x.size(); i++) {
/* Judge NaN */
if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) {
std::cout <<"Not a Number is i:" << i << std::endl;
continue;
}
/* Judge out of X-axis image */
if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) {
continue;
}
/* Judge out of Y-axis image */
if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) {
continue;
}
scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i);
if(!msg->intensities.empty()){
scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i);
}
if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) {
scan_image.max_y = (int)image_points_dataset.image_points.y.at(i);
} else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) {
scan_image.min_y = (int)image_points_dataset.image_points.y.at(i);
}
}
/*
* Create message(Topic)
*/
scan2image::ScanImage scan_image_msg;
scan_image_msg.header = msg->header;
scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height);
scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height);
scan_image_msg.max_y = scan_image.max_y;
scan_image_msg.min_y = scan_image.min_y;
/*
* Publish message(Topic)
*/
transformed_point_data.publish(scan_image_msg);
/*
* Init zero
*/
memset(scan_image.distance, 0, sizeof(float) * imageSize.width * imageSize.height);
memset(scan_image.intensity, 0, sizeof(float) * imageSize.width * imageSize.height);
scan_image.max_y = NO_DATA;
scan_image.min_y = NO_DATA;
}
int main(int argc, char **argv)
{
isProjection = false;
isIntrinsic = false;
ros::init(argc, argv, "scan2image");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("scan", 1, scanCallback);
ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback);
ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback);
transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1);
ros::spin();
free(scan_image.distance);
free(scan_image.intensity);
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: GenericConfigurationChangeRequest.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-04-03 15:47:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "GenericConfigurationChangeRequest.hxx"
#include "framework/FrameworkHelper.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;
namespace sd { namespace framework {
GenericConfigurationChangeRequest::GenericConfigurationChangeRequest (
const Reference<XResourceId>& rxResourceId,
Mode eMode) throw(::com::sun::star::lang::IllegalArgumentException)
: GenericConfigurationChangeRequestInterfaceBase(MutexOwner::maMutex),
mxResourceId(rxResourceId),
meMode(eMode)
{
if ( ! rxResourceId.is() || rxResourceId->getResourceURL().getLength()==0)
throw ::com::sun::star::lang::IllegalArgumentException();
}
GenericConfigurationChangeRequest::~GenericConfigurationChangeRequest (void) throw()
{
}
void SAL_CALL GenericConfigurationChangeRequest::execute (
const Reference<XConfiguration>& rxConfiguration)
throw (RuntimeException)
{
if (rxConfiguration.is())
{
switch (meMode)
{
case Activation:
rxConfiguration->addResource(mxResourceId);
break;
case Deactivation:
rxConfiguration->removeResource(mxResourceId);
break;
}
}
}
OUString SAL_CALL GenericConfigurationChangeRequest::getName (void)
throw (RuntimeException)
{
return OUString::createFromAscii("GenericConfigurationChangeRequest ")
+ OUString::createFromAscii(meMode==Activation ? "activate " : "deactivate ")
+ FrameworkHelper::ResourceIdToString(mxResourceId);
}
void SAL_CALL GenericConfigurationChangeRequest::setName (const OUString& rsName)
throw (RuntimeException)
{
(void)rsName;
// Ignored.
}
} } // end of namespace sd::framework
<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007/07/24 10:58:28 af 1.2.22.1: #i18486# Fixed resync problems.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: GenericConfigurationChangeRequest.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-04-03 13:30:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "GenericConfigurationChangeRequest.hxx"
#include "framework/FrameworkHelper.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;
namespace sd { namespace framework {
GenericConfigurationChangeRequest::GenericConfigurationChangeRequest (
const Reference<XResourceId>& rxResourceId,
const Mode eMode) throw(::com::sun::star::lang::IllegalArgumentException)
: GenericConfigurationChangeRequestInterfaceBase(MutexOwner::maMutex),
mxResourceId(rxResourceId),
meMode(eMode)
{
if ( ! rxResourceId.is() || rxResourceId->getResourceURL().getLength()==0)
throw ::com::sun::star::lang::IllegalArgumentException();
}
GenericConfigurationChangeRequest::~GenericConfigurationChangeRequest (void) throw()
{
}
void SAL_CALL GenericConfigurationChangeRequest::execute (
const Reference<XConfiguration>& rxConfiguration)
throw (RuntimeException)
{
if (rxConfiguration.is())
{
switch (meMode)
{
case Activation:
rxConfiguration->addResource(mxResourceId);
break;
case Deactivation:
rxConfiguration->removeResource(mxResourceId);
break;
}
}
}
OUString SAL_CALL GenericConfigurationChangeRequest::getName (void)
throw (RuntimeException)
{
return OUString::createFromAscii("GenericConfigurationChangeRequest ")
+ OUString::createFromAscii(meMode==Activation ? "activate " : "deactivate ")
+ FrameworkHelper::ResourceIdToString(mxResourceId);
}
void SAL_CALL GenericConfigurationChangeRequest::setName (const OUString& rsName)
throw (RuntimeException)
{
(void)rsName;
// Ignored.
}
} } // end of namespace sd::framework
<|endoftext|>
|
<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? L'А' : L'а');
if (letter > (is_capital ? L'Е' : L'е')) {
return static_cast<int>(letter) - first_letter_code + 2;
}
else {
if (letter == (is_capital ? L'Ё' : L'ё')) {
return 7;
}
return static_cast<int>(letter) - first_letter_code + 1;
}
}
struct person {
std::string surname;
std::string name;
size_t year;
size_t i(size_t sort_i) const {
if (sort_i < surname.length()) {
return letterI(surname[sort_i], sort_i == 0);
}
else {
return 0;
}
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.surname << " ";
output << _person.name << " ";
output << _person.year;
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.surname;
input >> _person.name;
input >> _person.year;
return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
Persons_File() : is_empty(true), file_size(0) {
;
}
std::string file_name;
bool is_empty;
size_t file_size;
std::fstream stream;
void openNew(std::string _file_name) {
file_name = _file_name;
stream.open(file_name, std::ios::out);
}
void addToSize(person _person) {
file_size += _person.surname.size();
file_size += _person.name.size();
file_size += sizeof(_person.year);
file_size += 1 + 1 + 2;
}
};
using Output_Files = std::vector<std::ofstream>;
class Database_Sorter {
bool is_database_empty;
std::string database_file_name;
std::string vault_file_name;
public:
Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
: database_file_name(database_file_name),
database_file(database_file_name),
output_file(output_file_name),
RAM_amount(_RAM_amount),
is_database_empty(true)
{
vault_file_name = "F:\\1\\temp_files\\";
}
void sortDatabase() {
sortFile(database_file, database_file_name, RAM_amount + 1, 0);
}
~Database_Sorter() {
database_file.close();
output_file.close();
}
private:
void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
if (file_size < RAM_amount) {
}
else {
std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
for (size_t i = 0; i < persons_files.size(); i++) {
if (persons_files[i].file_size != 0) {
std::ifstream temp_file(persons_files[i].file_name);
try {
sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
}
catch (...) {
system("pause");
throw;
}
temp_file.close();
}
}
}
}
void RAMsort(std::ifstream & file, size_t sort_i) {
persons_outputted = 0;
persons.clear();
readFileIntoRAM(file);
sortPersons(persons, sort_i);
}
void readFileIntoRAM(std::ifstream & file) {
while (!file.eof()) {
person current_person;
file >> current_person;
persons.push_back(current_person);
}
}
void sortPersons(Persons const & entered_persons, size_t sort_i) {
Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
outputBucket(entered_persons, output_file);
}
else {
sortBuckets(buckets, sort_i + 1);
}
}
Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
Buckets buckets(34);
for (auto person : persons) {
size_t currentI = person.i(sort_i);
buckets[currentI].push_back(person);
}
return buckets;
}
bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
size_t first_bucket_i = persons[0].i(sort_i);
return buckets[first_bucket_i].size() == persons.size();
}
void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
for (auto person : bucket) {
outputPerson(person);
}
}
void outputPerson(person _person) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
output_file << _person;
persons_outputted++;
}
void sortBuckets(Buckets const & buckets, size_t sort_i) {
for (auto bucket : buckets) {
if (!bucket.empty()) {
sortPersons(bucket, sort_i);
}
}
}
std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
std::vector<Persons_File> files = createDerivedFiles(base_file_name);
while (!base_file.eof()) {
person current_person;
base_file >> current_person;
size_t currentI = current_person.i(sort_i);
if (files[currentI].is_empty) {
files[currentI].is_empty = false;
}
else {
files[currentI].stream << std::endl;
}
files[currentI].stream << current_person;
files[currentI].addToSize(current_person);
}
for (size_t i = 0; i < files.size(); i++) {
files[i].stream.close();
}
return files;
}
std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
std::vector<Persons_File> files(34);
for (size_t i = 0; i < files.size(); i++) {
std::stringstream string_stream;
std::string str;
if (base_file_name == database_file_name) {
string_stream << vault_file_name << i << ".txt";
}
else {
string_stream << base_file_name << "_" << i << ".txt";
}
string_stream >> str;
files[i].openNew(str);
}
return files;
}
std::vector<person> persons;
size_t persons_outputted;
std::ifstream database_file;
std::ofstream output_file;
size_t RAM_amount;
};
<commit_msg>Update Database_Sorter.hpp<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
char russian_letters[6];
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
size_t result = static_cast<int>(letter) - first_letter_code + 2;
return result;
}
else {
if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
return 7;
}
size_t result = static_cast<int>(letter) - first_letter_code + 2;
return result;
}
}
struct person {
std::string surname;
std::string name;
size_t year;
size_t i(size_t sort_i) const {
if (sort_i < surname.length()) {
return letterI(surname[sort_i], sort_i == 0);
}
else {
return 0;
}
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.surname << " ";
output << _person.name << " ";
output << _person.year;
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.surname;
input >> _person.name;
input >> _person.year;
return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
Persons_File() : is_empty(true), file_size(0) {
;
}
std::string file_name;
bool is_empty;
size_t file_size;
std::fstream stream;
void openNew(std::string _file_name) {
file_name = _file_name;
stream.open(file_name, std::ios::out);
}
void addToSize(person _person) {
file_size += _person.surname.size();
file_size += _person.name.size();
file_size += sizeof(_person.year);
file_size += 1 + 1 + 2;
}
};
using Output_Files = std::vector<std::ofstream>;
class Database_Sorter {
bool is_database_empty;
std::string database_file_name;
std::string vault_file_name;
public:
Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
: database_file_name(database_file_name),
database_file(database_file_name),
output_file(output_file_name),
RAM_amount(_RAM_amount),
is_database_empty(true)
{
vault_file_name = "F:\\1\\temp_files\\";
}
void sortDatabase() {
sortFile(database_file, database_file_name, RAM_amount + 1, 0);
}
~Database_Sorter() {
database_file.close();
output_file.close();
}
private:
void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
if (file_size < RAM_amount) {
RAMsort(file, sort_i);
}
else {
std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
for (size_t i = 0; i < persons_files.size(); i++) {
if (persons_files[i].file_size != 0) {
std::ifstream temp_file(persons_files[i].file_name);
sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
temp_file.close();
}
}
}
}
void RAMsort(std::ifstream & file, size_t sort_i) {
persons_outputted = 0;
persons.clear();
readFileIntoRAM(file);
sortPersons(persons, sort_i);
}
void readFileIntoRAM(std::ifstream & file) {
while (!file.eof()) {
person current_person;
file >> current_person;
persons.push_back(current_person);
}
}
void sortPersons(Persons const & entered_persons, size_t sort_i) {
Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
outputBucket(entered_persons, output_file);
}
else {
sortBuckets(buckets, sort_i + 1);
}
}
Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
Buckets buckets(34);
for (auto person : persons) {
size_t currentI = person.i(sort_i);
buckets[currentI].push_back(person);
}
return buckets;
}
bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
size_t first_bucket_i = persons[0].i(sort_i);
return buckets[first_bucket_i].size() == persons.size();
}
void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
for (auto person : bucket) {
outputPerson(person);
}
}
void outputPerson(person _person) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
output_file << _person;
persons_outputted++;
}
void sortBuckets(Buckets const & buckets, size_t sort_i) {
for (auto bucket : buckets) {
if (!bucket.empty()) {
sortPersons(bucket, sort_i);
}
}
}
std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
std::vector<Persons_File> files = createDerivedFiles(base_file_name);
while (!base_file.eof()) {
person current_person;
base_file >> current_person;
size_t currentI = current_person.i(sort_i);
if (files[currentI].is_empty) {
files[currentI].is_empty = false;
}
else {
files[currentI].stream << std::endl;
}
files[currentI].stream << current_person;
files[currentI].addToSize(current_person);
}
for (size_t i = 0; i < files.size(); i++) {
files[i].stream.close();
}
return files;
}
std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
std::vector<Persons_File> files(34);
for (size_t i = 0; i < files.size(); i++) {
std::stringstream string_stream;
std::string str;
if (base_file_name == database_file_name) {
string_stream << vault_file_name << i << ".txt";
}
else {
string_stream << base_file_name << "_" << i << ".txt";
}
string_stream >> str;
files[i].openNew(str);
}
return files;
}
std::vector<person> persons;
size_t persons_outputted;
std::ifstream database_file;
std::ofstream output_file;
size_t RAM_amount;
};
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <BaseResource.hpp>
#include <functional>
#include <string>
#include <memory>
#include <map>
#include <list>
#include <queue>
namespace rm
{
typedef std::shared_ptr<BaseResource> resource_ptr;
enum class LoadMode
{
Queue,
Block,
};
class ResourceManager
{
public:
ResourceManager();
virtual ~ResourceManager();
template<class T>
void initResource(std::string path);
template<class T>
std::shared_ptr<T> loadResource(std::string name, LoadMode mode);
template<class T>
std::shared_ptr<T> getResource(std::string name);
void unloadResource(std::string name, LoadMode mode);
void reloadResource(std::string name);
void initPack(std::string path);
void loadPack(std::string path, LoadMode mode);
void unloadPack (std::string path, LoadMode mode);
void reloadPack(std::string path);
void switchPack(std::string path, std::string path);
template<class T>
void createErrorResource(std::string path);
template<class T>
std::shared_ptr<T> getErrorResource();
void init(bool useNullForErrorRes);
void update();
void cleanupUnused();
bool isLoading();
size_t getNumToLoad();
std::list<resource_ptr> listAll();
size_t getRamUse();
size_t genNumResources();
void setLoadCompleteCallback(std::function callback);
private:
std::map<std::string, resource_ptr> resources;
std::map<std::string, resource_ptr> errorResources;
std::queue<resource_ptr> loadingQueue;
std::queue<resource_ptr> unloadQueue;
std::queue<resource_ptr> reloadQueue;
bool useNullForErrorRes;
std::function loadCompleteCallback;
void loadFromQueue();
void unloadFromQueue();
void reloadFromQueue();
};
#endif //RESOURCE_MANAGER_HPP<commit_msg>made ResourceManager monostate<commit_after>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <BaseResource.hpp>
#include <functional>
#include <string>
#include <memory>
#include <map>
#include <list>
#include <queue>
namespace rm
{
typedef std::shared_ptr<BaseResource> resource_ptr;
enum class LoadMode
{
Queue,
Block,
};
class ResourceManager
{
public:
template<class T>
static void initResource(std::string path);
template<class T>
static std::shared_ptr<T> loadResource(std::string name, LoadMode mode);
template<class T>
static std::shared_ptr<T> getResource(std::string name);
static void unloadResource(std::string name, LoadMode mode);
static void reloadResource(std::string name);
static void initPack(std::string path);
static void loadPack(std::string path, LoadMode mode);
static void unloadPack (std::string path, LoadMode mode);
static void reloadPack(std::string path);
static void switchPack(std::string path, std::string path);
template<class T>
static void createErrorResource(std::string path);
template<class T>
static std::shared_ptr<T> getErrorResource();
static void init(bool useNullForErrorRes);
static void update();
static void cleanupUnused();
static bool isLoading();
static size_t getNumToLoad();
static std::list<resource_ptr> listAll();
static size_t getRamUse();
static size_t genNumResources();
static void setLoadCompleteCallback(std::function callback);
private:
static std::map<std::string, resource_ptr> resources;
static std::map<std::string, resource_ptr> errorResources;
static std::queue<resource_ptr> loadingQueue;
static std::queue<resource_ptr> unloadQueue;
static std::queue<resource_ptr> reloadQueue;
static bool useNullForErrorRes;
static std::function loadCompleteCallback;
static void loadFromQueue();
static void unloadFromQueue();
static void reloadFromQueue();
};
#endif //RESOURCE_MANAGER_HPP<|endoftext|>
|
<commit_before>//
// File: GeneratedBlock.cpp
// Class GeneratedBlock
// Author Jonatan Rapp & Alexander Hederstaf
// All code is my own except where credited to others.
//
// Copyright © 2012 Catch22. All Rights Reserved.
//
// Date: Oct 10, 2012
//
// Description:
//
//
#include "GeneratedBlock.hpp"
GeneratedBlock::GeneratedBlock(int dy, Blocktype type)
{
this->dy = dy;
this->type = type;
}
GeneratedBlock::~GeneratedBlock()
{
}
bool operator==(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
return lhsBlock.dy == rhsBlock.dy && lhsBlock.type == rhsBlock.type;
}
bool operator<(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
/*
* return value based on type and dY to order
* the GeneratedBlocks.
*/
int thisValue = lhsBlock.dy*3 + lhsBlock.type == INCLINE ? 0 : lhsBlock.type == HORIZONTAL ? 1 : 2;
int otherValue = rhsBlock.dy*3 + rhsBlock.type == INCLINE ? 0 : rhsBlock.type == HORIZONTAL ? 1 : 2;
return thisValue < otherValue;
}
<commit_msg>Small fix in operator< overload - Added parantheses to properly calculate order values.<commit_after>//
// File: GeneratedBlock.cpp
// Class GeneratedBlock
// Author Jonatan Rapp & Alexander Hederstaf
// All code is my own except where credited to others.
//
// Copyright © 2012 Catch22. All Rights Reserved.
//
// Date: Oct 10, 2012
//
// Description:
//
//
#include "GeneratedBlock.hpp"
#include <stdio.h>
GeneratedBlock::GeneratedBlock(int dy, Blocktype type)
{
this->dy = dy;
this->type = type;
}
GeneratedBlock::~GeneratedBlock()
{
}
bool operator==(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
return lhsBlock.dy == rhsBlock.dy && lhsBlock.type == rhsBlock.type;
}
bool operator<(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
/*
* return value based on type and dY to order
* the GeneratedBlocks.
*/
int thisValue = lhsBlock.dy*3 + (lhsBlock.type == INCLINE ? 0 : lhsBlock.type == HORIZONTAL ? 1 : 2);
int otherValue = rhsBlock.dy*3 + (rhsBlock.type == INCLINE ? 0 : rhsBlock.type == HORIZONTAL ? 1 : 2);
return thisValue < otherValue;
}
<|endoftext|>
|
<commit_before># ifndef SPL_1D_SIGNAL_HH
# define SPL_1D_SIGNAL_HH
# include "NDSignal.hh"
# include "Point.hh"
# include <vector>
namespace spl{
template<typename V>
struct Signal1D;
namespace global{
template<>
template<typename V>
struct traits<Signal1D<V> >
{
typedef V value_type;
typedef Point1D point_type;
typedef Domain<1> domain_type;
typedef V sub_type;
typedef Signal1D<V> concrete_type;
};
template<typename oldType, typename newVal>
struct mute<Signal1D<oldType>,oldType,newVal>
{
typedef Signal1D<newVal> res;
};
}//!global
/* **
* Signal1D is a signal defined by only one dimension.
* This structure is more like a 1D array.
*/
template <typename V>
struct Signal1D : public NDSignal<Signal1D<V> >
{
typedef NDSignal<Signal1D<V> > parent;
Signal1D(unsigned w);
Signal1D(Domain<1> dom);
Signal1D(const spl::Signal1D<V> &sig);
V& operator()(unsigned x)
{
return at_impl(traits_point_type(Signal1D<V>)(x));
}
const V& operator()(unsigned x) const
{
return at_impl(traits_point_type(Signal1D<V>)(x));
}
private:
V& at_impl(const traits_point_type(Signal1D<V>)& p)
{
return _data[p._x];
}
const V& at_impl(const traits_point_type(Signal1D<V>)& p) const
{
return _data[p._x];
}
public:
const unsigned length() const
{
return parent::_domain[0];
}
explicit operator V* ()
{
return _data;
}
explicit operator const V* () const
{
return _data;
}
Signal1D clone_impl() const
{
Signal1D ret(this->domain());
for_each_lin(ret, x)
ret(x) = (*this)(x);
return ret;
}
private:
V *_data;
};
}//!spl
#include "1DSignal.hxx"
# endif
<commit_msg>Likewise<commit_after># ifndef SPL_1D_SIGNAL_HH
# define SPL_1D_SIGNAL_HH
# include "NDSignal.hh"
# include "Point.hh"
# include <vector>
namespace spl{
template<typename V>
struct Signal1D;
namespace global{
template<>
template<typename V>
struct traits<Signal1D<V> >
{
typedef V value_type;
typedef Point1D point_type;
typedef Domain<1> domain_type;
typedef V sub_type;
typedef Signal1D<V> concrete_type;
};
template<typename oldType, typename newVal>
struct mute<Signal1D<oldType>,oldType,newVal>
{
typedef Signal1D<newVal> res;
};
}//!global
/* **
* Signal1D is a signal defined by only one dimension.
* This structure is more like a 1D array.
*/
template <typename V>
struct Signal1D : public NDSignal<Signal1D<V> >
{
typedef NDSignal<Signal1D<V> > parent;
Signal1D(unsigned w);
Signal1D(Domain<1> dom);
Signal1D(const spl::Signal1D<V> &sig);
V& operator()(unsigned x)
{
return at_impl(traits_point_type(Signal1D<V>)(x));
}
const V& operator()(unsigned x) const
{
return at_impl(traits_point_type(Signal1D<V>)(x));
}
private:
V& at_impl(const traits_point_type(Signal1D<V>)& p)
{
return _data[p._x];
}
const V& at_impl(const traits_point_type(Signal1D<V>)& p) const
{
return _data[p._x];
}
public:
const unsigned length() const
{
return parent::_domain[0];
}
explicit operator V* ()
{
return _data;
}
explicit operator const V* () const
{
return _data;
}
Signal1D clone_impl() const
{
Signal1D ret(this->domain());
for_each_lin(ret, x)
ret(x) = (*this)(x);
return ret;
}
private:
V *_data;
template <typename T>
friend struct NDSignal;
};
}//!spl
#include "1DSignal.hxx"
# endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Benjamin YanXiang Huang
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 yxbh 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 HOLDER 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.
*/
#pragma once
#include <chrono>
#include <type_traits>
/**
* @class ElapsedTimer
* @brief
* A simple std::chrono based timer for measuring elapsed time.
* Use any of the std::chrono duration type to create a new ElapsedTimer.
*/
template<class Duration_T = std::chrono::milliseconds,
class Test = typename std::enable_if<
std::is_same<Duration_T, std::chrono::microseconds>::value ||
std::is_same<Duration_T, std::chrono::milliseconds>::value ||
std::is_same<Duration_T, std::chrono::seconds>::value
>::type
>
class ElapsedTimer
{
public:
typedef Duration_T DurationType;
typedef std::chrono::high_resolution_clock ClockType;
typedef ClockType::time_point TimePointType;
private:
DurationType m_Duration;
TimePointType m_BeforeTP, m_AfterTP;
public:
ElapsedTimer(void)
: m_Duration(0), m_BeforeTP(ClockType::now()), m_AfterTP(m_BeforeTP) {}
/** @return the elapsed time as the templated duration type. */
inline DurationType elapsed(void)
{
m_AfterTP = ClockType::now();
m_Duration += std::chrono::duration_cast<DurationType>(m_AfterTP - m_BeforeTP);
m_BeforeTP = m_AfterTP;
return m_Duration;
}
inline void restart(void)
{
m_BeforeTP = ClockType::now();
m_Duration = DurationType(0);
}
};<commit_msg>add ElapsedTimer to bh namespace<commit_after>/*
Copyright (c) 2015, Benjamin YanXiang Huang
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 yxbh 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 HOLDER 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.
*/
#pragma once
#include <chrono>
#include <type_traits>
namespace bh
{
/**
* @class ElapsedTimer
* @brief
* A simple std::chrono based timer for measuring elapsed time.
* Use any of the std::chrono duration type to create a new ElapsedTimer.
*/
template<class Duration_T = std::chrono::milliseconds,
class Test = typename std::enable_if<
std::is_same<Duration_T, std::chrono::microseconds>::value ||
std::is_same<Duration_T, std::chrono::milliseconds>::value ||
std::is_same<Duration_T, std::chrono::seconds>::value
>::type
>
class ElapsedTimer
{
public:
typedef Duration_T DurationType;
typedef std::chrono::high_resolution_clock ClockType;
typedef ClockType::time_point TimePointType;
private:
DurationType m_Duration;
TimePointType m_BeforeTP, m_AfterTP;
public:
ElapsedTimer(void)
: m_Duration(0), m_BeforeTP(ClockType::now()), m_AfterTP(m_BeforeTP) {}
/** @return the elapsed time as the templated duration type. */
inline DurationType elapsed(void)
{
m_AfterTP = ClockType::now();
m_Duration += std::chrono::duration_cast<DurationType>(m_AfterTP - m_BeforeTP);
m_BeforeTP = m_AfterTP;
return m_Duration;
}
inline void restart(void)
{
m_BeforeTP = ClockType::now();
m_Duration = DurationType(0);
}
}; // ElapsedTimer class
} // bh namespace<|endoftext|>
|
<commit_before>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* 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.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>
TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
QToolBar(parent), textEdit_(textEdit)
{
setWindowTitle(tr("Format actions"));
setObjectName(tr("Formattoolbar"));
actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
QIcon(":bold")), tr("&Bold"), this);
actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
actionTextBold->setPriority(QAction::LowPriority);
QFont bold;
bold.setBold(true);
actionTextBold->setFont(bold);
connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
addAction(actionTextBold);
actionTextBold->setCheckable(true);
actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
QIcon(":italic")), tr("&Italic"), this);
actionTextItalic->setPriority(QAction::LowPriority);
actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
QFont italic;
italic.setItalic(true);
actionTextItalic->setFont(italic);
connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
addAction(actionTextItalic);
actionTextItalic->setCheckable(true);
actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
QIcon(":underlined")), tr("&Underline"), this);
actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
actionTextUnderline->setPriority(QAction::LowPriority);
QFont underline;
underline.setUnderline(true);
actionTextUnderline->setFont(underline);
connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
addAction(actionTextUnderline);
actionTextUnderline->setCheckable(true);
actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
QIcon(":strikedout")), tr("&Strike Out"), this);
actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
actionTextStrikeOut->setPriority(QAction::LowPriority);
QFont strikeOut;
strikeOut.setStrikeOut(true);
actionTextStrikeOut->setFont(strikeOut);
connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
addAction(actionTextStrikeOut);
actionTextStrikeOut->setCheckable(true);
actionInsertHyperlink = new QAction(QIcon::fromTheme("emblem-web",QIcon(":hyperlink")),tr("&Hyperlink"),this);
actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
actionInsertHyperlink->setPriority(QAction::LowPriority);
connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
addAction(actionInsertHyperlink);
actionClearFormatting = new QAction(QIcon::fromTheme("TODO",QIcon(":clearFormatting")),tr("&Clear formatting"),this);
actionClearFormatting->setPriority(QAction::LowPriority);
actionClearFormatting->setShortcut(Qt::CTRL + Qt::Key_Space); // ms word clear font formatting shortcut
connect(actionClearFormatting,SIGNAL(triggered()),this,SLOT(clearCharFormat()));
addAction(actionClearFormatting);
QPixmap textPix(16, 16);
textPix.fill(textEdit_->palette().windowText().color());
actionTextColor = new QAction(textPix, tr("&Text color..."), this);
connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
addAction(actionTextColor);
QPixmap bPix(16, 16);
bPix.fill(textEdit_->palette().base().color());
actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
addAction(actionTextBColor);
fontComboBox = new QFontComboBox(this);
fontComboBox->setFocusPolicy(Qt::TabFocus);
addWidget(fontComboBox);
connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));
fontSizeComboBox = new QComboBox(this);
fontSizeComboBox->setFocusPolicy(Qt::TabFocus);
fontSizeComboBox->setObjectName("comboSize");
addWidget(fontSizeComboBox);
fontSizeComboBox->setEditable(true);
connect(fontSizeComboBox, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));
QFontDatabase db;
foreach(int size, db.standardSizes())
fontSizeComboBox->addItem(QString::number(size));
connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}
void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
QTextCursor cursor = textEdit_->textCursor();
if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);
textEdit_->mergeCurrentCharFormat(format);
}
void TextFormattingToolbar::clearCharFormat()
{
QTextCursor cursor = textEdit_->textCursor();
if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
cursor.select(QTextCursor::WordUnderCursor);
cursor.setCharFormat(QTextCharFormat());
}
void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
QFont f = format.font();
fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(f.pointSize())));
actionTextBold->setChecked(f.bold());
actionTextItalic->setChecked(f.italic());
actionTextUnderline->setChecked(f.underline());
actionTextStrikeOut->setChecked(f.strikeOut());
QPixmap textPix(16,16);
if(format.foreground().style() == Qt::NoBrush)
textPix.fill(textEdit_->palette().windowText().color());
else
textPix.fill(format.foreground().color());
actionTextColor->setIcon(textPix);
QPixmap bPix(16,16);
if(format.background().style() == Qt::NoBrush)
bPix.fill(textEdit_->palette().base().color());
else
bPix.fill(format.background().color());
actionTextBColor->setIcon(bPix);
}
void TextFormattingToolbar::boldText(){
QTextCharFormat fmt;
fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::italicText(){
QTextCharFormat fmt;
fmt.setFontItalic(actionTextItalic->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::underlinedText(){
QTextCharFormat fmt;
fmt.setFontUnderline(actionTextUnderline->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::strikedOutText(){
QTextCharFormat fmt;
fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::coloredText(){
QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setForeground(QBrush(col,Qt::SolidPattern));
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::markedText(){
QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setBackground(QBrush(col,Qt::SolidPattern));
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextBColor->setIcon(pix);
}
void TextFormattingToolbar::insertHyperlink()
{
QTextCursor cursor = textEdit_->textCursor();
QString selectedText = cursor.selectedText();
bool ok;
QString link = QInputDialog::getText(textEdit_,tr("Insert hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok);
if(!ok)
return;
/*TODO: de-formatting
if(link.isEmpty){
resetFonts()//or something like that
return;
}*/
/*TODO: check if link/e-mail is valid with the following regexps
QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive)
QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive)
*/
if(selectedText.isEmpty())
selectedText = link;
if(link.contains("@"))
cursor.insertHtml("<a href=mailto:"+link+"\">"+selectedText+"</a>");
else
cursor.insertHtml("<a href=\""+link+"\">"+selectedText+"</a>");
}
void TextFormattingToolbar::fontOfText(const QString &f){
QTextCharFormat fmt;
fmt.setFontFamily(f);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::pointSizeOfText(const QString &p){
qreal pointSize = p.toFloat();
if(p.toFloat() > 0){
QTextCharFormat fmt;
fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt);
}
}
void TextFormattingToolbar::setFont(QFont font)
{
fontComboBox->setCurrentFont(font);
fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(
font.pointSize())));
}
<commit_msg>fixed text formatting and clearing<commit_after>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* 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.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>
#include <QTextBlock>
#include <QDebug>
TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
QToolBar(parent), textEdit_(textEdit)
{
setWindowTitle(tr("Format actions"));
setObjectName(tr("Formattoolbar"));
actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
QIcon(":bold")), tr("&Bold"), this);
actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
actionTextBold->setPriority(QAction::LowPriority);
QFont bold;
bold.setBold(true);
actionTextBold->setFont(bold);
connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
addAction(actionTextBold);
actionTextBold->setCheckable(true);
actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
QIcon(":italic")), tr("&Italic"), this);
actionTextItalic->setPriority(QAction::LowPriority);
actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
QFont italic;
italic.setItalic(true);
actionTextItalic->setFont(italic);
connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
addAction(actionTextItalic);
actionTextItalic->setCheckable(true);
actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
QIcon(":underlined")), tr("&Underline"), this);
actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
actionTextUnderline->setPriority(QAction::LowPriority);
QFont underline;
underline.setUnderline(true);
actionTextUnderline->setFont(underline);
connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
addAction(actionTextUnderline);
actionTextUnderline->setCheckable(true);
actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
QIcon(":strikedout")), tr("&Strike Out"), this);
actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
actionTextStrikeOut->setPriority(QAction::LowPriority);
QFont strikeOut;
strikeOut.setStrikeOut(true);
actionTextStrikeOut->setFont(strikeOut);
connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
addAction(actionTextStrikeOut);
actionTextStrikeOut->setCheckable(true);
actionInsertHyperlink = new QAction(QIcon::fromTheme("emblem-web",QIcon(":hyperlink")),tr("&Hyperlink"),this);
actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
actionInsertHyperlink->setPriority(QAction::LowPriority);
connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
addAction(actionInsertHyperlink);
actionClearFormatting = new QAction(QIcon::fromTheme("TODO",QIcon(":clearFormatting")),tr("&Clear formatting"),this);
actionClearFormatting->setPriority(QAction::LowPriority);
actionClearFormatting->setShortcut(Qt::CTRL + Qt::Key_Space); // ms word clear font formatting shortcut
connect(actionClearFormatting,SIGNAL(triggered()),this,SLOT(clearCharFormat()));
addAction(actionClearFormatting);
QPixmap textPix(16, 16);
textPix.fill(textEdit_->palette().windowText().color());
actionTextColor = new QAction(textPix, tr("&Text color..."), this);
connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
addAction(actionTextColor);
QPixmap bPix(16, 16);
bPix.fill(textEdit_->palette().base().color());
actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
addAction(actionTextBColor);
fontComboBox = new QFontComboBox(this);
fontComboBox->setFocusPolicy(Qt::TabFocus);
addWidget(fontComboBox);
connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));
fontSizeComboBox = new QComboBox(this);
fontSizeComboBox->setFocusPolicy(Qt::TabFocus);
fontSizeComboBox->setObjectName("comboSize");
addWidget(fontSizeComboBox);
fontSizeComboBox->setEditable(true);
connect(fontSizeComboBox, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));
QFontDatabase db;
foreach(int size, db.standardSizes())
fontSizeComboBox->addItem(QString::number(size));
connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}
void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
QTextCursor cursor = textEdit_->textCursor();
QString block = cursor.block().text();
if(!cursor.atBlockStart() && !cursor.atBlockEnd())
if(!(block.at(cursor.positionInBlock()) == ' ') && !(block.at(cursor.positionInBlock()-1) == ' '))
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);
textEdit_->mergeCurrentCharFormat(format);
}
void TextFormattingToolbar::clearCharFormat()
{
QTextCursor cursor = textEdit_->textCursor();
QString block = cursor.block().text();
if(!cursor.atBlockStart() && !cursor.atBlockEnd())
if(!(block.at(cursor.positionInBlock()) == ' ') && !(block.at(cursor.positionInBlock()-1) == ' '))
cursor.select(QTextCursor::WordUnderCursor);
cursor.setCharFormat(QTextCharFormat());
textEdit_->setCurrentCharFormat(QTextCharFormat());
}
void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
QFont f = format.font();
fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(f.pointSize())));
actionTextBold->setChecked(f.bold());
actionTextItalic->setChecked(f.italic());
actionTextUnderline->setChecked(f.underline());
actionTextStrikeOut->setChecked(f.strikeOut());
QPixmap textPix(16,16);
if(format.foreground().style() == Qt::NoBrush)
textPix.fill(textEdit_->palette().windowText().color());
else
textPix.fill(format.foreground().color());
actionTextColor->setIcon(textPix);
QPixmap bPix(16,16);
if(format.background().style() == Qt::NoBrush)
bPix.fill(textEdit_->palette().base().color());
else
bPix.fill(format.background().color());
actionTextBColor->setIcon(bPix);
}
void TextFormattingToolbar::boldText(){
QTextCharFormat fmt;
fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::italicText(){
QTextCharFormat fmt;
fmt.setFontItalic(actionTextItalic->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::underlinedText(){
QTextCharFormat fmt;
fmt.setFontUnderline(actionTextUnderline->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::strikedOutText(){
QTextCharFormat fmt;
fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::coloredText(){
QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setForeground(QBrush(col,Qt::SolidPattern));
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::markedText(){
QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setBackground(QBrush(col,Qt::SolidPattern));
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextBColor->setIcon(pix);
}
void TextFormattingToolbar::insertHyperlink()
{
QTextCursor cursor = textEdit_->textCursor();
QString selectedText = cursor.selectedText();
bool ok;
QString link = QInputDialog::getText(textEdit_,tr("Insert hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok);
if(!ok)
return;
/*TODO: de-formatting
if(link.isEmpty){
resetFonts()//or something like that
return;
}*/
/*TODO: check if link/e-mail is valid with the following regexps
QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive)
QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive)
*/
if(selectedText.isEmpty())
selectedText = link;
if(link.contains("@"))
cursor.insertHtml("<a href=mailto:"+link+"\">"+selectedText+"</a>");
else
cursor.insertHtml("<a href=\""+link+"\">"+selectedText+"</a>");
}
void TextFormattingToolbar::fontOfText(const QString &f){
QTextCharFormat fmt;
fmt.setFontFamily(f);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::pointSizeOfText(const QString &p){
qreal pointSize = p.toFloat();
if(p.toFloat() > 0){
QTextCharFormat fmt;
fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt);
}
}
void TextFormattingToolbar::setFont(QFont font)
{
fontComboBox->setCurrentFont(font);
fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(
font.pointSize())));
}
<|endoftext|>
|
<commit_before>#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>
TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
QToolBar(parent), textEdit_(textEdit)
{
setWindowTitle(tr("Format actions"));
setObjectName(tr("Formattoolbar"));
actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
QIcon(":bold")), tr("&Bold"), this);
actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
actionTextBold->setPriority(QAction::LowPriority);
QFont bold;
bold.setBold(true);
actionTextBold->setFont(bold);
connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
addAction(actionTextBold);
actionTextBold->setCheckable(true);
actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
QIcon(":italic")), tr("&Italic"), this);
actionTextItalic->setPriority(QAction::LowPriority);
actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
QFont italic;
italic.setItalic(true);
actionTextItalic->setFont(italic);
connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
addAction(actionTextItalic);
actionTextItalic->setCheckable(true);
actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
QIcon(":underlined")), tr("&Underline"), this);
actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
actionTextUnderline->setPriority(QAction::LowPriority);
QFont underline;
underline.setUnderline(true);
actionTextUnderline->setFont(underline);
connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
addAction(actionTextUnderline);
actionTextUnderline->setCheckable(true);
actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
QIcon(":strikedout")), tr("&Strike Out"), this);
actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
actionTextStrikeOut->setPriority(QAction::LowPriority);
QFont strikeOut;
strikeOut.setStrikeOut(true);
actionTextStrikeOut->setFont(strikeOut);
connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
addAction(actionTextStrikeOut);
actionTextStrikeOut->setCheckable(true);
actionInsertHyperlink = new QAction(QIcon::fromTheme("hyperlink",QIcon(":hyperlink")),tr("&Hyperlink"),this);
actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
actionInsertHyperlink->setPriority(QAction::LowPriority);
connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
addAction(actionInsertHyperlink);
QPixmap textPix(16, 16);
textPix.fill(Qt::black);
actionTextColor = new QAction(textPix, tr("&Text color..."), this);
connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
addAction(actionTextColor);
QPixmap bPix(16, 16);
bPix.fill(Qt::white);
actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
addAction(actionTextBColor);
fontComboBox = new QFontComboBox(this);
fontComboBox->setFocusPolicy(Qt::TabFocus);
addWidget(fontComboBox);
connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));
comboSize = new QComboBox(this);
comboSize->setObjectName("comboSize");
addWidget(comboSize);
comboSize->setEditable(true);
connect(comboSize, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));
QFontDatabase db;
foreach(int size, db.standardSizes())
comboSize->addItem(QString::number(size));
comboSize->setCurrentIndex(comboSize->findText(QString::number(
QApplication::font().pointSize())));
connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}
void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
QTextCursor cursor = textEdit_->textCursor();
if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);
textEdit_->mergeCurrentCharFormat(format);
}
void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
QFont f = format.font();
fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize())));
actionTextBold->setChecked(f.bold());
actionTextItalic->setChecked(f.italic());
actionTextUnderline->setChecked(f.underline());
actionTextStrikeOut->setChecked(f.strikeOut());
QPixmap textPix(16,16);
textPix.fill(format.foreground().color());
actionTextColor->setIcon(textPix);
QPixmap bPix(16,16);
bPix.fill(format.background().color());
actionTextBColor->setIcon(bPix);
}
void TextFormattingToolbar::boldText(){
QTextCharFormat fmt;
fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::italicText(){
QTextCharFormat fmt;
fmt.setFontItalic(actionTextItalic->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::underlinedText(){
QTextCharFormat fmt;
fmt.setFontUnderline(actionTextUnderline->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::strikedOutText(){
QTextCharFormat fmt;
fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::coloredText(){
QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setForeground(col);
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::markedText(){
QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setBackground(col);
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::insertHyperlink()
{
QTextCursor cursor = textEdit_->textCursor();
// see textbrowser.cpp for link opening mechanism
QRegExpValidator validator;
QRegExp regex(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive); // url detection regexp
validator.setRegExp(regex);
QString defaultLink;
QString selectedText = cursor.selectedText();
int length = selectedText.length();
// check if a url is selected
if(cursor.hasSelection() && validator.validate(selectedText,length) == QValidator::Acceptable)
defaultLink = cursor.selectedText();
bool ok;
QString link = QInputDialog::getText(textEdit_,tr("Insert Hyperlink"),tr("Adr&ess:"),QLineEdit::Normal,defaultLink,&ok);
if(!ok)
return;
cursor.insertHtml("<a href=\""+link+"\">"+link+"</a>");
}
void TextFormattingToolbar::fontOfText(const QString &f){
QTextCharFormat fmt;
fmt.setFontFamily(f);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::pointSizeOfText(const QString &p){
qreal pointSize = p.toFloat();
if(p.toFloat() > 0){
QTextCharFormat fmt;
fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt);
}
}
<commit_msg>still more to do...<commit_after>#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>
#include <QDebug>
TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
QToolBar(parent), textEdit_(textEdit)
{
setWindowTitle(tr("Format actions"));
setObjectName(tr("Formattoolbar"));
actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
QIcon(":bold")), tr("&Bold"), this);
actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
actionTextBold->setPriority(QAction::LowPriority);
QFont bold;
bold.setBold(true);
actionTextBold->setFont(bold);
connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
addAction(actionTextBold);
actionTextBold->setCheckable(true);
actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
QIcon(":italic")), tr("&Italic"), this);
actionTextItalic->setPriority(QAction::LowPriority);
actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
QFont italic;
italic.setItalic(true);
actionTextItalic->setFont(italic);
connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
addAction(actionTextItalic);
actionTextItalic->setCheckable(true);
actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
QIcon(":underlined")), tr("&Underline"), this);
actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
actionTextUnderline->setPriority(QAction::LowPriority);
QFont underline;
underline.setUnderline(true);
actionTextUnderline->setFont(underline);
connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
addAction(actionTextUnderline);
actionTextUnderline->setCheckable(true);
actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
QIcon(":strikedout")), tr("&Strike Out"), this);
actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
actionTextStrikeOut->setPriority(QAction::LowPriority);
QFont strikeOut;
strikeOut.setStrikeOut(true);
actionTextStrikeOut->setFont(strikeOut);
connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
addAction(actionTextStrikeOut);
actionTextStrikeOut->setCheckable(true);
actionInsertHyperlink = new QAction(QIcon::fromTheme("hyperlink",QIcon(":hyperlink")),tr("&Hyperlink"),this);
actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
actionInsertHyperlink->setPriority(QAction::LowPriority);
connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
addAction(actionInsertHyperlink);
QPixmap textPix(16, 16);
textPix.fill(Qt::black);
actionTextColor = new QAction(textPix, tr("&Text color..."), this);
connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
addAction(actionTextColor);
QPixmap bPix(16, 16);
bPix.fill(Qt::white);
actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
addAction(actionTextBColor);
fontComboBox = new QFontComboBox(this);
fontComboBox->setFocusPolicy(Qt::TabFocus);
addWidget(fontComboBox);
connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));
comboSize = new QComboBox(this);
comboSize->setObjectName("comboSize");
addWidget(comboSize);
comboSize->setEditable(true);
connect(comboSize, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));
QFontDatabase db;
foreach(int size, db.standardSizes())
comboSize->addItem(QString::number(size));
comboSize->setCurrentIndex(comboSize->findText(QString::number(
QApplication::font().pointSize())));
connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}
void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
QTextCursor cursor = textEdit_->textCursor();
if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);
textEdit_->mergeCurrentCharFormat(format);
}
void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
QFont f = format.font();
fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize())));
actionTextBold->setChecked(f.bold());
actionTextItalic->setChecked(f.italic());
actionTextUnderline->setChecked(f.underline());
actionTextStrikeOut->setChecked(f.strikeOut());
QPixmap textPix(16,16);
textPix.fill(format.foreground().color());
actionTextColor->setIcon(textPix);
QPixmap bPix(16,16);
bPix.fill(format.background().color());
actionTextBColor->setIcon(bPix);
}
void TextFormattingToolbar::boldText(){
QTextCharFormat fmt;
fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::italicText(){
QTextCharFormat fmt;
fmt.setFontItalic(actionTextItalic->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::underlinedText(){
QTextCharFormat fmt;
fmt.setFontUnderline(actionTextUnderline->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::strikedOutText(){
QTextCharFormat fmt;
fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::coloredText(){
QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setForeground(col);
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::markedText(){
QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
if(!col.isValid())
return;
QTextCharFormat fmt;
fmt.setBackground(col);
mergeFormatOnWordOrSelection(fmt);
QPixmap pix(16, 16);
pix.fill(col);
actionTextColor->setIcon(pix);
}
void TextFormattingToolbar::insertHyperlink()
{
QTextCursor cursor = textEdit_->textCursor();
QString selectedText = cursor.selectedText();
if(selectedText.isEmpty())
return;
bool ok;
QString link = QInputDialog::getText(textEdit_,tr("Insert Hyperlink"),tr("Adr&ess:"),QLineEdit::Normal,selectedText,&ok);
if(!ok)
return;
/*TODO: de-formatting
if(link.isEmpty){
resetFonts()//or something like that
return;
}*/
/*TODO: check if link/e-mail is valid with the following regexps
QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive)
QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive)
*/
if(link.contains("@"))
cursor.insertHtml("<a href=mailto:"+link+"\">"+selectedText+"</a>");
else
cursor.insertHtml("<a href=\""+link+"\">"+selectedText+"</a>");
}
void TextFormattingToolbar::fontOfText(const QString &f){
QTextCharFormat fmt;
fmt.setFontFamily(f);
mergeFormatOnWordOrSelection(fmt);
}
void TextFormattingToolbar::pointSizeOfText(const QString &p){
qreal pointSize = p.toFloat();
if(p.toFloat() > 0){
QTextCharFormat fmt;
fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt);
}
}
<|endoftext|>
|
<commit_before>#include "davix_tool_util.hpp"
#include <config.h>
#include <string>
#include <sstream>
#include <algorithm>
#include <fcntl.h>
#include <ctime>
#include <simple_getpass/simple_get_pass.h>
namespace Davix{
namespace Tool{
std::string string_from_ptime(const time_t & t){
char b[255];
b[sizeof(b)-1]= '\0';
struct tm local_time={0};
(void) localtime_r(&t, &local_time);
strftime(b, 254, "%F %T", &local_time);
return std::string(b);
}
size_t ask_user_login(std::string & login){
char l[1024] ={0};
(std::cout << "Login: ").flush();
std::cin.getline(l, 1023);
login.assign(l);
std::fill(l, l+1024,'\0');
return login.size();
}
size_t ask_user_passwd(std::string & passwd){
char p[1024] ={0};
std::cout << "Password: ";
std::cout.flush();
if(simple_get_pass(p, 1023) > 0){
passwd.assign(p);
std::fill(p, p+1024,'\0');
return passwd.size();
}
return 0;
}
int setup_credential(OptParams & opts, DavixError** err){
// setup client side credential
if(opts.cred_path.empty() == false){
X509Credential cred;
if( cred.loadFromFilePEM( ((opts.priv_key.empty()== false)?(opts.priv_key):(opts.cred_path)),
opts.cred_path,
"",
err) <0){
return -1;
}
opts.params.setClientCertX509(cred);
}
// setup client login / password
opts.params.setClientLoginPasswordCallback(&DavixToolsAuthCallbackLoginPassword, &opts);
//setup aws creds
if(opts.aws_auth.first.empty() == false){
opts.params.setAwsAuthorizationKeys(opts.aws_auth.first, opts.aws_auth.second);
opts.params.setProtocol(RequestProtocol::AwsS3);
}
return 0;
}
int get_output_fstream(const Tool::OptParams & opts, const std::string & scope, DavixError** err){
int fd = -1;
if(opts.output_file_path.empty() == false){
if((fd = open(opts.output_file_path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0777)) <0 ){
davix_errno_to_davix_error(errno, scope, std::string("for destination file ").append(opts.output_file_path), err);
return -1;
}
}else{
fd = dup(STDOUT_FILENO);
}
return fd;
}
int get_input_fstream(const Tool::OptParams & opts, const std::string & scope, DavixError** err){
int fd = -1;
if(opts.input_file_path.empty() == false){
if((fd = open(opts.input_file_path.c_str(), O_RDONLY)) <0 ){
davix_errno_to_davix_error(errno, scope, std::string("for source file ").append(opts.input_file_path), err);
return -1;
}
}else{
fd = dup(STDOUT_FILENO);
}
return fd;
}
void err_display(DavixError ** err){
if(err && *err){
std::cerr << "("<< (*err)->getErrScope() <<") Error: "<< (*err)->getErrMsg() << std::endl;
DavixError::clearError(err);
}
}
std::string mode_to_stringmode(mode_t mode){
mode_t tmp_mode = mode;
//static const char * strv= "xwrxwrxwr";
char res[11];
std::fill(res, res+10, '-');
res[10]='\0';
for(int i=0; i <9; i++){
res[9-i] = ( mode = (tmp_mode >> 1)) & 0x01;
}
res[0]= S_ISDIR(mode);
return std::string(res);
}
int DavixToolsAuthCallbackLoginPassword(void* userdata, const SessionInfo & info, std::string & login, std::string & password,
int count, DavixError** err){
OptParams* opts = (OptParams*) userdata;
int ret = -1;
if(opts->userlogpasswd.first.empty() == false){
login = opts->userlogpasswd.first;
password = opts->userlogpasswd.second;
ret =0;
}else {
if(count > 0)
std::cout << "Authentication Failure, try again:\n";
else
std::cout << "Authentication needed:\n";
if( ask_user_login(login) > 0){
if(ask_user_passwd(password) > 0){
ret =0;
}
}
}
std::cout << std::endl;
if(ret < 0)
DavixError::setupError(err, "Davix::Tool::Auth",
StatusCode::LoginPasswordError,
"No valid login/password provided");
return ret;
}
std::string string_from_mode(mode_t mode){
const char* rmask ="xwr";
std::string str(10,'-');
str[0] = (S_ISDIR(mode))?'d':'-';
for(size_t i=0; i < 9; ++i){
str[9-i] = (( mode & (0x01 << i))?(rmask[i%3]):'-');
}
return str;
}
std::string string_from_size_t(size_t number, size_t size_string){
unsigned int digit= static_cast<unsigned int>(log10(static_cast<double>(number)));
std::ostringstream ss;
ss << number;
ss << std::string(((digit < size_string)?(size_string - digit):0), ' ');
return ss.str();
}
}
}
<commit_msg>- fix include problem on SL6<commit_after>#include "davix_tool_util.hpp"
#include <config.h>
#include <string>
#include <sstream>
#include <algorithm>
#include <fcntl.h>
#include <ctime>
#include <cmath>
#include <simple_getpass/simple_get_pass.h>
namespace Davix{
namespace Tool{
std::string string_from_ptime(const time_t & t){
char b[255];
b[sizeof(b)-1]= '\0';
struct tm local_time={0};
(void) localtime_r(&t, &local_time);
strftime(b, 254, "%F %T", &local_time);
return std::string(b);
}
size_t ask_user_login(std::string & login){
char l[1024] ={0};
(std::cout << "Login: ").flush();
std::cin.getline(l, 1023);
login.assign(l);
std::fill(l, l+1024,'\0');
return login.size();
}
size_t ask_user_passwd(std::string & passwd){
char p[1024] ={0};
std::cout << "Password: ";
std::cout.flush();
if(simple_get_pass(p, 1023) > 0){
passwd.assign(p);
std::fill(p, p+1024,'\0');
return passwd.size();
}
return 0;
}
int setup_credential(OptParams & opts, DavixError** err){
// setup client side credential
if(opts.cred_path.empty() == false){
X509Credential cred;
if( cred.loadFromFilePEM( ((opts.priv_key.empty()== false)?(opts.priv_key):(opts.cred_path)),
opts.cred_path,
"",
err) <0){
return -1;
}
opts.params.setClientCertX509(cred);
}
// setup client login / password
opts.params.setClientLoginPasswordCallback(&DavixToolsAuthCallbackLoginPassword, &opts);
//setup aws creds
if(opts.aws_auth.first.empty() == false){
opts.params.setAwsAuthorizationKeys(opts.aws_auth.first, opts.aws_auth.second);
opts.params.setProtocol(RequestProtocol::AwsS3);
}
return 0;
}
int get_output_fstream(const Tool::OptParams & opts, const std::string & scope, DavixError** err){
int fd = -1;
if(opts.output_file_path.empty() == false){
if((fd = open(opts.output_file_path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0777)) <0 ){
davix_errno_to_davix_error(errno, scope, std::string("for destination file ").append(opts.output_file_path), err);
return -1;
}
}else{
fd = dup(STDOUT_FILENO);
}
return fd;
}
int get_input_fstream(const Tool::OptParams & opts, const std::string & scope, DavixError** err){
int fd = -1;
if(opts.input_file_path.empty() == false){
if((fd = open(opts.input_file_path.c_str(), O_RDONLY)) <0 ){
davix_errno_to_davix_error(errno, scope, std::string("for source file ").append(opts.input_file_path), err);
return -1;
}
}else{
fd = dup(STDOUT_FILENO);
}
return fd;
}
void err_display(DavixError ** err){
if(err && *err){
std::cerr << "("<< (*err)->getErrScope() <<") Error: "<< (*err)->getErrMsg() << std::endl;
DavixError::clearError(err);
}
}
std::string mode_to_stringmode(mode_t mode){
mode_t tmp_mode = mode;
//static const char * strv= "xwrxwrxwr";
char res[11];
std::fill(res, res+10, '-');
res[10]='\0';
for(int i=0; i <9; i++){
res[9-i] = ( mode = (tmp_mode >> 1)) & 0x01;
}
res[0]= S_ISDIR(mode);
return std::string(res);
}
int DavixToolsAuthCallbackLoginPassword(void* userdata, const SessionInfo & info, std::string & login, std::string & password,
int count, DavixError** err){
OptParams* opts = (OptParams*) userdata;
int ret = -1;
if(opts->userlogpasswd.first.empty() == false){
login = opts->userlogpasswd.first;
password = opts->userlogpasswd.second;
ret =0;
}else {
if(count > 0)
std::cout << "Authentication Failure, try again:\n";
else
std::cout << "Authentication needed:\n";
if( ask_user_login(login) > 0){
if(ask_user_passwd(password) > 0){
ret =0;
}
}
}
std::cout << std::endl;
if(ret < 0)
DavixError::setupError(err, "Davix::Tool::Auth",
StatusCode::LoginPasswordError,
"No valid login/password provided");
return ret;
}
std::string string_from_mode(mode_t mode){
const char* rmask ="xwr";
std::string str(10,'-');
str[0] = (S_ISDIR(mode))?'d':'-';
for(size_t i=0; i < 9; ++i){
str[9-i] = (( mode & (0x01 << i))?(rmask[i%3]):'-');
}
return str;
}
std::string string_from_size_t(size_t number, size_t size_string){
unsigned int digit= static_cast<unsigned int>(log10(static_cast<double>(number)));
std::ostringstream ss;
ss << number;
ss << std::string(((digit < size_string)?(size_string - digit):0), ' ');
return ss.str();
}
}
}
<|endoftext|>
|
<commit_before>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "ImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include "PlaneGeometry.h"
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(NULL)
{
m_CameraController=NULL;
// m_CameraController = VtkInteractorCameraController::New();
// m_CameraController->AddRenderer(this);
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
BaseRenderer::SetData(iterator);
if (iterator != NULL) {
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
break;
}
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
m_VtkRenderer->Delete();
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update();
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update();
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
mapper2d->Update();
}
else
if(dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
mapper->Update();
if(dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()) || dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
m_VtkMapperPresent=true;
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
UpdateVtkActors();
Update();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
PlaneGeometry* myPlaneGeom =
dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(dynamic_cast<mitk::Image*>(node->GetData())==NULL)
{
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL) {
mapper2d->Paint(this);
}
}
}
}
delete it;
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
m_VtkRenderer = vtkRenderer::New();
m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
if(m_CameraController)
((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
BaseRenderer::Resize(w, h);
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
GetDisplayGeometry()->Fit();
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
Render();
glFlush();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}<commit_msg>Removed some lines for debug-purposes.<commit_after>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "ImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include "PlaneGeometry.h"
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(NULL)
{
m_CameraController=NULL;
m_CameraController = VtkInteractorCameraController::New();
m_CameraController->AddRenderer(this);
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
BaseRenderer::SetData(iterator);
if (iterator != NULL) {
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
break;
}
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
m_VtkRenderer->Delete();
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update();
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update();
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
mapper2d->Update();
}
else
if(dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
mapper->Update();
if(dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()) || dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()))
m_VtkMapperPresent=true;
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
UpdateVtkActors();
Update();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
PlaneGeometry* myPlaneGeom =
dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL) {
mapper2d->Paint(this);
}
}
}
delete it;
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
m_VtkRenderer = vtkRenderer::New();
m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
if(m_CameraController)
((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
BaseRenderer::Resize(w, h);
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
GetDisplayGeometry()->Fit();
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
Render();
glFlush();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}<|endoftext|>
|
<commit_before>/**
* @file ellis/core/flow.hpp
*
* @brief Ellis Flow public C++ header.
*
* This is the C++ header for Ellis Flow, which implements Ellis encoders and
* decoders.
*/
#pragma once
#ifndef ELLIS_CORE_FLOW_HPP_
#define ELLIS_CORE_FLOW_HPP_
namespace ellis {
namespace flow {
} /* namespace flow */
} /* namespace ellis */
#endif /* ELLIS_CORE_FLOW_HPP_ */
<commit_msg>include: remove unused flow.hpp<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef MockImpl_h__
#define MockImpl_h__
#include <type_traits>
#include <unordered_set>
#include <memory>
#include "mockutils/DynamicProxy.hpp"
#include "fakeit/StubbingImpl.hpp"
#include "fakeit/DomainObjects.hpp"
#include "fakeit/FakeIt.hpp"
namespace fakeit {
template<typename C, typename ... baseclasses>
class MockImpl : public MockObject<C>, public virtual ActualInvocationsSource {
public:
MockImpl(C &obj) :MockImpl<C, baseclasses...>(obj, true) {
}
MockImpl() : MockImpl<C, baseclasses...>(*(createFakeInstance()), false) {
}
virtual ~MockImpl() {
if (isSpy)
return;
FakeObject<C, baseclasses...>* fake = (FakeObject<C, baseclasses...>*) instance;
delete fake;
}
template<typename R, typename ... arglist>
MethodMock<C, R, arglist...>& stubMethodIfNotStubbed(DynamicProxy<C, baseclasses...> &proxy, R(C::*vMethod)(arglist...)) {
if (!proxy.isStubbed(vMethod)) {
auto methodMock = std::shared_ptr<MethodInvocationHandler<R, arglist...>> { new MethodMock<C, R, arglist...>(*this, vMethod) };
proxy.stubMethod(vMethod, methodMock);
}
Destructable * d = proxy.getMethodMock(vMethod);
MethodMock<C, R, arglist...> * methodMock = dynamic_cast<MethodMock<C, R, arglist...> *>(d);
return *methodMock;
}
/**
* Return all actual invocations of this mock.
*/
void getActualInvocations(std::unordered_set<Invocation*>& into) const override {
std::vector<ActualInvocationsSource*> vec;
proxy.getMethodMocks(vec);
for (ActualInvocationsSource * s : vec) {
s->getActualInvocations(into);
}
}
void reset() {
proxy.Reset();
if (!isSpy) {
FakeObject<C, baseclasses...>* fake = (FakeObject<C, baseclasses...>*) instance;
fake->initializeDataMembersArea();
}
}
virtual C& get() override {
return proxy.get();
}
template<class DATA_TYPE, typename ... arglist>
DataMemberStubbingRoot<C, DATA_TYPE> stubDataMember(DATA_TYPE C::*member, const arglist&... ctorargs) {
proxy.stubDataMember(member, ctorargs...);
return DataMemberStubbingRoot<C, DATA_TYPE>();
}
template<typename R, typename ... arglist, class = typename std::enable_if<!std::is_void<R>::value>::type>
FunctionStubbingRoot<C, R, arglist...> stub(R(C::*vMethod)(arglist...)) {
return FunctionStubbingRoot<C, R, arglist...>(
std::shared_ptr<MethodStubbingContext<C, R, arglist...>>(new MethodStubbingContextImpl<R, arglist...>(*this, vMethod)));
}
template<typename R, typename ... arglist, class = typename std::enable_if<std::is_void<R>::value>::type>
ProcedureStubbingRoot<C, R, arglist...> stub(R(C::*vMethod)(arglist...)) {
return ProcedureStubbingRoot<C, R, arglist...>(
std::shared_ptr<MethodStubbingContext<C, R, arglist...>>(new MethodStubbingContextImpl<R, arglist...>(*this, vMethod)));
}
protected:
DynamicProxy<C, baseclasses...> proxy;
C* instance; //
bool isSpy;
template<typename R, typename ... arglist>
class MethodStubbingContextImpl : public MethodStubbingContext<C, R, arglist...> {
MockImpl<C, baseclasses...>& mock;
typename MethodStubbingContext<C, R, arglist...>::MethodType vMethod;
public:
MethodStubbingContextImpl(MockImpl<C, baseclasses...>& mock, R(C::*vMethod)(arglist...)) :
mock(mock), vMethod(vMethod) {
}
virtual MethodMock<C, R, arglist...>& getMethodMock() override {
return mock.stubMethodIfNotStubbed(mock.proxy, vMethod);
}
virtual void getActualInvocations(std::unordered_set<Invocation*>& into) const override {
mock.getActualInvocations(into);
}
virtual typename MethodStubbingContext<C, R, arglist...>::MethodType getOriginalMethod() override {
void * mPtr = mock.getOriginalMethod(vMethod);
return union_cast<typename MethodStubbingContext<C, R, arglist...>::MethodType>(mPtr);
}
virtual MockObject<C>& getMock() override {
return mock;
}
};
void unmocked() {
struct UnmockedMethodInvocation : public UnexpectedMethodCallException {
UnmockedMethodInvocation() :UnexpectedMethodCallException( //
std::shared_ptr<Invocation> {new ActualInvocation<>(nextInvocationOrdinal(), UnknownMethod::instance())} //
){} //
} e;
FakeIt::getInstance().handle(e);
throw e;
}
static C* createFakeInstance() {
FakeObject<C, baseclasses...>* fake = new FakeObject<C, baseclasses...>();
fake->initializeDataMembersArea();
void* unmockedMethodStubPtr = union_cast<void*>(&MockImpl<C, baseclasses...>::unmocked);
fake->getVirtualTable().initAll(unmockedMethodStubPtr);
return (C*) fake;
}
template<typename R, typename ... arglist>
void * getOriginalMethod(R(C::*vMethod)(arglist...)) {
auto vt = proxy.getOriginalVT();
auto offset = VTUtils::getOffset(vMethod);
void * origMethodPtr = vt.getMethod(offset);
return origMethodPtr;
}
private:
MockImpl(C &obj, bool isSpy) :
proxy{ obj }, instance(&obj), isSpy(isSpy) {
}
};
}
#endif<commit_msg>change protected to private where possible<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef MockImpl_h__
#define MockImpl_h__
#include <type_traits>
#include <unordered_set>
#include <memory>
#include "mockutils/DynamicProxy.hpp"
#include "fakeit/StubbingImpl.hpp"
#include "fakeit/DomainObjects.hpp"
#include "fakeit/FakeIt.hpp"
namespace fakeit {
template<typename C, typename ... baseclasses>
class MockImpl : public MockObject<C>, public virtual ActualInvocationsSource {
public:
MockImpl(C &obj) :MockImpl<C, baseclasses...>(obj, true) {
}
MockImpl() : MockImpl<C, baseclasses...>(*(createFakeInstance()), false) {
}
virtual ~MockImpl() {
if (isSpy)
return;
FakeObject<C, baseclasses...>* fake = (FakeObject<C, baseclasses...>*) instance;
delete fake;
}
/**
* Return all actual invocations of this mock.
*/
void getActualInvocations(std::unordered_set<Invocation*>& into) const override {
std::vector<ActualInvocationsSource*> vec;
proxy.getMethodMocks(vec);
for (ActualInvocationsSource * s : vec) {
s->getActualInvocations(into);
}
}
void reset() {
proxy.Reset();
if (!isSpy) {
FakeObject<C, baseclasses...>* fake = (FakeObject<C, baseclasses...>*) instance;
fake->initializeDataMembersArea();
}
}
virtual C& get() override {
return proxy.get();
}
template<class DATA_TYPE, typename ... arglist>
DataMemberStubbingRoot<C, DATA_TYPE> stubDataMember(DATA_TYPE C::*member, const arglist&... ctorargs) {
proxy.stubDataMember(member, ctorargs...);
return DataMemberStubbingRoot<C, DATA_TYPE>();
}
template<typename R, typename ... arglist, class = typename std::enable_if<!std::is_void<R>::value>::type>
FunctionStubbingRoot<C, R, arglist...> stub(R(C::*vMethod)(arglist...)) {
return FunctionStubbingRoot<C, R, arglist...>(
std::shared_ptr<MethodStubbingContext<C, R, arglist...>>(new MethodStubbingContextImpl<R, arglist...>(*this, vMethod)));
}
template<typename R, typename ... arglist, class = typename std::enable_if<std::is_void<R>::value>::type>
ProcedureStubbingRoot<C, R, arglist...> stub(R(C::*vMethod)(arglist...)) {
return ProcedureStubbingRoot<C, R, arglist...>(
std::shared_ptr<MethodStubbingContext<C, R, arglist...>>(new MethodStubbingContextImpl<R, arglist...>(*this, vMethod)));
}
private:
DynamicProxy<C, baseclasses...> proxy;
C* instance; //
bool isSpy;
template<typename R, typename ... arglist>
class MethodStubbingContextImpl : public MethodStubbingContext<C, R, arglist...> {
MockImpl<C, baseclasses...>& mock;
typename MethodStubbingContext<C, R, arglist...>::MethodType vMethod;
public:
MethodStubbingContextImpl(MockImpl<C, baseclasses...>& mock, R(C::*vMethod)(arglist...)) :
mock(mock), vMethod(vMethod) {
}
virtual MethodMock<C, R, arglist...>& getMethodMock() override {
return mock.stubMethodIfNotStubbed(mock.proxy, vMethod);
}
virtual void getActualInvocations(std::unordered_set<Invocation*>& into) const override {
mock.getActualInvocations(into);
}
virtual typename MethodStubbingContext<C, R, arglist...>::MethodType getOriginalMethod() override {
void * mPtr = mock.getOriginalMethod(vMethod);
return union_cast<typename MethodStubbingContext<C, R, arglist...>::MethodType>(mPtr);
}
virtual MockObject<C>& getMock() override {
return mock;
}
};
void unmocked() {
struct UnmockedMethodInvocation : public UnexpectedMethodCallException {
UnmockedMethodInvocation() :UnexpectedMethodCallException( //
std::shared_ptr<Invocation> {new ActualInvocation<>(nextInvocationOrdinal(), UnknownMethod::instance())} //
){} //
} e;
FakeIt::getInstance().handle(e);
throw e;
}
static C* createFakeInstance() {
FakeObject<C, baseclasses...>* fake = new FakeObject<C, baseclasses...>();
fake->initializeDataMembersArea();
void* unmockedMethodStubPtr = union_cast<void*>(&MockImpl<C, baseclasses...>::unmocked);
fake->getVirtualTable().initAll(unmockedMethodStubPtr);
return (C*) fake;
}
template<typename R, typename ... arglist>
void * getOriginalMethod(R(C::*vMethod)(arglist...)) {
auto vt = proxy.getOriginalVT();
auto offset = VTUtils::getOffset(vMethod);
void * origMethodPtr = vt.getMethod(offset);
return origMethodPtr;
}
template<typename R, typename ... arglist>
MethodMock<C, R, arglist...>& stubMethodIfNotStubbed(DynamicProxy<C, baseclasses...> &proxy, R(C::*vMethod)(arglist...)) {
if (!proxy.isStubbed(vMethod)) {
auto methodMock = std::shared_ptr<MethodInvocationHandler<R, arglist...>> { new MethodMock<C, R, arglist...>(*this, vMethod) };
proxy.stubMethod(vMethod, methodMock);
}
Destructable * d = proxy.getMethodMock(vMethod);
MethodMock<C, R, arglist...> * methodMock = dynamic_cast<MethodMock<C, R, arglist...> *>(d);
return *methodMock;
}
MockImpl(C &obj, bool isSpy) :
proxy{ obj }, instance(&obj), isSpy(isSpy) {
}
};
}
#endif<|endoftext|>
|
<commit_before>#include "KBShortcutsDialog.hpp"
#include "I18N.hpp"
#include "libslic3r/Utils.hpp"
#include "GUI.hpp"
#include <wx/scrolwin.h>
#include <wx/display.h>
#include "GUI_App.hpp"
#include "wxExtensions.hpp"
#define NOTEBOOK_TOP 1
#define NOTEBOOK_LEFT 2
#define LISTBOOK_TOP 3
#define LISTBOOK_LEFT 4
#define TOOLBOOK 5
#define CHOICEBOOK 6
#define BOOK_TYPE NOTEBOOK_TOP
#if (BOOK_TYPE == NOTEBOOK_TOP) || (BOOK_TYPE == NOTEBOOK_LEFT)
#include <wx/notebook.h>
#elif (BOOK_TYPE == LISTBOOK_TOP) || (BOOK_TYPE == LISTBOOK_LEFT)
#include <wx/listbook.h>
#elif BOOK_TYPE == TOOLBOOK
#include <wx/toolbook.h>
#elif BOOK_TYPE == CHOICEBOOK
#include <wx/choicebk.h>
#endif // BOOK_TYPE
namespace Slic3r {
namespace GUI {
KBShortcutsDialog::KBShortcutsDialog()
: DPIDialog(NULL, wxID_ANY, wxString(SLIC3R_APP_NAME) + " - " + _(L("Keyboard Shortcuts")),
#if ENABLE_SCROLLABLE
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
#else
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE)
#endif // ENABLE_SCROLLABLE
{
SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
// fonts
const wxFont& font = wxGetApp().normal_font();
const wxFont& bold_font = wxGetApp().bold_font();
SetFont(font);
auto main_sizer = new wxBoxSizer(wxVERTICAL);
main_sizer->Add(create_header(this, bold_font), 0, wxEXPAND | wxALL, 10);
#if BOOK_TYPE == NOTEBOOK_TOP
wxNotebook* book = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_TOP);
#elif BOOK_TYPE == NOTEBOOK_LEFT
wxNotebook* book = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_LEFT);
#elif BOOK_TYPE == LISTBOOK_TOP
wxListbook* book = new wxListbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLB_TOP);
#elif BOOK_TYPE == LISTBOOK_LEFT
wxListbook* book = new wxListbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLB_LEFT);
#elif BOOK_TYPE == TOOLBOOK
wxToolbook* book = new wxToolbook(this, wxID_ANY);
#elif BOOK_TYPE == CHOICEBOOK
wxChoicebook* book = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxCHB_TOP);
#endif // BOOK_TYPE
main_sizer->Add(book, 1, wxEXPAND | wxALL, 10);
fill_shortcuts();
for (size_t i = 0; i < m_full_shortcuts.size(); ++i)
{
#if ENABLE_SCROLLABLE
wxPanel* page = create_page(book, m_full_shortcuts[i], font, bold_font);
m_pages.push_back(page);
book->AddPage(page, m_full_shortcuts[i].first, i == 0);
#else
book->AddPage(create_page(book, m_full_shortcuts[i], font, bold_font), m_full_shortcuts[i].first, i == 0);
#endif // ENABLE_SCROLLABLE
}
wxStdDialogButtonSizer* buttons = this->CreateStdDialogButtonSizer(wxOK);
this->SetEscapeId(wxID_OK);
main_sizer->Add(buttons, 0, wxEXPAND | wxALL, 5);
SetSizer(main_sizer);
main_sizer->SetSizeHints(this);
}
void KBShortcutsDialog::on_dpi_changed(const wxRect& suggested_rect)
{
m_logo_bmp.msw_rescale();
m_header_bitmap->SetBitmap(m_logo_bmp.bmp());
msw_buttons_rescale(this, em_unit(), { wxID_OK });
Layout();
Fit();
Refresh();
}
void KBShortcutsDialog::fill_shortcuts()
{
const std::string& ctrl = GUI::shortkey_ctrl_prefix();
const std::string& alt = GUI::shortkey_alt_prefix();
Shortcuts commands_shortcuts = {
// File
{ ctrl + "N", L("New project, clear plater") },
{ ctrl + "O", L("Open project STL/OBJ/AMF/3MF with config, clear plater") },
{ ctrl + "S", L("Save project (3mf)") },
{ ctrl + alt + "S", L("Save project as (3mf)") },
{ ctrl + "R", L("(Re)slice") },
// File>Import
{ ctrl + "I", L("Import STL/OBJ/AMF/3MF without config, keep plater") },
{ ctrl + "L", L("Import Config from ini/amf/3mf/gcode") },
{ ctrl + alt + "L", L("Load Config from ini/amf/3mf/gcode and merge") },
// File>Export
{ ctrl + "G", L("Export G-code") },
{ ctrl + "Shift+" + "G", L("Send G-code") },
{ ctrl + "E", L("Export config") },
{ ctrl + "U", L("Export to SD card / Flash drive") },
{ ctrl + "T", L("Eject SD card / Flash drive") },
// Edit
{ ctrl + "A", L("Select all objects") },
{ "Esc", L("Deselect all") },
{ "Del", L("Delete selected") },
{ ctrl + "Del", L("Delete all") },
{ ctrl + "Z", L("Undo") },
{ ctrl + "Y", L("Redo") },
{ ctrl + "C", L("Copy to clipboard") },
{ ctrl + "V", L("Paste from clipboard") },
{ "F5", L("Reload plater from disk") },
{ ctrl + "F", L("Search") },
// Window
{ ctrl + "1", L("Select Plater Tab") },
{ ctrl + "2", L("Select Print Settings Tab") },
{ ctrl + "3", L("Select Filament Settings Tab") },
{ ctrl + "4", L("Select Printer Settings Tab") },
{ ctrl + "5", L("Switch to 3D") },
{ ctrl + "6", L("Switch to Preview") },
{ ctrl + "J", L("Print host upload queue") },
// View
{ "0-6", L("Camera view") },
{ "E", L("Show/Hide object/instance labels") },
#if ENABLE_SLOPE_RENDERING
{ "D", L("Turn On/Off facets' slope rendering") },
#endif // ENABLE_SLOPE_RENDERING
// Configuration
{ ctrl + "P", L("Preferences") },
// Help
{ "?", L("Show keyboard shortcuts list") }
};
m_full_shortcuts.push_back(std::make_pair(_(L("Commands")), commands_shortcuts));
Shortcuts plater_shortcuts = {
{ "A", L("Arrange") },
{ "Shift+A", L("Arrange selection") },
{ "+", L("Add Instance of the selected object") },
{ "-", L("Remove Instance of the selected object") },
{ ctrl, L("Press to select multiple objects\nor move multiple objects with mouse") },
{ "Shift+", L("Press to activate selection rectangle") },
{ alt, L("Press to activate deselection rectangle") },
{ L("Arrow Up"), L("Move selection 10 mm in positive Y direction") },
{ L("Arrow Down"), L("Move selection 10 mm in negative Y direction") },
{ L("Arrow Left"), L("Move selection 10 mm in negative X direction") },
{ L("Arrow Right"), L("Move selection 10 mm in positive X direction") },
{ std::string("Shift+") + L("Any arrow"), L("Movement step set to 1 mm") },
{ ctrl + L("Any arrow"), L("Movement in camera space") },
{ L("Page Up"), L("Rotate selection 45 degrees CCW") },
{ L("Page Down"), L("Rotate selection 45 degrees CW") },
{ "M", L("Gizmo move") },
{ "S", L("Gizmo scale") },
{ "R", L("Gizmo rotate") },
{ "C", L("Gizmo cut") },
{ "F", L("Gizmo Place face on bed") },
{ "H", L("Gizmo SLA hollow") },
{ "L", L("Gizmo SLA support points") },
{ "Esc", L("Unselect gizmo or clear selection") },
{ "K", L("Change camera type (perspective, orthographic)") },
{ "B", L("Zoom to Bed") },
{ "Z", L("Zoom to selected object\nor all objects in scene, if none selected") },
{ "I", L("Zoom in") },
{ "O", L("Zoom out") },
#ifdef __linux__
{ ctrl + "M", L("Show/Hide 3Dconnexion devices settings dialog") },
#endif // __linux__
#if ENABLE_RENDER_PICKING_PASS
// Don't localize debugging texts.
{ "T", "Toggle picking pass texture rendering on/off" },
#endif // ENABLE_RENDER_PICKING_PASS
};
m_full_shortcuts.push_back(std::make_pair(_(L("Plater")), plater_shortcuts));
Shortcuts gizmos_shortcuts = {
{ "Shift+", L("Press to snap by 5% in Gizmo scale\nor to snap by 1mm in Gizmo move") },
{ "F", L("Scale selection to fit print volume\nin Gizmo scale") },
{ ctrl, L("Press to activate one direction scaling in Gizmo scale") },
{ alt, L("Press to scale (in Gizmo scale) or rotate (in Gizmo rotate)\nselected objects around their own center") },
};
m_full_shortcuts.push_back(std::make_pair(_(L("Gizmos")), gizmos_shortcuts));
Shortcuts preview_shortcuts = {
{ L("Arrow Up"), L("Upper Layer") },
{ L("Arrow Down"), L("Lower Layer") },
{ "U", L("Upper Layer") },
{ "D", L("Lower Layer") },
{ "L", L("Show/Hide Legend") }
};
m_full_shortcuts.push_back(std::make_pair(_(L("Preview")), preview_shortcuts));
Shortcuts layers_slider_shortcuts = {
{ L("Arrow Up"), L("Move current slider thumb Up") },
{ L("Arrow Down"), L("Move current slider thumb Down") },
{ L("Arrow Left"), L("Set upper thumb to current slider thumb") },
{ L("Arrow Right"), L("Set lower thumb to current slider thumb") },
{ "+", L("Add color change marker for current layer") },
{ "-", L("Delete color change marker for current layer") }
};
m_full_shortcuts.push_back(std::make_pair(_(L("Layers Slider")), layers_slider_shortcuts));
}
wxPanel* KBShortcutsDialog::create_header(wxWindow* parent, const wxFont& bold_font)
{
wxPanel* panel = new wxPanel(parent);
wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
wxFont header_font = bold_font;
#ifdef __WXOSX__
header_font.SetPointSize(14);
#else
header_font.SetPointSize(bold_font.GetPointSize() + 2);
#endif // __WXOSX__
sizer->AddStretchSpacer();
// logo
m_logo_bmp = ScalableBitmap(this, "PrusaSlicer_32px.png", 32);
m_header_bitmap = new wxStaticBitmap(panel, wxID_ANY, m_logo_bmp.bmp());
sizer->Add(m_header_bitmap, 0, wxEXPAND | wxLEFT | wxRIGHT, 10);
// text
wxStaticText* text = new wxStaticText(panel, wxID_ANY, _(L("Keyboard shortcuts")));
text->SetFont(header_font);
sizer->Add(text, 0, wxALIGN_CENTER_VERTICAL);
sizer->AddStretchSpacer();
panel->SetSizer(sizer);
return panel;
}
wxPanel* KBShortcutsDialog::create_page(wxWindow* parent, const std::pair<wxString, Shortcuts>& shortcuts, const wxFont& font, const wxFont& bold_font)
{
static const int max_items_per_column = 20;
int columns_count = 1 + (int)shortcuts.second.size() / max_items_per_column;
#if ENABLE_SCROLLABLE
wxScrolledWindow* page = new wxScrolledWindow(parent);
page->SetScrollbars(20, 20, 50, 50);
page->SetInitialSize(wxSize(850, 450));
#else
wxPanel* page = new wxPanel(parent);
#endif // ENABLE_SCROLLABLE
#if (BOOK_TYPE == LISTBOOK_TOP) || (BOOK_TYPE == LISTBOOK_LEFT)
wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, page, " " + shortcuts.first + " ");
sizer->GetStaticBox()->SetFont(bold_font);
#else
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
#endif // BOOK_TYPE
wxFlexGridSizer* grid_sizer = new wxFlexGridSizer(2 * columns_count, 5, 15);
int items_count = (int)shortcuts.second.size();
for (int i = 0; i < max_items_per_column; ++i)
{
for (int j = 0; j < columns_count; ++j)
{
int id = j * max_items_per_column + i;
if (id >= items_count)
break;
const auto& [shortcut, description] = shortcuts.second[id];
auto key = new wxStaticText(page, wxID_ANY, _(shortcut));
key->SetFont(bold_font);
grid_sizer->Add(key, 0, wxALIGN_CENTRE_VERTICAL);
auto desc = new wxStaticText(page, wxID_ANY, _(description));
desc->SetFont(font);
grid_sizer->Add(desc, 0, wxALIGN_CENTRE_VERTICAL);
}
}
sizer->Add(grid_sizer, 1, wxEXPAND | wxALL, 10);
page->SetSizer(sizer);
return page;
}
} // namespace GUI
} // namespace Slic3r
<commit_msg>ENABLE_GCODE_VIEWER -> Updated keyboard shortcuts dialog<commit_after>#include "libslic3r/libslic3r.h"
#include "KBShortcutsDialog.hpp"
#include "I18N.hpp"
#include "libslic3r/Utils.hpp"
#include "GUI.hpp"
#include <wx/scrolwin.h>
#include <wx/display.h>
#include "GUI_App.hpp"
#include "wxExtensions.hpp"
#define NOTEBOOK_TOP 1
#define NOTEBOOK_LEFT 2
#define LISTBOOK_TOP 3
#define LISTBOOK_LEFT 4
#define TOOLBOOK 5
#define CHOICEBOOK 6
#define BOOK_TYPE NOTEBOOK_TOP
#if (BOOK_TYPE == NOTEBOOK_TOP) || (BOOK_TYPE == NOTEBOOK_LEFT)
#include <wx/notebook.h>
#elif (BOOK_TYPE == LISTBOOK_TOP) || (BOOK_TYPE == LISTBOOK_LEFT)
#include <wx/listbook.h>
#elif BOOK_TYPE == TOOLBOOK
#include <wx/toolbook.h>
#elif BOOK_TYPE == CHOICEBOOK
#include <wx/choicebk.h>
#endif // BOOK_TYPE
namespace Slic3r {
namespace GUI {
KBShortcutsDialog::KBShortcutsDialog()
: DPIDialog(NULL, wxID_ANY, wxString(SLIC3R_APP_NAME) + " - " + _L("Keyboard Shortcuts"),
#if ENABLE_SCROLLABLE
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
#else
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE)
#endif // ENABLE_SCROLLABLE
{
SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
// fonts
const wxFont& font = wxGetApp().normal_font();
const wxFont& bold_font = wxGetApp().bold_font();
SetFont(font);
auto main_sizer = new wxBoxSizer(wxVERTICAL);
main_sizer->Add(create_header(this, bold_font), 0, wxEXPAND | wxALL, 10);
#if BOOK_TYPE == NOTEBOOK_TOP
wxNotebook* book = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_TOP);
#elif BOOK_TYPE == NOTEBOOK_LEFT
wxNotebook* book = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_LEFT);
#elif BOOK_TYPE == LISTBOOK_TOP
wxListbook* book = new wxListbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLB_TOP);
#elif BOOK_TYPE == LISTBOOK_LEFT
wxListbook* book = new wxListbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLB_LEFT);
#elif BOOK_TYPE == TOOLBOOK
wxToolbook* book = new wxToolbook(this, wxID_ANY);
#elif BOOK_TYPE == CHOICEBOOK
wxChoicebook* book = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxCHB_TOP);
#endif // BOOK_TYPE
main_sizer->Add(book, 1, wxEXPAND | wxALL, 10);
fill_shortcuts();
for (size_t i = 0; i < m_full_shortcuts.size(); ++i)
{
#if ENABLE_SCROLLABLE
wxPanel* page = create_page(book, m_full_shortcuts[i], font, bold_font);
m_pages.push_back(page);
book->AddPage(page, m_full_shortcuts[i].first, i == 0);
#else
book->AddPage(create_page(book, m_full_shortcuts[i], font, bold_font), m_full_shortcuts[i].first, i == 0);
#endif // ENABLE_SCROLLABLE
}
wxStdDialogButtonSizer* buttons = this->CreateStdDialogButtonSizer(wxOK);
this->SetEscapeId(wxID_OK);
main_sizer->Add(buttons, 0, wxEXPAND | wxALL, 5);
SetSizer(main_sizer);
main_sizer->SetSizeHints(this);
}
void KBShortcutsDialog::on_dpi_changed(const wxRect& suggested_rect)
{
m_logo_bmp.msw_rescale();
m_header_bitmap->SetBitmap(m_logo_bmp.bmp());
msw_buttons_rescale(this, em_unit(), { wxID_OK });
Layout();
Fit();
Refresh();
}
void KBShortcutsDialog::fill_shortcuts()
{
const std::string& ctrl = GUI::shortkey_ctrl_prefix();
const std::string& alt = GUI::shortkey_alt_prefix();
Shortcuts commands_shortcuts = {
// File
{ ctrl + "N", L("New project, clear plater") },
{ ctrl + "O", L("Open project STL/OBJ/AMF/3MF with config, clear plater") },
{ ctrl + "S", L("Save project (3mf)") },
{ ctrl + alt + "S", L("Save project as (3mf)") },
{ ctrl + "R", L("(Re)slice") },
// File>Import
{ ctrl + "I", L("Import STL/OBJ/AMF/3MF without config, keep plater") },
{ ctrl + "L", L("Import Config from ini/amf/3mf/gcode") },
{ ctrl + alt + "L", L("Load Config from ini/amf/3mf/gcode and merge") },
// File>Export
{ ctrl + "G", L("Export G-code") },
{ ctrl + "Shift+" + "G", L("Send G-code") },
{ ctrl + "E", L("Export config") },
{ ctrl + "U", L("Export to SD card / Flash drive") },
{ ctrl + "T", L("Eject SD card / Flash drive") },
// Edit
{ ctrl + "A", L("Select all objects") },
{ "Esc", L("Deselect all") },
{ "Del", L("Delete selected") },
{ ctrl + "Del", L("Delete all") },
{ ctrl + "Z", L("Undo") },
{ ctrl + "Y", L("Redo") },
{ ctrl + "C", L("Copy to clipboard") },
{ ctrl + "V", L("Paste from clipboard") },
{ "F5", L("Reload plater from disk") },
{ ctrl + "F", L("Search") },
// Window
{ ctrl + "1", L("Select Plater Tab") },
{ ctrl + "2", L("Select Print Settings Tab") },
{ ctrl + "3", L("Select Filament Settings Tab") },
{ ctrl + "4", L("Select Printer Settings Tab") },
{ ctrl + "5", L("Switch to 3D") },
{ ctrl + "6", L("Switch to Preview") },
{ ctrl + "J", L("Print host upload queue") },
// View
{ "0-6", L("Camera view") },
{ "E", L("Show/Hide object/instance labels") },
#if ENABLE_SLOPE_RENDERING
{ "D", L("Turn On/Off facets' slope rendering") },
#endif // ENABLE_SLOPE_RENDERING
// Configuration
{ ctrl + "P", L("Preferences") },
// Help
{ "?", L("Show keyboard shortcuts list") }
};
m_full_shortcuts.push_back(std::make_pair(_L("Commands"), commands_shortcuts));
Shortcuts plater_shortcuts = {
{ "A", L("Arrange") },
{ "Shift+A", L("Arrange selection") },
{ "+", L("Add Instance of the selected object") },
{ "-", L("Remove Instance of the selected object") },
{ ctrl, L("Press to select multiple objects\nor move multiple objects with mouse") },
{ "Shift+", L("Press to activate selection rectangle") },
{ alt, L("Press to activate deselection rectangle") },
{ L("Arrow Up"), L("Move selection 10 mm in positive Y direction") },
{ L("Arrow Down"), L("Move selection 10 mm in negative Y direction") },
{ L("Arrow Left"), L("Move selection 10 mm in negative X direction") },
{ L("Arrow Right"), L("Move selection 10 mm in positive X direction") },
{ std::string("Shift+") + L("Any arrow"), L("Movement step set to 1 mm") },
{ ctrl + L("Any arrow"), L("Movement in camera space") },
{ L("Page Up"), L("Rotate selection 45 degrees CCW") },
{ L("Page Down"), L("Rotate selection 45 degrees CW") },
{ "M", L("Gizmo move") },
{ "S", L("Gizmo scale") },
{ "R", L("Gizmo rotate") },
{ "C", L("Gizmo cut") },
{ "F", L("Gizmo Place face on bed") },
{ "H", L("Gizmo SLA hollow") },
{ "L", L("Gizmo SLA support points") },
{ "Esc", L("Unselect gizmo or clear selection") },
{ "K", L("Change camera type (perspective, orthographic)") },
{ "B", L("Zoom to Bed") },
{ "Z", L("Zoom to selected object\nor all objects in scene, if none selected") },
{ "I", L("Zoom in") },
{ "O", L("Zoom out") },
#ifdef __linux__
{ ctrl + "M", L("Show/Hide 3Dconnexion devices settings dialog") },
#endif // __linux__
#if ENABLE_RENDER_PICKING_PASS
// Don't localize debugging texts.
{ "T", "Toggle picking pass texture rendering on/off" },
#endif // ENABLE_RENDER_PICKING_PASS
};
m_full_shortcuts.push_back(std::make_pair(_L("Plater"), plater_shortcuts));
Shortcuts gizmos_shortcuts = {
{ "Shift+", L("Press to snap by 5% in Gizmo scale\nor to snap by 1mm in Gizmo move") },
{ "F", L("Scale selection to fit print volume\nin Gizmo scale") },
{ ctrl, L("Press to activate one direction scaling in Gizmo scale") },
{ alt, L("Press to scale (in Gizmo scale) or rotate (in Gizmo rotate)\nselected objects around their own center") },
};
m_full_shortcuts.push_back(std::make_pair(_L("Gizmos"), gizmos_shortcuts));
Shortcuts preview_shortcuts = {
{ L("Arrow Up"), L("Upper Layer") },
{ L("Arrow Down"), L("Lower Layer") },
{ "U", L("Upper Layer") },
{ "D", L("Lower Layer") },
{ "L", L("Show/Hide Legend") }
};
m_full_shortcuts.push_back(std::make_pair(_L("Preview"), preview_shortcuts));
Shortcuts layers_slider_shortcuts = {
{ L("Arrow Up"), L("Move current slider thumb Up") },
{ L("Arrow Down"), L("Move current slider thumb Down") },
{ L("Arrow Left"), L("Set upper thumb to current slider thumb") },
{ L("Arrow Right"), L("Set lower thumb to current slider thumb") },
{ "+", L("Add color change marker for current layer") },
{ "-", L("Delete color change marker for current layer") },
{ "Shift+", L("Press to speed up 5 times while moving thumb\nwith arrow keys or mouse wheel") },
{ ctrl, L("Press to speed up 5 times while moving thumb\nwith arrow keys or mouse wheel") },
};
m_full_shortcuts.push_back(std::make_pair(_L("Layers Slider"), layers_slider_shortcuts));
#if ENABLE_GCODE_VIEWER
Shortcuts sequential_slider_shortcuts = {
{ L("Arrow Left"), L("Move current slider thumb Left") },
{ L("Arrow Right"), L("Move current slider thumb Right") },
{ "Shift+", L("Press to speed up 5 times while moving thumb\nwith arrow keys or mouse wheel") },
{ ctrl, L("Press to speed up 5 times while moving thumb\nwith arrow keys or mouse wheel") },
};
m_full_shortcuts.push_back(std::make_pair(_L("Sequential Slider"), sequential_slider_shortcuts));
#endif // ENABLE_GCODE_VIEWER
}
wxPanel* KBShortcutsDialog::create_header(wxWindow* parent, const wxFont& bold_font)
{
wxPanel* panel = new wxPanel(parent);
wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
wxFont header_font = bold_font;
#ifdef __WXOSX__
header_font.SetPointSize(14);
#else
header_font.SetPointSize(bold_font.GetPointSize() + 2);
#endif // __WXOSX__
sizer->AddStretchSpacer();
// logo
m_logo_bmp = ScalableBitmap(this, "PrusaSlicer_32px.png", 32);
m_header_bitmap = new wxStaticBitmap(panel, wxID_ANY, m_logo_bmp.bmp());
sizer->Add(m_header_bitmap, 0, wxEXPAND | wxLEFT | wxRIGHT, 10);
// text
wxStaticText* text = new wxStaticText(panel, wxID_ANY, _L("Keyboard shortcuts"));
text->SetFont(header_font);
sizer->Add(text, 0, wxALIGN_CENTER_VERTICAL);
sizer->AddStretchSpacer();
panel->SetSizer(sizer);
return panel;
}
wxPanel* KBShortcutsDialog::create_page(wxWindow* parent, const std::pair<wxString, Shortcuts>& shortcuts, const wxFont& font, const wxFont& bold_font)
{
static const int max_items_per_column = 20;
int columns_count = 1 + (int)shortcuts.second.size() / max_items_per_column;
#if ENABLE_SCROLLABLE
wxScrolledWindow* page = new wxScrolledWindow(parent);
page->SetScrollbars(20, 20, 50, 50);
page->SetInitialSize(wxSize(850, 450));
#else
wxPanel* page = new wxPanel(parent);
#endif // ENABLE_SCROLLABLE
#if (BOOK_TYPE == LISTBOOK_TOP) || (BOOK_TYPE == LISTBOOK_LEFT)
wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, page, " " + shortcuts.first + " ");
sizer->GetStaticBox()->SetFont(bold_font);
#else
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
#endif // BOOK_TYPE
wxFlexGridSizer* grid_sizer = new wxFlexGridSizer(2 * columns_count, 5, 15);
int items_count = (int)shortcuts.second.size();
for (int i = 0; i < max_items_per_column; ++i)
{
for (int j = 0; j < columns_count; ++j)
{
int id = j * max_items_per_column + i;
if (id >= items_count)
break;
const auto& [shortcut, description] = shortcuts.second[id];
auto key = new wxStaticText(page, wxID_ANY, _(shortcut));
key->SetFont(bold_font);
grid_sizer->Add(key, 0, wxALIGN_CENTRE_VERTICAL);
auto desc = new wxStaticText(page, wxID_ANY, _(description));
desc->SetFont(font);
grid_sizer->Add(desc, 0, wxALIGN_CENTRE_VERTICAL);
}
}
sizer->Add(grid_sizer, 1, wxEXPAND | wxALL, 10);
page->SetSizer(sizer);
return page;
}
} // namespace GUI
} // namespace Slic3r
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QFuture>
#include <QtConcurrent/QtConcurrentRun>
#include <QtQml>
#include <QMetaType>
#include <QtTest/qtestcase.h>
#include <kdb.hpp>
#include "treeviewmodel.hpp"
#include "confignode.hpp"
#include "undomanager.hpp"
#include "guibackend.hpp"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
qRegisterMetaType<TreeViewModel> ("TreeViewModel");
qRegisterMetaType<ConfigNode> ("ConfigNode");
qRegisterMetaType<UndoManager> ("UndoManager");
qRegisterMetaType<GUIBackend> ("GUIBackend");
QString locale = QLocale::system().name();
QTranslator tr;
tr.load(QString(":/qml/i18n/lang_") + locale + QString(".qm"));
app.installTranslator(&tr);
QQmlApplicationEngine engine;
QQmlContext* ctxt = engine.rootContext();
UndoManager manager;
kdb::KDB kdb;
kdb::KeySet config;
try
{
kdb.get(config, "/");
}
catch(kdb::KDBException const& e)
{
qDebug() << QString::fromStdString(e.what());
}
TreeViewModel* model = new TreeViewModel;
model->setKeySet(config);
kdb::KeySet pluginConfig;
pluginConfig.append(kdb::Key("system", KEY_END));
pluginConfig.append(kdb::Key("user", KEY_END));
TreeViewModel* pluginConfigModel = new TreeViewModel;
pluginConfigModel->setKeySet(pluginConfig);
GUIBackend backend;
ctxt->setContextProperty("undoManager", &manager);
ctxt->setContextProperty("externTreeModel", model);
ctxt->setContextProperty("guiBackend", &backend);
ctxt->setContextProperty("pluginConfig", pluginConfigModel);
//populate model in new thread, else the view is blocked
QtConcurrent::run(model, &TreeViewModel::populateModel);
engine.load(QUrl(QStringLiteral("qrc:/qml/SplashScreen.qml")));
return app.exec();
}
<commit_msg>Load SplashScreen before populating model<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QFuture>
#include <QtConcurrent/QtConcurrentRun>
#include <QtQml>
#include <QMetaType>
#include <QtTest/qtestcase.h>
#include <kdb.hpp>
#include "treeviewmodel.hpp"
#include "confignode.hpp"
#include "undomanager.hpp"
#include "guibackend.hpp"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
qRegisterMetaType<TreeViewModel> ("TreeViewModel");
qRegisterMetaType<ConfigNode> ("ConfigNode");
qRegisterMetaType<UndoManager> ("UndoManager");
qRegisterMetaType<GUIBackend> ("GUIBackend");
QString locale = QLocale::system().name();
QTranslator tr;
tr.load(QString(":/qml/i18n/lang_") + locale + QString(".qm"));
app.installTranslator(&tr);
QQmlApplicationEngine engine;
QQmlContext* ctxt = engine.rootContext();
UndoManager manager;
kdb::KDB kdb;
kdb::KeySet config;
try
{
kdb.get(config, "/");
}
catch(kdb::KDBException const& e)
{
qDebug() << QString::fromStdString(e.what());
}
TreeViewModel* model = new TreeViewModel;
model->setKeySet(config);
kdb::KeySet pluginConfig;
pluginConfig.append(kdb::Key("system", KEY_END));
pluginConfig.append(kdb::Key("user", KEY_END));
TreeViewModel* pluginConfigModel = new TreeViewModel;
pluginConfigModel->setKeySet(pluginConfig);
GUIBackend backend;
ctxt->setContextProperty("undoManager", &manager);
ctxt->setContextProperty("externTreeModel", model);
ctxt->setContextProperty("guiBackend", &backend);
ctxt->setContextProperty("pluginConfig", pluginConfigModel);
engine.load(QUrl(QStringLiteral("qrc:/qml/SplashScreen.qml")));
//populate model in new thread, else the view is blocked
QtConcurrent::run(model, &TreeViewModel::populateModel);
return app.exec();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.
=========================================================================*/
#include "QmitkPointListWidget.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"
QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
m_PointSetNode(NULL),
m_NodeObserverTag(0)
{
QGridLayout* layout = new QGridLayout;
layout->setContentsMargins( 0, 0, 0, 0 );
this->setLayout( layout );
this->setContentsMargins( 0, 0, 0, 0 );
m_ListView = new QmitkPointListView( this );
layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols
const QIcon iconEdit( btnSetPoints_xpm );
m_BtnEdit = new QPushButton( iconEdit, "", this );
m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
layout->addWidget( m_BtnEdit, 1, 0 );
const QIcon iconClear( btnClear_xpm ); // clears whole point set
m_BtnClear = new QPushButton( iconClear, "", this );
m_BtnClear->setToolTip("Erase all points from list");
connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
layout->addWidget( m_BtnClear, 1, 1 );
const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
m_BtnLoad = new QPushButton( iconLoad, "", this );
m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
layout->addWidget( m_BtnLoad, 1, 2 );
const QIcon iconSave( btnSave_xpm ); // saves point set to file
m_BtnSave = new QPushButton( iconSave, "", this );
m_BtnSave->setToolTip("Save points to file");
connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
layout->addWidget( m_BtnSave, 1, 3 );
ObserveNewNode(NULL);
}
QmitkPointListWidget::~QmitkPointListWidget()
{
}
void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
ObserveNewNode(node);
if (node)
{
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
m_ListView->SetPointSet( pointSet );
}
else
{
m_ListView->SetPointSet( NULL );
}
}
void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
m_ListView->SetMultiWidget( multiWidget );
}
void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
if (deactivate)
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
}
}
void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
// remove old observer
if ( m_PointSetNode != NULL )
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
}
m_PointSetNode = node;
// add new observer if neccessary
if ( m_PointSetNode != NULL )
{
itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
}
else
{
m_NodeObserverTag = 0;
}
m_BtnEdit->setEnabled( m_PointSetNode != NULL );
m_BtnClear->setEnabled( m_PointSetNode != NULL );
m_BtnLoad->setEnabled( m_PointSetNode != NULL );
m_BtnSave->setEnabled( m_PointSetNode != NULL );
}
void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
m_PointSetNode = NULL;
m_NodeObserverTag = 0;
m_ListView->SetPointSet( NULL );
}
void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
if (m_PointSetNode)
{
if (checked)
{
m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
}
else if ( m_Interactor )
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
}
emit EditPointSets(checked);
}
}
void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions
switch( QMessageBox::question( this, tr("Clear Points"),
tr("Remove all points from the displayed list?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
{
case QMessageBox::Yes:
if (pointSet)
{
mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
pointsContainer->Initialize(); // a call to initialize results in clearing the points container
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
case QMessageBox::No:
default:
break;
}
emit PointListChanged();
}
void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
if (!m_PointSetNode) return;
// get the name of the file to load
QString filename = QFileDialog::getOpenFileName( QString::null, "MITK Point Sets (*.mps)", NULL );
if ( filename.isEmpty() ) return;
// attempt to load file
try
{
mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
reader->SetFileName( filename.latin1() );
reader->Update();
mitk::PointSet::Pointer pointSet = reader->GetOutput();
if ( pointSet.IsNull() )
{
QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
return;
}
// loading successful
bool interactionOn( m_Interactor.IsNotNull() );
if (interactionOn)
{
OnEditPointSetButtonToggled(false);
}
m_PointSetNode->SetData( pointSet );
m_ListView->SetPointSet( pointSet );
if (interactionOn)
{
OnEditPointSetButtonToggled(true);
}
}
catch(...)
{
QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
}
emit PointListChanged();
}
void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
if (pointSet->GetSize() == 0) return;
// let the user choose a file
std::string name("");
QString fileNameProposal = "PointSet.mps";
QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.latin1() );
if ( aFilename.isEmpty() ) return;
try
{
// instantiate the writer and add the point-sets to write
mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
writer->SetInput( pointSet );
writer->SetFileName( aFilename.latin1() );
writer->Update();
}
catch(...)
{
QMessageBox::warning( this, "Save point set",
QString("File writer reported problems writing %1\n\n"
"PLEASE CHECK output file!").arg(aFilename) );
}
}
<commit_msg>COMP: restructuring<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.
=========================================================================*/
#include "QmitkPointListWidget.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"
QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
m_PointSetNode(NULL),
m_NodeObserverTag(0)
{
QGridLayout* layout = new QGridLayout;
layout->setContentsMargins( 0, 0, 0, 0 );
this->setLayout( layout );
this->setContentsMargins( 0, 0, 0, 0 );
m_ListView = new QmitkPointListView( this );
layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols
const QIcon iconEdit( btnSetPoints_xpm );
m_BtnEdit = new QPushButton( iconEdit, "", this );
m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
layout->addWidget( m_BtnEdit, 1, 0 );
const QIcon iconClear( btnClear_xpm ); // clears whole point set
m_BtnClear = new QPushButton( iconClear, "", this );
m_BtnClear->setToolTip("Erase all points from list");
connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
layout->addWidget( m_BtnClear, 1, 1 );
const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
m_BtnLoad = new QPushButton( iconLoad, "", this );
m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
layout->addWidget( m_BtnLoad, 1, 2 );
const QIcon iconSave( btnSave_xpm ); // saves point set to file
m_BtnSave = new QPushButton( iconSave, "", this );
m_BtnSave->setToolTip("Save points to file");
connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
layout->addWidget( m_BtnSave, 1, 3 );
ObserveNewNode(NULL);
}
QmitkPointListWidget::~QmitkPointListWidget()
{
}
void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
ObserveNewNode(node);
if (node)
{
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
m_ListView->SetPointSet( pointSet );
}
else
{
m_ListView->SetPointSet( NULL );
}
}
void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
m_ListView->SetMultiWidget( multiWidget );
}
void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
if (deactivate)
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
}
}
void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
// remove old observer
if ( m_PointSetNode != NULL )
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
}
m_PointSetNode = node;
// add new observer if neccessary
if ( m_PointSetNode != NULL )
{
itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
}
else
{
m_NodeObserverTag = 0;
}
m_BtnEdit->setEnabled( m_PointSetNode != NULL );
m_BtnClear->setEnabled( m_PointSetNode != NULL );
m_BtnLoad->setEnabled( m_PointSetNode != NULL );
m_BtnSave->setEnabled( m_PointSetNode != NULL );
}
void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
m_PointSetNode = NULL;
m_NodeObserverTag = 0;
m_ListView->SetPointSet( NULL );
}
void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
if (m_PointSetNode)
{
if (checked)
{
m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
}
else if ( m_Interactor )
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
}
emit EditPointSets(checked);
}
}
void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions
switch( QMessageBox::question( this, tr("Clear Points"),
tr("Remove all points from the displayed list?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
{
case QMessageBox::Yes:
if (pointSet)
{
mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
pointsContainer->Initialize(); // a call to initialize results in clearing the points container
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
case QMessageBox::No:
default:
break;
}
emit PointListChanged();
}
void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
if (!m_PointSetNode) return;
// get the name of the file to load
QString filename = QFileDialog::getOpenFileName( NULL, QString::null, "MITK Point Sets (*.mps)", NULL );
if ( filename.isEmpty() ) return;
// attempt to load file
try
{
mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
reader->SetFileName( filename.latin1() );
reader->Update();
mitk::PointSet::Pointer pointSet = reader->GetOutput();
if ( pointSet.IsNull() )
{
QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
return;
}
// loading successful
bool interactionOn( m_Interactor.IsNotNull() );
if (interactionOn)
{
OnEditPointSetButtonToggled(false);
}
m_PointSetNode->SetData( pointSet );
m_ListView->SetPointSet( pointSet );
if (interactionOn)
{
OnEditPointSetButtonToggled(true);
}
}
catch(...)
{
QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
}
emit PointListChanged();
}
void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
if (pointSet->GetSize() == 0) return;
// let the user choose a file
std::string name("");
QString fileNameProposal = "PointSet.mps";
QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.latin1() );
if ( aFilename.isEmpty() ) return;
try
{
// instantiate the writer and add the point-sets to write
mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
writer->SetInput( pointSet );
writer->SetFileName( aFilename.latin1() );
writer->Update();
}
catch(...)
{
QMessageBox::warning( this, "Save point set",
QString("File writer reported problems writing %1\n\n"
"PLEASE CHECK output file!").arg(aFilename) );
}
}
<|endoftext|>
|
<commit_before>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* 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. */
/**********************************************************************/
#ifndef HPP_OPTIONS_DEFINED
#define HPP_OPTIONS_DEFINED
/**
* @file Options.hpp
* @brief Define options to be used in the game.
*/
// C Libraries
#include <getopt.h>
/**
* @namespace Options
* @brief All functions and variables related to Transport problem.
*
* Define the prototype to a function to parse arguments and
* set variables to be used by the Transport problem
*/
struct Options
{
bool verbose;
std::string output;
Options() : verbose{false}, output{} {}
/**
* @brief Parse arguments came from the command line.
*
* Set game options and flags, using as background
* the getopt.h package.
*
* @param argc Number of arguments in the command line
* @param argv Array of string with the arguments
*/
void parse_args(int argc, char **argv);
};
#endif
<commit_msg>Changing comments<commit_after>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* 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. */
/**********************************************************************/
#ifndef HPP_OPTIONS_DEFINED
#define HPP_OPTIONS_DEFINED
/**
* @file Options.hpp
* @brief Define options to be used in the game.
*/
// C Libraries
#include <getopt.h>
/**
* @class Options
* @brief All functions and variables related to Transport problem.
*
* Define the prototype to a function to parse arguments and
* set variables to be used by the Transport problem
*/
struct Options
{
bool verbose;
std::string output;
Options() : verbose{false}, output{} {}
/**
* @brief Parse arguments came from the command line.
*
* Set game options and flags, using as background
* the getopt.h package.
*
* @param argc Number of arguments in the command line
* @param argv Array of string with the arguments
*/
void parse_args(int argc, char **argv);
};
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007-2012, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED
#include <boost/version.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/ptime.hpp"
#include <boost/cstdint.hpp>
#include <string>
// OVERVIEW
//
// This section contains fundamental time types used internall by
// libtorrent and exposed through various places in the API. The two
// basic types are ``ptime`` and ``time_duration``. The first represents
// a point in time and the second the difference between two points
// in time.
//
// The internal representation of these types is implementation defined
// and they can only be constructed via one of the construction functions
// that take a well defined time unit (seconds, minutes, etc.). They can
// only be turned into well defined time units by the accessor functions
// (total_microseconds(), etc.).
//
// .. note::
// In a future version of libtorrent, these types will be replaced
// by the standard timer types from ``std::chrono``.
namespace libtorrent
{
char const* time_now_string();
std::string log_time();
TORRENT_EXPORT ptime const& time_now();
TORRENT_EXPORT ptime time_now_hires();
TORRENT_EXPORT ptime min_time();
TORRENT_EXPORT ptime max_time();
#if defined TORRENT_USE_BOOST_DATE_TIME || defined TORRENT_USE_QUERY_PERFORMANCE_TIMER
TORRENT_EXPORT time_duration seconds(int s);
TORRENT_EXPORT time_duration milliseconds(int s);
TORRENT_EXPORT time_duration microsec(int s);
TORRENT_EXPORT time_duration minutes(int s);
TORRENT_EXPORT time_duration hours(int s);
TORRENT_EXPORT int total_seconds(time_duration td);
TORRENT_EXPORT int total_milliseconds(time_duration td);
TORRENT_EXPORT boost::int64_t total_microseconds(time_duration td);
#elif TORRENT_USE_CLOCK_GETTIME || TORRENT_USE_SYSTEM_TIME || TORRENT_USE_ABSOLUTE_TIME
// hidden
inline int total_seconds(time_duration td)
{ return td.diff / 1000000; }
// hidden
inline int total_milliseconds(time_duration td)
{ return td.diff / 1000; }
// hidden
inline boost::int64_t total_microseconds(time_duration td)
{ return td.diff; }
// hidden
inline time_duration microsec(boost::int64_t s)
{ return time_duration(s); }
// hidden
inline time_duration milliseconds(boost::int64_t s)
{ return time_duration(s * 1000); }
// hidden
inline time_duration seconds(boost::int64_t s)
{ return time_duration(s * 1000000); }
// hidden
inline time_duration minutes(boost::int64_t s)
{ return time_duration(s * 1000000 * 60); }
// hidden
inline time_duration hours(boost::int64_t s)
{ return time_duration(s * 1000000 * 60 * 60); }
#endif // TORRENT_USE_CLOCK_GETTIME
}
#endif // TORRENT_TIME_HPP_INCLUDED
<commit_msg>export time_now_string for unit tests<commit_after>/*
Copyright (c) 2007-2012, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED
#include <boost/version.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/ptime.hpp"
#include <boost/cstdint.hpp>
#include <string>
// OVERVIEW
//
// This section contains fundamental time types used internall by
// libtorrent and exposed through various places in the API. The two
// basic types are ``ptime`` and ``time_duration``. The first represents
// a point in time and the second the difference between two points
// in time.
//
// The internal representation of these types is implementation defined
// and they can only be constructed via one of the construction functions
// that take a well defined time unit (seconds, minutes, etc.). They can
// only be turned into well defined time units by the accessor functions
// (total_microseconds(), etc.).
//
// .. note::
// In a future version of libtorrent, these types will be replaced
// by the standard timer types from ``std::chrono``.
namespace libtorrent
{
TORRENT_EXTRA_EXPORT char const* time_now_string();
std::string log_time();
TORRENT_EXPORT ptime const& time_now();
TORRENT_EXPORT ptime time_now_hires();
TORRENT_EXPORT ptime min_time();
TORRENT_EXPORT ptime max_time();
#if defined TORRENT_USE_BOOST_DATE_TIME || defined TORRENT_USE_QUERY_PERFORMANCE_TIMER
TORRENT_EXPORT time_duration seconds(int s);
TORRENT_EXPORT time_duration milliseconds(int s);
TORRENT_EXPORT time_duration microsec(int s);
TORRENT_EXPORT time_duration minutes(int s);
TORRENT_EXPORT time_duration hours(int s);
TORRENT_EXPORT int total_seconds(time_duration td);
TORRENT_EXPORT int total_milliseconds(time_duration td);
TORRENT_EXPORT boost::int64_t total_microseconds(time_duration td);
#elif TORRENT_USE_CLOCK_GETTIME || TORRENT_USE_SYSTEM_TIME || TORRENT_USE_ABSOLUTE_TIME
// hidden
inline int total_seconds(time_duration td)
{ return td.diff / 1000000; }
// hidden
inline int total_milliseconds(time_duration td)
{ return td.diff / 1000; }
// hidden
inline boost::int64_t total_microseconds(time_duration td)
{ return td.diff; }
// hidden
inline time_duration microsec(boost::int64_t s)
{ return time_duration(s); }
// hidden
inline time_duration milliseconds(boost::int64_t s)
{ return time_duration(s * 1000); }
// hidden
inline time_duration seconds(boost::int64_t s)
{ return time_duration(s * 1000000); }
// hidden
inline time_duration minutes(boost::int64_t s)
{ return time_duration(s * 1000000 * 60); }
// hidden
inline time_duration hours(boost::int64_t s)
{ return time_duration(s * 1000000 * 60 * 60); }
#endif // TORRENT_USE_CLOCK_GETTIME
}
#endif // TORRENT_TIME_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#pragma once
#include "seq.hpp"
#include "util.hpp"
#include "value.hpp"
#include <memory>
#include <vector>
namespace imu {
namespace ty {
template<typename mixin = no_mixin>
struct base_node : public mixin {
typedef std::shared_ptr<base_node> p;
mixin _mixin;
virtual ~base_node()
{}
};
template<typename mixin = no_mixin>
struct basic_node : public base_node<mixin> {
typedef std::shared_ptr<basic_node> p;
typedef typename base_node<mixin>::p base;
std::vector<base> _arr;
inline basic_node()
: _arr(32)
{}
inline basic_node(const p& root)
: _arr(root->_arr)
{}
inline basic_node(const base& root, const base& node)
: basic_node()
{
_arr[0] = root;
_arr[1] = node;
}
inline basic_node(const base& child)
: basic_node()
{
_arr[0] = child;
}
static inline base new_path(uint64_t level, const base& node) {
base out(node);
for(auto l = level; level != 0; level -= 5) {
out = base(nu<basic_node>(out));
}
return out;
}
static inline p push_tail(
uint64_t cnt
, uint64_t level
, const p& parent
, const base& tail) {
p out(nu<basic_node>(*parent));
base insert;
uint64_t idx = ((cnt - 1) >> level) & 0x01f;
if (level == 5) {
insert = tail;
}
else {
auto child = parent->_arr[idx];
if (child) {
auto as_base = std::dynamic_pointer_cast<basic_node>(child);
insert = push_tail(cnt, level - 5, as_base, tail);
}
else {
insert = new_path(level - 5, tail);
}
}
out->_arr[idx] = insert;
return out;
}
};
template<typename Value, typename mixin = no_mixin>
struct basic_leaf : public base_node<mixin> {
typedef std::shared_ptr<basic_leaf> p;
typedef base_node<mixin> base;
typedef basic_node<mixin> node;
std::vector<Value> _arr;
inline basic_leaf()
{}
inline basic_leaf(const basic_leaf::p& a)
: _arr(a->_arr)
{}
inline basic_leaf(const Value& val)
{ _arr.push_back(val); }
inline const Value& operator[](uint64_t n) const {
return _arr[n];
}
static inline typename base::p assoc(
const typename base::p& n, uint64_t level,
uint64_t k, const Value& v) {
uint64_t idx = (k >> level) & 0x01f;
if (level == 0) {
auto leaf = std::static_pointer_cast<basic_leaf>(n);
leaf->_arr[idx] = v;
return leaf;
}
else {
auto bn = std::static_pointer_cast<node>(n);
auto ret = nu<node>(bn);
ret->_arr[idx] = assoc(bn->_arr[idx], level - 5, k, v);
return ret;
}
}
};
template<
typename Value = value
, typename mixin = no_mixin
, typename node = basic_node<>
, typename leaf = basic_leaf<Value>
>
struct basic_vector : public mixin {
typedef typename mixin::template semantics<basic_vector>::p p;
typedef typename node::base base_node;
typedef leaf leaf_type;
typedef Value value_type;
uint64_t _cnt;
uint64_t _shift;
typename node::p _root;
typename leaf::p _tail;
inline basic_vector()
: _cnt(0)
, _shift(5)
, _root(nu<node>())
, _tail(nu<leaf>())
{}
inline basic_vector(const p& v)
: _cnt(v->_cnt)
, _shift(v->_shift)
, _root(v->_root)
, _tail(nu<leaf>(v->_tail))
{}
inline basic_vector(const p& v, const Value& val)
: _cnt(v->_cnt + 1)
, _shift(v->_shift)
, _tail(v->_tail)
{
if ((v->_cnt - v->tail_off()) < 32) {
_shift = v->_shift;
_root = v->_root;
_tail->_arr.push_back(val);
}
else {
extend_root(v, val);
}
}
template<typename T>
static inline p from_std(const T& coll) {
auto out = nu<basic_vector>();
for (auto& val : coll) {
out = nu<basic_vector>(out, val);
}
return out;
}
inline bool is_empty() const {
return _cnt == 0;
}
inline uint64_t count() const {
return _cnt;
}
inline const value_type& nth(uint64_t n) const {
return (*leaf_for(n))[n & 0x01f];
}
template<typename T>
inline const T& nth(uint64_t n) const {
return value_cast<T>(nth(n));
}
inline const value_type& operator[](uint64_t n) const {
return nth(n);
}
inline const value_type& operator()(uint64_t n) const {
return nth(n);
}
template<typename S>
inline friend bool operator== (const p& self, const S& x) {
return seqs::equiv(seq(self), x);
}
template<typename S>
inline friend bool operator== (const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(seq(self), x);
}
inline uint64_t tail_off() const {
return (_cnt < 32) ? 0 : ((_cnt - 1) >> 5) << 5;
}
inline const typename leaf::p leaf_for(uint64_t n) const {
if (n >= 0 && n < _cnt) {
if (n >= tail_off()) {
return _tail;
}
typename node::base out = _root;
for (auto level = _shift; level > 0; level -= 5) {
auto inner = std::dynamic_pointer_cast<node>(out);
out = inner->_arr[(n >> level) & 0x01f];
}
return std::dynamic_pointer_cast<leaf>(out);
}
throw out_of_bounds(n, _cnt);
}
inline void extend_root(const p& v, const value_type& val) {
auto new_leaf = nu<leaf>(v->_tail);
_tail = nu<leaf>(val);
bool overflow = ((v->_cnt >> 5) > (1 << v->_shift));
if (overflow) {
_shift = v->_shift + 5;
_root = nu<node>(v->_root, node::new_path(v->_shift, new_leaf));
}
else {
_root = node::push_tail(v->_cnt, _shift, v->_root, new_leaf);
}
}
static inline p assoc(const p& v, uint64_t idx, const value_type& val) {
if (0 <= idx && idx < v->_cnt) {
auto ret = imu::nu<basic_vector>(v);
if (v->tail_off() <= idx) {
ret->_tail->_arr[(idx & 0x01)] = val;
}
else {
auto root = leaf::assoc(ret->_root, ret->_shift, idx, val);
ret->_root = std::static_pointer_cast<node>(root);
}
return ret;
}
else {
return nu<basic_vector>(v, val);
}
}
};
typedef basic_vector<> vector;
template<typename V = vector, typename mixin = no_mixin>
struct basic_chunked_seq : public no_mixin {
typedef std::shared_ptr<basic_chunked_seq> p;
typedef typename V::value_type value_type;
typedef typename V::leaf_type leaf_type;
mixin _mixin;
typename V::p _vec;
uint64_t _idx;
uint64_t _off;
typename leaf_type::p _leaf;
inline basic_chunked_seq(const typename V::p& v, uint64_t i, uint64_t o)
: _vec(v)
, _idx(i)
, _off(o)
, _leaf(v->leaf_for(_idx))
{}
inline bool is_empty() const {
return (_off >= _leaf->_arr.size());
}
template<typename T>
inline const T& first() const {
return value_cast<T>((*_leaf)[_off]);
}
inline const value_type& first() const {
return (*_leaf)[_off];
};
inline p rest() const {
if (!is_empty()) {
return nu<basic_chunked_seq>(_vec, _idx, _off + 1);
}
return p();
}
template<typename S>
inline friend bool operator== (const p& self, const S& x) {
return seqs::equiv(self, x);
}
template<typename S>
inline friend bool operator== (const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(self, x);
}
};
typedef basic_chunked_seq<> chunked_seq;
}
inline ty::vector::p vector() {
return nu<ty::vector>();
}
template<typename Arg>
inline ty::vector::p vector(const ty::vector::p& v, const Arg& x) {
return conj(v, x);
}
template<typename Arg, typename... Args>
inline ty::vector::p vector(const ty::vector::p& v, const Arg& x, Args... args) {
return vector(conj(v, x), args...);
}
template<typename Arg, typename... Args>
inline ty::vector::p vector(const Arg& x, Args... args) {
return vector(vector(), x, args...);
}
template<typename T>
inline auto vector(const T& coll)
-> decltype(std::begin(coll), std::end(coll), ty::list::p()) {
return ty::vector::from_std(coll);
}
template<typename T>
inline ty::vector::p vector(std::initializer_list<T> l) {
return ty::vector::from_std(l);
}
// @cond HIDE
template<typename... TS>
inline decltype(auto) seq(
const std::shared_ptr<ty::basic_vector<TS...>>& v) {
typedef typename ty::basic_vector<TS...> V;
typedef typename ty::basic_chunked_seq<> S;
if (!v || v->is_empty()) {
return typename S::p();
}
return nu<S>(v, 0, 0);
}
template<typename... TS>
inline decltype(auto) seq(ty::basic_vector<TS...>* const & v) {
typedef typename ty::basic_vector<TS...> V;
typedef typename ty::basic_chunked_seq<V> S;
if (!v || v->is_empty()) {
return typename S::p();
}
return nu<S>(v, 0, 0);
}
template<typename T, typename... TS>
inline ty::vector::p conj(
const typename ty::basic_vector<TS...>::p& v, const T& x) {
return nu<ty::vector>(v, x);
}
// @endcond
}
<commit_msg>Fix conj on vector<commit_after>#pragma once
#include "seq.hpp"
#include "util.hpp"
#include "value.hpp"
#include <memory>
#include <vector>
namespace imu {
namespace ty {
template<typename mixin = no_mixin>
struct base_node : public mixin {
typedef std::shared_ptr<base_node> p;
mixin _mixin;
virtual ~base_node()
{}
};
template<typename mixin = no_mixin>
struct basic_node : public base_node<mixin> {
typedef std::shared_ptr<basic_node> p;
typedef typename base_node<mixin>::p base;
std::vector<base> _arr;
inline basic_node()
: _arr(32)
{}
inline basic_node(const p& root)
: _arr(root->_arr)
{}
inline basic_node(const base& root, const base& node)
: basic_node()
{
_arr[0] = root;
_arr[1] = node;
}
inline basic_node(const base& child)
: basic_node()
{
_arr[0] = child;
}
static inline base new_path(uint64_t level, const base& node) {
base out(node);
for(auto l = level; level != 0; level -= 5) {
out = base(nu<basic_node>(out));
}
return out;
}
static inline p push_tail(
uint64_t cnt
, uint64_t level
, const p& parent
, const base& tail) {
p out(nu<basic_node>(*parent));
base insert;
uint64_t idx = ((cnt - 1) >> level) & 0x01f;
if (level == 5) {
insert = tail;
}
else {
auto child = parent->_arr[idx];
if (child) {
auto as_base = std::dynamic_pointer_cast<basic_node>(child);
insert = push_tail(cnt, level - 5, as_base, tail);
}
else {
insert = new_path(level - 5, tail);
}
}
out->_arr[idx] = insert;
return out;
}
};
template<typename Value, typename mixin = no_mixin>
struct basic_leaf : public base_node<mixin> {
typedef std::shared_ptr<basic_leaf> p;
typedef base_node<mixin> base;
typedef basic_node<mixin> node;
std::vector<Value> _arr;
inline basic_leaf()
{}
inline basic_leaf(const basic_leaf::p& a)
: _arr(a->_arr)
{}
inline basic_leaf(const Value& val)
{ _arr.push_back(val); }
inline const Value& operator[](uint64_t n) const {
return _arr[n];
}
static inline typename base::p assoc(
const typename base::p& n, uint64_t level,
uint64_t k, const Value& v) {
uint64_t idx = (k >> level) & 0x01f;
if (level == 0) {
auto leaf = std::static_pointer_cast<basic_leaf>(n);
leaf->_arr[idx] = v;
return leaf;
}
else {
auto bn = std::static_pointer_cast<node>(n);
auto ret = nu<node>(bn);
ret->_arr[idx] = assoc(bn->_arr[idx], level - 5, k, v);
return ret;
}
}
};
struct vector_tag {};
template<
typename Value = value
, typename mixin = no_mixin
, typename node = basic_node<>
, typename leaf = basic_leaf<Value>
>
struct basic_vector : public mixin, vector_tag {
typedef typename mixin::template semantics<basic_vector>::p p;
typedef typename node::base base_node;
typedef leaf leaf_type;
typedef Value value_type;
uint64_t _cnt;
uint64_t _shift;
typename node::p _root;
typename leaf::p _tail;
inline basic_vector()
: _cnt(0)
, _shift(5)
, _root(nu<node>())
, _tail(nu<leaf>())
{}
inline basic_vector(const p& v)
: _cnt(v->_cnt)
, _shift(v->_shift)
, _root(v->_root)
, _tail(nu<leaf>(v->_tail))
{}
inline basic_vector(const p& v, const Value& val)
: _cnt(v->_cnt + 1)
, _shift(v->_shift)
, _tail(v->_tail)
{
if ((v->_cnt - v->tail_off()) < 32) {
_shift = v->_shift;
_root = v->_root;
_tail->_arr.push_back(val);
}
else {
extend_root(v, val);
}
}
template<typename T>
static inline p from_std(const T& coll) {
auto out = nu<basic_vector>();
for (auto& val : coll) {
out = nu<basic_vector>(out, val);
}
return out;
}
inline bool is_empty() const {
return _cnt == 0;
}
inline uint64_t count() const {
return _cnt;
}
inline const value_type& nth(uint64_t n) const {
return (*leaf_for(n))[n & 0x01f];
}
template<typename T>
inline const T& nth(uint64_t n) const {
return value_cast<T>(nth(n));
}
inline const value_type& operator[](uint64_t n) const {
return nth(n);
}
inline const value_type& operator()(uint64_t n) const {
return nth(n);
}
template<typename S>
inline friend bool operator== (const p& self, const S& x) {
return seqs::equiv(seq(self), x);
}
template<typename S>
inline friend bool operator== (const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(seq(self), x);
}
inline uint64_t tail_off() const {
return (_cnt < 32) ? 0 : ((_cnt - 1) >> 5) << 5;
}
inline const typename leaf::p leaf_for(uint64_t n) const {
if (n >= 0 && n < _cnt) {
if (n >= tail_off()) {
return _tail;
}
typename node::base out = _root;
for (auto level = _shift; level > 0; level -= 5) {
auto inner = std::dynamic_pointer_cast<node>(out);
out = inner->_arr[(n >> level) & 0x01f];
}
return std::dynamic_pointer_cast<leaf>(out);
}
throw out_of_bounds(n, _cnt);
}
inline void extend_root(const p& v, const value_type& val) {
auto new_leaf = nu<leaf>(v->_tail);
_tail = nu<leaf>(val);
bool overflow = ((v->_cnt >> 5) > (1 << v->_shift));
if (overflow) {
_shift = v->_shift + 5;
_root = nu<node>(v->_root, node::new_path(v->_shift, new_leaf));
}
else {
_root = node::push_tail(v->_cnt, _shift, v->_root, new_leaf);
}
}
static inline p assoc(const p& v, uint64_t idx, const value_type& val) {
if (0 <= idx && idx < v->_cnt) {
auto ret = imu::nu<basic_vector>(v);
if (v->tail_off() <= idx) {
ret->_tail->_arr[(idx & 0x01)] = val;
}
else {
auto root = leaf::assoc(ret->_root, ret->_shift, idx, val);
ret->_root = std::static_pointer_cast<node>(root);
}
return ret;
}
else {
return nu<basic_vector>(v, val);
}
}
};
typedef basic_vector<> vector;
template<typename V = vector, typename mixin = no_mixin>
struct basic_chunked_seq : public no_mixin {
typedef std::shared_ptr<basic_chunked_seq> p;
typedef typename V::value_type value_type;
typedef typename V::leaf_type leaf_type;
mixin _mixin;
typename V::p _vec;
uint64_t _idx;
uint64_t _off;
typename leaf_type::p _leaf;
inline basic_chunked_seq(const typename V::p& v, uint64_t i, uint64_t o)
: _vec(v)
, _idx(i)
, _off(o)
, _leaf(v->leaf_for(_idx))
{}
inline bool is_empty() const {
return (_off >= _leaf->_arr.size());
}
template<typename T>
inline const T& first() const {
return value_cast<T>((*_leaf)[_off]);
}
inline const value_type& first() const {
return (*_leaf)[_off];
};
inline p rest() const {
if (!is_empty()) {
return nu<basic_chunked_seq>(_vec, _idx, _off + 1);
}
return p();
}
template<typename S>
inline friend bool operator== (const p& self, const S& x) {
return seqs::equiv(self, x);
}
template<typename S>
inline friend bool operator== (const p& self, const std::shared_ptr<S>& x) {
return seqs::equiv(self, x);
}
};
typedef basic_chunked_seq<> chunked_seq;
}
inline ty::vector::p vector() {
return nu<ty::vector>();
}
template<typename Arg>
inline ty::vector::p vector(const ty::vector::p& v, const Arg& x) {
return conj(v, x);
}
template<typename Arg, typename... Args>
inline ty::vector::p vector(const ty::vector::p& v, const Arg& x, Args... args) {
return vector(conj(v, x), args...);
}
template<typename Arg, typename... Args>
inline ty::vector::p vector(const Arg& x, Args... args) {
return vector(vector(), x, args...);
}
template<typename T>
inline auto vector(const T& coll)
-> decltype(std::begin(coll), std::end(coll), ty::list::p()) {
return ty::vector::from_std(coll);
}
template<typename T>
inline ty::vector::p vector(std::initializer_list<T> l) {
return ty::vector::from_std(l);
}
// @cond HIDE
template<typename... TS>
inline decltype(auto) seq(
const std::shared_ptr<ty::basic_vector<TS...>>& v) {
typedef typename ty::basic_vector<TS...> V;
typedef typename ty::basic_chunked_seq<> S;
if (!v || v->is_empty()) {
return typename S::p();
}
return nu<S>(v, 0, 0);
}
template<typename... TS>
inline decltype(auto) seq(ty::basic_vector<TS...>* const & v) {
typedef typename ty::basic_vector<TS...> V;
typedef typename ty::basic_chunked_seq<V> S;
if (!v || v->is_empty()) {
return typename S::p();
}
return nu<S>(v, 0, 0);
}
template<typename V, typename T>
inline typename std::enable_if<
std::is_base_of<
ty::vector_tag
, typename semantics::real_type<V>::type
>::value,
typename semantics::real_type<V>::type::p
>::type
conj(const V& v, const T& x) {
typedef typename semantics::real_type<V>::type type;
return nu<type>(v, x);
}
// @endcond
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Implementation of a Restricted Boltzmann Machine
*/
#pragma once
#include "cpp_utils/assert.hpp" //Assertions
#include "cpp_utils/stop_watch.hpp" //Performance counter
#include "etl/etl.hpp"
#include "standard_rbm.hpp"
#include "layer_traits.hpp"
#include "util/converter.hpp" //converter
namespace dll {
/*!
* \brief Standard version of Restricted Boltzmann Machine
*
* This follows the definition of a RBM by Geoffrey Hinton.
*/
template <typename Desc>
struct rbm final : public standard_rbm<rbm<Desc>, Desc> {
using desc = Desc; ///< The layer descriptor
using weight = typename desc::weight; ///< The weight type
using this_type = rbm<desc>; ///< The type of this layer
using base_type = standard_rbm<this_type, desc>; ///< The base type
using input_t = typename rbm_base_traits<this_type>::input_t;
using output_t = typename rbm_base_traits<this_type>::output_t;
using input_one_t = typename rbm_base_traits<this_type>::input_one_t;
using output_one_t = typename rbm_base_traits<this_type>::output_one_t;
static constexpr const std::size_t num_visible = desc::num_visible; ///< The number of visible units
static constexpr const std::size_t num_hidden = desc::num_hidden; ///< The number of hidden units
static constexpr const unit_type visible_unit = desc::visible_unit; ///< The type of visible units
static constexpr const unit_type hidden_unit = desc::hidden_unit; ///< The type of hidden units
static constexpr bool dbn_only = layer_traits<this_type>::is_dbn_only();
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, num_visible>;
using w_type = etl::fast_matrix<weight, num_visible, num_hidden>; ///< The type used to store weights
using b_type = etl::fast_vector<weight, num_hidden>; ///< The type used to store hidden biases
using c_type = etl::fast_vector<weight, num_visible>; ///< The type used to store visible biases
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
c_type c; //!< Visible biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
std::unique_ptr<c_type> bak_c; //!< Backup Visible biases
//Reconstruction data
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v1; //!< State of the visible units
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h1_a; //!< Activation probabilities of hidden units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h1_s; //!< Sampled value of hidden units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v2_a; //!< Activation probabilities of visible units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v2_s; //!< Sampled value of visible units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h2_a; //!< Activation probabilities of hidden units after last CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h2_s; //!< Sampled value of hidden units after last CD-step
//No copying
rbm(const rbm& rbm) = delete;
rbm& operator=(const rbm& rbm) = delete;
//No moving
rbm(rbm&& rbm) = delete;
rbm& operator=(rbm&& rbm) = delete;
/*!
* \brief Initialize a RBM with basic weights.
*
* The weights are initialized from a normal distribution of
* zero-mean and 0.1 variance.
*/
rbm()
: standard_rbm<rbm<Desc>, Desc>(), b(0.0), c(0.0) {
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
static constexpr std::size_t input_size() noexcept {
return num_visible;
}
static constexpr std::size_t output_size() noexcept {
return num_hidden;
}
static constexpr std::size_t parameters() noexcept {
return num_visible * num_hidden;
}
static std::string to_short_string() {
return "RBM: " + std::to_string(num_visible) + "(" + to_string(visible_unit) + ") -> " + std::to_string(num_hidden) + "(" + to_string(hidden_unit) + ")";
}
template<typename DRBM>
static void dyn_init(DRBM& dyn){
dyn.init_layer(num_visible, num_hidden);
dyn.batch_size = layer_traits<this_type>::batch_size();
}
void prepare_input(input_one_t&) const {
// Nothing to do
}
template <std::size_t B>
auto prepare_input_batch(){
return etl::fast_dyn_matrix<weight, B, num_visible>();
}
template <std::size_t B>
auto prepare_output_batch(){
return etl::fast_dyn_matrix<weight, B, num_hidden>();
}
};
/*!
* \brief Simple traits to pass information around from the real
* class to the CRTP class.
*/
template <typename Desc>
struct rbm_base_traits<rbm<Desc>> {
using desc = Desc;
using weight = typename desc::weight;
using input_one_t = etl::dyn_vector<weight>;
using output_one_t = etl::dyn_vector<weight>;
using input_t = std::vector<input_one_t>;
using output_t = std::vector<output_one_t>;
};
//Allow odr-use of the constexpr static members
template <typename Desc>
const std::size_t rbm<Desc>::num_visible;
template <typename Desc>
const std::size_t rbm<Desc>::num_hidden;
} //end of dll namespace
<commit_msg>Fix prepare_input<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Implementation of a Restricted Boltzmann Machine
*/
#pragma once
#include "cpp_utils/assert.hpp" //Assertions
#include "cpp_utils/stop_watch.hpp" //Performance counter
#include "etl/etl.hpp"
#include "standard_rbm.hpp"
#include "layer_traits.hpp"
#include "util/converter.hpp" //converter
namespace dll {
/*!
* \brief Standard version of Restricted Boltzmann Machine
*
* This follows the definition of a RBM by Geoffrey Hinton.
*/
template <typename Desc>
struct rbm final : public standard_rbm<rbm<Desc>, Desc> {
using desc = Desc; ///< The layer descriptor
using weight = typename desc::weight; ///< The weight type
using this_type = rbm<desc>; ///< The type of this layer
using base_type = standard_rbm<this_type, desc>; ///< The base type
using input_t = typename rbm_base_traits<this_type>::input_t;
using output_t = typename rbm_base_traits<this_type>::output_t;
using input_one_t = typename rbm_base_traits<this_type>::input_one_t;
using output_one_t = typename rbm_base_traits<this_type>::output_one_t;
static constexpr const std::size_t num_visible = desc::num_visible; ///< The number of visible units
static constexpr const std::size_t num_hidden = desc::num_hidden; ///< The number of hidden units
static constexpr const unit_type visible_unit = desc::visible_unit; ///< The type of visible units
static constexpr const unit_type hidden_unit = desc::hidden_unit; ///< The type of hidden units
static constexpr bool dbn_only = layer_traits<this_type>::is_dbn_only();
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, num_visible>;
using w_type = etl::fast_matrix<weight, num_visible, num_hidden>; ///< The type used to store weights
using b_type = etl::fast_vector<weight, num_hidden>; ///< The type used to store hidden biases
using c_type = etl::fast_vector<weight, num_visible>; ///< The type used to store visible biases
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
c_type c; //!< Visible biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
std::unique_ptr<c_type> bak_c; //!< Backup Visible biases
//Reconstruction data
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v1; //!< State of the visible units
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h1_a; //!< Activation probabilities of hidden units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h1_s; //!< Sampled value of hidden units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v2_a; //!< Activation probabilities of visible units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_visible> v2_s; //!< Sampled value of visible units after first CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h2_a; //!< Activation probabilities of hidden units after last CD-step
conditional_fast_matrix_t<!dbn_only, weight, num_hidden> h2_s; //!< Sampled value of hidden units after last CD-step
//No copying
rbm(const rbm& rbm) = delete;
rbm& operator=(const rbm& rbm) = delete;
//No moving
rbm(rbm&& rbm) = delete;
rbm& operator=(rbm&& rbm) = delete;
/*!
* \brief Initialize a RBM with basic weights.
*
* The weights are initialized from a normal distribution of
* zero-mean and 0.1 variance.
*/
rbm()
: standard_rbm<rbm<Desc>, Desc>(), b(0.0), c(0.0) {
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
static constexpr std::size_t input_size() noexcept {
return num_visible;
}
static constexpr std::size_t output_size() noexcept {
return num_hidden;
}
static constexpr std::size_t parameters() noexcept {
return num_visible * num_hidden;
}
static std::string to_short_string() {
return "RBM: " + std::to_string(num_visible) + "(" + to_string(visible_unit) + ") -> " + std::to_string(num_hidden) + "(" + to_string(hidden_unit) + ")";
}
template<typename DRBM>
static void dyn_init(DRBM& dyn){
dyn.init_layer(num_visible, num_hidden);
dyn.batch_size = layer_traits<this_type>::batch_size();
}
void prepare_input(input_one_t& input) const {
// Need to initialize the dimensions of the matrix
input = input_one_t(num_visible);
}
template <std::size_t B>
auto prepare_input_batch(){
return etl::fast_dyn_matrix<weight, B, num_visible>();
}
template <std::size_t B>
auto prepare_output_batch(){
return etl::fast_dyn_matrix<weight, B, num_hidden>();
}
};
/*!
* \brief Simple traits to pass information around from the real
* class to the CRTP class.
*/
template <typename Desc>
struct rbm_base_traits<rbm<Desc>> {
using desc = Desc;
using weight = typename desc::weight;
using input_one_t = etl::dyn_vector<weight>;
using output_one_t = etl::dyn_vector<weight>;
using input_t = std::vector<input_one_t>;
using output_t = std::vector<output_one_t>;
};
//Allow odr-use of the constexpr static members
template <typename Desc>
const std::size_t rbm<Desc>::num_visible;
template <typename Desc>
const std::size_t rbm<Desc>::num_hidden;
} //end of dll namespace
<|endoftext|>
|
<commit_before>/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_UTIL_coeffNOMIAL_HPP
#define PIC_UTIL_coeffNOMIAL_HPP
#include <vector>
#include "../base.hpp"
#ifndef PIC_DISABLE_EIGEN
#ifndef PIC_EIGEN_NOT_BUNDLED
#include "../externals/Eigen/QR"
#include "../externals/Eigen/Eigenvalues"
#else
#include <Eigen/QR>
#endif
#endif
namespace pic {
class Polynomial
{
public:
std::vector<float> coeff;
bool all_coeff_positive;
/**
* @brief Polynomial
*/
Polynomial()
{
all_coeff_positive = true;
}
/**
* @brief Polynomial
* @param nCoeff
*/
Polynomial(int nCoeff)
{
for(int i = 0; i < nCoeff; i++) {
coeff.push_back(0.0f);
}
all_coeff_positive = true;
}
/**
* @brief coeffnomial
* @param coeff
* @param nCoeff
*/
Polynomial(float *coeff, int nCoeff)
{
if(nCoeff < 1 || coeff == NULL) {
return;
}
this->coeff.assign(coeff, coeff + nCoeff);
computeAllCoeffPositive();
}
~Polynomial()
{
}
/**
* @brief computeAllCoeffPositive
*/
void computeAllCoeffPositive()
{
int counter = 0;
for (const float &c : coeff) {
if(c < 0.0f) {
counter++;
}
}
all_coeff_positive = counter < 1;
}
/**
* @brief print
*/
void print()
{
printf("%s\n", toString().c_str());
}
std::string toString()
{
std::string ret = "";
if(coeff.empty()) {
return ret;
}
int nCoeff = coeff.size();
if(nCoeff > 1) {
std::string sep = "+ ";
if(coeff[1] < 0.0f) {
sep = " ";
}
ret = fromNumberToString(coeff[0]) + sep;
for(int i = 1; i < (nCoeff - 1); i++) {
if(coeff[i + 1] > 0.0f) {
sep = "+ ";
} else {
sep = " ";
}
ret += fromNumberToString(coeff[i]) + " * x^" + fromNumberToString(i) + sep;
}
ret += fromNumberToString(coeff[nCoeff - 1]) + " * x^" + fromNumberToString(nCoeff - 1);
} else {
ret = fromNumberToString(coeff[0]);
}
return ret;
}
/**
* @brief getArray
* @return
*/
float *getArray(float *ret)
{
if(ret == NULL) {
ret = new float[coeff.size()];
}
for(int i = 0; i < coeff.size(); i++) {
ret[i] = coeff[i];
}
return ret;
}
/**
* @brief eval
* @param x
* @return
*/
float eval(float x)
{
float val = 0.f;
float M = 1.f;
for (const float &c : coeff) {
val += c * M;
M *= x;
}
return val;
}
/**
* @brief dEval
* @param t
* @return
*/
float dEval(float x)
{
int nCoeff = coeff.size();
if(nCoeff < 2) {
return 0.0f;
}
float ret = coeff[nCoeff - 1] * float(nCoeff - 1);
for(int i = (nCoeff - 2); i > 0 ; i--) {
ret = (ret * x) + coeff[i] * float(i);
}
return ret;
}
/**
* @brief fit
* @param x
* @param y
* @param n
*/
void fit(std::vector<float> &x, std::vector<float> &y, int n)
{
#ifndef PIC_DISABLE_EIGEN
if(n < 1 || (x.size() != y.size())) {
return;
}
coeff.clear();
int np1 = n + 1;
int s = int(x.size());
Eigen::MatrixXf A(s, np1);
Eigen::VectorXf b(s);
for(int i = 0; i < s; i++) {
b(i) = y[i];
A(i, n) = 1.0f;
}
for(int j = (n - 1); j >= 0; j--) {
for(int i = 0; i < s; i++) {
A(i, j) = x[i] * A(i, j + 1);
}
}
Eigen::VectorXf _x = A.colPivHouseholderQr().solve(b);
for(int i = n; i >= 0; i--) {
coeff.push_back(_x(i));
}
#endif
}
/**
* @brief normalForm
*/
void normalForm()
{
int last = coeff.size() - 1;
if(fabsf(coeff[last]) > 0.0f) {
for(int i = 0; i < last; i++) {
coeff[i] /= coeff[last];
}
coeff[last] = 1.0f;
}
}
/**
* @brief horner
* @param d
* @param remainder
* @return
*/
Polynomial horner(float d, float &remainder)
{
int nCoeff = coeff.size();
Polynomial p(nCoeff - 1);
p.coeff[nCoeff - 2] = coeff[nCoeff - 1];
for(int i = (nCoeff - 3); i >= 0 ; i--) {
p.coeff[i] = (p.coeff[i + 1] * d + coeff[i + 1]);
}
p.computeAllCoeffPositive();
remainder = coeff[0] + p.coeff[0] * d;
return p;
}
/**
* @brief getRoots
* @param x
* @return
*/
bool getRoots(float *x)
{
int nCoeff = coeff.size();
if(nCoeff < 2) {
return false;
}
if(nCoeff == 2) {
//this coefficient may be not positive
if(coeff[1] > 0.0f) {
x[0] = -coeff[0] / coeff[1];
return true;
} else {
return false;
}
}
if(nCoeff == 3) {
//these coefficients may be not positive
return getSecondOrderRoots(coeff[2], coeff[1], coeff[0], &x[0], &x[1]);
}
if(all_coeff_positive) {
return false;
}
float max_coeff0 = -1.0f;
for(int i = 1; i < coeff.size(); i++) {
float tmp = fabsf(coeff[i]);
if(tmp > max_coeff0) {
max_coeff0 = tmp;
}
}
float tmp = fabsf(coeff[0]);
float max_coeff;
if(max_coeff0 < tmp) {
max_coeff = tmp;
} else {
max_coeff = max_coeff0;
}
float lower_bound = fabsf(coeff[0]) / (fabsf(coeff[0]) + max_coeff0);
#ifdef PIC_DEBUG
float upper_bound = 1.0f + max_coeff / fabsf(coeff[0]);
printf("Upper bound: %f\n", upper_bound);
printf("Lower bound: %f\n", lower_bound);
#endif
float x_p = lower_bound;
float x_n;
bool notConverged = true;
int counter = 0;
float E_x_p;
while(notConverged) {
E_x_p = eval(x_p);
x_n = x_p - E_x_p / dEval(x_p);
x_p = x_n;
counter++;
notConverged = (fabsf(E_x_p) > 1e-4f) && (counter < 200);
}
if(counter == 200) {
return false;
} else {
*x = x_n;
return true;
}
}
/**
* @brief getAllRoots
* @param x
* @return
*/
bool getAllRoots(float *x)
{
for(int i = 0; i < coeff.size() - 1; i++) {
x[i] = FLT_MAX;
}
bool bOut = getRoots(&x[0]);
if(!bOut) {
return false;
}
float r;
Polynomial p = horner(x[0], r);
p.normalForm();
int nCoeff = coeff.size();
for(int i = 1; i < (nCoeff - 2); i++) {
p.print();
bool bOut = p.getRoots(&x[i]);
if(!bOut) {
return true;
}
p = p.horner(x[i], r);
p.normalForm();
}
return true;
}
/**
* @brief getQuarticRoots --> MANDATORY p[0] == 1.0
* @param p
* @param x
* @return
*/
static bool getQuarticRoots(float *p, float *x)
{
#ifndef PIC_DISABLE_EIGEN
Eigen::Matrix4f m;
m << -p[1], -p[2], -p[3], -p[4],
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f;
Eigen::EigenSolver<Eigen::Matrix4f> es(m);
Eigen::Vector4cf e = es.eigenvalues();
bool bOut = false;
if(fabsf(e(0).imag()) < 1e-6f) {
x[0] = e(0).real();
bOut = true;
}
if(fabsf(e(1).imag()) < 1e-6f) {
x[1] = e(1).real();
bOut = true;
}
if(fabsf(e(2).imag()) < 1e-6f) {
x[2] = e(2).real();
bOut = true;
}
if(fabsf(e(3).imag()) < 1e-6f) {
x[3] = e(3).real();
bOut = true;
}
return bOut;
#else
return true;
#endif
}
//Solver for second order equations, ax^2 + b x + c = 0
static bool getSecondOrderRoots(float a, float b, float c, float *x0, float *x1)
{
float delta = b * b - 4.0f * a * c;
if(delta >= 0.0f) {
float dnum = 2.0f * a;
delta = sqrtf(delta);
*x0 = (-b + delta) / dnum;
*x1 = (-b - delta) / dnum;
return true;
} else {
return false;
}
}
//Solver for second order equations, ax^2 + b x + c = 0, when b is even
static bool getSecondOrderRootsS(float a, float b, float c, float *x0, float *x1)
{
float delta = b * b - a * c;
if(delta >= 0.0f) {
delta = sqrtf(delta);
*x0 = (-b + delta) / a;
*x1 = (-b - delta) / a;
return true;
} else {
return false;
}
}
};
} // end namespace pic
#endif //PIC_UTIL_coeffNOMIAL_HPP
<commit_msg>Update include/util/polynomial.hpp<commit_after>/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_UTIL_coeffNOMIAL_HPP
#define PIC_UTIL_coeffNOMIAL_HPP
#include <vector>
#include "../base.hpp"
#ifndef PIC_DISABLE_EIGEN
#ifndef PIC_EIGEN_NOT_BUNDLED
#include "../externals/Eigen/QR"
#include "../externals/Eigen/Eigenvalues"
#else
#include <Eigen/QR>
#endif
#endif
namespace pic {
class Polynomial
{
public:
std::vector<float> coeff;
bool all_coeff_positive;
/**
* @brief Polynomial
*/
Polynomial()
{
all_coeff_positive = true;
}
/**
* @brief Polynomial
* @param nCoeff
*/
Polynomial(int nCoeff)
{
for(int i = 0; i < nCoeff; i++) {
coeff.push_back(0.0f);
}
all_coeff_positive = true;
}
/**
* @brief coeffnomial
* @param coeff
* @param nCoeff
*/
Polynomial(float *coeff, int nCoeff)
{
if(nCoeff < 1 || coeff == NULL) {
return;
}
this->coeff.assign(coeff, coeff + nCoeff);
computeAllCoeffPositive();
}
~Polynomial()
{
}
/**
* @brief computeAllCoeffPositive
*/
void computeAllCoeffPositive()
{
int counter = 0;
for (const float &c : coeff) {
if(c < 0.0f) {
counter++;
}
}
all_coeff_positive = counter < 1;
}
/**
* @brief print
*/
void print()
{
printf("%s\n", toString().c_str());
}
std::string toString()
{
std::string ret = "";
if(coeff.empty()) {
return ret;
}
int nCoeff = coeff.size();
if(nCoeff > 1) {
std::string sep = "+ ";
if(coeff[1] < 0.0f) {
sep = " ";
}
ret = fromNumberToString(coeff[0]) + sep;
for(int i = 1; i < (nCoeff - 1); i++) {
if(coeff[i + 1] > 0.0f) {
sep = "+ ";
} else {
sep = " ";
}
ret += fromNumberToString(coeff[i]) + " * x^" + fromNumberToString(i) + sep;
}
ret += fromNumberToString(coeff[nCoeff - 1]) + " * x^" + fromNumberToString(nCoeff - 1);
} else {
ret = fromNumberToString(coeff[0]);
}
return ret;
}
/**
* @brief getArray
* @return
*/
float *getArray(float *ret)
{
if(ret == NULL) {
ret = new float[coeff.size()];
}
for(int i = 0; i < coeff.size(); i++) {
ret[i] = coeff[i];
}
return ret;
}
/**
* @brief eval
* @param x
* @return
*/
float eval(float x)
{
float val = 0.f;
float M = 1.f;
for (const float &c : coeff) {
val += c * M;
M *= x;
}
return val;
}
/**
* @brief dEval
* @param t
* @return
*/
float dEval(float x)
{
int nCoeff = coeff.size();
if(nCoeff < 2) {
return 0.0f;
}
float ret = coeff[nCoeff - 1] * float(nCoeff - 1);
for(int i = (nCoeff - 2); i > 0 ; i--) {
ret = (ret * x) + coeff[i] * float(i);
}
return ret;
}
/**
* @brief fit
* @param x
* @param y
* @param n
*/
void fit(std::vector<float> &x, std::vector<float> &y, int n)
{
#ifndef PIC_DISABLE_EIGEN
if(n < 1 || (x.size() != y.size())) {
return;
}
coeff.clear();
int np1 = n + 1;
int s = int(x.size());
Eigen::MatrixXf A(s, np1);
Eigen::VectorXf b(s);
for(int i = 0; i < s; i++) {
b(i) = y[i];
A(i, n) = 1.0f;
}
for(int j = (n - 1); j >= 0; j--) {
for(int i = 0; i < s; i++) {
A(i, j) = x[i] * A(i, j + 1);
}
}
Eigen::VectorXf _x = A.colPivHouseholderQr().solve(b);
for(int i = n; i >= 0; i--) {
coeff.push_back(_x(i));
}
#endif
}
/**
* @brief normalForm
*/
void normalForm()
{
int last = coeff.size() - 1;
if(fabsf(coeff[last]) > 0.0f) {
for(int i = 0; i < last; i++) {
coeff[i] /= coeff[last];
}
coeff[last] = 1.0f;
}
}
/**
* @brief horner
* @param d
* @param remainder
* @return
*/
Polynomial horner(float d, float &remainder)
{
int nCoeff = coeff.size();
Polynomial p(nCoeff - 1);
p.coeff[nCoeff - 2] = coeff[nCoeff - 1];
for(int i = (nCoeff - 3); i >= 0 ; i--) {
p.coeff[i] = (p.coeff[i + 1] * d + coeff[i + 1]);
}
p.computeAllCoeffPositive();
remainder = coeff[0] + p.coeff[0] * d;
return p;
}
/**
* @brief getRoots
* @param x
* @return
*/
bool getRoots(float *x)
{
int nCoeff = coeff.size();
if(nCoeff < 2) {
return false;
}
if(nCoeff == 2) {
//this coefficient may be not positive
if(coeff[1] > 0.0f) {
x[0] = -coeff[0] / coeff[1];
return true;
} else {
return false;
}
}
if(nCoeff == 3) {
//these coefficients may be not positive
return getSecondOrderRoots(coeff[2], coeff[1], coeff[0], &x[0], &x[1]);
}
if(all_coeff_positive) {
return false;
}
float max_coeff0 = -1.0f;
for(int i = 1; i < coeff.size(); i++) {
float tmp = fabsf(coeff[i]);
if(tmp > max_coeff0) {
max_coeff0 = tmp;
}
}
float tmp = fabsf(coeff[0]);
float max_coeff;
if(max_coeff0 < tmp) {
max_coeff = tmp;
} else {
max_coeff = max_coeff0;
}
float lower_bound = fabsf(coeff[0]) / (fabsf(coeff[0]) + max_coeff0);
#ifdef PIC_DEBUG
float upper_bound = 1.0f + max_coeff / fabsf(coeff[0]);
printf("Upper bound: %f\n", upper_bound);
printf("Lower bound: %f\n", lower_bound);
#endif
float x_p = lower_bound;
float x_n;
bool notConverged = true;
int counter = 0;
float E_x_p;
while(notConverged) {
E_x_p = eval(x_p);
x_n = x_p - E_x_p / dEval(x_p);
x_p = x_n;
counter++;
notConverged = (fabsf(E_x_p) > 1e-4f) && (counter < 200);
}
if(counter == 200) {
return false;
} else {
*x = x_n;
return true;
}
}
/**
* @brief getAllRoots
* @param x
* @return
*/
bool getAllRoots(float *x)
{
for(int i = 0; i < coeff.size() - 1; i++) {
x[i] = FLT_MAX;
}
bool bOut = getRoots(&x[0]);
if(!bOut) {
return false;
}
float r;
Polynomial p = horner(x[0], r);
p.normalForm();
int nCoeff = coeff.size();
for(int i = 1; i < (nCoeff - 2); i++) {
bool bOut = p.getRoots(&x[i]);
if(!bOut) {
return true;
}
p = p.horner(x[i], r);
p.normalForm();
}
return true;
}
/**
* @brief getQuarticRoots --> MANDATORY p[5] == 1.0
* @param p
* @param x
* @return
*/
static bool getQuarticRoots(float *p, float *x)
{
#ifndef PIC_DISABLE_EIGEN
Eigen::Matrix4f m;
m << -p[3], -p[2], -p[1], -p[0],
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f;
Eigen::EigenSolver<Eigen::Matrix4f> es(m);
Eigen::Vector4cf e = es.eigenvalues();
bool bOut = false;
if(fabsf(e(0).imag()) < 1e-6f) {
x[0] = e(0).real();
bOut = true;
}
if(fabsf(e(1).imag()) < 1e-6f) {
x[1] = e(1).real();
bOut = true;
}
if(fabsf(e(2).imag()) < 1e-6f) {
x[2] = e(2).real();
bOut = true;
}
if(fabsf(e(3).imag()) < 1e-6f) {
x[3] = e(3).real();
bOut = true;
}
return bOut;
#else
return true;
#endif
}
//Solver for second order equations, ax^2 + b x + c = 0
static bool getSecondOrderRoots(float a, float b, float c, float *x0, float *x1)
{
float delta = b * b - 4.0f * a * c;
if(delta >= 0.0f) {
float dnum = 2.0f * a;
delta = sqrtf(delta);
*x0 = (-b + delta) / dnum;
*x1 = (-b - delta) / dnum;
return true;
} else {
return false;
}
}
//Solver for second order equations, ax^2 + b x + c = 0, when b is even
static bool getSecondOrderRootsS(float a, float b, float c, float *x0, float *x1)
{
float delta = b * b - a * c;
if(delta >= 0.0f) {
delta = sqrtf(delta);
*x0 = (-b + delta) / a;
*x1 = (-b - delta) / a;
return true;
} else {
return false;
}
}
};
} // end namespace pic
#endif //PIC_UTIL_coeffNOMIAL_HPP
<|endoftext|>
|
<commit_before>// Copyright ***********************************************************
//
// File ecmdMain.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */
// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************
/**
@file ecmdMain.C
@brief Main Program entry point for ecmdDllClient Application
*/
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define ecmdMain_C
#include <stdio.h>
#include <string>
#include <ecmdClientCapi.H>
#include <ecmdInterpreter.H>
#include <ecmdReturnCodes.H>
#include <ecmdCommandUtils.H>
#include <ecmdSharedUtils.H>
#undef ecmdMain_C
int main (int argc, char *argv[])
{
uint32_t rc = 0;
std::string cmdsave;
char buf[200];
for (int i = 0; i < argc; i++) {
cmdsave += argv[i];
cmdsave += " ";
}
cmdsave += "\n";
if (getenv ("ECMD_DLL_FILE") == NULL) {
printf("ecmd - You must set ECMD_DLL_FILE in order to run the eCMD command line client\n");
rc = ECMD_INVALID_DLL_FILENAME;
} else {
/* Load the one specified by ECMD_DLL_FILE */
rc = ecmdLoadDll("");
}
if (rc == ECMD_SUCCESS) {
/* Check to see if we are using stdin to pass in multiple commands */
if (ecmdParseOption(&argc, &argv, "-stdin")) {
/* Grab any other args that may be there */
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/* There shouldn't be any more args when doing a -stdin */
if (argc > 1) {
ecmdOutputError("ecmd - Invalid args passed to ecmd in -stdin mode\n");
rc = ECMD_INVALID_ARGS;
} else {
std::vector< std::string > commands;
int c_argc;
char* c_argv[21]; ///< A limit of 20 tokens(args) per command
char* buffer = NULL;
int bufflen = 0;
int commlen;
/* ecmdParseStdInCommands reads from stdin and returns a vector of strings */
/* each string contains one command (ie 'ecmdquery version') */
/* When Ctrl-D or EOF is reached this function will fail to break out of loop */
while ((rc = ecmdParseStdinCommands(commands)) != ECMD_SUCCESS) {
rc = 0;
/* Walk through individual commands from ecmdParseStdInCommands */
for (std::vector< std::string >::iterator commit = commands.begin(); commit != commands.end(); commit ++) {
c_argc = 0;
/* Create a char buffer to hold the whole command, we will use this to create pointers to each token in the command (like argc,argv) */
commlen = commit->length();
if ( commlen > bufflen) {
if (buffer != NULL) delete[] buffer;
buffer = new char[commlen + 20];
bufflen = commlen + 19;
}
// Beam "error" of possible NULL 'buffer' value requires mutually
// exclusive conditions (need an argument present to enter
// "commands" FOR loop but commit->length = 0 ie. no command). So
// tell beam to ignore NULL pointer message for 'buffer' parm via
// comment on next line.
strcpy(buffer, commit->c_str()); /*passing null object*/
/* Now start carving this thing up */
bool lookingForStart = true; /* Are we looking for the start of a word ? */
for (int c = 0; c < commlen; c++) {
if (lookingForStart) {
if (buffer[c] != ' ' && buffer[c] != '\t') {
c_argv[c_argc++] = &buffer[c];
lookingForStart = false;
}
} else {
/* Looking for the end */
if (buffer[c] == ' ' || buffer[c] == '\t') {
buffer[c] = '\0';
lookingForStart = true;
}
}
if (c_argc > 20) {
ecmdOutputError("ecmd - Found a command with greater then 20 arguments, not supported\n");
rc = ECMD_INVALID_ARGS;
break;
}
}
/* We now want to call the command interpreter to handle what the user provided us */
if (!rc) rc = ecmdCallInterpreters(c_argc, c_argv);
if (rc == ECMD_INT_UNKNOWN_COMMAND) {
if (strlen(c_argv[0]) < 200)
sprintf(buf,"ecmd - Unknown Command specified '%s'\n", c_argv[0]);
else
sprintf(buf,"ecmd - Unknown Command specified \n");
ecmdOutputError(buf);
} else if (rc) {
std::string parse = ecmdGetErrorMsg(rc, false);
if (parse.length() > 0) {
/* Display the registered message right away BZ#160 */
ecmdOutput(parse.c_str());
}
parse = ecmdParseReturnCode(rc);
if (strlen(c_argv[0]) + parse.length() < 300)
sprintf(buf,"ecmd - '%s' returned with error code %X (%s)\n", c_argv[0], rc, parse.c_str());
else
sprintf(buf,"ecmd - Command returned with error code %X (%s)\n", rc, parse.c_str());
ecmdOutputError(buf);
break;
}
if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {
ecmdOutput((*commit + "\n").c_str());
}
} /* tokens loop */
if (rc) break;
}
if (buffer != NULL) delete[] buffer;
} /* invalid args if */
} else {
/* Standard command line command */
/* We now want to call the command interpreter to handle what the user provided us */
rc = ecmdCallInterpreters(argc - 1, argv + 1);
if (rc == ECMD_INT_UNKNOWN_COMMAND) {
if (strlen(argv[1]) < 200)
sprintf(buf,"ecmd - Unknown Command specified '%s'\n", argv[1]);
else
sprintf(buf,"ecmd - Unknown Command specified \n");
ecmdOutputError(buf);
} else if (rc) {
std::string parse = ecmdGetErrorMsg(rc, false);
if (parse.length() > 0) {
/* Display the registered message right away BZ#160 */
ecmdOutput(parse.c_str());
}
parse = ecmdParseReturnCode(rc);
if (strlen(argv[1]) + parse.length() < 300)
sprintf(buf,"ecmd - '%s' returned with error code %X (%s)\n", argv[1], rc, parse.c_str());
else
sprintf(buf,"ecmd - Command returned with error code %X (%s)\n", rc, parse.c_str());
ecmdOutputError(buf);
}
}
/* Move these outputs into the if !rc to fix BZ#224 - cje */
if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {
ecmdOutput(cmdsave.c_str());
}
ecmdUnloadDll();
}
exit(rc);
}
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- -------- ------------------------------
// CENGEL Initial Creation
// none STGC7449 04/18/05 prahl Clean up Beam messages.
//
// End Change Log *****************************************************
<commit_msg>Fixed segfault with no args<commit_after>// Copyright ***********************************************************
//
// File ecmdMain.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */
// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************
/**
@file ecmdMain.C
@brief Main Program entry point for ecmdDllClient Application
*/
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define ecmdMain_C
#include <stdio.h>
#include <string>
#include <ecmdClientCapi.H>
#include <ecmdInterpreter.H>
#include <ecmdReturnCodes.H>
#include <ecmdCommandUtils.H>
#include <ecmdSharedUtils.H>
#undef ecmdMain_C
int main (int argc, char *argv[])
{
uint32_t rc = 0;
std::string cmdsave;
char buf[200];
for (int i = 0; i < argc; i++) {
cmdsave += argv[i];
cmdsave += " ";
}
cmdsave += "\n";
if (getenv ("ECMD_DLL_FILE") == NULL) {
printf("ecmd - You must set ECMD_DLL_FILE in order to run the eCMD command line client\n");
rc = ECMD_INVALID_DLL_FILENAME;
} else {
/* Load the one specified by ECMD_DLL_FILE */
rc = ecmdLoadDll("");
}
if (rc == ECMD_SUCCESS) {
/* Check to see if we are using stdin to pass in multiple commands */
if (ecmdParseOption(&argc, &argv, "-stdin")) {
/* Grab any other args that may be there */
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/* There shouldn't be any more args when doing a -stdin */
if (argc > 1) {
ecmdOutputError("ecmd - Invalid args passed to ecmd in -stdin mode\n");
rc = ECMD_INVALID_ARGS;
} else {
std::vector< std::string > commands;
int c_argc;
char* c_argv[21]; ///< A limit of 20 tokens(args) per command
char* buffer = NULL;
int bufflen = 0;
int commlen;
/* ecmdParseStdInCommands reads from stdin and returns a vector of strings */
/* each string contains one command (ie 'ecmdquery version') */
/* When Ctrl-D or EOF is reached this function will fail to break out of loop */
while ((rc = ecmdParseStdinCommands(commands)) != ECMD_SUCCESS) {
rc = 0;
/* Walk through individual commands from ecmdParseStdInCommands */
for (std::vector< std::string >::iterator commit = commands.begin(); commit != commands.end(); commit ++) {
c_argc = 0;
/* Create a char buffer to hold the whole command, we will use this to create pointers to each token in the command (like argc,argv) */
commlen = commit->length();
if ( commlen > bufflen) {
if (buffer != NULL) delete[] buffer;
buffer = new char[commlen + 20];
bufflen = commlen + 19;
}
// Beam "error" of possible NULL 'buffer' value requires mutually
// exclusive conditions (need an argument present to enter
// "commands" FOR loop but commit->length = 0 ie. no command). So
// tell beam to ignore NULL pointer message for 'buffer' parm via
// comment on next line.
strcpy(buffer, commit->c_str()); /*passing null object*/
/* Now start carving this thing up */
bool lookingForStart = true; /* Are we looking for the start of a word ? */
for (int c = 0; c < commlen; c++) {
if (lookingForStart) {
if (buffer[c] != ' ' && buffer[c] != '\t') {
c_argv[c_argc++] = &buffer[c];
lookingForStart = false;
}
} else {
/* Looking for the end */
if (buffer[c] == ' ' || buffer[c] == '\t') {
buffer[c] = '\0';
lookingForStart = true;
}
}
if (c_argc > 20) {
ecmdOutputError("ecmd - Found a command with greater then 20 arguments, not supported\n");
rc = ECMD_INVALID_ARGS;
break;
}
}
/* We now want to call the command interpreter to handle what the user provided us */
if (!rc) rc = ecmdCallInterpreters(c_argc, c_argv);
if (rc == ECMD_INT_UNKNOWN_COMMAND) {
if (strlen(c_argv[0]) < 200)
sprintf(buf,"ecmd - Unknown Command specified '%s'\n", c_argv[0]);
else
sprintf(buf,"ecmd - Unknown Command specified \n");
ecmdOutputError(buf);
} else if (rc) {
std::string parse = ecmdGetErrorMsg(rc, false);
if (parse.length() > 0) {
/* Display the registered message right away BZ#160 */
ecmdOutput(parse.c_str());
}
parse = ecmdParseReturnCode(rc);
if (strlen(c_argv[0]) + parse.length() < 300)
sprintf(buf,"ecmd - '%s' returned with error code %X (%s)\n", c_argv[0], rc, parse.c_str());
else
sprintf(buf,"ecmd - Command returned with error code %X (%s)\n", rc, parse.c_str());
ecmdOutputError(buf);
break;
}
if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {
ecmdOutput((*commit + "\n").c_str());
}
} /* tokens loop */
if (rc) break;
}
if (buffer != NULL) delete[] buffer;
} /* invalid args if */
} else {
/* Standard command line command */
/* We now want to call the command interpreter to handle what the user provided us */
rc = ecmdCallInterpreters(argc - 1, argv + 1);
if (rc == ECMD_INT_UNKNOWN_COMMAND) {
if (argv[1] == NULL)
sprintf(buf,"ecmd - Must specify a command to execute\n");
else if (strlen(argv[1]) < 200)
sprintf(buf,"ecmd - Unknown Command specified '%s'\n", argv[1]);
else
sprintf(buf,"ecmd - Unknown Command specified \n");
ecmdOutputError(buf);
} else if (rc) {
std::string parse = ecmdGetErrorMsg(rc, false);
if (parse.length() > 0) {
/* Display the registered message right away BZ#160 */
ecmdOutput(parse.c_str());
}
parse = ecmdParseReturnCode(rc);
if (strlen(argv[1]) + parse.length() < 300)
sprintf(buf,"ecmd - '%s' returned with error code %X (%s)\n", argv[1], rc, parse.c_str());
else
sprintf(buf,"ecmd - Command returned with error code %X (%s)\n", rc, parse.c_str());
ecmdOutputError(buf);
}
}
/* Move these outputs into the if !rc to fix BZ#224 - cje */
if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {
ecmdOutput(cmdsave.c_str());
}
ecmdUnloadDll();
}
exit(rc);
}
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- -------- ------------------------------
// CENGEL Initial Creation
// none STGC7449 04/18/05 prahl Clean up Beam messages.
//
// End Change Log *****************************************************
<|endoftext|>
|
<commit_before>// DDCPP/standard/bits/DD_partial_sum.hpp
#ifndef DD_PARTIAL_SUM_INCLUDED_
# define DD_PARTIAL_SUM_INCLUDED_ 1
# include "DD_Iterator.hpp"
# include "DD_Range.hpp"
# include "DD_next.hpp"
DD_DETAIL_BEGIN_
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_>
UndirectionalIteratorT2_ partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT2_ result_begin__
) {
if (begin__ != end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__; ++result_begin__) {
*::DD::next(result_begin__) = *result_begin__ + *begin__;
}
}
return result_begin__;
}
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_>
Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_> partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT1_ result_begin__,
UndirectionalIteratorT1_ result_end__
) {
if (begin__ != end__ && result_begin__ != result_end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__ && ::DD::next(result_end__) != end__; ++result_begin__) {
*::DD::next(result_begin__) = *result_begin__ + *begin__;
}
}
return Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_>(begin__, result_begin__);
}
DD_DETAIL_END_
DD_BEGIN_
using detail_::partial_sum;
DD_END_
#endif
<commit_msg>Add more overloaded version for 'DD::partial_sum'<commit_after>// DDCPP/standard/bits/DD_partial_sum.hpp
#ifndef DD_PARTIAL_SUM_INCLUDED_
# define DD_PARTIAL_SUM_INCLUDED_ 1
# include "DD_Iterator.hpp"
# include "DD_Range.hpp"
# include "DD_next.hpp"
DD_DETAIL_BEGIN_
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_>
UndirectionalIteratorT2_ partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT2_ result_begin__
) {
if (begin__ != end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__; ++result_begin__) {
*::DD::next(result_begin__) = *result_begin__ + *begin__;
}
}
return result_begin__;
}
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_, typename BinaryFunctionT_>
UndirectionalIteratorT2_ partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT2_ result_begin__,
BinaryFunctionT_ add__
) {
if (begin__ != end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__; ++result_begin__) {
*::DD::next(result_begin__) = add__(*result_begin__, *begin__);
}
}
return result_begin__;
}
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_>
Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_> partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT1_ result_begin__,
UndirectionalIteratorT1_ result_end__
) {
if (begin__ != end__ && result_begin__ != result_end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__ && ::DD::next(result_end__) != end__; ++result_begin__) {
*::DD::next(result_begin__) = *result_begin__ + *begin__;
}
}
return Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_>(begin__, result_begin__);
}
template <typename UndirectionalIteratorT1_, typename UndirectionalIteratorT2_, typename BinaryFunctionT_>
Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_> partial_sum(
UndirectionalIteratorT1_ begin__,
UndirectionalIteratorT1_ end__,
UndirectionalIteratorT1_ result_begin__,
UndirectionalIteratorT1_ result_end__,
BinaryFunctionT_ add__
) {
if (begin__ != end__ && result_begin__ != result_end__) {
*result_begin__ = *begin__;
for (; ++begin__ != end__ && ::DD::next(result_end__) != end__; ++result_begin__) {
*::DD::next(result_begin__) = add__(*result_begin__, *begin__);
}
}
return Pair<UndirectionalIteratorT1_, UndirectionalIteratorT2_>(begin__, result_begin__);
}
template <typename UndirectionalRangeT1_, typename UndirectionalRangeT2_>
inline Pair<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT1_), DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT2_)> partial_sum(
UndirectionalRangeT1_& range__,
UndirectionalRangeT1_& result_range__
) DD_NOEXCEPT_AS(static_cast<Pair<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT1_) DD_COMMA DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT2_)>>(
::DD::detail_::partial_sum(DD_SPLIT_RANGE(range__) DD_COMMA DD_SPLIT_RANGE(result_range__))
)) {
return ::DD::detail_::partial_sum(DD_SPLIT_RANGE(range__), DD_SPLIT_RANGE(result_range__));
}
template <typename UndirectionalRangeT1_, typename UndirectionalRangeT2_, typename BinaryFunctionT_>
inline Pair<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT1_), DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT2_)> partial_sum(
UndirectionalRangeT1_& range__,
UndirectionalRangeT1_& result_range__,
BinaryFunctionT_ add__
) DD_NOEXCEPT_AS(static_cast<Pair<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT1_) DD_COMMA DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT2_)>>(
::DD::detail_::partial_sum(DD_SPLIT_RANGE(range__) DD_COMMA DD_SPLIT_RANGE(result_range__) DD_COMMA add__)
)) {
return ::DD::detail_::partial_sum(DD_SPLIT_RANGE(range__), DD_SPLIT_RANGE(result_range__), add__);
}
DD_DETAIL_END_
DD_BEGIN_
using detail_::partial_sum;
DD_END_
#endif
<|endoftext|>
|
<commit_before>#include "vast/util/command_line.h"
namespace vast {
namespace util {
bool command_line::mode_add(std::string name,
std::string desc,
std::string prompt,
std::string history_file)
{
if (modes_.count(name))
return false;
auto m = std::make_shared<mode>(
std::move(name), std::move(desc),
std::move(prompt), std::move(history_file));
modes_.emplace(m->name, m);
return true;
}
bool command_line::mode_rm(std::string const& name)
{
if (! modes_.count(name))
return false;
modes_.erase(name);
return true;
}
bool command_line::mode_push(std::string const& mode)
{
if (! modes_.count(mode))
return false;
mode_stack_.push_back(modes_[mode]);
return true;
}
bool command_line::mode_pop()
{
if (mode_stack_.empty())
return false;
mode_stack_.pop_back();
return true;
}
bool command_line::cmd_add(std::string const& mode, std::string cmd, callback f)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
if (m.callbacks.count(cmd))
return false;
m.el.complete(cmd);
m.callbacks.emplace(std::move(cmd), std::move(f));
return true;
}
bool command_line::cmd_rm(std::string const& mode, std::string const& cmd)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
if (! m.callbacks.count(cmd))
return false;
m.callbacks.erase(cmd);
return true;
}
bool command_line::on_unknown_command(std::string const& mode, callback f)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
m.unknown_command = f;
return true;
}
bool command_line::append_to_history(std::string const& entry)
{
if (mode_stack_.empty())
return false;
mode_stack_.back()->hist.enter(entry);
mode_stack_.back()->hist.save();
return true;
}
bool command_line::process(bool& callback_result)
{
if (mode_stack_.empty())
return false;
auto current = mode_stack_.back();
current->el.reset(); // Fixes TTY weirdness when switching between modes.
std::string cmd;
if (! current->el.get(cmd))
return false;
// Trim string.
auto first_non_ws = cmd.find_first_not_of(" \t");
auto last_non_ws = cmd.find_last_not_of(" \t");
if (first_non_ws != std::string::npos)
cmd = cmd.substr(first_non_ws, last_non_ws - first_non_ws + 1);
auto space = cmd.find(' ');
auto key = cmd.substr(0, space);
if (! current->callbacks.count(key))
{
if (! current->unknown_command)
return false;
callback_result = current->unknown_command(std::move(cmd));
return true;
}
auto args = space == std::string::npos ? cmd : cmd.substr(++space);
callback_result = current->callbacks[key](std::move(args));
current->hist.enter(cmd);
current->hist.save();
return true;
}
bool command_line::get(char& c)
{
return mode_stack_.empty() ? false : mode_stack_.back()->el.get(c);
}
command_line::mode::mode(std::string name,
std::string desc,
std::string prompt,
std::string filename)
: name{std::move(name)},
description{std::move(desc)},
hist{1000, true, std::move(filename)}
{
el.source();
el.set(hist);
if (! prompt.empty())
el.set(editline::prompt{std::move(prompt)});
}
} // namespace util
} // namespace vast
<commit_msg>Add extra space after completion.<commit_after>#include "vast/util/command_line.h"
namespace vast {
namespace util {
bool command_line::mode_add(std::string name,
std::string desc,
std::string prompt,
std::string history_file)
{
if (modes_.count(name))
return false;
auto m = std::make_shared<mode>(
std::move(name), std::move(desc),
std::move(prompt), std::move(history_file));
modes_.emplace(m->name, m);
return true;
}
bool command_line::mode_rm(std::string const& name)
{
if (! modes_.count(name))
return false;
modes_.erase(name);
return true;
}
bool command_line::mode_push(std::string const& mode)
{
if (! modes_.count(mode))
return false;
mode_stack_.push_back(modes_[mode]);
return true;
}
bool command_line::mode_pop()
{
if (mode_stack_.empty())
return false;
mode_stack_.pop_back();
return true;
}
bool command_line::cmd_add(std::string const& mode, std::string cmd, callback f)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
if (m.callbacks.count(cmd))
return false;
m.el.complete(cmd + ' ');
m.callbacks.emplace(std::move(cmd), std::move(f));
return true;
}
bool command_line::cmd_rm(std::string const& mode, std::string const& cmd)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
if (! m.callbacks.count(cmd))
return false;
m.callbacks.erase(cmd);
return true;
}
bool command_line::on_unknown_command(std::string const& mode, callback f)
{
if (! modes_.count(mode))
return false;
auto& m = *modes_[mode];
m.unknown_command = f;
return true;
}
bool command_line::append_to_history(std::string const& entry)
{
if (mode_stack_.empty())
return false;
mode_stack_.back()->hist.enter(entry);
mode_stack_.back()->hist.save();
return true;
}
bool command_line::process(bool& callback_result)
{
if (mode_stack_.empty())
return false;
auto current = mode_stack_.back();
current->el.reset(); // Fixes TTY weirdness when switching between modes.
std::string cmd;
if (! current->el.get(cmd))
return false;
// Trim string.
auto first_non_ws = cmd.find_first_not_of(" \t");
auto last_non_ws = cmd.find_last_not_of(" \t");
if (first_non_ws != std::string::npos)
cmd = cmd.substr(first_non_ws, last_non_ws - first_non_ws + 1);
auto space = cmd.find(' ');
auto key = cmd.substr(0, space);
if (! current->callbacks.count(key))
{
if (! current->unknown_command)
return false;
callback_result = current->unknown_command(std::move(cmd));
return true;
}
auto args = space == std::string::npos ? cmd : cmd.substr(++space);
callback_result = current->callbacks[key](std::move(args));
current->hist.enter(cmd);
current->hist.save();
return true;
}
bool command_line::get(char& c)
{
return mode_stack_.empty() ? false : mode_stack_.back()->el.get(c);
}
command_line::mode::mode(std::string name,
std::string desc,
std::string prompt,
std::string filename)
: name{std::move(name)},
description{std::move(desc)},
hist{1000, true, std::move(filename)}
{
el.source();
el.set(hist);
if (! prompt.empty())
el.set(editline::prompt{std::move(prompt)});
}
} // namespace util
} // namespace vast
<|endoftext|>
|
<commit_before>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++98-compat"
#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#endif // CLANG
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
struct Single {
using ParentTypes = std::tuple<>;
};
template<typename T>
struct Service;
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
namespace detail {
enum class enabler {};
template <bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
template<int ...>
struct seq { };
template<int N, int ...S>
struct seq_gen : seq_gen<N-1, N-1, S...> { };
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
struct Holder {};
template<typename T>
struct InstanceHolder final : Holder {
explicit InstanceHolder(std::shared_ptr<T> instance) : _instance{std::move(instance)} {}
std::shared_ptr<T> getInstance() const {
return _instance;
}
private:
std::shared_ptr<T> _instance;
};
template<typename T, typename... Args>
struct CallbackHolder final : Holder {
using callback_t = std::function<std::shared_ptr<T>(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{std::move(callback)} {}
std::shared_ptr<T> operator ()(Args... args) {
return _callback(args...);
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
template <typename T> void type_id() {}
using type_id_fn = void(*)();
} // namespace detail
struct Container : std::enable_shared_from_this<Container> {
private:
template<typename Condition, typename T = detail::enabler> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = detail::enabler> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template <typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using holder_cont = std::unordered_map<detail::type_id_fn, holder_ptr>;
constexpr static detail::enabler null = {};
public:
Container() = default;
Container(const Container &) = default;
Container(Container &&) = default;
Container& operator =(const Container &) = default;
Container& operator =(Container &&) = default;
~Container() = default;
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(std::move(service), tuple_seq<parent_types<T>>{});
}
template<typename T>
void instance() {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>());
}
template<typename T, disable_if<is_abstract<T>> = null, disable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return get_service<T>();
}
template<typename T, enable_if<is_container<T>> = null>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>> = null, enable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>> = null>
std::shared_ptr<T> service() {
auto it = _services.find(&detail::template type_id<T>);
if (it != _services.end()) {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
save_callback<T, dependency_types<T>>(tuple_seq<dependency_types<T>>{}, callback);
}
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>> = null>
std::shared_ptr<T> get_service() {
auto it = _services.find(&detail::template type_id<T>);
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
} else {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, disable_if<is_service_single<T>> = null>
std::shared_ptr<T> get_service() {
return make_service<T>();
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(std::move(service));
}
template<typename Tuple, int ...S>
std::tuple<std::shared_ptr<tuple_element<S, Tuple>>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> callback_make_service(detail::seq<S...>, Tuple dependencies) const {
auto it = _callbacks.find(&detail::template type_id<T>);
if (it != _callbacks.end()) {
auto holder = static_cast<detail::CallbackHolder<T, tuple_element<S, Tuple>...>*>(it->second.get());
if (holder) {
return (*holder)(std::get<S>(dependencies)...);
}
}
return {};
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies);
if (service) {
return service;
}
return std::make_shared<T>(std::get<S>(dependencies)...);
}
template <typename T>
std::shared_ptr<T> make_service() {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service<T>(seq, dependency<dependency_types<T>>(seq));
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(std::move(service));
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[&detail::template type_id<T>] = detail::make_unique<detail::InstanceHolder<T>>(std::move(service));
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[&detail::template type_id<T>] = detail::make_unique<detail::CallbackHolder<T, std::shared_ptr<tuple_element<S, Tuple>>...>>(callback);
}
holder_cont _callbacks;
holder_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
auto container = std::make_shared<T>(std::forward<Args>(args)...);
container->init();
return container;
}
} // namespace kgr
#if defined(__clang__)
#pragma clang diagnostic pop
#endif // CLANG
<commit_msg>there's no need for the template disambiguator as detail is not a dependent name<commit_after>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++98-compat"
#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#endif // CLANG
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
struct Single {
using ParentTypes = std::tuple<>;
};
template<typename T>
struct Service;
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
namespace detail {
enum class enabler {};
template <bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
template<int ...>
struct seq { };
template<int N, int ...S>
struct seq_gen : seq_gen<N-1, N-1, S...> { };
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
struct Holder {};
template<typename T>
struct InstanceHolder final : Holder {
explicit InstanceHolder(std::shared_ptr<T> instance) : _instance{std::move(instance)} {}
std::shared_ptr<T> getInstance() const {
return _instance;
}
private:
std::shared_ptr<T> _instance;
};
template<typename T, typename... Args>
struct CallbackHolder final : Holder {
using callback_t = std::function<std::shared_ptr<T>(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{std::move(callback)} {}
std::shared_ptr<T> operator ()(Args... args) {
return _callback(args...);
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
template <typename T> void type_id() {}
using type_id_fn = void(*)();
} // namespace detail
struct Container : std::enable_shared_from_this<Container> {
private:
template<typename Condition, typename T = detail::enabler> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = detail::enabler> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template <typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using holder_cont = std::unordered_map<detail::type_id_fn, holder_ptr>;
constexpr static detail::enabler null = {};
public:
Container() = default;
Container(const Container &) = default;
Container(Container &&) = default;
Container& operator =(const Container &) = default;
Container& operator =(Container &&) = default;
~Container() = default;
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(std::move(service), tuple_seq<parent_types<T>>{});
}
template<typename T>
void instance() {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>());
}
template<typename T, disable_if<is_abstract<T>> = null, disable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return get_service<T>();
}
template<typename T, enable_if<is_container<T>> = null>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>> = null, enable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>> = null>
std::shared_ptr<T> service() {
auto it = _services.find(&detail::type_id<T>);
if (it != _services.end()) {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
save_callback<T, dependency_types<T>>(tuple_seq<dependency_types<T>>{}, callback);
}
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>> = null>
std::shared_ptr<T> get_service() {
auto it = _services.find(&detail::type_id<T>);
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
} else {
auto holder = static_cast<detail::InstanceHolder<T>*>(it->second.get());
if (holder) {
return holder->getInstance();
}
}
return {};
}
template<typename T, disable_if<is_service_single<T>> = null>
std::shared_ptr<T> get_service() {
return make_service<T>();
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(std::move(service));
}
template<typename Tuple, int ...S>
std::tuple<std::shared_ptr<tuple_element<S, Tuple>>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> callback_make_service(detail::seq<S...>, Tuple dependencies) const {
auto it = _callbacks.find(&detail::type_id<T>);
if (it != _callbacks.end()) {
auto holder = static_cast<detail::CallbackHolder<T, tuple_element<S, Tuple>...>*>(it->second.get());
if (holder) {
return (*holder)(std::get<S>(dependencies)...);
}
}
return {};
}
template<typename T, typename Tuple, int ...S>
std::shared_ptr<T> make_service(detail::seq<S...> seq, Tuple dependencies) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies);
if (service) {
return service;
}
return std::make_shared<T>(std::get<S>(dependencies)...);
}
template <typename T>
std::shared_ptr<T> make_service() {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service<T>(seq, dependency<dependency_types<T>>(seq));
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(std::move(service));
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[&detail::type_id<T>] = detail::make_unique<detail::InstanceHolder<T>>(std::move(service));
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[&detail::type_id<T>] = detail::make_unique<detail::CallbackHolder<T, std::shared_ptr<tuple_element<S, Tuple>>...>>(callback);
}
holder_cont _callbacks;
holder_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
auto container = std::make_shared<T>(std::forward<Args>(args)...);
container->init();
return container;
}
} // namespace kgr
#if defined(__clang__)
#pragma clang diagnostic pop
#endif // CLANG
<|endoftext|>
|
<commit_before>/*
* Copyright 2018 Google, Inc.
*
* 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 holders 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.
*
* Authors: Gabe Black
*/
#ifndef __SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
#define __SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
#include <iostream>
#include <string>
#include <vector>
#include "../core/sc_module.hh" // for sc_gen_unique_name
#include "../core/sc_prim.hh"
#include "sc_signal_inout_if.hh"
#include "warn_unimpl.hh" // for warn_unimpl
namespace sc_core
{
class sc_port_base;
class sc_trace_file;
// Nonstandard
// Despite having a warning "FOR INTERNAL USE ONLY!" in all caps above this
// class definition in the Accellera implementation, it appears in their
// examples and test programs, and so we need to have it here as well.
struct sc_trace_params
{
sc_trace_file *tf;
std::string name;
sc_trace_params(sc_trace_file *tf, const std::string &name) :
tf(tf), name(name)
{}
};
typedef std::vector<sc_trace_params *> sc_trace_params_vec;
template <class T, sc_writer_policy WRITER_POLICY=SC_ONE_WRITER>
class sc_signal : public sc_signal_inout_if<T>,
public sc_prim_channel
{
public:
sc_signal() : sc_signal_inout_if<T>(),
sc_prim_channel(sc_gen_unique_name("signal"))
{}
explicit sc_signal(const char *name) : sc_signal_inout_if<T>(),
sc_prim_channel(name)
{}
explicit sc_signal(const char *name, const T &initial_value) :
sc_signal_inout_if<T>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal() {}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const T&
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const T *)nullptr;
}
operator const T&() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const T *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const T&)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<T, WRITER_POLICY> &
operator = (const T&)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<T, WRITER_POLICY> &
operator = (const sc_signal<T, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
private:
// Disabled
sc_signal(const sc_signal<T, WRITER_POLICY> &) :
sc_signal_inout_if<T>(), sc_prim_channel("")
{}
};
template <class T, sc_writer_policy WRITER_POLICY>
inline std::ostream &
operator << (std::ostream &os, const sc_signal<T, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return os;
}
template <sc_writer_policy WRITER_POLICY>
class sc_signal<bool, WRITER_POLICY> :
public sc_signal_inout_if<bool>, public sc_prim_channel
{
public:
sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *name, const bool &initial_value) :
sc_signal_inout_if<bool>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const bool &
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const bool *)nullptr;
}
operator const bool &() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const bool *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const bool &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<bool, WRITER_POLICY> &
operator = (const bool &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<bool, WRITER_POLICY> &
operator = (const sc_signal<bool, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
posedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
negedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
posedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
negedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
private:
// Disabled
sc_signal(const sc_signal<bool, WRITER_POLICY> &) :
sc_signal_inout_if<bool>(), sc_prim_channel("")
{}
};
template <sc_writer_policy WRITER_POLICY>
class sc_signal<sc_dt::sc_logic, WRITER_POLICY> :
public sc_signal_inout_if<sc_dt::sc_logic>, public sc_prim_channel
{
public:
sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *name,
const sc_dt::sc_logic &initial_value) :
sc_signal_inout_if<sc_dt::sc_logic>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const sc_dt::sc_logic &
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const sc_dt::sc_logic *)nullptr;
}
operator const sc_dt::sc_logic &() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const sc_dt::sc_logic *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const sc_dt::sc_logic &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<sc_dt::sc_logic, WRITER_POLICY> &
operator = (const sc_dt::sc_logic &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<sc_dt::sc_logic, WRITER_POLICY> &
operator = (const sc_signal<sc_dt::sc_logic, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
posedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
negedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
posedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
negedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
private:
// Disabled
sc_signal(const sc_signal<sc_dt::sc_logic, WRITER_POLICY> &) :
sc_signal_inout_if<sc_dt::sc_logic>(), sc_prim_channel("")
{}
};
} // namespace sc_core
#endif //__SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
<commit_msg>systemc: Add m_cur_val and m_new_val to sc_signal.<commit_after>/*
* Copyright 2018 Google, Inc.
*
* 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 holders 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.
*
* Authors: Gabe Black
*/
#ifndef __SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
#define __SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
#include <iostream>
#include <string>
#include <vector>
#include "../core/sc_module.hh" // for sc_gen_unique_name
#include "../core/sc_prim.hh"
#include "sc_signal_inout_if.hh"
#include "warn_unimpl.hh" // for warn_unimpl
namespace sc_core
{
class sc_port_base;
class sc_trace_file;
// Nonstandard
// Despite having a warning "FOR INTERNAL USE ONLY!" in all caps above this
// class definition in the Accellera implementation, it appears in their
// examples and test programs, and so we need to have it here as well.
struct sc_trace_params
{
sc_trace_file *tf;
std::string name;
sc_trace_params(sc_trace_file *tf, const std::string &name) :
tf(tf), name(name)
{}
};
typedef std::vector<sc_trace_params *> sc_trace_params_vec;
template <class T, sc_writer_policy WRITER_POLICY=SC_ONE_WRITER>
class sc_signal : public sc_signal_inout_if<T>,
public sc_prim_channel
{
public:
sc_signal() : sc_signal_inout_if<T>(),
sc_prim_channel(sc_gen_unique_name("signal"))
{}
explicit sc_signal(const char *name) : sc_signal_inout_if<T>(),
sc_prim_channel(name)
{}
explicit sc_signal(const char *name, const T &initial_value) :
sc_signal_inout_if<T>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal() {}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const T&
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const T *)nullptr;
}
operator const T&() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const T *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const T&)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<T, WRITER_POLICY> &
operator = (const T&)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<T, WRITER_POLICY> &
operator = (const sc_signal<T, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
// These members which store the current and future value of the signal
// are not specified in the standard but are referred to directly by one
// of the tests.
T m_cur_val;
T m_new_val;
private:
// Disabled
sc_signal(const sc_signal<T, WRITER_POLICY> &) :
sc_signal_inout_if<T>(), sc_prim_channel("")
{}
};
template <class T, sc_writer_policy WRITER_POLICY>
inline std::ostream &
operator << (std::ostream &os, const sc_signal<T, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return os;
}
template <sc_writer_policy WRITER_POLICY>
class sc_signal<bool, WRITER_POLICY> :
public sc_signal_inout_if<bool>, public sc_prim_channel
{
public:
sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *name, const bool &initial_value) :
sc_signal_inout_if<bool>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const bool &
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const bool *)nullptr;
}
operator const bool &() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const bool *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const bool &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<bool, WRITER_POLICY> &
operator = (const bool &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<bool, WRITER_POLICY> &
operator = (const sc_signal<bool, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
posedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
negedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
posedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
negedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
private:
// Disabled
sc_signal(const sc_signal<bool, WRITER_POLICY> &) :
sc_signal_inout_if<bool>(), sc_prim_channel("")
{}
};
template <sc_writer_policy WRITER_POLICY>
class sc_signal<sc_dt::sc_logic, WRITER_POLICY> :
public sc_signal_inout_if<sc_dt::sc_logic>, public sc_prim_channel
{
public:
sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
explicit sc_signal(const char *name,
const sc_dt::sc_logic &initial_value) :
sc_signal_inout_if<sc_dt::sc_logic>(), sc_prim_channel(name)
{
// Need to consume initial_value.
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual ~sc_signal()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
register_port(sc_port_base &, const char *)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const sc_dt::sc_logic &
read() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const sc_dt::sc_logic *)nullptr;
}
operator const sc_dt::sc_logic &() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(const sc_dt::sc_logic *)nullptr;
}
virtual sc_writer_policy
get_writer_policy() const
{
return WRITER_POLICY;
}
virtual void
write(const sc_dt::sc_logic &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
sc_signal<sc_dt::sc_logic, WRITER_POLICY> &
operator = (const sc_dt::sc_logic &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
sc_signal<sc_dt::sc_logic, WRITER_POLICY> &
operator = (const sc_signal<sc_dt::sc_logic, WRITER_POLICY> &)
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *this;
}
virtual const sc_event &
default_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
value_changed_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
posedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual const sc_event &
negedge_event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return *(sc_event *)nullptr;
}
virtual bool
event() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
posedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual bool
negedge() const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
return false;
}
virtual void
print(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual void
dump(std::ostream & =std::cout) const
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
virtual const char *kind() const { return "sc_signal"; }
protected:
virtual void
update()
{
sc_channel_warn_unimpl(__PRETTY_FUNCTION__);
}
private:
// Disabled
sc_signal(const sc_signal<sc_dt::sc_logic, WRITER_POLICY> &) :
sc_signal_inout_if<sc_dt::sc_logic>(), sc_prim_channel("")
{}
};
} // namespace sc_core
#endif //__SYSTEMC_EXT_CHANNEL_SC_SIGNAL_HH__
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
namespace gcl::functional
{
template <class... Ts>
struct overload : Ts... {
using Ts::operator()...;
using bases_types = std::tuple<Ts...>; // allow operator() function_traits
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>; // not required in C++20, but Msvc need this deduction guide for some reasons ...
template <typename T>
decltype(auto) wrap(T&& func)
{ // wrap any functor into a deductible type/value
return [func](auto&&... args) -> decltype(auto) {
return std::invoke(func, std::forward<decltype(args)>(args)...);
};
}
}
#include <gcl/mp/function_traits.hpp>
namespace gcl::functional::type_traits
{
template <class>
struct is_overload : std::false_type {};
template <class... Ts>
struct is_overload<gcl::functional::overload<Ts...>> : std::true_type {};
template <class... Ts>
constexpr static auto is_overload_v = is_overload<Ts...>::value;
template <typename T>
struct overload_arguments;
template <typename ... Ts>
struct overload_arguments<gcl::functional::overload<Ts...>> {
// std::tuple<std::tuple<args1...>, std::tuple<args2...>, etc.>
using types = std::tuple<typename gcl::mp::function_traits_t<decltype(&Ts::operator())>::arguments...>;
// std::tuple<args1..., args2..., etc.>
using concatenated_types =
decltype(std::tuple_cat(typename gcl::mp::function_traits_t<decltype(&Ts::operator())>::arguments{}...));
};
template <typename T>
using overload_arguments_t = typename overload_arguments<T>::type;
}
#include <functional>
namespace gcl::functional::tests::type_traits
{
static_assert(gcl::functional::type_traits::is_overload_v<gcl::functional::overload<>>);
static_assert(not gcl::functional::type_traits::is_overload_v<std::function<void()>>);
}<commit_msg>[functional] add more tests<commit_after>#pragma once
#include <utility>
namespace gcl::functional
{
template <class... Ts>
struct overload : Ts... {
using Ts::operator()...;
using bases_types = std::tuple<Ts...>; // allow operator() function_traits
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>; // not required in C++20, but Msvc need this deduction guide for some reasons ...
template <typename T>
decltype(auto) wrap(T&& func)
{ // wrap any functor into a deductible type/value
return [func](auto&&... args) -> decltype(auto) {
return std::invoke(func, std::forward<decltype(args)>(args)...);
};
}
}
#include <gcl/mp/function_traits.hpp>
namespace gcl::functional::type_traits
{
template <class>
struct is_overload : std::false_type {};
template <class... Ts>
struct is_overload<gcl::functional::overload<Ts...>> : std::true_type {};
template <class... Ts>
constexpr static auto is_overload_v = is_overload<Ts...>::value;
template <typename T>
struct overload_arguments;
template <typename... Ts>
struct overload_arguments<gcl::functional::overload<Ts...>> {
using types = std::tuple<typename gcl::mp::function_traits_t<decltype(&Ts::operator())>::arguments...>;
using concatenated_types =
decltype(std::tuple_cat(typename gcl::mp::function_traits_t<decltype(&Ts::operator())>::arguments{}...));
};
template <typename T>
using overload_arguments_t = typename overload_arguments<T>::types;
template <typename T>
using overload_concatenated_arguments_t = typename overload_arguments<T>::concatenated_types;
}
#include <functional>
namespace gcl::functional::tests::type_traits
{
static_assert(gcl::functional::type_traits::is_overload_v<gcl::functional::overload<>>);
static_assert(not gcl::functional::type_traits::is_overload_v<std::function<void()>>);
using overload_type = decltype(gcl::functional::overload{[](int) {}, []() {}, [](char, double) {}});
using overload_type_arguments_t = gcl::functional::type_traits::overload_arguments_t<overload_type>;
static_assert(std::tuple_size_v<overload_type_arguments_t> == 3);
static_assert(std::is_same_v<std::tuple_element_t<0, overload_type_arguments_t>, std::tuple<int>>);
static_assert(std::is_same_v<std::tuple_element_t<1, overload_type_arguments_t>, std::tuple<>>);
static_assert(std::is_same_v<std::tuple_element_t<2, overload_type_arguments_t>, std::tuple<char, double>>);
using overload_type_concatenated_arguments_t =
gcl::functional::type_traits::overload_concatenated_arguments_t<overload_type>;
static_assert(std::tuple_size_v<overload_type_concatenated_arguments_t> == 3);
static_assert(std::is_same_v<std::tuple_element_t<0, overload_type_concatenated_arguments_t>, int>);
static_assert(std::is_same_v<std::tuple_element_t<1, overload_type_concatenated_arguments_t>, char>);
static_assert(std::is_same_v<std::tuple_element_t<2, overload_type_concatenated_arguments_t>, double>);
}<|endoftext|>
|
<commit_before>///
/// @file min_max.hpp
/// @brief In order to make the code more readable primecount allows
/// to use the min and max functions with different types
/// if both types are integral and type A >= type B.
///
/// int64_t a = 100;
/// int32_t b = 999;
///
/// primecount::max(a, b); // compiles
/// primecount::max(b, a); // does not compile
///
/// std::max(a, b); // does not compile
/// std::max(b, a); // does not compile
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef MIN_MAX_HPP
#define MIN_MAX_HPP
#if __cplusplus >= 201103L
#include <int128_t.hpp>
#include <algorithm>
#include <type_traits>
namespace primecount {
/// Check if A and B are:
/// 1) Same types
/// 2) Different integral types which satisfy:
/// sizeof(A) > sizeof(B) ||
/// (sizeof(A) == sizeof(B) && is_unsigned<A> && is_signed<B>)
///
template <typename A, typename B>
struct is_comparable
{
enum {
value = std::is_same<A, B>::value || ((
prt::is_integral<A>::value &&
prt::is_integral<B>::value) && (
sizeof(A) > sizeof(B) || (
sizeof(A) == sizeof(B) &&
std::is_unsigned<A>::value &&
std::is_signed<B>::value)))
};
};
/// Convenience min function for different types.
template <typename A, typename B>
inline B min(A a, B b)
{
static_assert(is_comparable<A, B>::value,
"min(A, B): Cannot compare types A and B");
return (B) std::min(a, (A) b);
}
/// Convenience min function for different types.
template <typename A, typename B>
inline B min3(A a, B b, B c)
{
static_assert(is_comparable<A, B>::value,
"min3(A, B, B): Cannot compare types A and B");
return (B) std::min(a, (A) std::min(b, c));
}
/// Convenience max function for different types.
template <typename A, typename B>
inline A max(A a, B b)
{
static_assert(is_comparable<A, B>::value,
"max(A, B): Cannot compare types A and B");
return std::max(a, (A) b);
}
/// Convenience max function for different types.
template <typename A, typename B>
inline A max3(A a, B b, B c)
{
static_assert(is_comparable<A, B>::value,
"max3(A, B, B): Cannot compare types A and B");
return std::max(a, (A) std::max(b, c));
}
} // namespace
#else /* C++98 */
#include <algorithm>
#include <cassert>
namespace primecount {
template <typename A, typename B>
inline B min(A a, B b)
{
assert(sizeof(A) >= sizeof(B));
return (B) std::min(a, (A) b);
}
template <typename A, typename B>
inline B min3(A a, B b, B c)
{
assert(sizeof(A) >= sizeof(B));
return (B) std::min(a, (A) std::min(b, c));
}
template <typename A, typename B>
inline A max(A a, B b)
{
assert(sizeof(A) >= sizeof(B));
return std::max(a, (A) b);
}
template <typename A, typename B>
inline A max3(A a, B b, B c)
{
assert(sizeof(A) >= sizeof(B));
return std::max(a, (A) std::max(b, c));
}
} // namespace
#endif
#endif // MIN_MAX_HPP
<commit_msg>Make C++11 only<commit_after>///
/// @file min_max.hpp
/// @brief Template min and max functions that allow comparing
/// different types if both types are integral
/// and sizeof(A) >= sizeof(B).
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef MIN_MAX_HPP
#define MIN_MAX_HPP
#include <int128_t.hpp>
#include <algorithm>
#include <type_traits>
namespace primecount {
/// Check if A and B are:
/// 1) Same types
/// 2) Different integral types which satisfy:
/// sizeof(A) > sizeof(B) ||
/// (sizeof(A) == sizeof(B) && is_unsigned<A> && is_signed<B>)
///
template <typename A, typename B>
struct is_comparable
{
enum {
value = std::is_same<A, B>::value || ((
prt::is_integral<A>::value &&
prt::is_integral<B>::value) && (
sizeof(A) > sizeof(B) || (
sizeof(A) == sizeof(B) &&
std::is_unsigned<A>::value &&
std::is_signed<B>::value)))
};
};
template <typename A, typename B>
inline B min(A a, B b)
{
static_assert(is_comparable<A, B>::value,
"min(A, B): Cannot compare types A and B");
return (B) std::min(a, (A) b);
}
template <typename A, typename B>
inline B min3(A a, B b, B c)
{
static_assert(is_comparable<A, B>::value,
"min3(A, B, B): Cannot compare types A and B");
return (B) std::min(a, (A) std::min(b, c));
}
template <typename A, typename B>
inline A max(A a, B b)
{
static_assert(is_comparable<A, B>::value,
"max(A, B): Cannot compare types A and B");
return std::max(a, (A) b);
}
template <typename A, typename B>
inline A max3(A a, B b, B c)
{
static_assert(is_comparable<A, B>::value,
"max3(A, B, B): Cannot compare types A and B");
return std::max(a, (A) std::max(b, c));
}
} // namespace
#endif
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2016 Xu Cheng
See licensing at:
https://opensource.org/licenses/MIT
*/
#pragma once
#include <exception>
#include <string>
#include "pbc-streamopen.hpp"
namespace pbc
{
namespace backend
{
#include <pbc/pbc.h>
};
class NotInitializedError : public std::runtime_error
{
public:
NotInitializedError() : runtime_error("Object is not initialized.") {}
};
class AlreadyInitializedError : public std::runtime_error
{
public:
AlreadyInitializedError()
: runtime_error("Object is already initialized.")
{
}
};
class InitializationError : public std::runtime_error
{
public:
InitializationError() : runtime_error("Failed to initialize object.") {}
InitializationError(const std::string& msg) : runtime_error(msg) {}
};
class ElementTypeError : public std::runtime_error
{
public:
ElementTypeError() : runtime_error("Element has wrong type.") {}
}
class Pairing;
class PairingParam;
class Element;
typedef std::shared_ptr<Pairing> PairingPtr;
typedef std::shared_ptr<PairingParam> PairingParamPtr;
typedef std::shared_ptr<Element> ElementPtr;
class PairingParam
{
public:
PairingParam() = default;
PairingParam(const PairingParam&) = delete;
~PairingParam() { backend::pbc_param_clear(_param); }
std::string to_str() const
{
std::stringstream buf;
backend::stream_fd_ptr sfd = backend::streamopen(buf);
backend::pbc_param_out_str(sfd->fd,
*(backend::pbc_param_t*)&_param);
backend::streamclose(sfd);
return buf.str();
}
static PairingParamPtr init_from_str(const std::string& param_str)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
if (backend::pbc_param_init_set_str(ptr->_param,
param_str.c_str()) != 0)
throw InitializationError(
"Failed to initialize pairing parameter.");
return ptr;
}
static PairingParamPtr gen_type_a(int rbits = 160, int qbits = 512)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_a_gen(ptr->_param, rbits, qbits);
return ptr;
}
static PairingParamPtr gen_type_i(int group_size = 696)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_i_gen(ptr->_param, group_size);
return ptr;
}
static PairingParamPtr gen_type_e(int rbits = 160, int qbits = 1024)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_e_gen(ptr->_param, rbits, qbits);
return ptr;
}
static PairingParamPtr gen_type_f(int bits = 160)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_f_gen(ptr->_param, bits);
return ptr;
}
private:
friend class Pairing;
backend::pbc_param_t _param;
};
class Pairing
{
public:
Pairing() = default;
Pairing(const Pairing&) = delete;
~Pairing() { pairing_clear(_pairing); }
static PairingPtr init_from_param_str(const std::string& param_str)
{
return Pairing::init_from_param(
PairingParam::init_from_str(param_str));
PairingPtr ptr = std::make_shared<Pairing>();
if (backend::pairing_init_set_str(ptr->_pairing,
param_str.c_str()) != 0)
throw InitializationError("Failed to initialize pairing.");
return ptr;
}
static PairingPtr init_from_param(const PairingParamPtr& param)
{
PairingPtr ptr = std::make_shared<Pairing>();
backend::pairing_init_pbc_param(ptr->_pairing, param->_param);
return ptr;
}
bool symmetric() const
{
return backend::pairing_is_symmetric(
*(backend::pairing_t*)&_pairing);
}
int g1_bytes_length() const
{
return backend::pairing_length_in_bytes_G1(
*(backend::pairing_t*)&_pairing);
}
int g1_x_only_bytes_length() const
{
return backend::pairing_length_in_bytes_x_only_G1(
*(backend::pairing_t*)&_pairing);
}
int g1_compressed_bytes_length() const
{
return backend::pairing_length_in_bytes_compressed_G1(
*(backend::pairing_t*)&_pairing);
}
int g2_bytes_length() const
{
return backend::pairing_length_in_bytes_G2(
*(backend::pairing_t*)&_pairing);
}
int g2_x_only_bytes_length() const
{
return backend::pairing_length_in_bytes_x_only_G2(
*(backend::pairing_t*)&_pairing);
}
int g2_compressed_bytes_length() const
{
return backend::pairing_length_in_bytes_compressed_G2(
*(backend::pairing_t*)&_pairing);
}
int gt_bytes_length() const
{
return backend::pairing_length_in_bytes_GT(
*(backend::pairing_t*)&_pairing);
}
int zr_bytes_length() const
{
return backend::pairing_length_in_bytes_Zr(
*(backend::pairing_t*)&_pairing);
}
private:
friend class Element;
backend::pairing_t _pairing;
};
enum class ElementType { G1, G2, GT, Zr, NotInitialized };
std::ostream& operator<<(std::ostream& o, ElementType type)
{
switch (type) {
case ElementType::G1: o << "G1"; break;
case ElementType::G2: o << "G2"; break;
case ElementType::GT: o << "GT"; break;
case ElementType::Zr: o << "Zr"; break;
case ElementType::NotInitialized: o << "NotInitialized"; break;
}
return o;
}
class Element
{
public:
Element() : _type(ElementType::NotInitialized) {}
Element(const Element& e) : _type(e._type)
{
if (_type != ElementType::NotInitialized) {
backend::element_init_same_as(
_element, *(backend::element_t*)&e._element);
backend::element_set(_element,
*(backend::element_t*)&e._element);
}
}
Element(Element&& e) noexcept : _type(e._type)
{
std::memcpy(&_element[0], &e._element[0],
sizeof(backend::element_t));
e._type = ElementType::NotInitialized;
}
~Element()
{
if (_type != ElementType::NotInitialized) {
backend::element_clear(_element);
_type = ElementType::NotInitialized;
}
}
#define Element_Init_Func(type, type_lowercase) \
void init_##type_lowercase(const PairingPtr pairing) \
{ \
if (_type != ElementType::NotInitialized) \
throw AlreadyInitializedError(); \
backend::element_init_##type(_element, pairing->_pairing); \
_type = ElementType::type; \
}
Element_Init_Func(G1, g1);
Element_Init_Func(G2, g2);
Element_Init_Func(GT, gt);
Element_Init_Func(Zr, zr);
#undef Element_Init_Func
void init_same_as(const Element& e)
{
if (_type != ElementType::NotInitialized)
throw AlreadyInitializedError();
if (e._type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_init_same_as(_element,
*(backend::element_t*)&e._element);
_type = e._type;
}
ElementType type() const { return _type; }
std::string to_str(int base = 10) const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
std::stringstream buf;
backend::stream_fd_ptr sfd = backend::streamopen(buf);
backend::element_out_str(sfd->fd, base,
*(backend::element_t*)&_element);
backend::streamclose(sfd);
return buf.str();
}
Element& operator=(Element&& e)
{
std::memcpy(&_element[0], &e._element[0],
sizeof(backend::element_t));
_type = e._type;
e._type = ElementType::NotInitialized;
return *this;
}
Element& operator=(const Element& e)
{
if (_type != ElementType::NotInitialized && _type != e._type) {
backend::element_clear(_element);
if (e._type != ElementType::NotInitialized)
backend::element_init_same_as(
_element, *(backend::element_t*)&e._element);
}
if (e._type != ElementType::NotInitialized)
backend::element_set(_element,
*(backend::element_t*)&e._element);
_type = e._type;
return *this;
}
Element& operator=(int i)
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_set_si(_element, i);
return *this;
}
Element& random()
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_random(_element);
return *this;
}
Element& from_str(const std::string& s, int base = 10)
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_set_str(_element, s.c_str(), base);
return *this;
}
bool operator==(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
return false;
else if (_type != e._type)
return false;
else
return backend::element_cmp(
*(backend::element_t*)&_element,
*(backend::element_t*)&e._element) == 0;
}
bool operator==(int i) const
{
if (_type == ElementType::NotInitialized) return false;
Element e;
e.init_same_as(*this);
e = i;
return operator==(e);
}
bool operator!=(const Element& e) const { return !operator==(e); }
bool operator!=(int i) const { return !operator==(i); }
Element operator+(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_add(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator+=(const Element& e)
{
operator=(operator+(e));
return *this;
}
Element operator-(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_sub(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator-=(const Element& e)
{
operator=(operator-(e));
return *this;
}
Element operator*(int i) const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
Element out;
out.init_same_as(*this);
backend::element_mul_si(out._element,
*(backend::element_t*)&_element, i);
return out;
}
Element operator*(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (e._type != ElementType::Zr) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_mul_zn(out._element,
*(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator*=(int i)
{
operator=(operator*(i));
return *this;
}
Element operator*=(const Element& e)
{
operator=(operator*(e));
return *this;
}
Element operator/(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_div(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator/=(const Element& e)
{
operator=(operator/(e));
return *this;
}
Element operator-() const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
Element out;
out.init_same_as(*this);
backend::element_neg(out._element, *(backend::element_t*)&_element);
return out;
}
private:
backend::element_t _element;
ElementType _type;
};
std::ostream& operator<<(std::ostream& o, const Element& e)
{
o << e.to_str();
return o;
}
};
<commit_msg>add missing ;<commit_after>/*
The MIT License (MIT)
Copyright (c) 2016 Xu Cheng
See licensing at:
https://opensource.org/licenses/MIT
*/
#pragma once
#include <exception>
#include <string>
#include "pbc-streamopen.hpp"
namespace pbc
{
namespace backend
{
#include <pbc/pbc.h>
};
class NotInitializedError : public std::runtime_error
{
public:
NotInitializedError() : runtime_error("Object is not initialized.") {}
};
class AlreadyInitializedError : public std::runtime_error
{
public:
AlreadyInitializedError()
: runtime_error("Object is already initialized.")
{
}
};
class InitializationError : public std::runtime_error
{
public:
InitializationError() : runtime_error("Failed to initialize object.") {}
InitializationError(const std::string& msg) : runtime_error(msg) {}
};
class ElementTypeError : public std::runtime_error
{
public:
ElementTypeError() : runtime_error("Element has wrong type.") {}
};
class Pairing;
class PairingParam;
class Element;
typedef std::shared_ptr<Pairing> PairingPtr;
typedef std::shared_ptr<PairingParam> PairingParamPtr;
typedef std::shared_ptr<Element> ElementPtr;
class PairingParam
{
public:
PairingParam() = default;
PairingParam(const PairingParam&) = delete;
~PairingParam() { backend::pbc_param_clear(_param); }
std::string to_str() const
{
std::stringstream buf;
backend::stream_fd_ptr sfd = backend::streamopen(buf);
backend::pbc_param_out_str(sfd->fd,
*(backend::pbc_param_t*)&_param);
backend::streamclose(sfd);
return buf.str();
}
static PairingParamPtr init_from_str(const std::string& param_str)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
if (backend::pbc_param_init_set_str(ptr->_param,
param_str.c_str()) != 0)
throw InitializationError(
"Failed to initialize pairing parameter.");
return ptr;
}
static PairingParamPtr gen_type_a(int rbits = 160, int qbits = 512)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_a_gen(ptr->_param, rbits, qbits);
return ptr;
}
static PairingParamPtr gen_type_i(int group_size = 696)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_i_gen(ptr->_param, group_size);
return ptr;
}
static PairingParamPtr gen_type_e(int rbits = 160, int qbits = 1024)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_e_gen(ptr->_param, rbits, qbits);
return ptr;
}
static PairingParamPtr gen_type_f(int bits = 160)
{
PairingParamPtr ptr = std::make_shared<PairingParam>();
backend::pbc_param_init_f_gen(ptr->_param, bits);
return ptr;
}
private:
friend class Pairing;
backend::pbc_param_t _param;
};
class Pairing
{
public:
Pairing() = default;
Pairing(const Pairing&) = delete;
~Pairing() { pairing_clear(_pairing); }
static PairingPtr init_from_param_str(const std::string& param_str)
{
return Pairing::init_from_param(
PairingParam::init_from_str(param_str));
PairingPtr ptr = std::make_shared<Pairing>();
if (backend::pairing_init_set_str(ptr->_pairing,
param_str.c_str()) != 0)
throw InitializationError("Failed to initialize pairing.");
return ptr;
}
static PairingPtr init_from_param(const PairingParamPtr& param)
{
PairingPtr ptr = std::make_shared<Pairing>();
backend::pairing_init_pbc_param(ptr->_pairing, param->_param);
return ptr;
}
bool symmetric() const
{
return backend::pairing_is_symmetric(
*(backend::pairing_t*)&_pairing);
}
int g1_bytes_length() const
{
return backend::pairing_length_in_bytes_G1(
*(backend::pairing_t*)&_pairing);
}
int g1_x_only_bytes_length() const
{
return backend::pairing_length_in_bytes_x_only_G1(
*(backend::pairing_t*)&_pairing);
}
int g1_compressed_bytes_length() const
{
return backend::pairing_length_in_bytes_compressed_G1(
*(backend::pairing_t*)&_pairing);
}
int g2_bytes_length() const
{
return backend::pairing_length_in_bytes_G2(
*(backend::pairing_t*)&_pairing);
}
int g2_x_only_bytes_length() const
{
return backend::pairing_length_in_bytes_x_only_G2(
*(backend::pairing_t*)&_pairing);
}
int g2_compressed_bytes_length() const
{
return backend::pairing_length_in_bytes_compressed_G2(
*(backend::pairing_t*)&_pairing);
}
int gt_bytes_length() const
{
return backend::pairing_length_in_bytes_GT(
*(backend::pairing_t*)&_pairing);
}
int zr_bytes_length() const
{
return backend::pairing_length_in_bytes_Zr(
*(backend::pairing_t*)&_pairing);
}
private:
friend class Element;
backend::pairing_t _pairing;
};
enum class ElementType { G1, G2, GT, Zr, NotInitialized };
std::ostream& operator<<(std::ostream& o, ElementType type)
{
switch (type) {
case ElementType::G1: o << "G1"; break;
case ElementType::G2: o << "G2"; break;
case ElementType::GT: o << "GT"; break;
case ElementType::Zr: o << "Zr"; break;
case ElementType::NotInitialized: o << "NotInitialized"; break;
}
return o;
}
class Element
{
public:
Element() : _type(ElementType::NotInitialized) {}
Element(const Element& e) : _type(e._type)
{
if (_type != ElementType::NotInitialized) {
backend::element_init_same_as(
_element, *(backend::element_t*)&e._element);
backend::element_set(_element,
*(backend::element_t*)&e._element);
}
}
Element(Element&& e) noexcept : _type(e._type)
{
std::memcpy(&_element[0], &e._element[0],
sizeof(backend::element_t));
e._type = ElementType::NotInitialized;
}
~Element()
{
if (_type != ElementType::NotInitialized) {
backend::element_clear(_element);
_type = ElementType::NotInitialized;
}
}
#define Element_Init_Func(type, type_lowercase) \
void init_##type_lowercase(const PairingPtr pairing) \
{ \
if (_type != ElementType::NotInitialized) \
throw AlreadyInitializedError(); \
backend::element_init_##type(_element, pairing->_pairing); \
_type = ElementType::type; \
}
Element_Init_Func(G1, g1);
Element_Init_Func(G2, g2);
Element_Init_Func(GT, gt);
Element_Init_Func(Zr, zr);
#undef Element_Init_Func
void init_same_as(const Element& e)
{
if (_type != ElementType::NotInitialized)
throw AlreadyInitializedError();
if (e._type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_init_same_as(_element,
*(backend::element_t*)&e._element);
_type = e._type;
}
ElementType type() const { return _type; }
std::string to_str(int base = 10) const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
std::stringstream buf;
backend::stream_fd_ptr sfd = backend::streamopen(buf);
backend::element_out_str(sfd->fd, base,
*(backend::element_t*)&_element);
backend::streamclose(sfd);
return buf.str();
}
Element& operator=(Element&& e)
{
std::memcpy(&_element[0], &e._element[0],
sizeof(backend::element_t));
_type = e._type;
e._type = ElementType::NotInitialized;
return *this;
}
Element& operator=(const Element& e)
{
if (_type != ElementType::NotInitialized && _type != e._type) {
backend::element_clear(_element);
if (e._type != ElementType::NotInitialized)
backend::element_init_same_as(
_element, *(backend::element_t*)&e._element);
}
if (e._type != ElementType::NotInitialized)
backend::element_set(_element,
*(backend::element_t*)&e._element);
_type = e._type;
return *this;
}
Element& operator=(int i)
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_set_si(_element, i);
return *this;
}
Element& random()
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_random(_element);
return *this;
}
Element& from_str(const std::string& s, int base = 10)
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
backend::element_set_str(_element, s.c_str(), base);
return *this;
}
bool operator==(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
return false;
else if (_type != e._type)
return false;
else
return backend::element_cmp(
*(backend::element_t*)&_element,
*(backend::element_t*)&e._element) == 0;
}
bool operator==(int i) const
{
if (_type == ElementType::NotInitialized) return false;
Element e;
e.init_same_as(*this);
e = i;
return operator==(e);
}
bool operator!=(const Element& e) const { return !operator==(e); }
bool operator!=(int i) const { return !operator==(i); }
Element operator+(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_add(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator+=(const Element& e)
{
operator=(operator+(e));
return *this;
}
Element operator-(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_sub(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator-=(const Element& e)
{
operator=(operator-(e));
return *this;
}
Element operator*(int i) const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
Element out;
out.init_same_as(*this);
backend::element_mul_si(out._element,
*(backend::element_t*)&_element, i);
return out;
}
Element operator*(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (e._type != ElementType::Zr) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_mul_zn(out._element,
*(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator*=(int i)
{
operator=(operator*(i));
return *this;
}
Element operator*=(const Element& e)
{
operator=(operator*(e));
return *this;
}
Element operator/(const Element& e) const
{
if (_type == ElementType::NotInitialized ||
e._type == ElementType::NotInitialized)
throw NotInitializedError();
if (_type != e._type) throw ElementTypeError();
Element out;
out.init_same_as(*this);
backend::element_div(out._element, *(backend::element_t*)&_element,
*(backend::element_t*)&e._element);
return out;
}
Element operator/=(const Element& e)
{
operator=(operator/(e));
return *this;
}
Element operator-() const
{
if (_type == ElementType::NotInitialized)
throw NotInitializedError();
Element out;
out.init_same_as(*this);
backend::element_neg(out._element, *(backend::element_t*)&_element);
return out;
}
private:
backend::element_t _element;
ElementType _type;
};
std::ostream& operator<<(std::ostream& o, const Element& e)
{
o << e.to_str();
return o;
}
};
<|endoftext|>
|
<commit_before>#ifndef __VECTOR_2D__
#define __VECTOR_2D__
// Copyright (C) Kevin Suffern 2000-2007.
// This C++ code is for non-commercial purposes only.
// This C++ code is licensed under the GNU General Public License Version 2.
// See the file COPYING.txt for the full license.
#include "Matrix.h"
class Normal;
class Point2D;
//----------------------------------------- class Vector2D
class Vector2D {
public:
double x, y;
public:
Vector2D(void); // default constructor
Vector2D(double a); // constructor
Vector2D(double _x, double _y); // constructor
Vector2D(const Vector2D& v); // copy constructor
Vector2D(const Normal& n); // constructs a vector from a Normal
Vector2D(const Point2D& p); // constructs a vector from a point
~Vector2D (void); // destructor
Vector2D& // assignment operator
operator= (const Vector2D& rhs);
Vector2D& // assign a Normal to a vector
operator= (const Normal& rhs);
Vector2D& // assign a Point2D to a vector
operator= (const Point2D& rhs);
Vector2D // unary minus
operator- (void) const;
double // length
length(void);
double // square of the length
len_squared(void);
Vector2D // multiplication by a double on the right
operator* (const double a) const;
Vector2D // division by a double
operator/ (const double a) const;
Vector2D // addition
operator+ (const Vector2D& v) const;
Vector2D& // compound addition
operator+= (const Vector2D& v);
Vector2D // subtraction
operator- (const Vector2D& v) const;
double // dot product
operator* (const Vector2D& b) const;
Vector2D // cross product
operator^ (const Vector2D& v) const;
void // convert vector to a unit vector
normalize(void);
Vector2D& // return a unit vector, and normalize the vector
hat(void);
};
// inlined member functions
// ------------------------------------------------------------------------ unary minus
// this does not change the current vector
// this allows ShadeRec objects to be declared as constant arguments in many shading
// functions that reverse the direction of a ray that's stored in the ShadeRec object
inline Vector2D
Vector2D::operator- (void) const {
return (Vector2D(-x, -y));
}
// --------------------------------------------------------------------- len_squared
// the square of the length
inline double
Vector2D::len_squared(void) {
return (x * x + y * y);
}
// ----------------------------------------------------------------------- operator*
// multiplication by a double on the right
inline Vector2D
Vector2D::operator* (const double a) const {
return (Vector2D(x * a, y * a));
}
// ----------------------------------------------------------------------- operator/
// division by a double
inline Vector2D
Vector2D::operator/ (const double a) const {
return (Vector2D(x / a, y / a));
}
// ----------------------------------------------------------------------- operator+
// addition
inline Vector2D
Vector2D::operator+ (const Vector2D& v) const {
return (Vector2D(x + v.x, y + v.y));
}
// ----------------------------------------------------------------------- operator-
// subtraction
inline Vector2D
Vector2D::operator- (const Vector2D& v) const {
return (Vector2D(x - v.x, y - v.y));
}
// ----------------------------------------------------------------------- operator*
// dot product
inline double
Vector2D::operator* (const Vector2D& v) const {
return (x * v.x + y * v.y);
}
// ----------------------------------------------------------------------- operator^
// cross product
inline Vector2D
Vector2D::operator^ (const Vector2D& v) const {
return (Vector2D(x * v.y - y * v.x));
}
// --------------------------------------------------------------------- operator+=
// compound addition
inline Vector2D&
Vector2D::operator+= (const Vector2D& v) {
x += v.x; y += v.y;
return (*this);
}
// inlined non-member function
// ----------------------------------------------------------------------- operator*
// multiplication by a double on the left
Vector2D // prototype
operator* (const double a, const Vector2D& v);
inline Vector2D
operator* (const double a, const Vector2D& v) {
return (Vector2D(a * v.x, a * v.y));
}
#endif
<commit_msg>Deleted unused matrix class<commit_after>#ifndef __VECTOR_2D__
#define __VECTOR_2D__
// Copyright (C) Kevin Suffern 2000-2007.
// This C++ code is for non-commercial purposes only.
// This C++ code is licensed under the GNU General Public License Version 2.
// See the file COPYING.txt for the full license.
class Normal;
class Point2D;
//----------------------------------------- class Vector2D
class Vector2D {
public:
double x, y;
public:
Vector2D(void); // default constructor
Vector2D(double a); // constructor
Vector2D(double _x, double _y); // constructor
Vector2D(const Vector2D& v); // copy constructor
Vector2D(const Normal& n); // constructs a vector from a Normal
Vector2D(const Point2D& p); // constructs a vector from a point
~Vector2D (void); // destructor
Vector2D& // assignment operator
operator= (const Vector2D& rhs);
Vector2D& // assign a Normal to a vector
operator= (const Normal& rhs);
Vector2D& // assign a Point2D to a vector
operator= (const Point2D& rhs);
Vector2D // unary minus
operator- (void) const;
double // length
length(void);
double // square of the length
len_squared(void);
Vector2D // multiplication by a double on the right
operator* (const double a) const;
Vector2D // division by a double
operator/ (const double a) const;
Vector2D // addition
operator+ (const Vector2D& v) const;
Vector2D& // compound addition
operator+= (const Vector2D& v);
Vector2D // subtraction
operator- (const Vector2D& v) const;
double // dot product
operator* (const Vector2D& b) const;
Vector2D // cross product
operator^ (const Vector2D& v) const;
void // convert vector to a unit vector
normalize(void);
Vector2D& // return a unit vector, and normalize the vector
hat(void);
};
// inlined member functions
// ------------------------------------------------------------------------ unary minus
// this does not change the current vector
// this allows ShadeRec objects to be declared as constant arguments in many shading
// functions that reverse the direction of a ray that's stored in the ShadeRec object
inline Vector2D
Vector2D::operator- (void) const {
return (Vector2D(-x, -y));
}
// --------------------------------------------------------------------- len_squared
// the square of the length
inline double
Vector2D::len_squared(void) {
return (x * x + y * y);
}
// ----------------------------------------------------------------------- operator*
// multiplication by a double on the right
inline Vector2D
Vector2D::operator* (const double a) const {
return (Vector2D(x * a, y * a));
}
// ----------------------------------------------------------------------- operator/
// division by a double
inline Vector2D
Vector2D::operator/ (const double a) const {
return (Vector2D(x / a, y / a));
}
// ----------------------------------------------------------------------- operator+
// addition
inline Vector2D
Vector2D::operator+ (const Vector2D& v) const {
return (Vector2D(x + v.x, y + v.y));
}
// ----------------------------------------------------------------------- operator-
// subtraction
inline Vector2D
Vector2D::operator- (const Vector2D& v) const {
return (Vector2D(x - v.x, y - v.y));
}
// ----------------------------------------------------------------------- operator*
// dot product
inline double
Vector2D::operator* (const Vector2D& v) const {
return (x * v.x + y * v.y);
}
// ----------------------------------------------------------------------- operator^
// cross product
inline Vector2D
Vector2D::operator^ (const Vector2D& v) const {
return (Vector2D(x * v.y - y * v.x));
}
// --------------------------------------------------------------------- operator+=
// compound addition
inline Vector2D&
Vector2D::operator+= (const Vector2D& v) {
x += v.x; y += v.y;
return (*this);
}
// inlined non-member function
// ----------------------------------------------------------------------- operator*
// multiplication by a double on the left
Vector2D // prototype
operator* (const double a, const Vector2D& v);
inline Vector2D
operator* (const double a, const Vector2D& v) {
return (Vector2D(a * v.x, a * v.y));
}
#endif
<|endoftext|>
|
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
/*
* Main program to start and inject a DLL into a process via a remote thread.
*
* For background see:
* - http://en.wikipedia.org/wiki/DLL_injection#Approaches_on_Microsoft_Windows
* - http://www.codeproject.com/KB/threads/completeinject.aspx
* - http://www.codeproject.com/KB/threads/winspy.aspx
* - http://www.codeproject.com/KB/DLL/DLL_Injection_tutorial.aspx
* - http://www.codeproject.com/KB/threads/APIHooking.aspx
*
* Other slightly different techniques:
* - http://www.fr33project.org/pages/projects/phook.htm
* - http://www.hbgary.com/loading-a-dll-without-calling-loadlibrary
* - http://securityxploded.com/ntcreatethreadex.php
*/
#include <string>
#include <windows.h>
#include <stdio.h>
#include "inject.h"
/**
* Determine whether an argument should be quoted.
*/
static bool
needsQuote(const char *arg)
{
char c;
while (true) {
c = *arg++;
if (c == '\0') {
break;
}
if (c == ' ' || c == '\t' || c == '\"') {
return true;
}
if (c == '\\') {
c = *arg++;
if (c == '\0') {
break;
}
if (c == '"') {
return true;
}
}
}
return false;
}
static void
quoteArg(std::string &s, const char *arg)
{
char c;
unsigned backslashes = 0;
s.push_back('"');
while (true) {
c = *arg++;
if (c == '\0') {
break;
} else if (c == '"') {
while (backslashes) {
s.push_back('\\');
--backslashes;
}
s.push_back('\\');
} else {
if (c == '\\') {
++backslashes;
} else {
backslashes = 0;
}
}
s.push_back(c);
}
s.push_back('"');
}
int
main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "inject dllname.dll command [args] ...\n");
return 1;
}
const char *szDll = argv[1];
if (!USE_SHARED_MEM) {
SetEnvironmentVariableA("INJECT_DLL", szDll);
} else {
SetSharedMem(szDll);
}
PROCESS_INFORMATION processInfo;
HANDLE hProcess;
BOOL bAttach;
if (isdigit(argv[2][0])) {
bAttach = TRUE;
BOOL bRet;
HANDLE hToken = NULL;
bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
if (!bRet) {
fprintf(stderr, "error: OpenProcessToken returned %u\n", (unsigned)bRet);
return 1;
}
LUID Luid;
bRet = LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Luid);
if (!bRet) {
fprintf(stderr, "error: LookupPrivilegeValue returned %u\n", (unsigned)bRet);
return 1;
}
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = Luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof tp, NULL, NULL);
if (!bRet) {
fprintf(stderr, "error: AdjustTokenPrivileges returned %u\n", (unsigned)bRet);
return 1;
}
DWORD dwDesiredAccess =
PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_QUERY_LIMITED_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ;
DWORD dwProcessId = atol(argv[2]);
hProcess = OpenProcess(
dwDesiredAccess,
FALSE /* bInheritHandle */,
dwProcessId);
if (!hProcess) {
DWORD dwLastError = GetLastError();
fprintf(stderr, "error: failed to open process %lu (%lu)\n", dwProcessId, dwLastError);
return 1;
}
} else {
bAttach = FALSE;
std::string commandLine;
char sep = 0;
for (int i = 2; i < argc; ++i) {
const char *arg = argv[i];
if (sep) {
commandLine.push_back(sep);
}
if (needsQuote(arg)) {
quoteArg(commandLine, arg);
} else {
commandLine.append(arg);
}
sep = ' ';
}
STARTUPINFO startupInfo;
memset(&startupInfo, 0, sizeof startupInfo);
startupInfo.cb = sizeof startupInfo;
// Create the process in suspended state
if (!CreateProcessA(
NULL,
const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
0, // process attributes
0, // thread attributes
TRUE, // inherit handles
CREATE_SUSPENDED,
NULL, // environment
NULL, // current directory
&startupInfo,
&processInfo)) {
fprintf(stderr, "error: failed to execute %s\n", commandLine.c_str());
return 1;
}
hProcess = processInfo.hProcess;
}
/*
* XXX: Mixed architecture don't quite work. See also
* http://www.corsix.org/content/dll-injection-and-wow64
*/
{
typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
PFNISWOW64PROCESS pfnIsWow64Process;
pfnIsWow64Process = (PFNISWOW64PROCESS)
GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
if (pfnIsWow64Process) {
BOOL isParentWow64 = FALSE;
BOOL isChildWow64 = FALSE;
if (pfnIsWow64Process(GetCurrentProcess(), &isParentWow64) &&
pfnIsWow64Process(hProcess, &isChildWow64) &&
isParentWow64 != isChildWow64) {
fprintf(stderr, "error: binaries mismatch: you need to use the "
#ifdef _WIN64
"32-bits"
#else
"64-bits"
#endif
" apitrace binaries to trace this application\n");
TerminateProcess(hProcess, 1);
return 1;
}
}
}
const char *szDllName;
szDllName = "injectee.dll";
char szDllPath[MAX_PATH];
GetModuleFileNameA(NULL, szDllPath, sizeof szDllPath);
getDirName(szDllPath);
strncat(szDllPath, szDllName, sizeof szDllPath - strlen(szDllPath) - 1);
const char *szError = NULL;
if (!injectDll(hProcess, szDllPath, &szError)) {
fprintf(stderr, "error: %s\n", szError);
TerminateProcess(hProcess, 1);
return 1;
}
if (bAttach) {
return 0;
}
// Start main process thread
ResumeThread(processInfo.hThread);
// Wait for it to finish
WaitForSingleObject(hProcess, INFINITE);
if (pSharedMem && !pSharedMem->bReplaced) {
fprintf(stderr, "warning: %s was never used: application probably does not use this API\n", szDll);
}
DWORD exitCode = ~0;
GetExitCodeProcess(hProcess, &exitCode);
CloseHandle(hProcess);
CloseHandle(processInfo.hThread);
return (int)exitCode;
}
<commit_msg>inject: Use a semaphore to prevent multiple runs of inject to interfere with each other.<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
/*
* Main program to start and inject a DLL into a process via a remote thread.
*
* For background see:
* - http://en.wikipedia.org/wiki/DLL_injection#Approaches_on_Microsoft_Windows
* - http://www.codeproject.com/KB/threads/completeinject.aspx
* - http://www.codeproject.com/KB/threads/winspy.aspx
* - http://www.codeproject.com/KB/DLL/DLL_Injection_tutorial.aspx
* - http://www.codeproject.com/KB/threads/APIHooking.aspx
*
* Other slightly different techniques:
* - http://www.fr33project.org/pages/projects/phook.htm
* - http://www.hbgary.com/loading-a-dll-without-calling-loadlibrary
* - http://securityxploded.com/ntcreatethreadex.php
*/
#include <string>
#include <windows.h>
#include <stdio.h>
#include "inject.h"
/**
* Determine whether an argument should be quoted.
*/
static bool
needsQuote(const char *arg)
{
char c;
while (true) {
c = *arg++;
if (c == '\0') {
break;
}
if (c == ' ' || c == '\t' || c == '\"') {
return true;
}
if (c == '\\') {
c = *arg++;
if (c == '\0') {
break;
}
if (c == '"') {
return true;
}
}
}
return false;
}
static void
quoteArg(std::string &s, const char *arg)
{
char c;
unsigned backslashes = 0;
s.push_back('"');
while (true) {
c = *arg++;
if (c == '\0') {
break;
} else if (c == '"') {
while (backslashes) {
s.push_back('\\');
--backslashes;
}
s.push_back('\\');
} else {
if (c == '\\') {
++backslashes;
} else {
backslashes = 0;
}
}
s.push_back(c);
}
s.push_back('"');
}
int
main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "inject dllname.dll command [args] ...\n");
return 1;
}
HANDLE hSemaphore = NULL;
const char *szDll = argv[1];
if (!USE_SHARED_MEM) {
SetEnvironmentVariableA("INJECT_DLL", szDll);
} else {
hSemaphore = CreateSemaphore(NULL, 1, 1, "inject_semaphore");
if (hSemaphore == NULL) {
fprintf(stderr, "error: failed to create semaphore\n");
return 1;
}
DWORD dwWait = WaitForSingleObject(hSemaphore, 0);
if (dwWait == WAIT_TIMEOUT) {
fprintf(stderr, "info: waiting for another inject instance to finish\n");
dwWait = WaitForSingleObject(hSemaphore, INFINITE);
}
if (dwWait != WAIT_OBJECT_0) {
fprintf(stderr, "error: failed to enter semaphore gate\n");
return 1;
}
SetSharedMem(szDll);
}
PROCESS_INFORMATION processInfo;
HANDLE hProcess;
BOOL bAttach;
if (isdigit(argv[2][0])) {
bAttach = TRUE;
BOOL bRet;
HANDLE hToken = NULL;
bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
if (!bRet) {
fprintf(stderr, "error: OpenProcessToken returned %u\n", (unsigned)bRet);
return 1;
}
LUID Luid;
bRet = LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Luid);
if (!bRet) {
fprintf(stderr, "error: LookupPrivilegeValue returned %u\n", (unsigned)bRet);
return 1;
}
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = Luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof tp, NULL, NULL);
if (!bRet) {
fprintf(stderr, "error: AdjustTokenPrivileges returned %u\n", (unsigned)bRet);
return 1;
}
DWORD dwDesiredAccess =
PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_QUERY_LIMITED_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ;
DWORD dwProcessId = atol(argv[2]);
hProcess = OpenProcess(
dwDesiredAccess,
FALSE /* bInheritHandle */,
dwProcessId);
if (!hProcess) {
DWORD dwLastError = GetLastError();
fprintf(stderr, "error: failed to open process %lu (%lu)\n", dwProcessId, dwLastError);
return 1;
}
} else {
bAttach = FALSE;
std::string commandLine;
char sep = 0;
for (int i = 2; i < argc; ++i) {
const char *arg = argv[i];
if (sep) {
commandLine.push_back(sep);
}
if (needsQuote(arg)) {
quoteArg(commandLine, arg);
} else {
commandLine.append(arg);
}
sep = ' ';
}
STARTUPINFO startupInfo;
memset(&startupInfo, 0, sizeof startupInfo);
startupInfo.cb = sizeof startupInfo;
// Create the process in suspended state
if (!CreateProcessA(
NULL,
const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
0, // process attributes
0, // thread attributes
TRUE, // inherit handles
CREATE_SUSPENDED,
NULL, // environment
NULL, // current directory
&startupInfo,
&processInfo)) {
fprintf(stderr, "error: failed to execute %s\n", commandLine.c_str());
return 1;
}
hProcess = processInfo.hProcess;
}
/*
* XXX: Mixed architecture don't quite work. See also
* http://www.corsix.org/content/dll-injection-and-wow64
*/
{
typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
PFNISWOW64PROCESS pfnIsWow64Process;
pfnIsWow64Process = (PFNISWOW64PROCESS)
GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
if (pfnIsWow64Process) {
BOOL isParentWow64 = FALSE;
BOOL isChildWow64 = FALSE;
if (pfnIsWow64Process(GetCurrentProcess(), &isParentWow64) &&
pfnIsWow64Process(hProcess, &isChildWow64) &&
isParentWow64 != isChildWow64) {
fprintf(stderr, "error: binaries mismatch: you need to use the "
#ifdef _WIN64
"32-bits"
#else
"64-bits"
#endif
" apitrace binaries to trace this application\n");
TerminateProcess(hProcess, 1);
return 1;
}
}
}
const char *szDllName;
szDllName = "injectee.dll";
char szDllPath[MAX_PATH];
GetModuleFileNameA(NULL, szDllPath, sizeof szDllPath);
getDirName(szDllPath);
strncat(szDllPath, szDllName, sizeof szDllPath - strlen(szDllPath) - 1);
const char *szError = NULL;
if (!injectDll(hProcess, szDllPath, &szError)) {
fprintf(stderr, "error: %s\n", szError);
TerminateProcess(hProcess, 1);
return 1;
}
if (bAttach) {
return 0;
}
// Start main process thread
ResumeThread(processInfo.hThread);
// Wait for it to finish
WaitForSingleObject(hProcess, INFINITE);
if (pSharedMem && !pSharedMem->bReplaced) {
fprintf(stderr, "warning: %s was never used: application probably does not use this API\n", szDll);
}
DWORD exitCode = ~0;
GetExitCodeProcess(hProcess, &exitCode);
CloseHandle(hProcess);
CloseHandle(processInfo.hThread);
if (hSemaphore) {
ReleaseSemaphore(hSemaphore, 1, NULL);
CloseHandle(hSemaphore);
}
return (int)exitCode;
}
<|endoftext|>
|
<commit_before>/*
Empath - Mailer for KDE
Copyright 1999, 2000
Rik Hemsley <rik@kde.org>
Wilco Greven <j.w.greven@student.utwente.nl>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// System includes
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
// KDE includes
#include <kuniqueapp.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kcmdlineargs.h>
// Local includes
#include "Empath.h"
#include "EmpathUI.h"
static const char* description=I18N_NOOP("Empath, the KDE Mail Client");
static const char* VERSION="0.0.1";
int
main(int argc, char ** argv)
{
KAboutData aboutData( "empath", I18N_NOOP("Empath"),
VERSION, description, KAboutData::License_GPL,
"(c) 1999-2000, The Empath Team");
aboutData.addAuthor("Rik Hemsley",0, "rik@kde.org");
aboutData.addAuthor("Wilco Greven",0, "j.w.greven@student.utwente.nl");
KCmdLineArgs::init( argc, argv, &aboutData );
// Don't do anything if we're being run as root.
if (getuid() == 0 || geteuid() == 0) {
fprintf(stderr, "DO NOT RUN GUI APPS AS ROOT !\n");
return 1;
}
// Pick a sensible umask for everything Empath does.
int prev_umask = umask(077);
#define DOSOMEDOSOMEDOSOME
#ifdef DOSOMEDOSOMEDOSOME
if (!KUniqueApplication::start())
exit(0);
KUniqueApplication app;
#else
KApplication app;
#endif
// Create the kernel.
Empath::start();
// Create the user interface.
EmpathUI * ui = new EmpathUI;
// Attempt to get the UI up and running quickly.
app.processEvents();
// Initialise the kernel.
empath->init();
// Enter the event loop.
int retval = app.exec();
delete ui;
ui = 0;
empath->shutdown();
// Restore umask.
umask(prev_umask);
return retval;
}
// vim:ts=4:sw=4:tw=78
<commit_msg>This one needed License_GPL changing to just GPL too<commit_after>/*
Empath - Mailer for KDE
Copyright 1999, 2000
Rik Hemsley <rik@kde.org>
Wilco Greven <j.w.greven@student.utwente.nl>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// System includes
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
// KDE includes
#include <kuniqueapp.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kcmdlineargs.h>
// Local includes
#include "Empath.h"
#include "EmpathUI.h"
static const char* description=I18N_NOOP("Empath, the KDE Mail Client");
static const char* VERSION="0.0.1";
int
main(int argc, char ** argv)
{
KAboutData aboutData( "empath", I18N_NOOP("Empath"),
VERSION, description, KAboutData::GPL,
"(c) 1999-2000, The Empath Team");
aboutData.addAuthor("Rik Hemsley",0, "rik@kde.org");
aboutData.addAuthor("Wilco Greven",0, "j.w.greven@student.utwente.nl");
KCmdLineArgs::init( argc, argv, &aboutData );
// Don't do anything if we're being run as root.
if (getuid() == 0 || geteuid() == 0) {
fprintf(stderr, "DO NOT RUN GUI APPS AS ROOT !\n");
return 1;
}
// Pick a sensible umask for everything Empath does.
int prev_umask = umask(077);
#define DOSOMEDOSOMEDOSOME
#ifdef DOSOMEDOSOMEDOSOME
if (!KUniqueApplication::start())
exit(0);
KUniqueApplication app;
#else
KApplication app;
#endif
// Create the kernel.
Empath::start();
// Create the user interface.
EmpathUI * ui = new EmpathUI;
// Attempt to get the UI up and running quickly.
app.processEvents();
// Initialise the kernel.
empath->init();
// Enter the event loop.
int retval = app.exec();
delete ui;
ui = 0;
empath->shutdown();
// Restore umask.
umask(prev_umask);
return retval;
}
// vim:ts=4:sw=4:tw=78
<|endoftext|>
|
<commit_before>#include <string>
#include <memory>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "model/feature_cache.h"
using namespace std;
namespace redgiant {
class FeatureCacheTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(FeatureCacheTest);
CPPUNIT_TEST(test_create_feature_space);
CPPUNIT_TEST(test_create_feature);
CPPUNIT_TEST(test_get_feature);
CPPUNIT_TEST_SUITE_END();
public:
FeatureCacheTest() = default;
virtual ~FeatureCacheTest() = default;
protected:
void test_create_feature_space() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::FeatureType::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::FeatureType::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::FeatureType::kInteger);
CPPUNIT_ASSERT(!!space_a); // not null
CPPUNIT_ASSERT(!!space_b); // not null
CPPUNIT_ASSERT(!!space_c); // not null
auto aa = cache->get_space("A");
CPPUNIT_ASSERT(space_a == aa);
CPPUNIT_ASSERT_EQUAL(1ULL, (unsigned long long)(aa->get_id()));
CPPUNIT_ASSERT_EQUAL(string("A"), aa->get_name());
auto bb = cache->get_space("BB");
CPPUNIT_ASSERT(space_b == bb);
CPPUNIT_ASSERT_EQUAL(2ULL, (unsigned long long)(bb->get_id()));
CPPUNIT_ASSERT_EQUAL(string("BB"), bb->get_name());
// replace "A"
auto space_d = cache->create_space("A", 4, FeatureSpace::FeatureType::kString);
auto dd = cache->get_space("A");
CPPUNIT_ASSERT(!!space_d); // not null
CPPUNIT_ASSERT(space_d == dd);
CPPUNIT_ASSERT_EQUAL(4ULL, (unsigned long long)(dd->get_id()));
CPPUNIT_ASSERT_EQUAL(string("A"), dd->get_name());
}
void test_create_feature() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::FeatureType::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::FeatureType::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::FeatureType::kInteger);
auto f1 = cache->create_or_get_feature("111", "A");
auto f2 = cache->create_or_get_feature("xxx", space_b);
auto f3 = cache->create_or_get_feature("yyy", space_c);
CPPUNIT_ASSERT(!!f1); // not null
CPPUNIT_ASSERT_EQUAL(string("111"), f1->get_key());
CPPUNIT_ASSERT_EQUAL(111ULL, FeatureSpace::get_part_feature_id(f1->get_id()));
CPPUNIT_ASSERT(!!f2); // not null
CPPUNIT_ASSERT_EQUAL(string("xxx"), f2->get_key());
CPPUNIT_ASSERT(f2->get_id() != FeatureSpace::kInvalidId);
CPPUNIT_ASSERT(!f3); // null
}
void test_get_feature() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::kInteger);
auto f1 = cache->create_or_get_feature("111", "A");
auto f2 = cache->create_or_get_feature("xxx", space_b);
auto f3 = cache->create_or_get_feature("222", space_c);
auto f4 = cache->create_or_get_feature("222", "CCC");
CPPUNIT_ASSERT(f3 == f4); // null
CPPUNIT_ASSERT_EQUAL(string("222"), f4->get_key());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(FeatureCacheTest);
} /* namespace redgiant */
<commit_msg>fix unit test<commit_after>#include <string>
#include <memory>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "model/feature_cache.h"
using namespace std;
namespace redgiant {
class FeatureCacheTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(FeatureCacheTest);
CPPUNIT_TEST(test_create_feature_space);
CPPUNIT_TEST(test_create_feature);
CPPUNIT_TEST(test_get_feature);
CPPUNIT_TEST_SUITE_END();
public:
FeatureCacheTest() = default;
virtual ~FeatureCacheTest() = default;
protected:
void test_create_feature_space() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::FeatureType::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::FeatureType::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::FeatureType::kInteger);
CPPUNIT_ASSERT(!!space_a); // not null
CPPUNIT_ASSERT(!!space_b); // not null
CPPUNIT_ASSERT(!!space_c); // not null
auto aa = cache->get_space("A");
CPPUNIT_ASSERT(space_a == aa);
CPPUNIT_ASSERT_EQUAL(1ULL, (unsigned long long)(aa->get_id()));
CPPUNIT_ASSERT_EQUAL(string("A"), aa->get_name());
auto bb = cache->get_space("BB");
CPPUNIT_ASSERT(space_b == bb);
CPPUNIT_ASSERT_EQUAL(2ULL, (unsigned long long)(bb->get_id()));
CPPUNIT_ASSERT_EQUAL(string("BB"), bb->get_name());
// replace "A"
auto space_d = cache->create_space("A", 4, FeatureSpace::FeatureType::kString);
auto dd = cache->get_space("A");
CPPUNIT_ASSERT(!!space_d); // not null
CPPUNIT_ASSERT(space_d == dd);
CPPUNIT_ASSERT_EQUAL(4ULL, (unsigned long long)(dd->get_id()));
CPPUNIT_ASSERT_EQUAL(string("A"), dd->get_name());
}
void test_create_feature() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::FeatureType::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::FeatureType::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::FeatureType::kInteger);
auto f1 = cache->create_or_get_feature("111", "A");
auto f2 = cache->create_or_get_feature("xxx", space_b);
auto f3 = cache->create_or_get_feature("yyy", space_c);
CPPUNIT_ASSERT(!!f1); // not null
CPPUNIT_ASSERT_EQUAL(string("111"), f1->get_key());
CPPUNIT_ASSERT_EQUAL(111ULL, (unsigned long long)FeatureSpace::get_part_feature_id(f1->get_id()));
CPPUNIT_ASSERT(!!f2); // not null
CPPUNIT_ASSERT_EQUAL(string("xxx"), f2->get_key());
CPPUNIT_ASSERT(f2->get_id() != FeatureSpace::kInvalidId);
CPPUNIT_ASSERT(!f3); // null
}
void test_get_feature() {
auto cache = std::unique_ptr<FeatureCache>(new FeatureCache());
auto space_a = cache->create_space("A", 1, FeatureSpace::kInteger);
auto space_b = cache->create_space("BB", 2, FeatureSpace::kString);
auto space_c = cache->create_space("CCC", 3, FeatureSpace::kInteger);
auto f1 = cache->create_or_get_feature("111", "A");
auto f2 = cache->create_or_get_feature("xxx", space_b);
auto f3 = cache->create_or_get_feature("222", space_c);
auto f4 = cache->create_or_get_feature("222", "CCC");
CPPUNIT_ASSERT(f3 == f4); // null
CPPUNIT_ASSERT_EQUAL(string("222"), f4->get_key());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(FeatureCacheTest);
} /* namespace redgiant */
<|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/>.
*/
/** @file jsonrpc.cpp
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
// @debris disabled as tests fail with:
// unknown location(0): fatal error in "jsonrpc_setMining": std::exception: Exception -32003 : Client connector error: : libcurl error: 28
// /home/gav/Eth/cpp-ethereum/test/jsonrpc.cpp(169): last checkpoint
#if ETH_JSONRPC && 0
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libweb3jsonrpc/WebThreeStubServer.h>
#include <libweb3jsonrpc/CorsHttpServer.h>
//#include <json/json.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"
BOOST_AUTO_TEST_SUITE(jsonrpc)
using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;
WebThreeDirect* web3;
unique_ptr<WebThreeStubServer> jsonrpcServer;
unique_ptr<WebThreeStubClient> jsonrpcClient;
struct Setup
{
Setup()
{
static bool setup = false;
if (setup)
return;
setup = true;
dev::p2p::NetworkPreferences nprefs(30303, std::string(), false);
web3 = new WebThreeDirect("Ethereum(++) tests", "", true, {"eth", "shh"}, nprefs);
web3->setIdealPeerCount(5);
web3->ethereum()->setForceMining(true);
auto server = new jsonrpc::HttpServer(8080);
jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(*server, *web3, {}));
jsonrpcServer->setIdentities({});
jsonrpcServer->StartListening();
auto client = new jsonrpc::HttpClient("http://localhost:8080");
jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(*client));
}
};
string fromAscii(string _s)
{
bytes b = asBytes(_s);
return "0x" + toHex(b);
}
BOOST_FIXTURE_TEST_SUITE(environment, Setup)
BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
cnote << "Testing jsonrpc defaultBlock...";
int defaultBlock = jsonrpcClient->eth_defaultBlock();
BOOST_CHECK_EQUAL(defaultBlock, web3->ethereum()->getDefault());
}
BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
cnote << "Testing jsonrpc gasPrice...";
string gasPrice = jsonrpcClient->eth_gasPrice();
BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}
BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
cnote << "Testing jsonrpc isListening...";
web3->startNetwork();
bool listeningOn = jsonrpcClient->eth_listening();
BOOST_CHECK_EQUAL(listeningOn, web3->isNetworkStarted());
web3->stopNetwork();
bool listeningOff = jsonrpcClient->eth_listening();
BOOST_CHECK_EQUAL(listeningOff, web3->isNetworkStarted());
}
BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
cnote << "Testing jsonrpc isMining...";
web3->ethereum()->startMining();
bool miningOn = jsonrpcClient->eth_mining();
BOOST_CHECK_EQUAL(miningOn, web3->ethereum()->isMining());
web3->ethereum()->stopMining();
bool miningOff = jsonrpcClient->eth_mining();
BOOST_CHECK_EQUAL(miningOff, web3->ethereum()->isMining());
}
BOOST_AUTO_TEST_CASE(jsonrpc_accounts)
{
cnote << "Testing jsonrpc accounts...";
std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
jsonrpcServer->setAccounts(keys);
Json::Value k = jsonrpcClient->eth_accounts();
jsonrpcServer->setAccounts({});
BOOST_CHECK_EQUAL(k.isArray(), true);
BOOST_CHECK_EQUAL(k.size(), keys.size());
for (auto &i:k)
{
auto it = std::find_if(keys.begin(), keys.end(), [i](dev::KeyPair const& keyPair)
{
return jsToAddress(i.asString()) == keyPair.address();
});
BOOST_CHECK_EQUAL(it != keys.end(), true);
}
}
BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
cnote << "Testing jsonrpc number2...";
int number = jsonrpcClient->eth_number();
BOOST_CHECK_EQUAL(number, web3->ethereum()->number() + 1);
dev::eth::mine(*(web3->ethereum()), 1);
int numberAfter = jsonrpcClient->eth_number();
BOOST_CHECK_EQUAL(number + 1, numberAfter);
BOOST_CHECK_EQUAL(numberAfter, web3->ethereum()->number() + 1);
}
BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
cnote << "Testing jsonrpc peerCount...";
int peerCount = jsonrpcClient->eth_peerCount();
BOOST_CHECK_EQUAL(web3->peerCount(), peerCount);
}
BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
cnote << "Testing jsonrpc setListening...";
jsonrpcClient->eth_setListening(true);
BOOST_CHECK_EQUAL(web3->isNetworkStarted(), true);
jsonrpcClient->eth_setListening(false);
BOOST_CHECK_EQUAL(web3->isNetworkStarted(), false);
}
BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
cnote << "Testing jsonrpc setMining...";
jsonrpcClient->eth_setMining(true);
BOOST_CHECK_EQUAL(web3->ethereum()->isMining(), true);
jsonrpcClient->eth_setMining(false);
BOOST_CHECK_EQUAL(web3->ethereum()->isMining(), false);
}
BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
cnote << "Testing jsonrpc stateAt...";
dev::KeyPair key = KeyPair::create();
auto address = key.address();
string stateAt = jsonrpcClient->eth_stateAt(toJS(address), "0");
BOOST_CHECK_EQUAL(toJS(web3->ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}
BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
cnote << "Testing jsonrpc transact...";
string coinbase = jsonrpcClient->eth_coinbase();
BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3->ethereum()->address());
dev::KeyPair key = KeyPair::create();
auto address = key.address();
auto receiver = KeyPair::create();
web3->ethereum()->setAddress(address);
coinbase = jsonrpcClient->eth_coinbase();
BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3->ethereum()->address());
BOOST_CHECK_EQUAL(jsToAddress(coinbase), address);
jsonrpcServer->setAccounts({key});
auto balance = web3->ethereum()->balanceAt(address, 0);
string balanceString = jsonrpcClient->eth_balanceAt(toJS(address));
double countAt = jsonrpcClient->eth_countAt(toJS(address));
BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3->ethereum()->countAt(address));
BOOST_CHECK_EQUAL(countAt, 0);
BOOST_CHECK_EQUAL(toJS(balance), balanceString);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "0");
dev::eth::mine(*(web3->ethereum()), 1);
balance = web3->ethereum()->balanceAt(address, 0);
balanceString = jsonrpcClient->eth_balanceAt(toJS(address));
BOOST_CHECK_EQUAL(toJS(balance), balanceString);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "1500000000000000000");
auto txAmount = balance / 2u;
auto gasPrice = 10 * dev::eth::szabo;
auto gas = dev::eth::c_txGas;
Json::Value t;
t["from"] = toJS(address);
t["value"] = jsToDecimal(toJS(txAmount));
t["to"] = toJS(receiver.address());
t["data"] = toJS(bytes());
t["gas"] = toJS(gas);
t["gasPrice"] = toJS(gasPrice);
jsonrpcClient->eth_transact(t);
jsonrpcServer->setAccounts({});
dev::eth::mine(*(web3->ethereum()), 1);
countAt = jsonrpcClient->eth_countAt(toJS(address));
auto balance2 = web3->ethereum()->balanceAt(receiver.address());
string balanceString2 = jsonrpcClient->eth_balanceAt(toJS(receiver.address()));
BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3->ethereum()->countAt(address));
BOOST_CHECK_EQUAL(countAt, 1);
BOOST_CHECK_EQUAL(toJS(balance2), balanceString2);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString2), "750000000000000000");
BOOST_CHECK_EQUAL(txAmount, balance2);
}
BOOST_AUTO_TEST_CASE(simple_contract)
{
cnote << "Testing jsonrpc contract...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = "contract test {\n"
" function f(uint a) returns(uint d) { return a * 7; }\n"
"}\n";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value call;
call["to"] = contractAddress;
call["data"] = "0x00000000000000000000000000000000000000000000000000000000000000001";
string result = jsonrpcClient->eth_call(call);
BOOST_CHECK_EQUAL(result, "0x0000000000000000000000000000000000000000000000000000000000000007");
}
BOOST_AUTO_TEST_CASE(contract_storage)
{
cnote << "Testing jsonrpc contract storage...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = R"(
contract test {
uint hello;
function writeHello(uint value) returns(bool d){
hello = value;
return true;
}
}
)";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value transact;
transact["to"] = contractAddress;
transact["data"] = "0x00000000000000000000000000000000000000000000000000000000000000003";
jsonrpcClient->eth_transact(transact);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value storage = jsonrpcClient->eth_storageAt(contractAddress);
BOOST_CHECK_EQUAL(storage.getMemberNames().size(), 1);
// bracers are required, cause msvc couldnt handle this macro in for statement
for (auto name: storage.getMemberNames())
{
BOOST_CHECK_EQUAL(storage[name].asString(), "0x03");
}
}
BOOST_AUTO_TEST_CASE(sha3)
{
cnote << "Testing jsonrpc sha3...";
string testString = "multiply(uint256)";
h256 expected = dev::sha3(testString);
auto hexValue = fromAscii(testString);
string result = jsonrpcClient->web3_sha3(hexValue);
BOOST_CHECK_EQUAL(toJS(expected), result);
BOOST_CHECK_EQUAL("0xc6888fa159d67f77c2f3d7a402e199802766bd7e8d4d1ecd2274fc920265d56a", result);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
#endif
<commit_msg>removed CorsHTTPServer<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/>.
*/
/** @file jsonrpc.cpp
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
// @debris disabled as tests fail with:
// unknown location(0): fatal error in "jsonrpc_setMining": std::exception: Exception -32003 : Client connector error: : libcurl error: 28
// /home/gav/Eth/cpp-ethereum/test/jsonrpc.cpp(169): last checkpoint
#if ETH_JSONRPC && 0
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libweb3jsonrpc/WebThreeStubServer.h>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"
BOOST_AUTO_TEST_SUITE(jsonrpc)
using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;
WebThreeDirect* web3;
unique_ptr<WebThreeStubServer> jsonrpcServer;
unique_ptr<WebThreeStubClient> jsonrpcClient;
struct Setup
{
Setup()
{
static bool setup = false;
if (setup)
return;
setup = true;
dev::p2p::NetworkPreferences nprefs(30303, std::string(), false);
web3 = new WebThreeDirect("Ethereum(++) tests", "", true, {"eth", "shh"}, nprefs);
web3->setIdealPeerCount(5);
web3->ethereum()->setForceMining(true);
auto server = new jsonrpc::HttpServer(8080);
jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(*server, *web3, {}));
jsonrpcServer->setIdentities({});
jsonrpcServer->StartListening();
auto client = new jsonrpc::HttpClient("http://localhost:8080");
jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(*client));
}
};
string fromAscii(string _s)
{
bytes b = asBytes(_s);
return "0x" + toHex(b);
}
BOOST_FIXTURE_TEST_SUITE(environment, Setup)
BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
cnote << "Testing jsonrpc defaultBlock...";
int defaultBlock = jsonrpcClient->eth_defaultBlock();
BOOST_CHECK_EQUAL(defaultBlock, web3->ethereum()->getDefault());
}
BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
cnote << "Testing jsonrpc gasPrice...";
string gasPrice = jsonrpcClient->eth_gasPrice();
BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}
BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
cnote << "Testing jsonrpc isListening...";
web3->startNetwork();
bool listeningOn = jsonrpcClient->eth_listening();
BOOST_CHECK_EQUAL(listeningOn, web3->isNetworkStarted());
web3->stopNetwork();
bool listeningOff = jsonrpcClient->eth_listening();
BOOST_CHECK_EQUAL(listeningOff, web3->isNetworkStarted());
}
BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
cnote << "Testing jsonrpc isMining...";
web3->ethereum()->startMining();
bool miningOn = jsonrpcClient->eth_mining();
BOOST_CHECK_EQUAL(miningOn, web3->ethereum()->isMining());
web3->ethereum()->stopMining();
bool miningOff = jsonrpcClient->eth_mining();
BOOST_CHECK_EQUAL(miningOff, web3->ethereum()->isMining());
}
BOOST_AUTO_TEST_CASE(jsonrpc_accounts)
{
cnote << "Testing jsonrpc accounts...";
std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
jsonrpcServer->setAccounts(keys);
Json::Value k = jsonrpcClient->eth_accounts();
jsonrpcServer->setAccounts({});
BOOST_CHECK_EQUAL(k.isArray(), true);
BOOST_CHECK_EQUAL(k.size(), keys.size());
for (auto &i:k)
{
auto it = std::find_if(keys.begin(), keys.end(), [i](dev::KeyPair const& keyPair)
{
return jsToAddress(i.asString()) == keyPair.address();
});
BOOST_CHECK_EQUAL(it != keys.end(), true);
}
}
BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
cnote << "Testing jsonrpc number2...";
int number = jsonrpcClient->eth_number();
BOOST_CHECK_EQUAL(number, web3->ethereum()->number() + 1);
dev::eth::mine(*(web3->ethereum()), 1);
int numberAfter = jsonrpcClient->eth_number();
BOOST_CHECK_EQUAL(number + 1, numberAfter);
BOOST_CHECK_EQUAL(numberAfter, web3->ethereum()->number() + 1);
}
BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
cnote << "Testing jsonrpc peerCount...";
int peerCount = jsonrpcClient->eth_peerCount();
BOOST_CHECK_EQUAL(web3->peerCount(), peerCount);
}
BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
cnote << "Testing jsonrpc setListening...";
jsonrpcClient->eth_setListening(true);
BOOST_CHECK_EQUAL(web3->isNetworkStarted(), true);
jsonrpcClient->eth_setListening(false);
BOOST_CHECK_EQUAL(web3->isNetworkStarted(), false);
}
BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
cnote << "Testing jsonrpc setMining...";
jsonrpcClient->eth_setMining(true);
BOOST_CHECK_EQUAL(web3->ethereum()->isMining(), true);
jsonrpcClient->eth_setMining(false);
BOOST_CHECK_EQUAL(web3->ethereum()->isMining(), false);
}
BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
cnote << "Testing jsonrpc stateAt...";
dev::KeyPair key = KeyPair::create();
auto address = key.address();
string stateAt = jsonrpcClient->eth_stateAt(toJS(address), "0");
BOOST_CHECK_EQUAL(toJS(web3->ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}
BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
cnote << "Testing jsonrpc transact...";
string coinbase = jsonrpcClient->eth_coinbase();
BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3->ethereum()->address());
dev::KeyPair key = KeyPair::create();
auto address = key.address();
auto receiver = KeyPair::create();
web3->ethereum()->setAddress(address);
coinbase = jsonrpcClient->eth_coinbase();
BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3->ethereum()->address());
BOOST_CHECK_EQUAL(jsToAddress(coinbase), address);
jsonrpcServer->setAccounts({key});
auto balance = web3->ethereum()->balanceAt(address, 0);
string balanceString = jsonrpcClient->eth_balanceAt(toJS(address));
double countAt = jsonrpcClient->eth_countAt(toJS(address));
BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3->ethereum()->countAt(address));
BOOST_CHECK_EQUAL(countAt, 0);
BOOST_CHECK_EQUAL(toJS(balance), balanceString);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "0");
dev::eth::mine(*(web3->ethereum()), 1);
balance = web3->ethereum()->balanceAt(address, 0);
balanceString = jsonrpcClient->eth_balanceAt(toJS(address));
BOOST_CHECK_EQUAL(toJS(balance), balanceString);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "1500000000000000000");
auto txAmount = balance / 2u;
auto gasPrice = 10 * dev::eth::szabo;
auto gas = dev::eth::c_txGas;
Json::Value t;
t["from"] = toJS(address);
t["value"] = jsToDecimal(toJS(txAmount));
t["to"] = toJS(receiver.address());
t["data"] = toJS(bytes());
t["gas"] = toJS(gas);
t["gasPrice"] = toJS(gasPrice);
jsonrpcClient->eth_transact(t);
jsonrpcServer->setAccounts({});
dev::eth::mine(*(web3->ethereum()), 1);
countAt = jsonrpcClient->eth_countAt(toJS(address));
auto balance2 = web3->ethereum()->balanceAt(receiver.address());
string balanceString2 = jsonrpcClient->eth_balanceAt(toJS(receiver.address()));
BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3->ethereum()->countAt(address));
BOOST_CHECK_EQUAL(countAt, 1);
BOOST_CHECK_EQUAL(toJS(balance2), balanceString2);
BOOST_CHECK_EQUAL(jsToDecimal(balanceString2), "750000000000000000");
BOOST_CHECK_EQUAL(txAmount, balance2);
}
BOOST_AUTO_TEST_CASE(simple_contract)
{
cnote << "Testing jsonrpc contract...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = "contract test {\n"
" function f(uint a) returns(uint d) { return a * 7; }\n"
"}\n";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value call;
call["to"] = contractAddress;
call["data"] = "0x00000000000000000000000000000000000000000000000000000000000000001";
string result = jsonrpcClient->eth_call(call);
BOOST_CHECK_EQUAL(result, "0x0000000000000000000000000000000000000000000000000000000000000007");
}
BOOST_AUTO_TEST_CASE(contract_storage)
{
cnote << "Testing jsonrpc contract storage...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = R"(
contract test {
uint hello;
function writeHello(uint value) returns(bool d){
hello = value;
return true;
}
}
)";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value transact;
transact["to"] = contractAddress;
transact["data"] = "0x00000000000000000000000000000000000000000000000000000000000000003";
jsonrpcClient->eth_transact(transact);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value storage = jsonrpcClient->eth_storageAt(contractAddress);
BOOST_CHECK_EQUAL(storage.getMemberNames().size(), 1);
// bracers are required, cause msvc couldnt handle this macro in for statement
for (auto name: storage.getMemberNames())
{
BOOST_CHECK_EQUAL(storage[name].asString(), "0x03");
}
}
BOOST_AUTO_TEST_CASE(sha3)
{
cnote << "Testing jsonrpc sha3...";
string testString = "multiply(uint256)";
h256 expected = dev::sha3(testString);
auto hexValue = fromAscii(testString);
string result = jsonrpcClient->web3_sha3(hexValue);
BOOST_CHECK_EQUAL(toJS(expected), result);
BOOST_CHECK_EQUAL("0xc6888fa159d67f77c2f3d7a402e199802766bd7e8d4d1ecd2274fc920265d56a", result);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-present Facebook, Inc.
*
* 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 <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h>
#include <proxygen/httpserver/HTTPServerAcceptor.h>
#include <proxygen/httpserver/HTTPServerOptions.h>
#include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h>
#include <proxygen/lib/http/session/HTTPDownstreamSession.h>
#include <proxygen/lib/http/session/HTTPSession.h>
#include <proxygen/lib/http/session/SimpleController.h>
#include <wangle/acceptor/ManagedConnection.h>
namespace apache {
namespace thrift {
namespace {
// Class for managing lifetime of objects supporting an HTTP2 session.
class HTTP2RoutingSessionManager
: public proxygen::HTTPSession::EmptyInfoCallback {
public:
~HTTP2RoutingSessionManager() = default;
proxygen::HTTPDownstreamSession* CreateSession(
proxygen::HTTPServerOptions* options,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress* peerAddress,
wangle::TransportInfo const& tinfo) {
// Create the SimpleController
auto ipConfig = proxygen::HTTPServer::IPConfig(
*peerAddress, proxygen::HTTPServer::Protocol::HTTP2);
auto acceptorConfig =
proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options);
serverAcceptor_ =
proxygen::HTTPServerAcceptor::make(acceptorConfig, *options);
controller_ = new proxygen::SimpleController(serverAcceptor_.get());
// Get the HTTP2 Codec
auto codecFactory =
proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig);
auto h2codec =
codecFactory.getCodec("h2", proxygen::TransportDirection::DOWNSTREAM);
// Obtain the proper routing address
folly::SocketAddress localAddress;
try {
sock->getLocalAddress(&localAddress);
} catch (...) {
VLOG(3) << "couldn't get local address for socket";
localAddress = folly::SocketAddress("0.0.0.0", 0);
}
VLOG(4) << "Created new session for peer " << *peerAddress;
// Create the DownstreamSession
auto session = new proxygen::HTTPDownstreamSession(
proxygen::WheelTimerInstance(std::chrono::milliseconds(5)),
std::move(sock),
localAddress,
*peerAddress,
controller_,
std::move(h2codec),
tinfo,
this);
/*
if (acceptorConfig.maxConcurrentIncomingStreams) {
session->setMaxConcurrentIncomingStreams(
acceptorConfig.maxConcurrentIncomingStreams);
}
*/
// TODO: Improve the way max incoming streams is set
session->setMaxConcurrentIncomingStreams(100000);
// Set HTTP2 priorities flag on session object.
session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled);
// Set flow control parameters.
session->setFlowControl(
acceptorConfig.initialReceiveWindow,
acceptorConfig.receiveStreamWindowSize,
acceptorConfig.receiveSessionWindowSize);
if (acceptorConfig.writeBufferLimit > 0) {
session->setWriteBufferLimit(acceptorConfig.writeBufferLimit);
}
return session;
}
void onDestroy(const proxygen::HTTPSession&) override {
VLOG(4) << "HTTP2RoutingSessionManager::onDestroy";
// Session destroyed, so self destroy.
delete this;
}
private:
// Supporting objects for HTTP2 session managed by the callback.
std::unique_ptr<proxygen::HTTPServerAcceptor> serverAcceptor_;
// The controller should only be destroyed once onDestroy is called.
proxygen::SimpleController* controller_;
};
} // anonymous namespace
bool HTTP2RoutingHandler::canAcceptConnection(
const std::vector<uint8_t>& bytes) {
/*
* HTTP/2.0 requests start with the following sequence:
* Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a
* String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
*
* For more, see: https://tools.ietf.org/html/rfc7540#section-3.5
*/
if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) {
return true;
}
/*
* HTTP requests start with the following sequence:
* Octal: "0x485454502f..."
* String: "HTTP/X.X"
*
* For more, see: https://tools.ietf.org/html/rfc2616#section-3
*/
if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) {
return true;
}
return false;
}
bool HTTP2RoutingHandler::canAcceptEncryptedConnection(
const std::string& protocolName) {
return protocolName == "h2" || protocolName == "http";
}
void HTTP2RoutingHandler::handleConnection(
wangle::ConnectionManager* connectionManager,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress* peerAddress,
wangle::TransportInfo const& tinfo) {
// Create the DownstreamSession manager.
std::unique_ptr<HTTP2RoutingSessionManager> sessionManager(
new HTTP2RoutingSessionManager);
// Create the DownstreamSession
auto session = sessionManager->CreateSession(
options_.get(), std::move(sock), peerAddress, tinfo);
// Route the connection.
connectionManager->addConnection(session);
sessionManager.release();
session->startNow();
}
} // namspace thrift
} // namespace apache
<commit_msg>Cleanup HTTPSession.h<commit_after>/*
* Copyright 2004-present Facebook, Inc.
*
* 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 <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h>
#include <proxygen/httpserver/HTTPServerAcceptor.h>
#include <proxygen/httpserver/HTTPServerOptions.h>
#include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h>
#include <proxygen/lib/http/session/HTTPDownstreamSession.h>
#include <proxygen/lib/http/session/HTTPSession.h>
#include <proxygen/lib/http/session/SimpleController.h>
#include <wangle/acceptor/ManagedConnection.h>
namespace apache {
namespace thrift {
namespace {
// Class for managing lifetime of objects supporting an HTTP2 session.
class HTTP2RoutingSessionManager : public proxygen::EmptyInfoCallback {
public:
~HTTP2RoutingSessionManager() = default;
proxygen::HTTPDownstreamSession* CreateSession(
proxygen::HTTPServerOptions* options,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress* peerAddress,
wangle::TransportInfo const& tinfo) {
// Create the SimpleController
auto ipConfig = proxygen::HTTPServer::IPConfig(
*peerAddress, proxygen::HTTPServer::Protocol::HTTP2);
auto acceptorConfig =
proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options);
serverAcceptor_ =
proxygen::HTTPServerAcceptor::make(acceptorConfig, *options);
controller_ = new proxygen::SimpleController(serverAcceptor_.get());
// Get the HTTP2 Codec
auto codecFactory =
proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig);
auto h2codec =
codecFactory.getCodec("h2", proxygen::TransportDirection::DOWNSTREAM);
// Obtain the proper routing address
folly::SocketAddress localAddress;
try {
sock->getLocalAddress(&localAddress);
} catch (...) {
VLOG(3) << "couldn't get local address for socket";
localAddress = folly::SocketAddress("0.0.0.0", 0);
}
VLOG(4) << "Created new session for peer " << *peerAddress;
// Create the DownstreamSession
auto session = new proxygen::HTTPDownstreamSession(
proxygen::WheelTimerInstance(std::chrono::milliseconds(5)),
std::move(sock),
localAddress,
*peerAddress,
controller_,
std::move(h2codec),
tinfo,
this);
/*
if (acceptorConfig.maxConcurrentIncomingStreams) {
session->setMaxConcurrentIncomingStreams(
acceptorConfig.maxConcurrentIncomingStreams);
}
*/
// TODO: Improve the way max incoming streams is set
session->setMaxConcurrentIncomingStreams(100000);
// Set HTTP2 priorities flag on session object.
session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled);
// Set flow control parameters.
session->setFlowControl(
acceptorConfig.initialReceiveWindow,
acceptorConfig.receiveStreamWindowSize,
acceptorConfig.receiveSessionWindowSize);
if (acceptorConfig.writeBufferLimit > 0) {
session->setWriteBufferLimit(acceptorConfig.writeBufferLimit);
}
return session;
}
void onDestroy(const proxygen::HTTPSession&) override {
VLOG(4) << "HTTP2RoutingSessionManager::onDestroy";
// Session destroyed, so self destroy.
delete this;
}
private:
// Supporting objects for HTTP2 session managed by the callback.
std::unique_ptr<proxygen::HTTPServerAcceptor> serverAcceptor_;
// The controller should only be destroyed once onDestroy is called.
proxygen::SimpleController* controller_;
};
} // anonymous namespace
bool HTTP2RoutingHandler::canAcceptConnection(
const std::vector<uint8_t>& bytes) {
/*
* HTTP/2.0 requests start with the following sequence:
* Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a
* String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
*
* For more, see: https://tools.ietf.org/html/rfc7540#section-3.5
*/
if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) {
return true;
}
/*
* HTTP requests start with the following sequence:
* Octal: "0x485454502f..."
* String: "HTTP/X.X"
*
* For more, see: https://tools.ietf.org/html/rfc2616#section-3
*/
if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) {
return true;
}
return false;
}
bool HTTP2RoutingHandler::canAcceptEncryptedConnection(
const std::string& protocolName) {
return protocolName == "h2" || protocolName == "http";
}
void HTTP2RoutingHandler::handleConnection(
wangle::ConnectionManager* connectionManager,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress* peerAddress,
wangle::TransportInfo const& tinfo) {
// Create the DownstreamSession manager.
std::unique_ptr<HTTP2RoutingSessionManager> sessionManager(
new HTTP2RoutingSessionManager);
// Create the DownstreamSession
auto session = sessionManager->CreateSession(
options_.get(), std::move(sock), peerAddress, tinfo);
// Route the connection.
connectionManager->addConnection(session);
sessionManager.release();
session->startNow();
}
} // namspace thrift
} // namespace apache
<|endoftext|>
|
<commit_before>/*
* FogLAMP process class
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Massimiliano Pinto
*/
/**
* FogLAMP process base class
*/
#include <iostream>
#include <logger.h>
#include <process.h>
#include <service_record.h>
#define LOG_SERVICE_NAME "FogLAMP Process"
using namespace std;
// Destructor
FogLampProcess::~FogLampProcess()
{
delete m_client;
delete m_storage;
delete m_logger;
}
// Constructor
FogLampProcess::FogLampProcess(int argc, char** argv) :
m_stime(time(NULL)),
m_argc(argc),
m_arg_vals((const char**) argv)
{
string myName = LOG_SERVICE_NAME;
m_logger = new Logger(myName);
try
{
m_core_mngt_host = getArgValue("--address=");
m_core_mngt_port = atoi(getArgValue("--port=").c_str());
m_name = getArgValue("--name=");
}
catch (exception e)
{
throw runtime_error(string("Error while parsing required options: ") + e.what());
}
if (m_core_mngt_host.empty())
{
throw runtime_error("Error: --address is not specified");
}
else if (m_core_mngt_port == 0)
{
throw runtime_error("Error: --port is not specified");
}
else if (m_name.empty())
{
throw runtime_error("Error: --name is not specified");
}
m_logger->setMinLevel("warning"); // Default to warnings, errors and fatal for log messages
try
{
string minLogLevel = getArgValue("--loglevel=");
m_logger->setMinLevel(minLogLevel);
}
catch (exception e)
{
throw runtime_error(string("Error while parsing optional options: ") + e.what());
}
// Connection to FogLamp core microservice
m_client = new ManagementClient(m_core_mngt_host, m_core_mngt_port);
// Storage layer handle
ServiceRecord storageInfo("FogLAMP Storage");
if (!m_client->getService(storageInfo))
{
string errMsg("Unable to find storage service at ");
errMsg += m_core_mngt_host;
errMsg += ':';
errMsg += to_string(m_core_mngt_port);
throw runtime_error(errMsg);
}
if (!(m_storage = new StorageClient(storageInfo.getAddress(),
storageInfo.getPort())))
{
string errMsg("Unable to connect to storage service at ");
errMsg.append(storageInfo.getAddress());
errMsg += ':';
errMsg += to_string(storageInfo.getPort());
throw runtime_error(errMsg);
}
}
/**
* Get command line argument value like "--xyx=ABC"
* Argument name to pass is "--xyz="
*
* @param name The argument name (--xyz=)
* @return The argument value if found or an emopty string
*/
string FogLampProcess::getArgValue(const string& name) const
{
for (int i=1; i < m_argc; i++)
{
if (strncmp(m_arg_vals[i], name.c_str(), name.length()) == 0)
{
// Return the option value (after "--xyx=ABC"
return string(m_arg_vals[i] + name.length());
}
}
// Return empty string
return string("");
}
/**
* Return storage client
*/
StorageClient* FogLampProcess::getStorageClient() const
{
return m_storage;
}
/**
* Return management client
*/
ManagementClient* FogLampProcess::getManagementClient() const
{
return m_client;
}
/**
* Return Logger
*/
Logger *FogLampProcess::getLogger() const
{
return m_logger;
}
<commit_msg>FOGL-2423 Fix settign log level via command line<commit_after>/*
* FogLAMP process class
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Massimiliano Pinto
*/
/**
* FogLAMP process base class
*/
#include <iostream>
#include <logger.h>
#include <process.h>
#include <service_record.h>
#define LOG_SERVICE_NAME "FogLAMP Process"
using namespace std;
// Destructor
FogLampProcess::~FogLampProcess()
{
delete m_client;
delete m_storage;
delete m_logger;
}
// Constructor
FogLampProcess::FogLampProcess(int argc, char** argv) :
m_stime(time(NULL)),
m_argc(argc),
m_arg_vals((const char**) argv)
{
string myName = LOG_SERVICE_NAME;
m_logger = new Logger(myName);
try
{
m_core_mngt_host = getArgValue("--address=");
m_core_mngt_port = atoi(getArgValue("--port=").c_str());
m_name = getArgValue("--name=");
}
catch (exception e)
{
throw runtime_error(string("Error while parsing required options: ") + e.what());
}
if (m_core_mngt_host.empty())
{
throw runtime_error("Error: --address is not specified");
}
else if (m_core_mngt_port == 0)
{
throw runtime_error("Error: --port is not specified");
}
else if (m_name.empty())
{
throw runtime_error("Error: --name is not specified");
}
m_logger->setMinLevel("warning"); // Default to warnings, errors and fatal for log messages
try
{
string minLogLevel = getArgValue("--loglevel=");
if (!minLogLevel.empty())
{
m_logger->setMinLevel(minLogLevel);
}
}
catch (exception e)
{
throw runtime_error(string("Error while parsing optional options: ") + e.what());
}
// Connection to FogLamp core microservice
m_client = new ManagementClient(m_core_mngt_host, m_core_mngt_port);
// Storage layer handle
ServiceRecord storageInfo("FogLAMP Storage");
if (!m_client->getService(storageInfo))
{
string errMsg("Unable to find storage service at ");
errMsg += m_core_mngt_host;
errMsg += ':';
errMsg += to_string(m_core_mngt_port);
throw runtime_error(errMsg);
}
if (!(m_storage = new StorageClient(storageInfo.getAddress(),
storageInfo.getPort())))
{
string errMsg("Unable to connect to storage service at ");
errMsg.append(storageInfo.getAddress());
errMsg += ':';
errMsg += to_string(storageInfo.getPort());
throw runtime_error(errMsg);
}
}
/**
* Get command line argument value like "--xyx=ABC"
* Argument name to pass is "--xyz="
*
* @param name The argument name (--xyz=)
* @return The argument value if found or an emopty string
*/
string FogLampProcess::getArgValue(const string& name) const
{
for (int i=1; i < m_argc; i++)
{
if (strncmp(m_arg_vals[i], name.c_str(), name.length()) == 0)
{
// Return the option value (after "--xyx=ABC"
return string(m_arg_vals[i] + name.length());
}
}
// Return empty string
return string("");
}
/**
* Return storage client
*/
StorageClient* FogLampProcess::getStorageClient() const
{
return m_storage;
}
/**
* Return management client
*/
ManagementClient* FogLampProcess::getManagementClient() const
{
return m_client;
}
/**
* Return Logger
*/
Logger *FogLampProcess::getLogger() const
{
return m_logger;
}
<|endoftext|>
|
<commit_before>
#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
//#include "ctwin.h"
#endif
#include "global.h"
#include "ctexceptions.h"
#include "stringUtils.h"
#include "units.h"
#ifndef WIN32
#include "ctdir.h"
#endif
#include <fstream>
using namespace std;
//int writeToMatlab(const char* buf);
namespace Cantera {
/**
* Class to hold global data. Class Application is the top-level
* class that stores data that should persist for the duration of
* the process. The class should not be instantiated directly;
* instead, it is instantiated as needed by the functions declared
* here. At most one instance is created, and it is not destroyed
* until the process terminates.
*/
class Application {
public:
Application() : linelen(0), stop_on_error(false),
tmp_dir("/tmp") {}
virtual ~Application(){}
vector<string> inputDirs;
vector<string> errorMessage;
vector<string> warning;
vector<string> errorRoutine;
string msglog;
size_t linelen;
bool stop_on_error;
//bool write_log_to_cout;
//bool matlab;
map<string, string> options;
string tmp_dir;
};
/// Returns a pointer to the one and only instance of Application
Application* app();
void setDefaultDirectories();
static Application* __app = 0;
Unit* Unit::__u = 0;
static void appinit() {
if (__app == 0) __app = new Application;
}
Application* app() {
if (__app == 0) {
__app = new Application;
setDefaultDirectories();
}
return __app;
}
void setTmpDir(string tmp) { app()->tmp_dir = tmp; }
string tmpDir() { appinit(); return app()->tmp_dir; }
int nErrors() {return app()->errorMessage.size();}
void popError() {
appinit();
if (nErrors() > 0) {
__app->errorMessage.pop_back();
__app->errorRoutine.pop_back();
}
}
string lastErrorMessage() {
appinit();
if (nErrors() > 0)
return "\nProcedure: "+__app->errorRoutine.back()+"\nError: "+__app->errorMessage.back();
else
return "<no Cantera error>";
}
void showErrors(ostream& f) {
appinit();
int i = __app->errorMessage.size();
if (i == 0) return;
f << endl << endl;
f << "************************************************" << endl;
f << " Cantera Error! " << endl;
f << "************************************************" << endl << endl;
int j;
for (j = 0; j < i; j++) {
f << endl;
f << "Procedure: " << __app->errorRoutine[j] << endl;
f << "Error: " << __app->errorMessage[j] << endl;
}
f << endl << endl;
__app->errorMessage.clear();
__app->errorRoutine.clear();
//if (__app->stop_on_error) exit(-1);
}
void setError(string r, string msg) {
appinit();
__app->errorMessage.push_back(msg);
__app->errorRoutine.push_back(r);
}
/**
* Set the default directories for input files. Four directories are
* added to the search path used by findInputFile. These are
* 'data', 'data/inputs', 'data/thermo', and
* 'data/transport'. These names are for convenience only -
* findInputFile searches all of them, independent of the type of
* file. The location of the 'data' directory depends on how
* environment variables are set. If CANTERA_DATA_DIR is set, then
* this will be used instead of 'data'. In addition, if
* WIN_CANTERA_ROOT or CANTERA_ROOT are set, then 'data' is
* assumed to be a top-level subdirectory. WIN_CANTERA_ROOT should
* only be set on PCs, and should be in 'DOS' format, for example
* 'C:\CANTERA'. CANTERA_ROOT, on the other hand, should be in
* unix-like format ('/home/usr/cantera'). This allows Cantera to
* be built on PCs using a unix-like environment (Cygwin) and
* compiler (g++), as well as using Win32 compilers.
*/
void setDefaultDirectories() {
appinit();
vector<string>& dirs = __app->inputDirs;
// always look in the local directory first
dirs.push_back(".");
#ifdef WIN32
/*
* Under Windows, the Cantera setup utility puts data files in
* a directory 'Cantera\data' below the one the environment
* variable COMMONPROGRAMFILES points to. (This is usually
* C:\Program Files\Common Files.) If this environment
* variable is defined, then this directory is assumed to
* exist and is added to the search path.
*/
const char* comfiles = getenv("COMMONPROGRAMFILES");
if (comfiles != 0) {
string cfiles = string(comfiles);
// remove quotes if necessary
if (cfiles[0] == '\'')
cfiles = cfiles.substr(1,1000);
if (cfiles[cfiles.size()-1] == '\'') cfiles[cfiles.size()-1] = '\n';
string datadir = string(comfiles) + "/Cantera/data";
string tmpldir = string(comfiles) + "/Cantera/templates";
dirs.push_back(datadir);
dirs.push_back(tmpldir);
}
#endif
if (getenv("CANTERA_DATA") != 0) {
string datadir = string(getenv("CANTERA_DATA"));
dirs.push_back(datadir);
}
// CANTERA_ROOT is defined in file ctdir.h. This file is written
// during the build process (unix), and points to the directory
// specified by the 'prefix' option to 'configure', or else to
// /usr/local/cantera. This will generally not be defined under
// Windows.
#ifdef CANTERA_ROOT
string datadir = string(CANTERA_ROOT) + "/data";
dirs.push_back(datadir);
#endif
}
void addDirectory(string dir) {
appinit();
if (__app->inputDirs.size() == 0) setDefaultDirectories();
__app->inputDirs.push_back(stripnonprint(dir));
}
/**
* findInputFile():
*
* This routine will search for a file in the default
* locations specified for the application.
* See the routine setDefaultDirectories() listed above.
*
* The default set of directories specified for the application
* will be searched if a '/' or an '\\' is not found in
* name. If either is found then a relative path name is
* presumed and the default directories are not searched.
*
* The presence of the file is determined by whether the file
* can be opened for reading by the current user.
*
* Return
* -------
* The absolute path name of the first matching
* file is returned. If a relative path name
* is indicated, the relative path name is returned.
*
* If the file is not found, a message is written to
* stdout and a CanteraError exception is thrown.
*/
string findInputFile(string name) {
appinit();
int islash = name.find('/');
int ibslash = name.find('\\');
string inname;
vector<string>& dirs = __app->inputDirs;
if (dirs.size() == 0) setDefaultDirectories();
int nd;
if (islash < 0 && ibslash < 0) {
nd = dirs.size();
int i;
inname = "";
for (i = 0; i < nd; i++) {
inname = dirs[i] + "/" + name;
ifstream fin(inname.c_str());
if (fin) {
fin.close();
return inname;
}
}
string msg;
msg = "\nInput file " + name
+ " not found in director";
msg += (nd == 1 ? "y " : "ies ");
for (i = 0; i < nd; i++) {
msg += "\n'" + dirs[i] + "'";
if (i < nd-1) msg += ", ";
}
msg += "\n\n";
msg += "To fix this problem, either:\n";
msg += " a) move the missing files into the local directory;\n";
msg += " b) define environment variable CANTERA_DATA to\n";
msg += " point to the directory containing the file.";
throw CanteraError("findInputFile", msg);
return "";
}
else {
return name;
}
}
//void setMatlabMode(bool m) {
// appinit();
// __app->matlab = m;
//}
//void write(const string& msg) {cout << msg;}
//void write(const char* msg) {cout << msg;}
void writelog(const char* msg) {writelog(string(msg));}
//void getlog(string& s) {
// appinit();
// s = __app->msglog;
// //__app->msglog = "";
//}
//void clearlog() {
// __app->msglog = "";
//}
doublereal toSI(string unit) {
doublereal f = Unit::units()->toSI(unit);
if (f) return f;
else return 1.0;
}
doublereal actEnergyToSI(string unit) {
doublereal f = Unit::units()->actEnergyToSI(unit);
if (f) return f;
else return 1.0;
}
string canteraRoot() {
char* ctroot = 0;
ctroot = getenv("CANTERA_ROOT");
if (ctroot != 0) { return string(ctroot); }
else {
#ifdef CANTERA_ROOT
return string(CANTERA_ROOT);
#else
return "";
#endif
}
}
}
<commit_msg>added option to clear all entries in close_XML_File.<commit_after>
#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
//#include "ctwin.h"
#endif
#include "global.h"
#include "ctexceptions.h"
#include "stringUtils.h"
#include "units.h"
#include "xml.h"
#include "ctml.h"
#ifndef WIN32
#include "ctdir.h"
#endif
#include <fstream>
using namespace std;
//int writeToMatlab(const char* buf);
namespace Cantera {
/**
* Class to hold global data. Class Application is the top-level
* class that stores data that should persist for the duration of
* the process. The class should not be instantiated directly;
* instead, it is instantiated as needed by the functions declared
* here. At most one instance is created, and it is not destroyed
* until the process terminates.
*/
class Application {
public:
Application() : linelen(0), stop_on_error(false),
tmp_dir("/tmp") {}
virtual ~Application(){}
vector<string> inputDirs;
vector<string> errorMessage;
vector<string> warning;
vector<string> errorRoutine;
string msglog;
size_t linelen;
bool stop_on_error;
//bool write_log_to_cout;
//bool matlab;
map<string, string> options;
string tmp_dir;
map<string, XML_Node*> xmlfiles;
};
/// Returns a pointer to the one and only instance of Application
Application* app();
void setDefaultDirectories();
static Application* __app = 0;
Unit* Unit::__u = 0;
static void appinit() {
if (__app == 0) __app = new Application;
}
Application* app() {
if (__app == 0) {
__app = new Application;
setDefaultDirectories();
}
return __app;
}
XML_Node* get_XML_File(string file) {
if (app()->xmlfiles.find(file)
== app()->xmlfiles.end()) {
string path = findInputFile(file);
/*
* Check whether or not the file is XML. If not, it will
* be first processed with the preprocessor.
*/
string::size_type idot = path.rfind('.');
string ext, ff;
if (idot != string::npos) {
ext = path.substr(idot, path.size());
}
if (ext != ".xml" && ext != ".ctml") {
ctml::ct2ctml(path.c_str());
ff = path.substr(0,idot) + ".xml";
}
else {
ff = path;
}
ifstream s(ff.c_str());
XML_Node* x = new XML_Node("doc");
x->build(s);
__app->xmlfiles[file] = x;
}
return __app->xmlfiles[file];
}
void close_XML_File(string file) {
if (file == "all") {
map<string, XML_Node*>::iterator
b = app()->xmlfiles.begin(), e = app()->xmlfiles.end();
for(; b != e; ++b) {
delete b->second;
__app->xmlfiles.erase(b->first);
}
}
else if (app()->xmlfiles.find(file)
!= app()->xmlfiles.end()) {
delete __app->xmlfiles[file];
__app->xmlfiles.erase(file);
}
}
void setTmpDir(string tmp) { app()->tmp_dir = tmp; }
string tmpDir() { appinit(); return app()->tmp_dir; }
int nErrors() {return app()->errorMessage.size();}
void popError() {
appinit();
if (nErrors() > 0) {
__app->errorMessage.pop_back();
__app->errorRoutine.pop_back();
}
}
string lastErrorMessage() {
appinit();
if (nErrors() > 0)
return "\nProcedure: "+__app->errorRoutine.back()+"\nError: "+__app->errorMessage.back();
else
return "<no Cantera error>";
}
void showErrors(ostream& f) {
appinit();
int i = __app->errorMessage.size();
if (i == 0) return;
f << endl << endl;
f << "************************************************" << endl;
f << " Cantera Error! " << endl;
f << "************************************************" << endl << endl;
int j;
for (j = 0; j < i; j++) {
f << endl;
f << "Procedure: " << __app->errorRoutine[j] << endl;
f << "Error: " << __app->errorMessage[j] << endl;
}
f << endl << endl;
__app->errorMessage.clear();
__app->errorRoutine.clear();
//if (__app->stop_on_error) exit(-1);
}
void setError(string r, string msg) {
appinit();
__app->errorMessage.push_back(msg);
__app->errorRoutine.push_back(r);
}
/**
* Set the default directories for input files. Four directories are
* added to the search path used by findInputFile. These are
* 'data', 'data/inputs', 'data/thermo', and
* 'data/transport'. These names are for convenience only -
* findInputFile searches all of them, independent of the type of
* file. The location of the 'data' directory depends on how
* environment variables are set. If CANTERA_DATA_DIR is set, then
* this will be used instead of 'data'. In addition, if
* WIN_CANTERA_ROOT or CANTERA_ROOT are set, then 'data' is
* assumed to be a top-level subdirectory. WIN_CANTERA_ROOT should
* only be set on PCs, and should be in 'DOS' format, for example
* 'C:\CANTERA'. CANTERA_ROOT, on the other hand, should be in
* unix-like format ('/home/usr/cantera'). This allows Cantera to
* be built on PCs using a unix-like environment (Cygwin) and
* compiler (g++), as well as using Win32 compilers.
*/
void setDefaultDirectories() {
appinit();
vector<string>& dirs = __app->inputDirs;
// always look in the local directory first
dirs.push_back(".");
#ifdef WIN32
/*
* Under Windows, the Cantera setup utility puts data files in
* a directory 'Cantera\data' below the one the environment
* variable COMMONPROGRAMFILES points to. (This is usually
* C:\Program Files\Common Files.) If this environment
* variable is defined, then this directory is assumed to
* exist and is added to the search path.
*/
const char* comfiles = getenv("COMMONPROGRAMFILES");
if (comfiles != 0) {
string cfiles = string(comfiles);
// remove quotes if necessary
if (cfiles[0] == '\'')
cfiles = cfiles.substr(1,1000);
if (cfiles[cfiles.size()-1] == '\'') cfiles[cfiles.size()-1] = '\n';
string datadir = string(comfiles) + "/Cantera/data";
string tmpldir = string(comfiles) + "/Cantera/templates";
dirs.push_back(datadir);
dirs.push_back(tmpldir);
}
#endif
if (getenv("CANTERA_DATA") != 0) {
string datadir = string(getenv("CANTERA_DATA"));
dirs.push_back(datadir);
}
// CANTERA_ROOT is defined in file ctdir.h. This file is written
// during the build process (unix), and points to the directory
// specified by the 'prefix' option to 'configure', or else to
// /usr/local/cantera. This will generally not be defined under
// Windows.
#ifdef CANTERA_ROOT
string datadir = string(CANTERA_ROOT) + "/data";
dirs.push_back(datadir);
#endif
}
void addDirectory(string dir) {
appinit();
if (__app->inputDirs.size() == 0) setDefaultDirectories();
__app->inputDirs.push_back(stripnonprint(dir));
}
/**
* findInputFile():
*
* This routine will search for a file in the default
* locations specified for the application.
* See the routine setDefaultDirectories() listed above.
*
* The default set of directories specified for the application
* will be searched if a '/' or an '\\' is not found in
* name. If either is found then a relative path name is
* presumed and the default directories are not searched.
*
* The presence of the file is determined by whether the file
* can be opened for reading by the current user.
*
* Return
* -------
* The absolute path name of the first matching
* file is returned. If a relative path name
* is indicated, the relative path name is returned.
*
* If the file is not found, a message is written to
* stdout and a CanteraError exception is thrown.
*/
string findInputFile(string name) {
appinit();
int islash = name.find('/');
int ibslash = name.find('\\');
string inname;
vector<string>& dirs = __app->inputDirs;
if (dirs.size() == 0) setDefaultDirectories();
int nd;
if (islash < 0 && ibslash < 0) {
nd = dirs.size();
int i;
inname = "";
for (i = 0; i < nd; i++) {
inname = dirs[i] + "/" + name;
ifstream fin(inname.c_str());
if (fin) {
fin.close();
return inname;
}
}
string msg;
msg = "\nInput file " + name
+ " not found in director";
msg += (nd == 1 ? "y " : "ies ");
for (i = 0; i < nd; i++) {
msg += "\n'" + dirs[i] + "'";
if (i < nd-1) msg += ", ";
}
msg += "\n\n";
msg += "To fix this problem, either:\n";
msg += " a) move the missing files into the local directory;\n";
msg += " b) define environment variable CANTERA_DATA to\n";
msg += " point to the directory containing the file.";
throw CanteraError("findInputFile", msg);
return "";
}
else {
return name;
}
}
//void setMatlabMode(bool m) {
// appinit();
// __app->matlab = m;
//}
//void write(const string& msg) {cout << msg;}
//void write(const char* msg) {cout << msg;}
void writelog(const char* msg) {writelog(string(msg));}
//void getlog(string& s) {
// appinit();
// s = __app->msglog;
// //__app->msglog = "";
//}
//void clearlog() {
// __app->msglog = "";
//}
doublereal toSI(string unit) {
doublereal f = Unit::units()->toSI(unit);
if (f) return f;
else return 1.0;
}
doublereal actEnergyToSI(string unit) {
doublereal f = Unit::units()->actEnergyToSI(unit);
if (f) return f;
else return 1.0;
}
string canteraRoot() {
char* ctroot = 0;
ctroot = getenv("CANTERA_ROOT");
if (ctroot != 0) { return string(ctroot); }
else {
#ifdef CANTERA_ROOT
return string(CANTERA_ROOT);
#else
return "";
#endif
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the Util library.
Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)
#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>
namespace Util {
namespace UI {
extern Key keySymToKey(KeySym sym);
struct WindowEGL::WindowEGLData {
EGLDisplay display;
EGLContext context;
EGLSurface surface;
WindowEGLData() :
display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
}
~WindowEGLData() {
if (display != EGL_NO_DISPLAY) {
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (surface != EGL_NO_SURFACE) {
eglDestroySurface(display, surface);
}
if (context != EGL_NO_CONTEXT) {
eglDestroyContext(display, context);
}
eglTerminate(display);
}
}
};
WindowEGL::WindowEGL(const Window::Properties & properties) :
WindowX11(properties), eglData(new WindowEGLData) {
eglData->display = eglGetDisplay(x11Data->display);
if (eglData->display == EGL_NO_DISPLAY) {
throw std::runtime_error("Failed to open display.");
}
EGLint versionMajor;
EGLint versionMinor;
if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
throw std::runtime_error("Failed to initialize display.");
}
// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
throw std::runtime_error("EGL version less than 1.3 detected.");
}
// Define attributes of desired framebuffer configurations
EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
// Request a single framebuffer configuration
EGLConfig fbConfig;
EGLint fbCount;
if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
}
if (fbCount == 0) {
// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
EGLConfig fbConfigs[200];
eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
for (EGLint i = 0; i < fbCount; ++i) {
EGLint value;
// We want to render into a window
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
if (!(value & EGL_WINDOW_BIT)) {
continue;
}
// We want a configuration with a depth buffer
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
if (value == 0) {
continue;
}
fbConfig = fbConfigs[i];
}
}
if (fbCount == 0) {
throw std::runtime_error("No matching framebuffer configurations found.");
}
EGLint visualID;
eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);
const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
if (eglData->context == EGL_NO_CONTEXT) {
throw std::runtime_error("Failed to create OpenGL ES 2.x context. " +
StringUtils::toString(eglGetError()));
}
// Create X11 window
XVisualInfo templateInfo;
templateInfo.visualid = visualID;
int visualCount;
XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
if (visualsInfo == nullptr) {
throw std::runtime_error("Failed to find a matching visual.");
} else if (visualCount != 1) {
XFree(visualsInfo);
throw std::runtime_error("More than one visual found.");
}
x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
x11Data->freeColorMap = true;
XSetWindowAttributes windowAttribs;
windowAttribs.colormap = x11Data->colorMap;
windowAttribs.background_pixmap = None;
windowAttribs.border_pixel = 0;
windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
0, visualsInfo[0].depth,
InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);
XFree(visualsInfo);
if (!x11Data->window) {
throw std::runtime_error("Failed to create window.");
} else {
x11Data->freeWindow = true;
}
if (properties.borderless) {
x11Data->removeWindowBorder();
}
if (!properties.resizable) {
x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
static_cast<int>(properties.clientAreaHeight));
}
x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
if (x11Data->inputMethod == nullptr) {
throw std::runtime_error("Failed to create input method.");
}
x11Data->inputContext = XCreateIC(x11Data->inputMethod,
XNInputStyle, XIMPreeditNone | XIMStatusNone,
XNClientWindow, x11Data->window,
XNFocusWindow, x11Data->window,
nullptr);
if (x11Data->inputContext == nullptr) {
throw std::runtime_error("Failed to create input context.");
}
XStoreName(x11Data->display, x11Data->window, properties.title.c_str());
XMapWindow(x11Data->display, x11Data->window);
if (properties.positioned) {
XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
}
eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
if (eglData->surface == EGL_NO_SURFACE) {
throw std::runtime_error("Failed to create window surface.");
}
eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}
WindowEGL::~WindowEGL() = default;
void WindowEGL::swapBuffers() {
eglSwapBuffers(eglData->display, eglData->surface);
}
}
}
#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<commit_msg>Add eglErrorToString<commit_after>/*
This file is part of the Util library.
Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>
Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)
#include "WindowEGL.h"
#include "WindowX11Data.h"
#include "../StringUtils.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <EGL/egl.h>
#include <memory>
#include <stdexcept>
namespace Util {
namespace UI {
extern Key keySymToKey(KeySym sym);
struct WindowEGL::WindowEGLData {
EGLDisplay display;
EGLContext context;
EGLSurface surface;
WindowEGLData() :
display(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {
}
~WindowEGLData() {
if (display != EGL_NO_DISPLAY) {
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (surface != EGL_NO_SURFACE) {
eglDestroySurface(display, surface);
}
if (context != EGL_NO_CONTEXT) {
eglDestroyContext(display, context);
}
eglTerminate(display);
}
}
};
static std::string eglErrorToString(const EGLint errorCode) {
const std::string strErrorCode = StringUtils::toString(errorCode);
switch(errorCode) {
case EGL_SUCCESS:
return "EGL_SUCCESS/" + strErrorCode + ": The last function succeeded without error.";
case EGL_NOT_INITIALIZED:
return "EGL_NOT_INITIALIZED/" + strErrorCode + ": EGL is not initialized, or could not be initialized, for the specified EGL display connection.";
case EGL_BAD_ACCESS:
return "EGL_BAD_ACCESS/" + strErrorCode + ": EGL cannot access a requested resource (for example a context is bound in another thread).";
case EGL_BAD_ALLOC:
return "EGL_BAD_ALLOC/" + strErrorCode + ": EGL failed to allocate resources for the requested operation.";
case EGL_BAD_ATTRIBUTE:
return "EGL_BAD_ATTRIBUTE/" + strErrorCode + ": An unrecognized attribute or attribute value was passed in the attribute list.";
case EGL_BAD_CONTEXT:
return "EGL_BAD_CONTEXT/" + strErrorCode + ": An EGLContext argument does not name a valid EGL rendering context.";
case EGL_BAD_CONFIG:
return "EGL_BAD_CONFIG/" + strErrorCode + ": An EGLConfig argument does not name a valid EGL frame buffer configuration.";
case EGL_BAD_CURRENT_SURFACE:
return "EGL_BAD_CURRENT_SURFACE/" + strErrorCode + ": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.";
case EGL_BAD_DISPLAY:
return "EGL_BAD_DISPLAY/" + strErrorCode + ": An EGLDisplay argument does not name a valid EGL display connection.";
case EGL_BAD_SURFACE:
return "EGL_BAD_SURFACE/" + strErrorCode + ": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.";
case EGL_BAD_MATCH:
return "EGL_BAD_MATCH/" + strErrorCode + ": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).";
case EGL_BAD_PARAMETER:
return "EGL_BAD_PARAMETER/" + strErrorCode + ": One or more argument values are invalid.";
case EGL_BAD_NATIVE_PIXMAP:
return "EGL_BAD_NATIVE_PIXMAP/" + strErrorCode + ": A NativePixmapType argument does not refer to a valid native pixmap.";
case EGL_BAD_NATIVE_WINDOW:
return "EGL_BAD_NATIVE_WINDOW/" + strErrorCode + ": A NativeWindowType argument does not refer to a valid native window.";
case EGL_CONTEXT_LOST:
return "EGL_CONTEXT_LOST/" + strErrorCode + ": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.";
default:
return "";
}
}
WindowEGL::WindowEGL(const Window::Properties & properties) :
WindowX11(properties), eglData(new WindowEGLData) {
eglData->display = eglGetDisplay(x11Data->display);
if (eglData->display == EGL_NO_DISPLAY) {
throw std::runtime_error("Failed to open display.");
}
EGLint versionMajor;
EGLint versionMinor;
if (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {
throw std::runtime_error("Failed to initialize display.");
}
// EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION
if ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {
throw std::runtime_error("EGL version less than 1.3 detected.");
}
// Define attributes of desired framebuffer configurations
EGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,
EGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
// Request a single framebuffer configuration
EGLConfig fbConfig;
EGLint fbCount;
if (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {
throw std::runtime_error("Failed to retrieve a matching framebuffer configuration.");
}
if (fbCount == 0) {
// FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.
EGLConfig fbConfigs[200];
eglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);
for (EGLint i = 0; i < fbCount; ++i) {
EGLint value;
// We want to render into a window
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);
if (!(value & EGL_WINDOW_BIT)) {
continue;
}
// We want a configuration with a depth buffer
eglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);
if (value == 0) {
continue;
}
fbConfig = fbConfigs[i];
}
}
if (fbCount == 0) {
throw std::runtime_error("No matching framebuffer configurations found.");
}
EGLint visualID;
eglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);
const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
eglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);
if (eglData->context == EGL_NO_CONTEXT) {
throw std::runtime_error("Failed to create OpenGL ES 2.x context. " +
eglErrorToString(eglGetError()));
}
// Create X11 window
XVisualInfo templateInfo;
templateInfo.visualid = visualID;
int visualCount;
XVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);
if (visualsInfo == nullptr) {
throw std::runtime_error("Failed to find a matching visual.");
} else if (visualCount != 1) {
XFree(visualsInfo);
throw std::runtime_error("More than one visual found.");
}
x11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);
x11Data->freeColorMap = true;
XSetWindowAttributes windowAttribs;
windowAttribs.colormap = x11Data->colorMap;
windowAttribs.background_pixmap = None;
windowAttribs.border_pixel = 0;
windowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
x11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen),
0, 0, properties.clientAreaWidth, properties.clientAreaHeight,
0, visualsInfo[0].depth,
InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);
XFree(visualsInfo);
if (!x11Data->window) {
throw std::runtime_error("Failed to create window.");
} else {
x11Data->freeWindow = true;
}
if (properties.borderless) {
x11Data->removeWindowBorder();
}
if (!properties.resizable) {
x11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth),
static_cast<int>(properties.clientAreaHeight));
}
x11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);
if (x11Data->inputMethod == nullptr) {
throw std::runtime_error("Failed to create input method.");
}
x11Data->inputContext = XCreateIC(x11Data->inputMethod,
XNInputStyle, XIMPreeditNone | XIMStatusNone,
XNClientWindow, x11Data->window,
XNFocusWindow, x11Data->window,
nullptr);
if (x11Data->inputContext == nullptr) {
throw std::runtime_error("Failed to create input context.");
}
XStoreName(x11Data->display, x11Data->window, properties.title.c_str());
XMapWindow(x11Data->display, x11Data->window);
if (properties.positioned) {
XMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);
}
eglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);
if (eglData->surface == EGL_NO_SURFACE) {
throw std::runtime_error("Failed to create window surface.");
}
eglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);
}
WindowEGL::~WindowEGL() = default;
void WindowEGL::swapBuffers() {
eglSwapBuffers(eglData->display, eglData->surface);
}
}
}
#endif /* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) */
<|endoftext|>
|
<commit_before>#include "ctreestateaddstatement.h"
/* Constructor */
CTreeStateAddStatement::CTreeStateAddStatement(TreeState* prev, QString s)
{
previous = prev;
desired = previous; // TODO: copy constructor
desired->addChildStatement(s);
}
/* Update the state to the one with the add */
void CTreeStateAddStatement::execute()
{
current = desired;
}
/* Revert to the state before the add */
void CTreeStateAddStatement::undo()
{
current = previous;
}
/* Re-add the statement after undo */
void CTreeStateAddStatement::redo()
{
current = desired;
}
<commit_msg>Updated to use copy constructor<commit_after>#include "ctreestateaddstatement.h"
/* Constructor */
CTreeStateAddStatement::CTreeStateAddStatement(TreeState* prev, QString s)
{
previous = prev;
desired = TreeState(prev);
desired->addChildStatement(s);
}
/* Update the state to the one with the add */
void CTreeStateAddStatement::execute()
{
current = desired;
}
/* Revert to the state before the add */
void CTreeStateAddStatement::undo()
{
current = previous;
}
/* Re-add the statement after undo */
void CTreeStateAddStatement::redo()
{
current = desired;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Common_KeyValuePair_inl_
#define _Stroika_Foundation_Common_KeyValuePair_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Common {
/*
********************************************************************************
******************** Common::KeyValuePair<KEY_TYPE,VALUE_TYPE> *****************
********************************************************************************
*/
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename K2, typename V2,
enable_if_t<
is_copy_constructible<K2>::value and
is_copy_constructible<V2>::value and
is_convertible<const K2&, K2>::value and
is_convertible<const V2&, V2>::value,
int>
ENABLE_IF>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyType& key, const ValueType& value)
: fKey (key)
, fValue (value)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and
is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value,
int>
ENABLE_IF_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const pair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.first)
, fValue (src.second)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
!(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_NOT_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const pair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.first)
, fValue (src.second)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.fKey)
, fValue (src.fValue)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
!(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_NOT_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.fKey)
, fValue (src.fValue)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (const pair<KEY_TYPE2, VALUE_TYPE2>& rhs)
{
fKey = rhs.first;
fValue = rhs.second;
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& rhs)
{
rhs = _Right.fKey;
rhs = _Right.fValue;
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (pair<KEY_TYPE2, VALUE_TYPE2>&& rhs)
{
fKey = std::forward<KEY_TYPE2> (rhs.first);
fValue = std::forward<VALUE_TYPE2> (rhs.second);
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (KeyValuePair<KEY_TYPE2, VALUE_TYPE2>&& rhs)
{
fKey = std::forward<KEY_TYPE2> (rhs.fKey);
fValue = std::forward<VALUE_TYPE2> (rhs.fValue);
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool KeyValuePair<KEY_TYPE, VALUE_TYPE>::Equals (const KeyValuePair<KeyType, ValueType>& rhs) const
{
return fKey == rhs.fKey and fValue == rhs.fValue;
}
/*
********************************************************************************
************************** KeyValuePair operators ******************************
********************************************************************************
*/
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool operator== (const KeyValuePair<KEY_TYPE, VALUE_TYPE>& lhs, const KeyValuePair<KEY_TYPE, VALUE_TYPE>& rhs)
{
return lhs.Equals (rhs);
}
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool operator!= (const KeyValuePair<KEY_TYPE, VALUE_TYPE>& lhs, const KeyValuePair<KEY_TYPE, VALUE_TYPE>& rhs)
{
return not lhs.Equals (rhs);
}
}
}
}
#endif /*_Stroika_Foundation_Common_KeyValuePair_inl_*/
<commit_msg>fixed a few types with KeyValuePair<> change<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Common_KeyValuePair_inl_
#define _Stroika_Foundation_Common_KeyValuePair_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Common {
/*
********************************************************************************
******************** Common::KeyValuePair<KEY_TYPE,VALUE_TYPE> *****************
********************************************************************************
*/
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename K2, typename V2,
enable_if_t<
is_copy_constructible<K2>::value and
is_copy_constructible<V2>::value and
is_convertible<const K2&, K2>::value and
is_convertible<const V2&, V2>::value,
int>
ENABLE_IF>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyType& key, const ValueType& value)
: fKey (key)
, fValue (value)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and
is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value,
int>
ENABLE_IF_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const pair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.first)
, fValue (src.second)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
!(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_NOT_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const pair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.first)
, fValue (src.second)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.fKey)
, fValue (src.fValue)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2,
enable_if_t<
is_constructible<KEY_TYPE, const KEY_TYPE2&>::value and
is_constructible<VALUE_TYPE, const VALUE_TYPE2&>::value and
!(is_convertible<const KEY_TYPE2&, KEY_TYPE>::value and is_convertible<const VALUE_TYPE2&, VALUE_TYPE>::value),
int>
ENABLE_IF_NOT_CONVERTIBLE>
inline constexpr KeyValuePair<KEY_TYPE, VALUE_TYPE>::KeyValuePair (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& src)
: fKey (src.fKey)
, fValue (src.fValue)
{
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (const pair<KEY_TYPE2, VALUE_TYPE2>& rhs)
{
fKey = rhs.first;
fValue = rhs.second;
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
inline KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (const KeyValuePair<KEY_TYPE2, VALUE_TYPE2>& rhs)
{
rhs = rhs.fKey;
rhs = rhs.fValue;
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
inline KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (pair<KEY_TYPE2, VALUE_TYPE2>&& rhs)
{
fKey = std::forward<KEY_TYPE2> (rhs.first);
fValue = std::forward<VALUE_TYPE2> (rhs.second);
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
template <typename KEY_TYPE2, typename VALUE_TYPE2>
inline KeyValuePair<KEY_TYPE, VALUE_TYPE>& KeyValuePair<KEY_TYPE, VALUE_TYPE>::operator= (KeyValuePair<KEY_TYPE2, VALUE_TYPE2>&& rhs)
{
fKey = std::forward<KEY_TYPE2> (rhs.fKey);
fValue = std::forward<VALUE_TYPE2> (rhs.fValue);
return *this;
}
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool KeyValuePair<KEY_TYPE, VALUE_TYPE>::Equals (const KeyValuePair<KeyType, ValueType>& rhs) const
{
return fKey == rhs.fKey and fValue == rhs.fValue;
}
/*
********************************************************************************
************************** KeyValuePair operators ******************************
********************************************************************************
*/
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool operator== (const KeyValuePair<KEY_TYPE, VALUE_TYPE>& lhs, const KeyValuePair<KEY_TYPE, VALUE_TYPE>& rhs)
{
return lhs.Equals (rhs);
}
template <typename KEY_TYPE, typename VALUE_TYPE>
inline bool operator!= (const KeyValuePair<KEY_TYPE, VALUE_TYPE>& lhs, const KeyValuePair<KEY_TYPE, VALUE_TYPE>& rhs)
{
return not lhs.Equals (rhs);
}
}
}
}
#endif /*_Stroika_Foundation_Common_KeyValuePair_inl_*/
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file pervertexphongalphamaterial.cpp
* @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief PerVertexPhongAlphaMaterial class definition
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "pervertexphongalphamaterial.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QColor>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qshaderprogram.h>
#include <Qt3DRender/qparameter.h>
#include <Qt3DRender/qrenderpass.h>
#include <QFilterKey>
#include <Qt3DRender/qdepthtest.h>
#include <Qt3DRender/qblendequation.h>
#include <Qt3DRender/qblendequationarguments.h>
#include <Qt3DRender/qnodepthmask.h>
#include <Qt3DRender/qgraphicsapifilter.h>
#include <QUrl>
#include <QVector3D>
#include <QVector4D>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISP3DLIB;
using namespace Qt3DRender;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
PerVertexPhongAlphaMaterial::PerVertexPhongAlphaMaterial(QNode *parent)
: QMaterial(parent)
, m_pVertexEffect(new QEffect())
, m_pDiffuseParameter(new QParameter(QStringLiteral("kd"), QColor::fromRgbF(0.7f, 0.7f, 0.7f, 1.0f)))
, m_pSpecularParameter(new QParameter(QStringLiteral("ks"), QColor::fromRgbF(0.1f, 0.1f, 0.1f, 1.0f)))
, m_pShininessParameter(new QParameter(QStringLiteral("shininess"), 15.0f))
, m_pAlphaParameter(new QParameter("alpha", 0.5f))
, m_pVertexGL3Technique(new QTechnique())
, m_pVertexGL3RenderPass(new QRenderPass())
, m_pVertexGL3Shader(new QShaderProgram())
, m_pVertexGL2Technique(new QTechnique())
, m_pVertexGL2RenderPass(new QRenderPass())
, m_pVertexES2Technique(new QTechnique())
, m_pVertexES2RenderPass(new QRenderPass())
, m_pVertexES2Shader(new QShaderProgram())
, m_pFilterKey(new QFilterKey)
, m_pNoDepthMask(new QNoDepthMask())
, m_pBlendState(new QBlendEquationArguments())
, m_pBlendEquation(new QBlendEquation())
{
this->init();
}
//*************************************************************************************************************
PerVertexPhongAlphaMaterial::~PerVertexPhongAlphaMaterial()
{
}
//*************************************************************************************************************
void PerVertexPhongAlphaMaterial::init()
{
//Set shader
m_pVertexGL3Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/gl3/pervertexphongalpha.vert"))));
m_pVertexGL3Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/gl3/pervertexphongalpha.frag"))));
m_pVertexES2Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/es2/pervertexphongalpha.vert"))));
m_pVertexES2Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/es2/pervertexphongalpha.frag"))));
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexGL3Shader);
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexES2Shader);
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexES2Shader);
//Set OpenGL version
m_pVertexGL3Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
m_pVertexGL3Technique->graphicsApiFilter()->setMajorVersion(4);
m_pVertexGL3Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexGL3Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile);
m_pVertexGL3Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
m_pVertexGL3Technique->graphicsApiFilter()->setMajorVersion(2);
m_pVertexGL3Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexGL3Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
m_pVertexGL3Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGLES);
m_pVertexGL3Technique->graphicsApiFilter()->setMajorVersion(2);
m_pVertexGL3Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexGL3Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
//Setup transparency
m_pBlendState->setSourceRgb(QBlendEquationArguments::SourceAlpha);
m_pBlendState->setDestinationRgb(QBlendEquationArguments::OneMinusSourceAlpha);
m_pBlendEquation->setBlendFunction(QBlendEquation::Add);
m_pVertexGL3RenderPass->addRenderState(m_pBlendEquation);
m_pVertexGL2RenderPass->addRenderState(m_pBlendEquation);
m_pVertexES2RenderPass->addRenderState(m_pBlendEquation);
m_pVertexGL3RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexGL2RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexES2RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexGL3RenderPass->addRenderState(m_pBlendState);
m_pVertexGL2RenderPass->addRenderState(m_pBlendState);
m_pVertexES2RenderPass->addRenderState(m_pBlendState);
m_pFilterKey->setName(QStringLiteral("renderingStyle"));
m_pFilterKey->setValue(QStringLiteral("forward"));
m_pVertexGL3Technique->addFilterKey(m_pFilterKey);
m_pVertexGL2Technique->addFilterKey(m_pFilterKey);
m_pVertexES2Technique->addFilterKey(m_pFilterKey);
m_pVertexGL3Technique->addRenderPass(m_pVertexGL3RenderPass);
m_pVertexGL2Technique->addRenderPass(m_pVertexGL2RenderPass);
m_pVertexES2Technique->addRenderPass(m_pVertexES2RenderPass);
m_pVertexEffect->addTechnique(m_pVertexGL3Technique);
m_pVertexEffect->addTechnique(m_pVertexGL2Technique);
m_pVertexEffect->addTechnique(m_pVertexES2Technique);
m_pVertexEffect->addParameter(m_pDiffuseParameter);
m_pVertexEffect->addParameter(m_pSpecularParameter);
m_pVertexEffect->addParameter(m_pShininessParameter);
m_pVertexEffect->addParameter(m_pAlphaParameter);
this->setEffect(m_pVertexEffect);
}
//*************************************************************************************************************
float PerVertexPhongAlphaMaterial::alpha()
{
return m_pAlphaParameter->value().toFloat();
}
//*************************************************************************************************************
void PerVertexPhongAlphaMaterial::setAlpha(float alpha)
{
m_pAlphaParameter->setValue(alpha);
}
<commit_msg>[LIB-149] Fix naming bug<commit_after>//=============================================================================================================
/**
* @file pervertexphongalphamaterial.cpp
* @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief PerVertexPhongAlphaMaterial class definition
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "pervertexphongalphamaterial.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QColor>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qshaderprogram.h>
#include <Qt3DRender/qparameter.h>
#include <Qt3DRender/qrenderpass.h>
#include <QFilterKey>
#include <Qt3DRender/qdepthtest.h>
#include <Qt3DRender/qblendequation.h>
#include <Qt3DRender/qblendequationarguments.h>
#include <Qt3DRender/qnodepthmask.h>
#include <Qt3DRender/qgraphicsapifilter.h>
#include <QUrl>
#include <QVector3D>
#include <QVector4D>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISP3DLIB;
using namespace Qt3DRender;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
PerVertexPhongAlphaMaterial::PerVertexPhongAlphaMaterial(QNode *parent)
: QMaterial(parent)
, m_pVertexEffect(new QEffect())
, m_pDiffuseParameter(new QParameter(QStringLiteral("kd"), QColor::fromRgbF(0.7f, 0.7f, 0.7f, 1.0f)))
, m_pSpecularParameter(new QParameter(QStringLiteral("ks"), QColor::fromRgbF(0.1f, 0.1f, 0.1f, 1.0f)))
, m_pShininessParameter(new QParameter(QStringLiteral("shininess"), 15.0f))
, m_pAlphaParameter(new QParameter("alpha", 0.5f))
, m_pVertexGL3Technique(new QTechnique())
, m_pVertexGL3RenderPass(new QRenderPass())
, m_pVertexGL3Shader(new QShaderProgram())
, m_pVertexGL2Technique(new QTechnique())
, m_pVertexGL2RenderPass(new QRenderPass())
, m_pVertexES2Technique(new QTechnique())
, m_pVertexES2RenderPass(new QRenderPass())
, m_pVertexES2Shader(new QShaderProgram())
, m_pFilterKey(new QFilterKey)
, m_pNoDepthMask(new QNoDepthMask())
, m_pBlendState(new QBlendEquationArguments())
, m_pBlendEquation(new QBlendEquation())
{
this->init();
}
//*************************************************************************************************************
PerVertexPhongAlphaMaterial::~PerVertexPhongAlphaMaterial()
{
}
//*************************************************************************************************************
void PerVertexPhongAlphaMaterial::init()
{
//Set shader
m_pVertexGL3Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/gl3/pervertexphongalpha.vert"))));
m_pVertexGL3Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/gl3/pervertexphongalpha.frag"))));
m_pVertexES2Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/es2/pervertexphongalpha.vert"))));
m_pVertexES2Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/model/materials/shaders/es2/pervertexphongalpha.frag"))));
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexGL3Shader);
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexES2Shader);
m_pVertexGL3RenderPass->setShaderProgram(m_pVertexES2Shader);
//Set OpenGL version
m_pVertexGL3Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
m_pVertexGL3Technique->graphicsApiFilter()->setMajorVersion(4);
m_pVertexGL3Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexGL3Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile);
m_pVertexGL2Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL);
m_pVertexGL2Technique->graphicsApiFilter()->setMajorVersion(2);
m_pVertexGL2Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexGL2Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
m_pVertexES2Technique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGLES);
m_pVertexES2Technique->graphicsApiFilter()->setMajorVersion(2);
m_pVertexES2Technique->graphicsApiFilter()->setMinorVersion(0);
m_pVertexES2Technique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::NoProfile);
//Setup transparency
m_pBlendState->setSourceRgb(QBlendEquationArguments::SourceAlpha);
m_pBlendState->setDestinationRgb(QBlendEquationArguments::OneMinusSourceAlpha);
m_pBlendEquation->setBlendFunction(QBlendEquation::Add);
m_pVertexGL3RenderPass->addRenderState(m_pBlendEquation);
m_pVertexGL2RenderPass->addRenderState(m_pBlendEquation);
m_pVertexES2RenderPass->addRenderState(m_pBlendEquation);
m_pVertexGL3RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexGL2RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexES2RenderPass->addRenderState(m_pNoDepthMask);
m_pVertexGL3RenderPass->addRenderState(m_pBlendState);
m_pVertexGL2RenderPass->addRenderState(m_pBlendState);
m_pVertexES2RenderPass->addRenderState(m_pBlendState);
m_pFilterKey->setName(QStringLiteral("renderingStyle"));
m_pFilterKey->setValue(QStringLiteral("forward"));
m_pVertexGL3Technique->addFilterKey(m_pFilterKey);
m_pVertexGL2Technique->addFilterKey(m_pFilterKey);
m_pVertexES2Technique->addFilterKey(m_pFilterKey);
m_pVertexGL3Technique->addRenderPass(m_pVertexGL3RenderPass);
m_pVertexGL2Technique->addRenderPass(m_pVertexGL2RenderPass);
m_pVertexES2Technique->addRenderPass(m_pVertexES2RenderPass);
m_pVertexEffect->addTechnique(m_pVertexGL3Technique);
m_pVertexEffect->addTechnique(m_pVertexGL2Technique);
m_pVertexEffect->addTechnique(m_pVertexES2Technique);
m_pVertexEffect->addParameter(m_pDiffuseParameter);
m_pVertexEffect->addParameter(m_pSpecularParameter);
m_pVertexEffect->addParameter(m_pShininessParameter);
m_pVertexEffect->addParameter(m_pAlphaParameter);
this->setEffect(m_pVertexEffect);
}
//*************************************************************************************************************
float PerVertexPhongAlphaMaterial::alpha()
{
return m_pAlphaParameter->value().toFloat();
}
//*************************************************************************************************************
void PerVertexPhongAlphaMaterial::setAlpha(float alpha)
{
m_pAlphaParameter->setValue(alpha);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.